feat(webapp): dashboard agent — chat, reports, Investigate, Watch - #4418
feat(webapp): dashboard agent — chat, reports, Investigate, Watch#4418kathiekiwi wants to merge 391 commits into
Conversation
…ved slot Every chat row keeps the leading slot so titles align; watching spins like thinking (the hover title says which) and the short status text stays on hover.
…n through The endpoints require chatId (the same chat-scoped floor watch creation uses); the tools sent none and every call died as a 400.
…umber in one column The throughput label now sits vertically centered against its value+breakdown stack, and 842/830 start on the same vertical as +12/min and the other rows' values; sub labels follow their numbers.
…s, UI map, hands-on walkthrough
…aks plainly One conversational message with the watch's note, a lime CTA, and the same skeleton as the billing-limit email; the fielded fact sheet is gone and the unsubscribe link keeps its wiring with footer styling.
…d to mid-column, number in the value column
'Watch update — all clear / needs your attention', toned by kind; the identity moves to the details line and the subject follows suit.
…with starred scenarios
🦋 Changeset detectedLatest commit: 85b98ab The changes in this PR will be included in the next version bump. This PR includes changesets to release 27 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThis PR adds a Dashboard Agent feature set. It introduces a contracts package for shared schemas (view blocks, intents, page context, watches, trigger:// URIs), a dedicated database package for chats, investigations, and watches, and core agent tool/prompt logic. It adds a watch-tick lifecycle with checks, alerts (email, Slack, webhook), and unsubscribe flows. It adds API routes for watches, alerts, queue metrics, and run diagnostics. It redesigns the chat panel UI with investigation, report, and watch cards, suggested prompts, and unread-wake notifications. It adds a Storybook demo gallery with screenshot tooling, seed scripts, and removes "Docs" links from page headers across the webapp. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…t button; URLs are links The prompt now treats earlier turns' pages as history — deictic questions re-read the current page every turn, and page explanations end with a matching docs link. The report's contact action falls back to the contact page as a real external button instead of an ask round-trip, and answers that point at a URL carry it as a link.
…ress line, wake toast opens its chat as an agent Callout - navigate intents and navigate_to outputs resolve trigger:// URIs server-side and navigate in place; same-origin citation buttons navigate instead of opening a new tab. - The transcript autoscrolls on send and follows streaming near the bottom; a store-order stable merge stops messages landing mid-chat after a page change (server-side single-read follow-up noted). - The generic Working line yields to a tool-specific one. - The wake toast is the new agent Callout variant (chat icon) and opens the exact chat that woke.
…nside the label column
An in-flight tool call now shows a compact pill (per-tool phrase + spinner, watch-chip visual language) instead of raw streaming JSON — covering render_view and get_report, the biggest offenders. Completed and error states render as before; gallery in-flight examples reworked and a pill line-up section added.
The answer is the prose and the cards, never the input/output plumbing: a landed call disappears (the pill was its only trace), and only a FAILED call keeps its error row. Gallery example reworked accordingly.
Wakes are wake-shaped (banner renders), no prose points at tool rows that no longer render, footer-era phrasing removed, the four-wake variation matrix became one coherent story, and tests now enforce all of it (wake ids parse via the real WakeBanner, removed-UI phrases are banned).
Offering to fetch what a tool can fetch now is banned; 'how do I check X' about the user's project gets both the how-to and the actual check; only genuinely unreachable steps (their infra, their code, external pages) go to the user, clearly separated.
…flows # Conflicts: # .changeset/report-health.md # .server-changes/agent-detail-metrics-layout.md # .server-changes/paginate-concurrency-keys-table.md # .server-changes/queue-metrics-dashboard.md # apps/webapp/app/components/dashboard-agent/AgentChart.tsx # apps/webapp/app/components/metrics/MiniLineChart.tsx # apps/webapp/app/components/query/QueryEditor.tsx # apps/webapp/app/env.server.ts # apps/webapp/app/hooks/useMetricResourceQuery.ts # apps/webapp/app/presenters/v3/QueueListPresenter.server.ts # apps/webapp/app/presenters/v3/QueueMetricsPresenter.server.ts # apps/webapp/app/presenters/v3/RunQueueMetricsPresenter.server.ts # apps/webapp/app/presenters/v3/reports/health/health-data.ts # apps/webapp/app/presenters/v3/reports/health/health-messages.ts # apps/webapp/app/presenters/v3/reports/health/health.ts # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query/ExamplesContent.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query/TableSchemaContent.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.queues/route.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.queues_.$queueParam/route.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.tasks.standard.$taskParam/route.tsx # apps/webapp/app/routes/api.v1.query.schema.ts # apps/webapp/app/routes/resources.metric.tsx # apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query.ai-generate.tsx # apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsx # apps/webapp/app/routes/resources.queues.concurrency-keys.ts # apps/webapp/app/services/queryService.server.ts # apps/webapp/app/v3/querySchemas.ts # apps/webapp/app/v3/queueMetrics.server.ts # apps/webapp/test/reportHealth.test.ts # internal-packages/clickhouse/src/client/tsql.ts # internal-packages/run-engine/src/engine/systems/enqueueSystem.ts # internal-packages/tsql/src/query/schema.ts
@trigger.dev/build
trigger.dev
@trigger.dev/core
@trigger.dev/python
@trigger.dev/react-hooks
@trigger.dev/redis-worker
@trigger.dev/rsc
@trigger.dev/schema-to-json
@trigger.dev/sdk
commit: |
… uses the tenancy-scoped list signature The suite pinned a migration list that stopped before last_read_at (42703 on CI) and two tests still called listActiveWatchesForChats with the pre-tenancy array signature. Migrations are now read from the folder so a new one can't silently stale the schema.
There was a problem hiding this comment.
Actionable comments posted: 8
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx (1)
95-112: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGuard
getPromotedDashboardAgentPromptagainst failures, and skip it when access is already false.This loader backs the entire env layout (
Outletwraps every page under this environment), so it runs on nearly every navigation.getPromotedDashboardAgentPromptis called unconditionally and unguarded — if flag evaluation/parsing ever throws, it takes down the whole environment layout for a feature that's purely cosmetic (a suggested-prompt chip). It's also wasted work wheneverhasDashboardAgentAccessisfalse, sinceDashboardAgentnever consumespromotedPromptin that case (it early-returns children without rendering the panel).🛡️ Proposed fix: gate on access and fail closed
- const promotedDashboardAgentPrompt = await getPromotedDashboardAgentPrompt({ - orgFeatureFlags: (project.organization.featureFlags as Record<string, unknown>) ?? {}, - }); + const promotedDashboardAgentPrompt = hasDashboardAgentAccess + ? await getPromotedDashboardAgentPrompt({ + orgFeatureFlags: (project.organization.featureFlags as Record<string, unknown>) ?? {}, + }).catch((error) => { + logger.error("Failed to resolve promoted dashboard agent prompt", { error }); + return undefined; + }) + : undefined;
🟡 Minor comments (13)
apps/webapp/seed-agent-examples.mts-1598-1614 (1)
1598-1614: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
?.value ? … : undefinedcollapses a legitimate zero into the fallback.
pending,donePerMin,triggeredPerMinanddrainMinutesall treat a reported0as "absent" and fall back to theSTORY.*constants. On a recovered or quiet stand the card would read 0 pending while the prose quotes 4,812 — the exact disagreement this function exists to prevent. Use a nullish check instead.🐛 Guard on presence, not truthiness
- pending: metric("pending")?.value ? Math.round(metric("pending")!.value) : undefined, + pending: metric("pending")?.value != null ? Math.round(metric("pending")!.value) : undefined, worstQueueShare: flow?.attribution?.dim === "queue" ? flow.attribution.share : undefined, - donePerMin: vm.facts?.throughput?.donePerMin + donePerMin: vm.facts?.throughput?.donePerMin != null ? Math.round(vm.facts.throughput.donePerMin) : undefined, - triggeredPerMin: vm.facts?.throughput?.triggeredPerMin + triggeredPerMin: vm.facts?.throughput?.triggeredPerMin != null ? Math.round(vm.facts.throughput.triggeredPerMin) : undefined, - drainMinutes: drain?.value ? Math.round(drain.value) : undefined, + drainMinutes: drain?.value != null ? Math.round(drain.value) : undefined,apps/webapp/seed-queue-metrics.mts-581-597 (1)
581-597: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
DELETEwithoutmutations_syncraces the seeding insert that follows.
--resetruns these deletes and then line 941 inserts immediately. The sibling seeder guards the identical sequence withSETTINGS mutations_sync = 2and explains why: left asynchronous, the re-seed races its own predecessor and leaves a second copy of the data behind. Worth settingasync_insert: 0on line 572 too, so the rows are visible to theOPTIMIZE … FINALcalls on lines 949-952.🐛 Make the reset finish before seeding
await raw.command({ - query: `DELETE FROM trigger_dev.${table} WHERE environment_id = '${environmentId}'`, + query: `DELETE FROM trigger_dev.${table} WHERE environment_id = '${environmentId}' SETTINGS mutations_sync = 2`, });apps/webapp/seed-agent-examples-chats.mts-338-339 (1)
338-339: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse the
COMPLETED_WITH_ERRORSstatus literal in the TRQL query.
Failedis not a standard run status in Trigger.dev TRQL; usestatus = 'COMPLETED_WITH_ERRORS'so the seeded failed runs are counted.apps/webapp/seed-queue-metrics.mts-1-6 (1)
1-6: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winKeep this seeder consistent with
seed-agent-examples.mts's documented interop pattern.
seed-agent-examples.mtsdisables the sibling import-entry CommonJS boundary instead of running into the documented named-import loading failure, so this script should use the same default-binding import/interworking pattern.internal-packages/dashboard-agent-contracts/src/blocks.ts-133-146 (1)
133-146: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winRequire
http(s)on docs action targets.
targetis documented as “an https URL” fordocsactions, but the schema accepts any string. Since this field is LLM-authored UI input, prefer narrowing it tohttp://orhttps://URLs in the schema rather than leaving the contract to later validation.apps/webapp/app/services/dashboardAgentWatchChecks.ts-146-175 (1)
146-175: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winMake unreliable queued wait labels include the stale-first-enqueue caveat.
For
WAITING_TO_RESUME/RETRYING_AFTER_FAILURE/PAUSED,run.queuedAtis not a current queue entry, but this path still emitswaitBasis: "queued_at"and a confidentqueued for …label. Bake the caveat into the label or omit the label whenqueueWaitReliableis false so it can’t be surfaced as a current wait time downstream.♻️ Make the label carry its own caveat
if (run.queuedAt) { const waitMs = Math.max(0, end.getTime() - run.queuedAt.getTime()); return { waitMs, waitBasis: "queued_at", - waitLabel: `queued for ${formatMs(waitMs)}`, + waitLabel: queueWaitReliable + ? `queued for ${formatMs(waitMs)}` + : `time since first enqueue: ${formatMs(waitMs)}`, queueWaitReliable, }; }apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx-163-180 (1)
163-180: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
CitationButtonrenders different elements on server vs client.
pathis alwaysnullduring SSR, so the server emits aLinkButtonanchor while the first client render emits aButton— a hydration mismatch for every same-origin citation. Compute the path fromsameOriginPathafter mount (or keep one element type and branch insideonClick).♻️ One option: single element, branch on click
function CitationButton({ url, label }: { url: string; label: string }) { const navigate = useNavigate(); - const path = typeof window === "undefined" ? null : sameOriginPath(url, window.location.origin); - - if (path) { - return ( - <Button variant="docs/small" LeadingIcon={BookOpenIcon} onClick={() => navigate(path)}> - {label} - </Button> - ); - } - return ( - <LinkButton to={url} variant="docs/small" LeadingIcon={BookOpenIcon}> + <LinkButton + to={url} + variant="docs/small" + LeadingIcon={BookOpenIcon} + onClick={(event) => { + const path = sameOriginPath(url, window.location.origin); + if (!path) return; + event.preventDefault(); + navigate(path); + }} + > {label} </LinkButton> ); }apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx-166-189 (1)
166-189: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winPost-mutation reloads can coalesce onto a pre-mutation request.
loadHistoryreturns the in-flight promise, so thevoid loadHistory()calls indeleteChat(Line 422) andcancelWatch(Line 452) can piggyback on a GET that was issued before the POST landed and re-render the stale list — the deleted chat reappears, or the cancelled watch chip comes back, until something else triggers a reload. Chain a fresh request after the in-flight one instead of returning it.🐛 Sketch: let callers ask for post-mutation freshness
- const loadHistory = useCallback(async () => { - if (historyInFlight.current) return historyInFlight.current; + const loadHistory = useCallback(async (options?: { fresh?: boolean }) => { + if (historyInFlight.current) { + // A reload after a mutation must not adopt a request that was already + // in flight before it — that result predates the change. + if (!options?.fresh) return historyInFlight.current; + await historyInFlight.current; + } const request = (async () => {Then call
void loadHistory({ fresh: true })fromdeleteChatandcancelWatch.apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx-161-177 (1)
161-177: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAn enabled button that does nothing is a real click target outside the gallery.
useRunPathreturnsundefinedwhenever org/project/env context is missing — the storybook gallery is one such case, but any future host without that context is another. A user clicking gets silence with no feedback. Preferdisabled(or a tooltip explaining why) so the inert state is honest, and keep the gallery's visual review by passing an explicit prop rather than inferring it from missing context.apps/webapp/test/dashboardAgentWatchChecks.test.ts-123-134 (1)
123-134: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAssert the label in the stale-
queuedAtcase — that's the invariant this file exists to pin.The header calls out the wait label as the thing that must never call a time-from-creation a queue wait, but this test only checks
queueWaitReliableandwaitBasis. A regression that emitted"queued for 10m"for an untrustworthyqueuedAton a resumed run would still pass. Add the label (and theresult) assertion.💚 Proposed addition
expect(outcome.facts.queueWaitReliable).toBe(false); expect(outcome.facts.waitBasis).toBe("queued_at"); + expect(outcome.result).toBe("pending"); + // Reliability is false, so the label must not claim a queue wait. + expect(outcome.facts.waitLabel).not.toMatch(/queued for/);internal-packages/dashboard-agent/src/tools.ts-429-448 (1)
429-448: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winWrap the body read so an aborted/interrupted response doesn't escape as a throw.
The
fetchcall is guarded butawait res.text()on Line 431 is not. If the 30s abort fires while the body is streaming (or the connection resets mid-body), this rejects and the throw escapessearchTriggerDocs, breaking the documented "returns{ error }" contract thatsearch_docsrelies on.🛡️ Proposed fix
if (!res.ok) return { error: `The docs search failed (status ${res.status}).` }; - const body = await res.text(); + let body: string; + try { + body = await res.text(); + } catch (error) { + return { error: `Couldn't read the docs response: ${(error as Error).message}` }; + } let payload: any;internal-packages/dashboard-agent/src/tools.ts-872-883 (1)
872-883: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
list_errorsdoesn't clampperiod, unlikelist_runsandlist_deploys.Lines 845 and 1096 both run the model-supplied
periodthroughclampPeriod; Line 877 forwards it raw. Unless the errors route clamps server-side, the model can request an unbounded window here.♻️ Proposed fix
execute: async ({ status, taskIdentifier, search, period, limit }) => { + const effectivePeriod = period ? clampPeriod(period) : undefined; const sp = new URLSearchParams(); if (status) sp.append("filter[status]", status); if (taskIdentifier) sp.append("filter[taskIdentifier]", taskIdentifier); if (search) sp.append("filter[search]", search); - if (period) sp.append("filter[period]", period); + if (effectivePeriod) sp.append("filter[period]", effectivePeriod);apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts-72-78 (1)
72-78: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRounding
endMsup withMath.ceilincludes future time in the averaged window.Because
endMsis rounded up to the next bucket boundary, it can be ahead ofDate.now()by up tobucketSeconds(as much as ~1/12 of the requested period).startedPerMinand other rate fields then divide the real (bounded) count by a window that partly hasn't happened yet, systematically under-reporting throughput/rate by the same proportion.Math.floorgives identical cache-alignment benefits without ever querying/averaging over future time.🐛 Proposed fix
- const endMs = Math.ceil(Date.now() / (bucketSeconds * 1000)) * bucketSeconds * 1000; + const endMs = Math.floor(Date.now() / (bucketSeconds * 1000)) * bucketSeconds * 1000;Also applies to: 124-126
🧹 Nitpick comments (32)
apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx (1)
12-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate chart-card frame markup — parameterize
rowsinstead of reimplementing the frame for the empty state.
DemoChartCardhardcodesrows={demoChart.rows}with no way to override it, so the gallery's empty-chart state had to copy the entire border/title-strip/height JSX just to passrows={[]}.
apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx#L12-L30: accept an optionalrowsprop (defaulting todemoChart.rows) so callers can override the dataset.apps/webapp/app/routes/storybook.agent-ui/route.tsx#L300-L317: replaceEmptyChartCard's duplicated JSX with<DemoChartCard rows={[]} />(or equivalent) once the prop exists.apps/webapp/app/routes/storybook.agent-ui/route.tsx (1)
397-436: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider deriving
untrustworthyReportvia the real stale-guard function rather than hand-rolling its output shape.The comment above this block states it's "Derived exactly the way
applyStaleGuarddoes it," but the code manually reconstructs the transformation instead of calling that function. IfapplyStaleGuard(or equivalent) is exported and importable here, calling it directly would guarantee this fixture never drifts from the real stale-telemetry behavior it's meant to demonstrate.Please confirm whether the health report's stale-guard transformation (referenced as
applyStaleGuard) is exported in a form importable from this route (e.g. fromapps/webapp/app/presenters/v3/reports/health/health.ts), so this fixture could call it directly instead of duplicating its logic.apps/webapp/app/components/dashboard-agent/demo/demo.test.ts (1)
34-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe isolation guard misses side-effect and dynamic imports.
importSpecifiersonly matches… from "x", soimport "~/foo.server"andawait import("~/db.server")slip through the very check on lines 369-378 that exists to catch them.♻️ Broaden the specifier scan
-/** Every import specifier in a file, from both `import` and `export … from`. */ +/** Every module specifier in a file: `from "x"`, `import "x"` and `import("x")`. */ function importSpecifiers(source: string): string[] { - return [...source.matchAll(/(?:import|export)[\s\S]*?from\s+["']([^"']+)["']/g)].map( - (match) => match[1]! - ); + return [ + ...source.matchAll(/from\s+["']([^"']+)["']/g), + ...source.matchAll(/\bimport\s*\(\s*["']([^"']+)["']/g), + ...source.matchAll(/\bimport\s+["']([^"']+)["']/g), + ].map((match) => match[1]!); }apps/webapp/seed-agent-examples-chats.mts (1)
257-257: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winImport
VIEW_BLOCK_VERSIONinstead of hardcodingversion: 1.The demo fixtures stamp the envelope from the contracts constant; these seeded blocks hardcode
1. If the contract version is bumped, the strict envelope schema rejects these blocks and the cards silently degrade to plain tool rows — exactly the failure mode the transcripts exist to demonstrate. The package is already imported on line 29.♻️ Use the contract constant
-import { formatTriggerUri } from "`@internal/dashboard-agent-contracts`"; +import { formatTriggerUri, VIEW_BLOCK_VERSION } from "`@internal/dashboard-agent-contracts`";- const diagnosisEnvelope = { id: `diag_${w.failedRunId}`, version: 1 }; + const diagnosisEnvelope = { id: `diag_${w.failedRunId}`, version: VIEW_BLOCK_VERSION };const failuresChart = { id: "chart_failures_by_task", revision: 0, - version: 1, + version: VIEW_BLOCK_VERSION,const pendingChart = { id: "chart_pending_runs", revision: 0, - version: 1, + version: VIEW_BLOCK_VERSION,Also applies to: 332-362
apps/webapp/test/seedAgentExamplesChats.test.ts (1)
176-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRead the kind with the contracts parser rather than
split("/")[4].Positional indexing silently mis-classifies if the URI layout changes — a
runURI read asreportwould skip the resolution assertion entirely, and the test would still pass.demo.test.tsusessafeParseTriggerUrifor exactly this.♻️ Parse instead of index
for (const uri of uris) { - const kind = uri.split("/")[4]; - if (UNRESOLVABLE_KINDS.includes(kind)) continue; + const parsed = safeParseTriggerUri(uri); + expect(parsed.success, uri).toBe(true); + if (!parsed.success || UNRESOLVABLE_KINDS.includes(parsed.data.kind)) continue; const resolved = resolveTriggerUri(SCOPE, uri);Add the import:
import { safeParseTriggerUri } from "`@internal/dashboard-agent-contracts`";internal-packages/dashboard-agent-contracts/src/trigger-uri.ts (1)
320-341: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueDuplicate
lineparams are silently accepted, last one wins.
trigger://…/source/abc/a.ts?line=1&line=2parses asline: 2. Everything else in the grammar rejects non-canonical input (fragments, unknown params, empty segments), so accepting a duplicate here is inconsistent and lets two different URIs mean the same resource.♻️ Reject duplicates
for (const [key, value] of params) { if (key !== "line") { return { success: false, error: `unknown query param "${key}"` }; } + if (line !== undefined) { + return { success: false, error: "duplicate query param \"line\"" }; + } + if (!/^\d+$/.test(value) || Number(value) < 1) {internal-packages/dashboard-agent/src/watch-tick.ts (1)
212-224: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
wakeActioninfers the action type from "not fired".If
isTerminalWatchStatusever admits a third terminal status (e.g.cancelled, which the contract'swatchStatusSchemaincludes), the delivery-only path producestype: "watch.expired"withid: watch:<id>:cancelled— a type/id pair that doesn't describe what happened. Switching on the status explicitly keeps that from slipping through silently.♻️ Switch on the status
function wakeAction(watch: Watch, facts: Record<string, unknown>): WatchWakeAction { const spec = watch.spec as PersistedWatchSpec; + if (watch.status !== "fired" && watch.status !== "expired") { + throw new Error(`cannot build a wake for a ${watch.status} watch`); + } return { - type: watch.status === "fired" ? "watch.fired" : "watch.expired", + type: watch.status === "fired" ? "watch.fired" : "watch.expired",internal-packages/dashboard-agent/src/dashboard-agent.eval.ts (1)
582-585: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
APICallError.isInstance(error)for provider error detection.
error.name.includes("APICallError")depends on the error name surviving any wrapping or renaming; the SDK’s provided type guard is more reliable.♻️ Use the SDK's type guard
- const infra = error instanceof Error && error.name.includes("APICallError"); + const infra = APICallError.isInstance(error);plus
import { APICallError } from "ai";internal-packages/dashboard-agent/src/dashboard-agent.test.ts (1)
429-432: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPoll the eval-enqueue side effect instead of relying on a fixed sleep.
turnAtRatewaits only 30 ms before returning calls, which can still fail when the runner is loaded. Move the assertion out of the helper and make it wait for the expected call count, e.g.vi.waitFor(() => expect(calls).toHaveLength(1), { timeout: 2000 }); for the rate-0 path keep a bounded wait on “still empty” if needed.internal-packages/dashboard-agent-contracts/src/watch.ts (1)
38-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider
z.discriminatedUnion("kind", [...])instead ofz.union.All five branches share a literal
kinddiscriminator, so this is a textbook case forz.discriminatedUnion. With plainz.union, an invalid payload (e.g., wrongkindor a badrunId) produces a combinedinvalid_unionerror listing every failed branch, which is noisier to surface back to the agent/tool-caller than the targeted errordiscriminatedUniongives.♻️ Proposed refactor
-export const watchSpecSchema = z.union([ +export const watchSpecSchema = z.discriminatedUnion("kind", [ watchCommonSchema .extend({ kind: z.literal("run_start"), runId: z.string() }) .merge(runStateCadenceSchema),internal-packages/dashboard-agent-db/src/queries.ts (1)
684-698: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the shared unread-wake predicate.
The same
(last_read_at is null or coalesce(fired_at, last_checked_at) > last_read_at)clause plus thestatus in ('fired','expired')+ tenancy join is repeated verbatim incountUnreadWatchWakes,listUnreadWatchWakes(Line 744), andlistChatIdsWithUnreadWakes(Line 783). One helper returning theand(...)condition keeps the wake definition single-sourced — the doc comments already assert all three share it.♻️ Sketch
+function unreadWakeCondition(params: { organizationId: string; userId: string }) { + return and( + inArray(watches.status, ["fired", "expired"]), + eq(chats.organizationId, params.organizationId), + eq(chats.userId, params.userId), + isNull(chats.deletedAt), + sql`(${chats.lastReadAt} is null or coalesce(${watches.firedAt}, ${watches.lastCheckedAt}) > ${chats.lastReadAt})` + ); +}internal-packages/dashboard-agent/VERDICTS.md (1)
104-108: 📐 Maintainability & Code Quality | 🔵 TrivialTrack the documented
queuedDurationbug.
RunPresenter.server.tscomputingqueuedDurationasstartedAt − createdAtis recorded here as knowingly unfixed, which over-reports for delayed/scheduled runs in the dashboard. Want me to open an issue so it doesn't only live in this markdown file?internal-packages/dashboard-agent/src/dashboard-agent.ts (1)
622-626: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse the same non-null assertion as
withCacheBreakpointOnLast.
sanitized[sanitized.length - 1]is typedModelMessage | undefinedundernoUncheckedIndexedAccess, and it's then spread at Line 628. The helper at Line 378 already handles this with!; mirror it here so the two paths type-check identically.♻️ Proposed tweak
- const last = sanitized[sanitized.length - 1]; + const last = sanitized[sanitized.length - 1]!;internal-packages/dashboard-agent/src/tool-schemas.ts (1)
398-403: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winValidate the alert email shape in the schema.
z.string().email()makes the model's mistake a tool-validation error it can correct in-turn.♻️ Proposed change
email: z - .string() + .string() + .email() .optional() .describe("Email to alert. Omit to use the user's own account email."),apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)
92-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
unknown[]+as neverthrows away the block contract.
blocksForreturnsunknown[], forcingblocks as neverat theViewBlockscall site, so a block-shape change in@internal/dashboard-agent-contractswon't surface at compile time here. Typing the return as the catalog's block union would keep the boundary checked.Also applies to: 222-228
apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx (1)
471-476: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value
?? []hands a new array down on every render.
chatWatchesgets a fresh identity each render, which flows intoDashboardAgentChat→DashboardAgentMessagesand defeats thememoonDashboardAgentTurn(itswatchesprop always compares unequal). A module-levelconst NO_WATCHES: WatchChip[] = []fallback keeps the reference stable.apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx (1)
58-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueName the "no page context" fallback.
The inline
{ page: { kind: "other", path: "" }, signals: [] }is a placeholder context built at the call site; a shared named constant (e.g.UNKNOWN_PAGE_CONTEXTinsuggested-prompts/registry.ts) keeps the meaning of the emptypathexplicit and reusable.As per coding guidelines: "Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons."
Source: Coding guidelines
apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts (1)
217-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
SIGNAL_PRIORITYisn't exhaustiveness-checked, and the two iterators duplicate one loop.
SIGNAL_SLOTis aRecord<AgentPageSignalKind, …>, so a new signal kind fails to compile there — butSIGNAL_PRIORITYis a bare array, and since both iterators drive off it, a kind missing from the array silently never produces a chip.contextualPromptsis alsocontextualPromptsBySlotflattened in slot order.♻️ Make the priority list exhaustive and derive the flat list
-export const SIGNAL_PRIORITY: AgentPageSignalKind[] = [ +// A tuple typed against the kind union: omitting a new kind is a compile error. +export const SIGNAL_PRIORITY = [ "fresh_failure", "waiting_run", "slow_run", "concurrency_saturation", -]; +] as const satisfies readonly AgentPageSignalKind[];export function contextualPrompts(context: AgentPageContext, now: number): SuggestedPrompt[] { - const prompts: SuggestedPrompt[] = []; - for (const kind of SIGNAL_PRIORITY) { - for (const signal of context.signals) { - if (signal.kind !== kind) continue; - const prompt = promptForSignal(signal, now); - if (prompt) prompts.push(prompt); - } - } - return prompts; + const bySlot = contextualPromptsBySlot(context, now); + return PROMPT_SLOTS.flatMap((slot) => bySlot[slot]); }Note: this changes
contextualPromptsordering from signal-priority to slot order — keep the current loop if callers depend on the former.Also applies to: 284-320
apps/webapp/app/components/dashboard-agent/ReportView.tsx (1)
37-39: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueComment describes a registration side effect that doesn't exist.
healthMessagesis used purely as a value in the staticCATALOGSmap on Line 89 — nothing self-registers on import. Worth correcting so a future reader doesn't assume adding an import is enough to register a new report's catalog.apps/webapp/app/components/dashboard-agent/agent-badges.tsx (1)
46-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHand-rolled icon component signature duplicated across two files. Both files type heroicons components as a bare call signature returning
JSX.Element, which is version-sensitive (ForwardRefExoticComponent's call signature returnsReactNode) and duplicated rather than shared.
apps/webapp/app/components/dashboard-agent/agent-badges.tsx#L46-L46: change the exportedIconComponentalias toReact.ComponentType<{ className?: string }>.apps/webapp/app/components/dashboard-agent/WakeBanner.tsx#L77-L82: importIconComponentfrom./agent-badgesand typeTONE_ICONasRecord<AgentTone, IconComponent>instead of restating the signature inline.apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts (1)
28-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDismissals are permanent and the key set is never pruned.
Every dismissed id leaves a key behind forever, including operator-controlled promoted-prompt ids that rotate. Consider storing a timestamp instead of
"1"so stale entries can expire (and a chip can come back after a while), or prune on read.apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts (1)
192-195: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTest name contradicts its fixture.
running: 10against aconcurrencyLimitof 10 is at the limit, not "idle under its limit" — the case being covered is "at capacity with an empty queue". Renaming keeps the boundary this test pins obvious.apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts (1)
164-172: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
toContain("")passes vacuously if the fixture changes kind.Line 223 in this same file already uses the stronger pattern (
throw new Error("fixture changed")); the ternary here silently degrades to an assertion that can never fail. Prefer the narrowing guard for consistency.♻️ Proposed change
it("sends the full prompt text, not the short label", () => { const [failure] = resolveSuggestedPrompts(demoPageContexts.failedRun, { now: NOW }); + const page = demoPageContexts.failedRun.page; + if (page.kind !== "run") throw new Error("fixture changed"); expect(failure?.label).toBe("Why did this run fail?"); - expect(failure?.prompt).toContain( - demoPageContexts.failedRun.page.kind === "run" ? demoPageContexts.failedRun.page.runId : "" - ); + expect(failure?.prompt).toContain(page.runId); expect(failure?.prompt).toContain("12m ago"); });internal-packages/dashboard-agent/src/tools.ts (3)
596-624: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMisplaced doc block: the
renderInvestigationsdocs sit oncanonicalizeEvidence.Two doc comments are stacked here; the first (Lines 596-613, describing block stamping and
continueId) documentsrenderInvestigations, which is declared at Line 706. Move it there so tooling and readers attach it correctly.
722-779: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueTwo
investigationblocks in one view collapse into one row.
currentInvestigationIdis assigned from the first block's upsert, so a secondinvestigationblock in the samerender_viewcall revises the first rather than creating a second investigation — both blocks then carry the same id with different revisions. If the schema permits multiple investigation blocks per view, consider rejecting that up front (or scoping the id per block) rather than silently merging.
1078-1089: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueComment says "double-encode" but the code encodes once.
Line 1081 applies
encodeURIComponenta single time (task/my-task→task%2Fmy-task), which is what the route's un-escaping expects. Reword the comment. Also worth noting: unlike the neighbouring tools, this returnsresult.dataverbatim, so any series/histogram fields in the metrics payload land straight in the model's context — consider acurateQueuein line withcurateReport.apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts (1)
27-37: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winParse the
gitJSON blob with zod instead of a bare cast.
deployment.gitis untyped Prisma JSON; the cast asserts a shape that is never checked, so a legacy/oddly-shaped blob would flow straight into the API response (e.g.pullRequestNumberas a string). A smallz.object({...}).partial().safeParse()keeps the response contract honest.As per coding guidelines: "Use zod for validation in packages/core and apps/webapp".
♻️ Proposed refactor
-type GitMetaBlob = { - source?: string; - commitAuthorName?: string; - commitMessage?: string; - commitRef?: string; - remoteUrl?: string; - ghUsername?: string; - pullRequestNumber?: number; - pullRequestTitle?: string; - pullRequestState?: string; -}; +const GitMetaBlob = z + .object({ + source: z.string(), + commitAuthorName: z.string(), + commitMessage: z.string(), + commitRef: z.string(), + remoteUrl: z.string(), + ghUsername: z.string(), + pullRequestNumber: z.number(), + pullRequestTitle: z.string(), + pullRequestState: z.string(), + }) + .partial();- const git = (deployment?.git ?? undefined) as GitMetaBlob | undefined; + const parsedGit = deployment?.git ? GitMetaBlob.safeParse(deployment.git) : undefined; + const git = parsedGit?.success ? parsedGit.data : undefined;Also applies to: 73-73
Source: Coding guidelines
apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts (1)
156-159: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winMap
ServiceValidationErrorfromCreateAlertChannelService.callto a 4xx response.The catch block currently treats all
CreateAlertChannelService.callfailures as 500, including user-input validation failures such as alert-channel limits. DistinguishServiceValidationErrorhere and return a 4xx, so the agent can explain the fixable failure instead of seeing an internal error.apps/webapp/test/dashboardAgentRoutes.test.ts (1)
26-29: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDead mock.
vi.mock("~/env.server")just re-exports the original module, so it has no effect — either drop it or note why the module factory is needed (e.g. to force ESM interop ordering).apps/webapp/test/dashboardAgentWatchToken.test.ts (1)
15-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueHardcoded UAT prefix can drift.
WATCH_TOKEN_PREFIXis imported buttr_uat_is literal; if the rbac package ever changes its prefix, the "disguised" tokens in the cross-rejection tests stop testing what they claim while still passing. Export/import the constant from@trigger.dev/rbacif available.apps/webapp/test/dashboardAgentWatches.test.ts (1)
371-375: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConditional assertion can pass vacuously. If
second.okwere unexpectedly true theexistingIdcheck is skipped silently. Narrow with an earlyif (second.ok || !first.ok) throw new Error(...)(orexpect.fail) before asserting.apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts (1)
411-417: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueGuard the cast before reading
.code. Both predicates dereference anunknownvalue; a thrownnull/undefined(or a primitive) turns thecatchblock itself into aTypeError, losing the original failure. Atypeof error === "object" && error !== nullprefix makes them safe.🛡️ Proposed guard
function isWebAPIPlatformError(error: unknown): error is WebAPIPlatformError { - return (error as WebAPIPlatformError).code === ErrorCode.PlatformError; + return ( + typeof error === "object" && + error !== null && + (error as WebAPIPlatformError).code === ErrorCode.PlatformError + ); } function isWebAPIRateLimitedError(error: unknown): error is WebAPIRateLimitedError { - return (error as WebAPIRateLimitedError).code === ErrorCode.RateLimitedError; + return ( + typeof error === "object" && + error !== null && + (error as WebAPIRateLimitedError).code === ErrorCode.RateLimitedError + ); }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 32f81d27-7b23-4a54-8b29-c8916991756f
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (209)
.server-changes/dashboard-agent-first-turn-error.md.server-changes/dashboard-agent-investigate.md.server-changes/dashboard-agent-watch-alerts.md.server-changes/dashboard-agent-watches.md.server-changes/queue-metrics-api.md.server-changes/remove-header-docs-buttons.mdapps/webapp/.gitignoreapps/webapp/app/components/dashboard-agent/AgentChart.tsxapps/webapp/app/components/dashboard-agent/DashboardAgent.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsxapps/webapp/app/components/dashboard-agent/InvestigateButton.tsxapps/webapp/app/components/dashboard-agent/InvestigationCard.test.tsapps/webapp/app/components/dashboard-agent/InvestigationCard.tsxapps/webapp/app/components/dashboard-agent/ReportView.test.tsapps/webapp/app/components/dashboard-agent/ReportView.tsxapps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsxapps/webapp/app/components/dashboard-agent/WakeBanner.tsxapps/webapp/app/components/dashboard-agent/WatchChips.tsxapps/webapp/app/components/dashboard-agent/WatchWakeToast.tsxapps/webapp/app/components/dashboard-agent/agent-badges.tsxapps/webapp/app/components/dashboard-agent/chat-layout.test.tsapps/webapp/app/components/dashboard-agent/chat-layout.tsxapps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsxapps/webapp/app/components/dashboard-agent/demo/demo-chats.tsapps/webapp/app/components/dashboard-agent/demo/demo.test.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/chart.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/index.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/intents.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/messages.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/reports.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/watches.tsapps/webapp/app/components/dashboard-agent/demo/ids.tsapps/webapp/app/components/dashboard-agent/demo/index.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.test.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.tsapps/webapp/app/components/dashboard-agent/list-row.tsxapps/webapp/app/components/dashboard-agent/message-order.test.tsapps/webapp/app/components/dashboard-agent/message-order.tsapps/webapp/app/components/dashboard-agent/navigate-target.test.tsapps/webapp/app/components/dashboard-agent/navigate-target.tsapps/webapp/app/components/dashboard-agent/page-context-types.tsapps/webapp/app/components/dashboard-agent/page-label.test.tsapps/webapp/app/components/dashboard-agent/page-label.tsapps/webapp/app/components/dashboard-agent/progress-line.test.tsapps/webapp/app/components/dashboard-agent/progress-line.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.test.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.tsapps/webapp/app/components/dashboard-agent/report-sparkline.tsxapps/webapp/app/components/dashboard-agent/run-id.test.tsapps/webapp/app/components/dashboard-agent/run-id.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/index.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/registry.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.tsapps/webapp/app/components/dashboard-agent/tool-labels.test.tsapps/webapp/app/components/dashboard-agent/tool-labels.tsapps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.tsapps/webapp/app/components/dashboard-agent/view-blocks.test.tsapps/webapp/app/components/dashboard-agent/view-blocks.tsapps/webapp/app/components/dashboard-agent/view-catalog.tsxapps/webapp/app/components/dashboard-agent/watch-chips.test.tsapps/webapp/app/components/dashboard-agent/watch-chips.tsapps/webapp/app/components/metrics/MiniLineChart.tsxapps/webapp/app/components/primitives/Callout.tsxapps/webapp/app/components/runs/v3/agent/AgentMessageView.tsxapps/webapp/app/hooks/useAgentPageContext.tsapps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.tsapps/webapp/app/presenters/v3/reports/health/health-messages.tsapps/webapp/app/presenters/v3/reports/health/health.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.tsapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsxapps/webapp/app/routes/account.tokens/route.tsxapps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.tsapps/webapp/app/routes/api.v1.dashboard-agent.alerts.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.tsapps/webapp/app/routes/api.v1.queues.$queueParam.metrics.tsapps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsxapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.tsapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.tsapps/webapp/app/routes/storybook.agent-ui/manifest.tsapps/webapp/app/routes/storybook.agent-ui/route.tsxapps/webapp/app/routes/storybook.callout/route.tsxapps/webapp/app/services/dashboardAgentAlertContext.server.tsapps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.tsapps/webapp/app/services/dashboardAgentHeadStart.server.tsapps/webapp/app/services/dashboardAgentWatchAlerts.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.tsapps/webapp/app/services/dashboardAgentWatchToken.server.tsapps/webapp/app/services/dashboardAgentWatches.server.tsapps/webapp/app/services/resolveTriggerUri.server.tsapps/webapp/app/services/uatRoutePreamble.server.tsapps/webapp/app/utils/handle.tsapps/webapp/app/v3/alertsWorker.server.tsapps/webapp/app/v3/featureFlags.tsapps/webapp/app/v3/services/alerts/deliverAlert.server.tsapps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.tsapps/webapp/package.jsonapps/webapp/scripts/agent-ui-screenshots.tsapps/webapp/seed-agent-examples-chats.mtsapps/webapp/seed-agent-examples.mtsapps/webapp/seed-queue-metrics.mtsapps/webapp/test/dashboardAgentHeadStart.test.tsapps/webapp/test/dashboardAgentRoutes.test.tsapps/webapp/test/dashboardAgentWatchChecks.test.tsapps/webapp/test/dashboardAgentWatchToken.test.tsapps/webapp/test/dashboardAgentWatches.test.tsapps/webapp/test/reportHealth.test.tsapps/webapp/test/resolveTriggerUri.test.tsapps/webapp/test/seedAgentExamplesChats.test.tsapps/webapp/test/waitingRunDiagnosis.test.tsapps/webapp/vitest.config.tsinternal-packages/dashboard-agent-contracts/package.jsoninternal-packages/dashboard-agent-contracts/src/blocks.test.tsinternal-packages/dashboard-agent-contracts/src/blocks.tsinternal-packages/dashboard-agent-contracts/src/contracts.test.tsinternal-packages/dashboard-agent-contracts/src/evidence.tsinternal-packages/dashboard-agent-contracts/src/index.tsinternal-packages/dashboard-agent-contracts/src/intent.tsinternal-packages/dashboard-agent-contracts/src/page-context.tsinternal-packages/dashboard-agent-contracts/src/run-filters.tsinternal-packages/dashboard-agent-contracts/src/suggested-prompts.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.test.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.tsinternal-packages/dashboard-agent-contracts/src/watch.test.tsinternal-packages/dashboard-agent-contracts/src/watch.tsinternal-packages/dashboard-agent-contracts/tsconfig.jsoninternal-packages/dashboard-agent-contracts/vitest.config.tsinternal-packages/dashboard-agent-db/README.mdinternal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sqlinternal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sqlinternal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/_journal.jsoninternal-packages/dashboard-agent-db/package.jsoninternal-packages/dashboard-agent-db/src/ids.tsinternal-packages/dashboard-agent-db/src/index.tsinternal-packages/dashboard-agent-db/src/queries.tsinternal-packages/dashboard-agent-db/src/schema.tsinternal-packages/dashboard-agent/GUIDEBOOK.mdinternal-packages/dashboard-agent/PLAYBOOK.mdinternal-packages/dashboard-agent/VERDICTS.mdinternal-packages/dashboard-agent/package.jsoninternal-packages/dashboard-agent/src/dashboard-agent.eval.tsinternal-packages/dashboard-agent/src/dashboard-agent.test.tsinternal-packages/dashboard-agent/src/dashboard-agent.tsinternal-packages/dashboard-agent/src/index.tsinternal-packages/dashboard-agent/src/tool-schemas.tsinternal-packages/dashboard-agent/src/tools.tsinternal-packages/dashboard-agent/src/watch-tick.test.tsinternal-packages/dashboard-agent/src/watch-tick.tsinternal-packages/dashboard-agent/vitest.eval.config.tsinternal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sqlinternal-packages/database/prisma/schema.prismainternal-packages/emails/emails/alert-dashboard-agent-watch.tsxinternal-packages/emails/src/index.tsx
💤 Files with no reviewable changes (1)
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
The M5 entry-point list promised it; only the error-group page had it.
… buttons A superlative question is answered in words with the top item's name and number; the chart illustrates. The chart block gains up to three actions (ask — the user's own follow-up, or navigate with a canonical trigger:// target), rendered as buttons under the chart and wired through the panel's existing intent handling. A navigate target is a plain string at the input boundary and a non-parsing one costs the button, never the tool call.
The table is append-only quality data with no reader, so the sweep now drops rows past the period in one bounded statement per run.
…and the judge Payloads, outputs, query rows and file contents are replaced by their shape before a turn reaches the judge, and the row now keeps the derived verdict only.
A per-org feature flag the agent checks before every judged turn, and a turn is judged only on an explicit yes.
The CI lane reads its own variable and defaults to every turn, so neither lane can change the other's rate.
The docs claimed every turn is judged; the sampled rate, the redaction rule, the code-mode skip, the opt-out and the retention period are now written down in one place.
…ponsibility tools.ts now only assembles ready adapters, in the same frozen key order: the HTTP/JWT client, result curation, the docs client, the source-read ledger, evidence canonicalisation, investigation persistence, and the api/navigation/ watch/alert tool groups each own their own module. A pure move. The prompt-prefix fingerprints are unchanged, which is what keeps the head-start and agent prefixes byte-identical.
…ion, batch and adapters watch-tick.ts keeps the two task definitions and the per-watch check; the wake delivery, the condition lifecycle, the group tick and the db/session/callback adapters each move to their own module. A pure move: watch-tick.ts re-exports everything it exported before.
dashboardAgentWatchChecks.ts keeps the dispatcher, the failure envelope and the previous-facts reader, and re-exports the run, queue, error and health families plus the shared reader contract. A pure move; every import path is unchanged.
The chip factory and slot vocabulary, the evergreen docs chips, the per-page slot table and the signal chips each get their own module; registry.ts is now the public face that re-exports them. A pure move.
…ive investigations and watches
…d a committed snapshot
…nd narrate the rest with Haiku
…tead of passing it to the judge
…ing it The batch took the 500 soonest-expiring watches of a group every tick, so a group larger than the cap could leave the rest unchecked until the first 500 expired. The group is now ordered least-recently-checked first, with a generated cadence_minutes column and an index so the due predicate no longer re-parses the spec JSON per tick.
…e watch The page load reported unread wakes only, so a fresh browser whose watch was created elsewhere and hasn't fired yet never started polling: the wake landed without a toast or a dot until a reload. The loader now returns the active-watch presence too, in one read per page load.
The message-size checks ran after the body had been read, so a request without a content-length was buffered and parsed in full before being refused. An ingress cap on the agent's paths now counts the bytes as they arrive, and the chat proxy reads its body with a ceiling instead of reading it whole first.
…ir a retried submit
…ts refusal record
…re-running it A retried card submit was only repairable while the first attempt's watch was still active. Once it had fired, expired, or answered in one shot, the retry re-evaluated the condition and created a second operation. A watch_submissions ledger, keyed (chat_id, client_request_id), is now written before the condition is read and carries the outcome once there is one. A retry looks it up first: a recorded outcome is replayed, a different draft under the same id conflicts, and only a pending row proceeds - converging on the watch id reserved up front rather than creating another.
…the watch seam dashboardAgent.sweepWatches ran the watch sweep, the investigation sweep, the batch re-arm and eval retention together. Watch is about to ship as its own stacked PR, so the job is split where the cut will be: dashboardAgent.maintenance keeps the investigation sweep and eval retention, dashboardAgent.watchMaintenance takes watch expiry, delivery and the batch re-arm. Same cadence, and each backstop keeps its own try/catch.
The route-level check only sees a declared content-length; a body without one is already ended mid-stream by the ingress cap.
An AI assistant in a side panel on every dashboard page, behind the dashboard-agent feature flag. It reads runs, errors, queues, deploys and health through the public API (read-only, delegated user token), answers with rich cards, and can keep watching things after the conversation ends.
What's inside
@internal/dashboard-agent-contracts(trigger:// URI grammar, intents, watch specs, block envelope), investigations + watches tables, head-start reliability fix, eval sample-rate gate.get_reportrenders the deterministic health report as a card (metric grid, sparklines, Next steps button row); stale telemetry is flagged and never trusted for advice.db:seed:agent-examples, with--heartbeat/--degrade/--recoverfor demos).How to review
GUIDEBOOK.md — 10-minute local setup and a hands-on walkthrough of every case.
Notes
canAccessDashboardAgent; no behavior change with the flag off.