Skip to content

Commit a5b0654

Browse files
carderneTrigger.dev RepoOps
authored andcommitted
feat(webapp): add log search to Ask Trigger
Mono-RevId: 668e9842662e2c98d28af21fed9481669ecc0261
1 parent 59dc663 commit a5b0654

23 files changed

Lines changed: 697 additions & 122 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
area: webapp
3+
type: feature
4+
---
5+
6+
Ask Trigger can now search your environment's logs by message, level, task, run, or time range when the Logs page is available.

‎apps/webapp/app/components/dashboard-agent/tool-labels.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const TOOL_LABELS: Record<string, string> = {
77
list_runs: "Looking through runs",
88
get_run: "Reading the run",
99
get_run_trace: "Reading the run's trace",
10+
search_logs: "Searching logs",
1011
list_errors: "Looking through errors",
1112
get_error: "Reading the error",
1213
get_query_schema: "Reading the data schema",

‎apps/webapp/app/hooks/useOnboardingDeploymentLogs.test.ts‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,30 @@
11
// @vitest-environment jsdom
2-
import { createS2Container } from "@internal/testcontainers/webapp";
2+
import { createS2Container, type StartedS2Container } from "@internal/testcontainers/webapp";
33
import { AppendInput, AppendRecord, S2 } from "@s2-dev/streamstore";
4-
import { createElement, useEffect } from "react";
4+
import { act, createElement, useEffect } from "react";
55
import { createRoot } from "react-dom/client";
6-
import { act } from "react-dom/test-utils";
7-
import { expect, it } from "vitest";
6+
import { afterAll, beforeAll, expect, it } from "vitest";
87
import { deploymentLogsCache } from "~/components/runs/v3/deploymentLogsCache";
98
import { useOnboardingDeploymentLogs } from "./useOnboardingDeploymentLogs";
109

11-
it("recovers late terminal logs without reading or evicting legacy inspector cache entries", async () => {
12-
const server = await createS2Container();
13-
const client = new S2({
10+
let server: StartedS2Container;
11+
let client: S2;
12+
13+
beforeAll(async () => {
14+
server = await createS2Container();
15+
client = new S2({
1416
accessToken: "local-test",
1517
endpoints: { account: `${server.endpoint}/v1`, basin: `${server.endpoint}/v1` },
1618
retry: { maxAttempts: 1 },
1719
});
20+
await client.basins.reconfigure({ basin: server.basin, createStreamOnRead: false });
21+
}, 120_000);
22+
23+
afterAll(async () => {
24+
await server?.container.stop();
25+
}, 30_000);
26+
27+
it("recovers late terminal logs without reading or evicting legacy inspector cache entries", async () => {
1828
const element = document.createElement("div");
1929
const root = createRoot(element);
2030
const stream = `late-terminal-${Date.now()}`;
@@ -47,7 +57,6 @@ it("recovers late terminal logs without reading or evicting legacy inspector cac
4757
}
4858
}
4959
try {
50-
await client.basins.reconfigure({ basin: server.basin, createStreamOnRead: false });
5160
// The legacy inspector can cache a missing terminal stream as complete.
5261
// Its cache entry must not suppress onboarding's late-stream recovery.
5362
deploymentLogsCache.set(`${server.basin}/${stream}`, {
@@ -93,19 +102,12 @@ it("recovers late terminal logs without reading or evicting legacy inspector cac
93102
await act(async () => {
94103
root.unmount();
95104
});
96-
await server.container.stop();
97105
}
98106
expect(deploymentLogsCache.get(`${server.basin}/${stream}`)?.complete).toBe(true);
99107
expect(deploymentLogsCache.get(`onboarding:${server.basin}/${stream}`)).toBeUndefined();
100108
}, 60_000);
101109

102110
it("keeps BuildKit's first-build registry cache miss in the logs without flagging it as an error", async () => {
103-
const server = await createS2Container();
104-
const client = new S2({
105-
accessToken: "local-test",
106-
endpoints: { account: `${server.endpoint}/v1`, basin: `${server.endpoint}/v1` },
107-
retry: { maxAttempts: 1 },
108-
});
109111
const element = document.createElement("div");
110112
const root = createRoot(element);
111113
const stream = `cache-miss-${Date.now()}`;
@@ -169,6 +171,5 @@ it("keeps BuildKit's first-build registry cache miss in the logs without flaggin
169171
await act(async () => {
170172
root.unmount();
171173
});
172-
await server.container.stop();
173174
}
174175
}, 60_000);

‎apps/webapp/app/mcp/tools/logs.server.ts‎

Lines changed: 18 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import { parseDate } from "@trigger.dev/core/v3/isomorphic";
22
import { $replica } from "~/db.server";
33
import { LogDetailPresenter } from "~/presenters/v3/LogDetailPresenter.server";
4-
import { LogsListPresenter } from "~/presenters/v3/LogsListPresenter.server";
54
import { clickhouseFactory } from "~/services/clickhouse/clickhouseFactoryInstance.server";
65
import { hasLogsPageAccess } from "~/services/logsAccess.server";
7-
import { getCurrentPlan } from "~/services/platform.v3.server";
6+
import { LOGS_SEARCH_BUDGET_MS, searchLogsInEnvironment } from "~/services/logsSearch.server";
87
import type { AuthenticatedEnvironment } from "~/services/apiAuth.server";
9-
import { decodeLogsSearchCursor } from "~/utils/logSearchCursor.server";
108
import { ServiceValidationError } from "~/v3/services/common.server";
119
import type { McpToolContext } from "../gate/types";
1210
import type { McpToolDefinition } from "../registry.server";
@@ -37,9 +35,6 @@ function parseTime(value: string | undefined): number | undefined | null {
3735
return parseDate(value)?.getTime() ?? null;
3836
}
3937

40-
const SEARCH_BUDGET_MS = 10_000;
41-
const DEFAULT_PERIOD = "1d";
42-
4338
function createSearchLogs(searchBudgetMs: number, now: () => number) {
4439
return defineReadTool({
4540
name: "search_logs",
@@ -57,76 +52,24 @@ function createSearchLogs(searchBudgetMs: number, now: () => number) {
5752
const to = parseTime(input.to);
5853
if (to === null) return errorResult(`Invalid arguments: to=${input.to}`);
5954

60-
const plan = await getCurrentPlan(environment.organizationId);
61-
const retentionLimitDays = plan?.v3Subscription?.plan?.limits.logRetentionDays.number ?? 30;
62-
63-
const logsClickhouse = await clickhouseFactory.getClickhouseForOrganization(
64-
environment.organizationId,
65-
"logs"
66-
);
67-
const presenter = new LogsListPresenter($replica, logsClickhouse);
68-
const filters = {
69-
projectId: environment.projectId,
70-
tasks: input.tasks?.length ? input.tasks : undefined,
71-
runId: input.runId,
72-
search: input.search,
73-
period: input.period,
74-
from,
75-
to,
76-
levels: input.levels?.length ? input.levels : undefined,
77-
retentionLimitDays,
78-
};
79-
8055
try {
81-
const startedAt = now();
82-
const read = (cursor: string | undefined, pageSize: number) =>
83-
presenter.call(
84-
environment.organizationId,
85-
environment.id,
86-
{
87-
...filters,
88-
userId: ctx.identity.userId,
89-
cursor,
90-
defaultPeriod: DEFAULT_PERIOD,
91-
pageSize,
92-
},
93-
ctx.signal
94-
);
95-
96-
const first = await read(input.cursor, input.limit);
97-
const logs = [...first.logs];
98-
let page = first;
99-
let searchedTo = first.searchProgress.searchedTo;
100-
while (
101-
page.pagination.next &&
102-
logs.length < input.limit &&
103-
now() - startedAt < searchBudgetMs &&
104-
!ctx.signal.aborted
105-
) {
106-
page = await read(page.pagination.next, input.limit - logs.length);
107-
logs.push(...page.logs);
108-
searchedTo = page.searchProgress.searchedTo ?? searchedTo;
109-
}
110-
111-
const applied =
112-
first.pagination.cursorApplied && input.cursor
113-
? decodeLogsSearchCursor(input.cursor)
114-
: null;
115-
return textResult(
116-
formatLogsPage(
117-
{
118-
...page,
119-
logs,
120-
filters: first.filters,
121-
searchProgress: { ...page.searchProgress, searchedTo },
122-
},
123-
{
124-
searchedFrom: new Date(applied?.slice.remainingUpper ?? first.filters.to.getTime()),
125-
cursorIgnored: first.pagination.cursorApplied === false,
126-
budgetSpent: page.pagination.next !== undefined && logs.length < input.limit,
127-
}
128-
)
56+
const { page, ...coverage } = await searchLogsInEnvironment(
57+
environment,
58+
ctx.identity.userId,
59+
{
60+
tasks: input.tasks?.length ? input.tasks : undefined,
61+
runId: input.runId,
62+
search: input.search,
63+
period: input.period,
64+
from,
65+
to,
66+
levels: input.levels?.length ? input.levels : undefined,
67+
cursor: input.cursor,
68+
pageSize: input.limit,
69+
},
70+
{ signal: ctx.signal, budgetMs: searchBudgetMs, now }
12971
);
72+
return textResult(formatLogsPage(page, coverage));
13073
} catch (error) {
13174
if (error instanceof ServiceValidationError) return errorResult(error.message);
13275
throw error;
@@ -178,7 +121,7 @@ const getLog = defineReadTool({
178121
const PERIOD_WITH_RANGE = "Invalid arguments: Pass either period or from/to, not both";
179122

180123
export function createLogsTools({
181-
searchBudgetMs = SEARCH_BUDGET_MS,
124+
searchBudgetMs = LOGS_SEARCH_BUDGET_MS,
182125
now = () => performance.now(),
183126
}: { searchBudgetMs?: number; now?: () => number } = {}): McpToolDefinition[] {
184127
const searchLogs = createSearchLogs(searchBudgetMs, now);
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import {
2+
DASHBOARD_AGENT_LOG_EXCERPT_CHARS,
3+
DASHBOARD_AGENT_LOG_ID_CHARS,
4+
DASHBOARD_AGENT_LOG_SEARCH_LIMIT,
5+
dashboardAgentLogSearchBody,
6+
dashboardAgentLogSearchResult,
7+
type dashboardAgentLogSearchValidationError,
8+
sliceWellFormed,
9+
} from "@internal/dashboard-agent-contracts";
10+
import { json } from "@remix-run/server-runtime";
11+
import type { z } from "zod";
12+
import { isRunFriendlyId } from "~/components/dashboard-agent/run-id";
13+
import { getRequestAbortSignal } from "~/services/httpAsyncStorage.server";
14+
import { hasLogsPageAccess } from "~/services/logsAccess.server";
15+
import { searchLogsInEnvironment } from "~/services/logsSearch.server";
16+
import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server";
17+
import { DASHBOARD_AGENT_CLIENT } from "~/services/userActorEnvironment.server";
18+
import { ServiceValidationError } from "~/v3/services/common.server";
19+
20+
const { action, loader } = createActionApiRoute(
21+
{
22+
method: "POST",
23+
body: dashboardAgentLogSearchBody,
24+
allowJWT: true,
25+
authorization: { action: "read", resource: () => ({ type: "runs" }) },
26+
},
27+
async ({ body, authentication: { actor, environment } }) => {
28+
if (!actor?.verified || actor.client !== DASHBOARD_AGENT_CLIENT || actor.pat) {
29+
return json({ error: "Dashboard agent access required" }, { status: 403 });
30+
}
31+
32+
if (!(await hasLogsPageAccess(actor.sub, false, false, environment.organization.slug))) {
33+
return json({ error: "Logs are not available for this organization." }, { status: 403 });
34+
}
35+
36+
const { from, to, ...filters } = body;
37+
const { page, searchedFrom, cursorIgnored, budgetSpent } = await searchLogsInEnvironment(
38+
environment,
39+
actor.sub,
40+
{
41+
...filters,
42+
from: from === undefined ? undefined : Date.parse(from),
43+
to: to === undefined ? undefined : Date.parse(to),
44+
pageSize: DASHBOARD_AGENT_LOG_SEARCH_LIMIT,
45+
},
46+
{ signal: getRequestAbortSignal() }
47+
).catch((error: unknown) => {
48+
if (error instanceof ServiceValidationError) {
49+
throw json(
50+
{ code: "log_search_validation", error: error.message } satisfies z.output<
51+
typeof dashboardAgentLogSearchValidationError
52+
>,
53+
{ status: 400 }
54+
);
55+
}
56+
throw error;
57+
});
58+
const { complete, timedOut, stopped, expired, searchedTo } = page.searchProgress;
59+
60+
return json({
61+
logs: page.logs.map((log) => ({
62+
runId:
63+
log.runId.length <= DASHBOARD_AGENT_LOG_ID_CHARS && isRunFriendlyId(log.runId)
64+
? log.runId
65+
: undefined,
66+
taskIdentifier: sliceWellFormed(log.taskIdentifier, DASHBOARD_AGENT_LOG_ID_CHARS),
67+
level: log.level,
68+
timestamp: log.triggeredTimestamp,
69+
message:
70+
log.message.length > DASHBOARD_AGENT_LOG_EXCERPT_CHARS
71+
? `${sliceWellFormed(log.message, DASHBOARD_AGENT_LOG_EXCERPT_CHARS)}…`
72+
: log.message,
73+
})),
74+
range: { from: page.filters.from.toISOString(), to: page.filters.to.toISOString() },
75+
searchedFrom: searchedFrom.toISOString(),
76+
searchedTo,
77+
complete,
78+
retentionClamped: page.retention?.wasClamped ?? false,
79+
timedOut,
80+
stopped,
81+
expired,
82+
cursorIgnored,
83+
budgetSpent,
84+
nextCursor: dashboardAgentLogSearchResult.shape.nextCursor.safeParse(page.pagination.next)
85+
.data,
86+
} satisfies z.output<typeof dashboardAgentLogSearchResult>);
87+
}
88+
);
89+
90+
export { action, loader };
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { $replica } from "~/db.server";
2+
import { LogsListPresenter, type LogsListOptions } from "~/presenters/v3/LogsListPresenter.server";
3+
import { decodeLogsSearchCursor } from "~/utils/logSearchCursor.server";
4+
import type { AuthenticatedEnvironment } from "./apiAuth.server";
5+
import { clickhouseFactory } from "./clickhouse/clickhouseFactoryInstance.server";
6+
import { getCurrentPlan } from "./platform.v3.server";
7+
8+
export const LOGS_SEARCH_BUDGET_MS = 10_000;
9+
10+
type SearchOptions = Pick<
11+
LogsListOptions,
12+
"tasks" | "runId" | "search" | "period" | "from" | "to" | "levels" | "cursor"
13+
> & { pageSize: number };
14+
15+
/** Unlike the interactive list, keep reading slices until the caller has a page of results. */
16+
export async function searchLogsInEnvironment(
17+
environment: AuthenticatedEnvironment,
18+
userId: string,
19+
filters: SearchOptions,
20+
{
21+
signal,
22+
budgetMs = LOGS_SEARCH_BUDGET_MS,
23+
now = () => performance.now(),
24+
}: { signal: AbortSignal; budgetMs?: number; now?: () => number }
25+
) {
26+
const { id, organizationId, projectId } = environment;
27+
const plan = await getCurrentPlan(organizationId);
28+
const retentionLimitDays = plan?.v3Subscription?.plan?.limits.logRetentionDays.number ?? 30;
29+
const clickhouse = await clickhouseFactory.getClickhouseForOrganization(organizationId, "logs");
30+
const presenter = new LogsListPresenter($replica, clickhouse);
31+
const startedAt = now();
32+
const read = (cursor: string | undefined, pageSize: number) =>
33+
presenter.call(
34+
organizationId,
35+
id,
36+
{ ...filters, userId, projectId, cursor, pageSize, retentionLimitDays, defaultPeriod: "1d" },
37+
signal
38+
);
39+
40+
const first = await read(filters.cursor, filters.pageSize);
41+
const logs = [...first.logs];
42+
let page = first;
43+
let searchedTo = first.searchProgress.searchedTo;
44+
while (
45+
page.pagination.next &&
46+
logs.length < filters.pageSize &&
47+
now() - startedAt < budgetMs &&
48+
!signal.aborted
49+
) {
50+
page = await read(page.pagination.next, filters.pageSize - logs.length);
51+
logs.push(...page.logs);
52+
searchedTo = page.searchProgress.searchedTo ?? searchedTo;
53+
}
54+
55+
const applied =
56+
first.pagination.cursorApplied && filters.cursor
57+
? decodeLogsSearchCursor(filters.cursor)
58+
: null;
59+
return {
60+
page: {
61+
...page,
62+
logs,
63+
filters: first.filters,
64+
searchProgress: { ...page.searchProgress, searchedTo },
65+
},
66+
searchedFrom: new Date(applied?.slice.remainingUpper ?? first.filters.to.getTime()),
67+
cursorIgnored: first.pagination.cursorApplied === false,
68+
budgetSpent: page.pagination.next !== undefined && logs.length < filters.pageSize,
69+
};
70+
}

‎apps/webapp/app/services/userActorEnvironment.server.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { rbac } from "~/services/rbac.server";
1111

1212
const FORBIDDEN_ENVIRONMENT_CODE = "forbidden_environment";
1313

14-
const DASHBOARD_AGENT_CLIENT = "dashboard-agent";
14+
export const DASHBOARD_AGENT_CLIENT = "dashboard-agent";
1515

1616
/** Only the webapp's own mint yields this shape; a token minted from a PAT always names its `pat`. */
1717
export function isDashboardAgentUserActor(claims: UserActorClaims | undefined): boolean {

0 commit comments

Comments
 (0)