Skip to content

feat(webapp): dashboard agent — chat, reports, Investigate, Watch - #4418

Open
kathiekiwi wants to merge 391 commits into
mainfrom
feat/dashboard-agent-flows
Open

feat(webapp): dashboard agent — chat, reports, Investigate, Watch#4418
kathiekiwi wants to merge 391 commits into
mainfrom
feat/dashboard-agent-flows

Conversation

@kathiekiwi

@kathiekiwi kathiekiwi commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

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

  • Foundation@internal/dashboard-agent-contracts (trigger:// URI grammar, intents, watch specs, block envelope), investigations + watches tables, head-start reliability fix, eval sample-rate gate.
  • Reportsget_report renders the deterministic health report as a card (metric grid, sparklines, Next steps button row); stale telemetry is flagged and never trusted for advice.
  • Investigate — hypothesis-driven investigation on a live card with system-owned identity and revisions; entry buttons on failed runs, errors, backed-up queues and waiting runs; code-grounded when a repo is connected; server-generated follow-ups (Show code, View similar, Watch for a repeat).
  • Watch (Dashboard Agent: Watch (background condition watches + wake notifications + alerts) #4456) — one-shot background watches with a compact creation card on run/queue/error/health pages: resolution + observed outcome model, exactly-once wake delivery, expiry sweep, optional investigate-on-attention, standing email/Slack/webhook alerts with one-click unsubscribe. Queue conditions: drain, above/below N, stalled, oldest-age SLA.
  • UI — blank-state hero (Ask AI) with a Tab-to-accept placeholder and colored smart prompts, fullscreen mode, one persistent agent spinner across all phases.
  • Smart prompts — page-aware chips on every env page (37 routes, 24 page kinds); investigate/status chips appear only on loader-backed abnormal state.
  • Tooling — navigation, TRQL queries with live charts, deploy correlation, docs answers; golden eval suite; seeder for a live playground project (db:seed:agent-examples, with --heartbeat / --degrade / --recover for demos).

How to review

GUIDEBOOK.md — 10-minute local setup and a hands-on walkthrough of every case.

Notes

  • Everything is gated by canAccessDashboardAgent; no behavior change with the flag off.

…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.
…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.
'Watch update — all clear / needs your attention', toned by kind; the
identity moves to the details line and the subject follows suit.
@changeset-bot

changeset-bot Bot commented Jul 29, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 85b98ab

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 27 packages
Name Type
@trigger.dev/core Patch
trigger.dev Patch
@trigger.dev/build Patch
@trigger.dev/python Patch
@trigger.dev/redis-worker Patch
@trigger.dev/schema-to-json Patch
@trigger.dev/sdk Patch
@internal/cache Patch
@internal/clickhouse Patch
@internal/llm-model-catalog Patch
@internal/metrics-pipeline Patch
@trigger.dev/rbac Patch
@internal/redis Patch
@internal/replication Patch
@internal/run-engine Patch
@internal/run-store Patch
@internal/schedule-engine Patch
@trigger.dev/sso Patch
@internal/testcontainers Patch
@internal/tracing Patch
@internal/tsql Patch
@internal/dashboard-agent Patch
@internal/sdk-compat-tests Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch

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

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.48% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the feature in detail but omits the required issue reference, checklist, Testing, Changelog, and Screenshots sections. Add the required template sections, complete the checklist, document test steps, summarize the changelog, include screenshots, and reference the closing issue.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the dashboard agent chat, reports, Investigate, and Watch feature work.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/dashboard-agent-flows

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…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.
Base automatically changed from feat/queue-metrics-and-health to main July 29, 2026 15:45
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
@pkg-pr-new

pkg-pr-new Bot commented Jul 30, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@8d3676a

trigger.dev

npm i https://pkg.pr.new/trigger.dev@8d3676a

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@8d3676a

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@8d3676a

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@8d3676a

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@8d3676a

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@8d3676a

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@8d3676a

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@8d3676a

commit: 8d3676a

… 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Guard getPromotedDashboardAgentPrompt against failures, and skip it when access is already false.

This loader backs the entire env layout (Outlet wraps every page under this environment), so it runs on nearly every navigation. getPromotedDashboardAgentPrompt is 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 whenever hasDashboardAgentAccess is false, since DashboardAgent never consumes promotedPrompt in 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 ? … : undefined collapses a legitimate zero into the fallback.

pending, donePerMin, triggeredPerMin and drainMinutes all treat a reported 0 as "absent" and fall back to the STORY.* 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

DELETE without mutations_sync races the seeding insert that follows.

--reset runs these deletes and then line 941 inserts immediately. The sibling seeder guards the identical sequence with SETTINGS mutations_sync = 2 and explains why: left asynchronous, the re-seed races its own predecessor and leaves a second copy of the data behind. Worth setting async_insert: 0 on line 572 too, so the rows are visible to the OPTIMIZE … FINAL calls 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 win

Use the COMPLETED_WITH_ERRORS status literal in the TRQL query.

Failed is not a standard run status in Trigger.dev TRQL; use status = '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 win

Keep this seeder consistent with seed-agent-examples.mts's documented interop pattern.

seed-agent-examples.mts disables 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 win

Require http(s) on docs action targets.

target is documented as “an https URL” for docs actions, but the schema accepts any string. Since this field is LLM-authored UI input, prefer narrowing it to http:// or https:// 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 win

Make unreliable queued wait labels include the stale-first-enqueue caveat.

For WAITING_TO_RESUME / RETRYING_AFTER_FAILURE / PAUSED, run.queuedAt is not a current queue entry, but this path still emits waitBasis: "queued_at" and a confident queued for … label. Bake the caveat into the label or omit the label when queueWaitReliable is 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

CitationButton renders different elements on server vs client.

path is always null during SSR, so the server emits a LinkButton anchor while the first client render emits a Button — a hydration mismatch for every same-origin citation. Compute the path from sameOriginPath after mount (or keep one element type and branch inside onClick).

♻️ 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 win

Post-mutation reloads can coalesce onto a pre-mutation request.

loadHistory returns the in-flight promise, so the void loadHistory() calls in deleteChat (Line 422) and cancelWatch (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 }) from deleteChat and cancelWatch.

apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx-161-177 (1)

161-177: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

An enabled button that does nothing is a real click target outside the gallery.

useRunPath returns undefined whenever 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. Prefer disabled (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 win

Assert the label in the stale-queuedAt case — 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 queueWaitReliable and waitBasis. A regression that emitted "queued for 10m" for an untrustworthy queuedAt on a resumed run would still pass. Add the label (and the result) 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 win

Wrap the body read so an aborted/interrupted response doesn't escape as a throw.

The fetch call is guarded but await 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 escapes searchTriggerDocs, breaking the documented "returns { error }" contract that search_docs relies 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_errors doesn't clamp period, unlike list_runs and list_deploys.

Lines 845 and 1096 both run the model-supplied period through clampPeriod; 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 win

Rounding endMs up with Math.ceil includes future time in the averaged window.

Because endMs is rounded up to the next bucket boundary, it can be ahead of Date.now() by up to bucketSeconds (as much as ~1/12 of the requested period). startedPerMin and 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.floor gives 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 win

Duplicate chart-card frame markup — parameterize rows instead of reimplementing the frame for the empty state.
DemoChartCard hardcodes rows={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 pass rows={[]}.

  • apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx#L12-L30: accept an optional rows prop (defaulting to demoChart.rows) so callers can override the dataset.
  • apps/webapp/app/routes/storybook.agent-ui/route.tsx#L300-L317: replace EmptyChartCard'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 win

Consider deriving untrustworthyReport via the real stale-guard function rather than hand-rolling its output shape.

The comment above this block states it's "Derived exactly the way applyStaleGuard does it," but the code manually reconstructs the transformation instead of calling that function. If applyStaleGuard (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. from apps/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 win

The isolation guard misses side-effect and dynamic imports.

importSpecifiers only matches … from "x", so import "~/foo.server" and await 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 win

Import VIEW_BLOCK_VERSION instead of hardcoding version: 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 win

Read the kind with the contracts parser rather than split("/")[4].

Positional indexing silently mis-classifies if the URI layout changes — a run URI read as report would skip the resolution assertion entirely, and the test would still pass. demo.test.ts uses safeParseTriggerUri for 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 value

Duplicate line params are silently accepted, last one wins.

trigger://…/source/abc/a.ts?line=1&line=2 parses as line: 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

wakeAction infers the action type from "not fired".

If isTerminalWatchStatus ever admits a third terminal status (e.g. cancelled, which the contract's watchStatusSchema includes), the delivery-only path produces type: "watch.expired" with id: 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 value

Use 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 win

Poll the eval-enqueue side effect instead of relying on a fixed sleep.

turnAtRate waits 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 win

Consider z.discriminatedUnion("kind", [...]) instead of z.union.

All five branches share a literal kind discriminator, so this is a textbook case for z.discriminatedUnion. With plain z.union, an invalid payload (e.g., wrong kind or a bad runId) produces a combined invalid_union error listing every failed branch, which is noisier to surface back to the agent/tool-caller than the targeted error discriminatedUnion gives.

♻️ 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 win

Extract the shared unread-wake predicate.

The same (last_read_at is null or coalesce(fired_at, last_checked_at) > last_read_at) clause plus the status in ('fired','expired') + tenancy join is repeated verbatim in countUnreadWatchWakes, listUnreadWatchWakes (Line 744), and listChatIdsWithUnreadWakes (Line 783). One helper returning the and(...) 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 | 🔵 Trivial

Track the documented queuedDuration bug.

RunPresenter.server.ts computing queuedDuration as startedAt − createdAt is 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 value

Use the same non-null assertion as withCacheBreakpointOnLast.

sanitized[sanitized.length - 1] is typed ModelMessage | undefined under noUncheckedIndexedAccess, 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 win

Validate the alert email shape in the schema.

email accepts any string, so a malformed value only fails downstream (or worse, gets persisted as a subscription address). 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 never throws away the block contract.

blocksFor returns unknown[], forcing blocks as never at the ViewBlocks call site, so a block-shape change in @internal/dashboard-agent-contracts won'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.

chatWatches gets a fresh identity each render, which flows into DashboardAgentChatDashboardAgentMessages and defeats the memo on DashboardAgentTurn (its watches prop always compares unequal). A module-level const NO_WATCHES: WatchChip[] = [] fallback keeps the reference stable.

apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx (1)

58-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Name 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_CONTEXT in suggested-prompts/registry.ts) keeps the meaning of the empty path explicit 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_PRIORITY isn't exhaustiveness-checked, and the two iterators duplicate one loop.

SIGNAL_SLOT is a Record<AgentPageSignalKind, …>, so a new signal kind fails to compile there — but SIGNAL_PRIORITY is a bare array, and since both iterators drive off it, a kind missing from the array silently never produces a chip. contextualPrompts is also contextualPromptsBySlot flattened 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 contextualPrompts ordering 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 value

Comment describes a registration side effect that doesn't exist.

healthMessages is used purely as a value in the static CATALOGS map 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 win

Hand-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 returns ReactNode) and duplicated rather than shared.

  • apps/webapp/app/components/dashboard-agent/agent-badges.tsx#L46-L46: change the exported IconComponent alias to React.ComponentType<{ className?: string }>.
  • apps/webapp/app/components/dashboard-agent/WakeBanner.tsx#L77-L82: import IconComponent from ./agent-badges and type TONE_ICON as Record<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 value

Dismissals 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 value

Test name contradicts its fixture.

running: 10 against a concurrencyLimit of 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 value

Misplaced doc block: the renderInvestigations docs sit on canonicalizeEvidence.

Two doc comments are stacked here; the first (Lines 596-613, describing block stamping and continueId) documents renderInvestigations, which is declared at Line 706. Move it there so tooling and readers attach it correctly.


722-779: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Two investigation blocks in one view collapse into one row.

currentInvestigationId is assigned from the first block's upsert, so a second investigation block in the same render_view call 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 value

Comment says "double-encode" but the code encodes once.

Line 1081 applies encodeURIComponent a single time (task/my-tasktask%2Fmy-task), which is what the route's un-escaping expects. Reword the comment. Also worth noting: unlike the neighbouring tools, this returns result.data verbatim, so any series/histogram fields in the metrics payload land straight in the model's context — consider a curateQueue in line with curateReport.

apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts (1)

27-37: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Parse the git JSON blob with zod instead of a bare cast.

deployment.git is 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. pullRequestNumber as a string). A small z.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 win

Map ServiceValidationError from CreateAlertChannelService.call to a 4xx response.

The catch block currently treats all CreateAlertChannelService.call failures as 500, including user-input validation failures such as alert-channel limits. Distinguish ServiceValidationError here 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 value

Dead 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 value

Hardcoded UAT prefix can drift. WATCH_TOKEN_PREFIX is imported but tr_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/rbac if available.

apps/webapp/test/dashboardAgentWatches.test.ts (1)

371-375: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Conditional assertion can pass vacuously. If second.ok were unexpectedly true the existingId check is skipped silently. Narrow with an early if (second.ok || !first.ok) throw new Error(...) (or expect.fail) before asserting.

apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts (1)

411-417: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Guard the cast before reading .code. Both predicates dereference an unknown value; a thrown null/undefined (or a primitive) turns the catch block itself into a TypeError, losing the original failure. A typeof error === "object" && error !== null prefix 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e5f0f0 and 0dece13.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is 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.md
  • apps/webapp/.gitignore
  • apps/webapp/app/components/dashboard-agent/AgentChart.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgent.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigateButton.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.test.ts
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/ReportView.test.ts
  • apps/webapp/app/components/dashboard-agent/ReportView.tsx
  • apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx
  • apps/webapp/app/components/dashboard-agent/WakeBanner.tsx
  • apps/webapp/app/components/dashboard-agent/WatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/WatchWakeToast.tsx
  • apps/webapp/app/components/dashboard-agent/agent-badges.tsx
  • apps/webapp/app/components/dashboard-agent/chat-layout.test.ts
  • apps/webapp/app/components/dashboard-agent/chat-layout.tsx
  • apps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts
  • apps/webapp/app/components/dashboard-agent/demo/demo.test.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/chart.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/index.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/messages.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/reports.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/watches.ts
  • apps/webapp/app/components/dashboard-agent/demo/ids.ts
  • apps/webapp/app/components/dashboard-agent/demo/index.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.test.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.ts
  • apps/webapp/app/components/dashboard-agent/list-row.tsx
  • apps/webapp/app/components/dashboard-agent/message-order.test.ts
  • apps/webapp/app/components/dashboard-agent/message-order.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.test.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.ts
  • apps/webapp/app/components/dashboard-agent/page-context-types.ts
  • apps/webapp/app/components/dashboard-agent/page-label.test.ts
  • apps/webapp/app/components/dashboard-agent/page-label.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.test.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.test.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.ts
  • apps/webapp/app/components/dashboard-agent/report-sparkline.tsx
  • apps/webapp/app/components/dashboard-agent/run-id.test.ts
  • apps/webapp/app/components/dashboard-agent/run-id.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/index.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.test.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.ts
  • apps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.test.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.ts
  • apps/webapp/app/components/dashboard-agent/view-catalog.tsx
  • apps/webapp/app/components/dashboard-agent/watch-chips.test.ts
  • apps/webapp/app/components/dashboard-agent/watch-chips.ts
  • apps/webapp/app/components/metrics/MiniLineChart.tsx
  • apps/webapp/app/components/primitives/Callout.tsx
  • apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx
  • apps/webapp/app/hooks/useAgentPageContext.ts
  • apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts
  • apps/webapp/app/presenters/v3/reports/health/health-messages.ts
  • apps/webapp/app/presenters/v3/reports/health/health.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsx
  • apps/webapp/app/routes/account.tokens/route.tsx
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.ts
  • apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts
  • apps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsx
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.ts
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts
  • apps/webapp/app/routes/storybook.agent-ui/manifest.ts
  • apps/webapp/app/routes/storybook.agent-ui/route.tsx
  • apps/webapp/app/routes/storybook.callout/route.tsx
  • apps/webapp/app/services/dashboardAgentAlertContext.server.ts
  • apps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.ts
  • apps/webapp/app/services/dashboardAgentHeadStart.server.ts
  • apps/webapp/app/services/dashboardAgentWatchAlerts.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.ts
  • apps/webapp/app/services/dashboardAgentWatchToken.server.ts
  • apps/webapp/app/services/dashboardAgentWatches.server.ts
  • apps/webapp/app/services/resolveTriggerUri.server.ts
  • apps/webapp/app/services/uatRoutePreamble.server.ts
  • apps/webapp/app/utils/handle.ts
  • apps/webapp/app/v3/alertsWorker.server.ts
  • apps/webapp/app/v3/featureFlags.ts
  • apps/webapp/app/v3/services/alerts/deliverAlert.server.ts
  • apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
  • apps/webapp/package.json
  • apps/webapp/scripts/agent-ui-screenshots.ts
  • apps/webapp/seed-agent-examples-chats.mts
  • apps/webapp/seed-agent-examples.mts
  • apps/webapp/seed-queue-metrics.mts
  • apps/webapp/test/dashboardAgentHeadStart.test.ts
  • apps/webapp/test/dashboardAgentRoutes.test.ts
  • apps/webapp/test/dashboardAgentWatchChecks.test.ts
  • apps/webapp/test/dashboardAgentWatchToken.test.ts
  • apps/webapp/test/dashboardAgentWatches.test.ts
  • apps/webapp/test/reportHealth.test.ts
  • apps/webapp/test/resolveTriggerUri.test.ts
  • apps/webapp/test/seedAgentExamplesChats.test.ts
  • apps/webapp/test/waitingRunDiagnosis.test.ts
  • apps/webapp/vitest.config.ts
  • internal-packages/dashboard-agent-contracts/package.json
  • internal-packages/dashboard-agent-contracts/src/blocks.test.ts
  • internal-packages/dashboard-agent-contracts/src/blocks.ts
  • internal-packages/dashboard-agent-contracts/src/contracts.test.ts
  • internal-packages/dashboard-agent-contracts/src/evidence.ts
  • internal-packages/dashboard-agent-contracts/src/index.ts
  • internal-packages/dashboard-agent-contracts/src/intent.ts
  • internal-packages/dashboard-agent-contracts/src/page-context.ts
  • internal-packages/dashboard-agent-contracts/src/run-filters.ts
  • internal-packages/dashboard-agent-contracts/src/suggested-prompts.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.test.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.ts
  • internal-packages/dashboard-agent-contracts/src/watch.test.ts
  • internal-packages/dashboard-agent-contracts/src/watch.ts
  • internal-packages/dashboard-agent-contracts/tsconfig.json
  • internal-packages/dashboard-agent-contracts/vitest.config.ts
  • internal-packages/dashboard-agent-db/README.md
  • internal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sql
  • internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql
  • internal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/_journal.json
  • internal-packages/dashboard-agent-db/package.json
  • internal-packages/dashboard-agent-db/src/ids.ts
  • internal-packages/dashboard-agent-db/src/index.ts
  • internal-packages/dashboard-agent-db/src/queries.ts
  • internal-packages/dashboard-agent-db/src/schema.ts
  • internal-packages/dashboard-agent/GUIDEBOOK.md
  • internal-packages/dashboard-agent/PLAYBOOK.md
  • internal-packages/dashboard-agent/VERDICTS.md
  • internal-packages/dashboard-agent/package.json
  • internal-packages/dashboard-agent/src/dashboard-agent.eval.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.test.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.ts
  • internal-packages/dashboard-agent/src/index.ts
  • internal-packages/dashboard-agent/src/tool-schemas.ts
  • internal-packages/dashboard-agent/src/tools.ts
  • internal-packages/dashboard-agent/src/watch-tick.test.ts
  • internal-packages/dashboard-agent/src/watch-tick.ts
  • internal-packages/dashboard-agent/vitest.eval.config.ts
  • internal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sql
  • internal-packages/database/prisma/schema.prisma
  • internal-packages/emails/emails/alert-dashboard-agent-watch.tsx
  • internal-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

Comment thread apps/webapp/app/components/dashboard-agent/WatchChips.tsx
Comment thread apps/webapp/app/components/dashboard-agent/WatchWakeToast.tsx
Comment thread apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.ts
Comment thread apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts Outdated
Comment thread apps/webapp/app/services/dashboardAgentWatches.server.ts
Comment thread apps/webapp/test/dashboardAgentWatches.test.ts Outdated
Comment thread apps/webapp/test/dashboardAgentWatches.test.ts Outdated
Comment thread internal-packages/dashboard-agent-db/src/schema.ts Outdated
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.
…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.
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants