Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat: native subagent & workflow observability #5219

Mergedt3dotgg(GitHub profile, opens in a new tab)merged 42 commits intomain fromrefs/pull/5219/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHub

Problem

When a thread spawns subagents, runs a workflow, or drives Codex collab agents, the UI showed nothing useful: subagent tool calls and narration interleaved anonymously into the parent chat, progress ticks spammed the work log, background shells masqueraded as agents, the sidebar showed no status once the turn settled, and Stop only killed the parent turn while the fleet kept burning tokens.

Spec (final, decisions locked): https://n0hbggyouhn1.postplan.dev

image

Solution

Surface agents using only native provider emissions on the current orchestrator — no dependency on orchestrator v2 (#2829), zero migrations, zero new tables. Widened task.* activity payloads ride the existing event-sourced activity path; a client-side fold in client-runtime derives orchestration-v2-shaped subagent state (field names match #4779, so the v2 merge is a mapper swap).

Server

  • Contracts: additive TaskAgentLinkage on all task payloads (role, model, workflow name/phases, run handles, output file, owning agentId), new task.updated event, typed usage, tool attribution (agentId/parentToolUseId)
  • ClaudeAdapter: carries previously-dropped fields, handles task_updated, resolves parent_tool_use_id on tool events, keeps subagent narration out of the parent transcript (leak + Working-timer-reset fix), attributes subagent-internal shells to their owning agent, defensive workflow_progress parse, Workflow run handles
  • Codex: registers multi-agent-v2 children from thread/started/subAgentActivity (root-thread guard from live probe), intercepts child notifications, synthesizes the same task.* lifecycle (idle = resumable, cumulative usage, real names from agentPath)
  • Stop-everything: interrupt stops every live Claude task (Query.stopTask) and interrupts every live Codex child turn before the parent turn
  • Sidebar liveness: ThreadBackgroundLivenessService (in-memory, no persistence) exposes backgroundLiveness: working | monitoring on the thread shell — fleets read Working, watch loops read Monitoring
  • orchestration.getWorkflowScript RPC with TOCTOU-safe containment (open-then-verify inode, realpath under ~/.claude/projects, .js-only, size cap)

Web

  • Agents right-panel surface (the only roster): live workflows as bordered sections with a phase rail (per-phase segments with member status dots) and collapsible phase sections (live open, done collapsed); flat agent rows (no unfold); settled runs collapse to one line under "Earlier"; {} script opens a read-only script view
  • Spawn CTA row in chat: one anchored row per workflow run / direct-spawn batch, exempt from turn folds and overflow, membership pinned at first row (parallel-batch fix), coordinator status authoritative for workflows
  • Quiet timeline: agent-attributed tool rows re-homed to the panel, timelineBypass rows fold into the CTA, background shells stay ordinary work-log rows
  • All in-flight states present as Working (monitoring-pill rule); idle presents as settled

Mobile: same quiet-timeline fold; task.completed kept as terminal signal.

Verification

  • client-runtime: 30 fold tests (identity/activations, usage merges, bounds, cascade, nested agents); web: 1772 incl. quiet-timeline fixtures built from real persisted threads; server: adapter/ingestion/liveness/script-containment suites incl. a symlink-escape test and a stop-everything test
  • Live-tested over multiple rounds: Claude direct spawns + workflows (incl. 10-parallel), Codex collab fleets (10 agents), rerun workflows, monitoring threads — each round's findings fixed against exported wire/DB data

Remaining gaps

  • Codex fixtures should be generated from the captured wire logs (three schema-vs-wire divergences were found live)
  • Settled Codex rows show "assistant message" filler instead of a result summary
  • Script viewer is plain <pre> (no Shiki)
  • Mobile has only the timeline fold, no Agents sheet yet
  • Deferred by design: approval deep-links, transcript drill-in, forwardSubagentText/agentProgressSummaries off

🤖 Generated with Claude Code (Claude Fable 5)

Note

Add native subagent and workflow observability with an Agents panel, background liveness banner, and spawn CTA rows in the chat timeline

  • Adds a new Agents right panel surface (AgentsPanel.tsx) showing live status, elapsed timers, and activity text for each subagent or workflow member.
  • Introduces a background liveness banner in the chat view with a pulsing dot and Stop button when background work is detected via the new ThreadBackgroundLiveness service; sidebar rows show 'Working' or 'Monitoring' pills accordingly.
  • Adds spawn CTA rows to the chat timeline that collapse multiple subagent/workflow lifecycle entries into a single row with status, token count, and an affordance to open the Agents panel.
  • Enriches the Claude and Codex adapters with task.updated and tool.progress event emission, stable per-task activity IDs, agent linkage fields (agentKind, agentId, toolUseId, runHandles), workflow member coalescing, and interrupt-all-live-tasks behavior on turn stop.
  • Adds a getWorkflowScript WebSocket RPC backed by a TOCTOU-safe reader that serves .js files under ~/.claude/projects up to 256 KiB with structured error reasons.
  • Risk: RIGHT_PANEL_STORAGE_VERSION bumps from 7 to 8, invalidating persisted right panel state for existing users; task.progress activity IDs change from event-scoped to stable per-task IDs, which may affect clients that stored or compared those IDs.
Macroscope summarized f7673f3.

Dispositions (review round, explicit)

  • Spec divergence — accepted. The linked spec predates seven rounds of live testing. The rich inline workflow card, live strip, and expanded activity rows were built, tested live, and deliberately replaced by the single spawn CTA + Agents panel ("too much at once" — live-test decision). The spec link stays for design history; this description is the source of truth for what ships.
  • Mobile — accepted tradeoff for this PR. Mobile gets the quiet timeline and preserved terminal signals (Claude task.completed, Codex terminal task.updated, nested-agent terminals) but no Agents surface yet. Live fleets are less visible on mobile until they settle. The read-only mobile Agents sheet is the tracked fast-follow.
  • Script RPC scope — accepted with containment. getWorkflowScript takes threadId but does not yet verify the path against that thread's recorded runHandles (that registry is Orchestrator v2's read model; this PR is zero-migration by design). Access is bounded to the local paired user's own ~/.claude/projects (realpath re-containment, .js-only, TOCTOU-safe open, size cap). Thread-scoped verification is a small follow-up once v2's projection lands.
  • Event-rate bound. Workflow member fan-out is coalesced by a material-transition filter (emit only when a rendered field changes), and progress activities upsert under stable thread-scoped ids — worst case per coordinator tick is now proportional to changed members, not fleet size.

Note

High Risk Touches provider adapters, runtime ingestion, interrupt/stop paths, and Codex child-notification routing—security-sensitive file read RPC and behavior changes that can hide or mis-route live agent signals if classification drifts.

Overview Adds end-to-end subagent and workflow observability on the existing activity stream: ingestion stamps agentKind and linkage on task.* / tool rows, uses stable thread-scoped progress ids so ticks upsert instead of flooding retention, and maps Claude task_updated plus Codex collabAgent/* into shared task.updated / bypassed terminal updates.

Server behavior changes: ThreadBackgroundLiveness (in-memory) drives backgroundLiveness: working | monitoring on thread shells; runtime ingestion records task lifecycle and clears on session.exited. Stop now stops live Claude tasks (stopTask) and bounded Codex child turn/interrupt before the parent. Claude drops subagent narration from the parent transcript, attributes tools via parent_tool_use_id, parses workflow_progress with member coalescing, and Codex registers v2 children with explicit routing (root self-activity guard, interception before legacy suppressor). New read-scoped getWorkflowScript RPC reads .js under ~/.claude/projects with realpath containment and TOCTOU-safe open.

Mobile mirrors the web quiet timeline: hide agent-internal background work but keep nested agent terminals and Codex terminal bypass task.updated rows; task rows collapse by taskId.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f7673f31db68382d9516e103c88c03e9f6961623. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Summary by CodeRabbit

  • New Features

    • Added an Agents panel showing live and completed subagent workflows, phases, status, usage, and activity.
    • Added workflow script inspection with loading, truncation, and error states.
    • Added Working and Monitoring thread statuses with live background-task counts and a Stop action.
    • Added support for multi-agent collaboration, including nested tasks, progress, retries, and interruptions.
  • Bug Fixes

    • Reduced duplicate and internal activity in the work log while preserving meaningful task progress.
    • Improved task status, ownership, and usage reporting across providers.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 39.08% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Title check✅ PassedThe title clearly summarizes the primary change: native subagent and workflow observability.
      Description check✅ PassedThe description explains the problem, solution, UI changes, verification, tradeoffs, and remaining gaps, although it does not use every template heading.

      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.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      1 blocking correctness issue found. Diff is too large for automated approval analysis. A human reviewer should evaluate this PR.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/16cdc33f7c5108b4efea8eaa8b0937bd413be61a/apps/web/src/session-logic.ts#L845

      In collapseDerivedWorkLogEntries, direct-spawn tasks whose turnId is absent all share the same direct:no-turn group key, so agents from different turns (or legacy rows) collapse into a single CTA row with a combined agentTaskIds list — distinct spawn events are silently merged. The fallback in agentSpawnGroupKey should be scoped to a per-batch or per-activity identifier rather than a global "no-turn" string.

      No longer relevant as of 178eaf794b70d78caceb0b455046ebadffaaffb3

    5. Effect service conventions review: one clear violation (new shared mutable state held in a module global and consumed by two Effect services) plus one file-layout nit. Everything else in the changed Effect code (namespace imports from effect/* subpaths, per-session Map state inside Effect.gen, contract schemas) looks conformant.

      Posted via Macroscope — Effect Service Conventions
    6. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/95c204741c9321aa8ec4bb095fa0d1343fa74f80/apps/web/src/session-logic.ts#L692

      Codex subagent children that emit only task.started and task.updated lifecycle events (no task.progress or task.completed) get no spawn CTA row in the work log. deriveWorkLogEntries drops task.started and task.updated rows early, and isAgentInternalActivity only preserves bypassed task.progress/task.completed rows for CTA collapsing — so an agent whose lifecycle never includes those two kinds is silently absent from the timeline despite being registered. Consider admitting an initial agent task row (e.g. task.started with a taskId) as a CTA anchor, or synthesizing a progress row at start so the collapse logic has a seed.

      No longer relevant as of eb0fd9c404fad4f2c52b6123a117915816088036

    7. Effect service conventions: one new finding on the getWorkflowScript error type (dropped cause). Two findings from the previous run on this PR (module-global liveness registry in threadBackgroundLiveness.ts, mid-file import in ProjectionSnapshotQuery.ts) still appear unaddressed and are not repeated here.

      Posted via Macroscope — Effect Service Conventions
    8. [claude-fable-5] RESPONDING ON BEHALF OF THEO


      Addressed since: CTA batches now seed from task.started rows (which always precede other lifecycle rows for a batch) and task.updated rows carry the repeated linkage bundle, so start/updated-only children still form a CTA. Codex children additionally synthesize a task.started from subAgentActivity: started since 95c204741.

    9. Effect service conventions: two findings on the new ThreadBackgroundLiveness service. The rest of the changed Effect code (namespace imports, Effect.fn usage, yield* ThreadBackgroundLivenessService acquisition inside make) looks consistent with the conventions.

      Posted via Macroscope — Effect Service Conventions
    10. Two Effect service convention issues in the new modules; details inline.

      Posted via Macroscope — Effect Service Conventions
    11. One finding on the new orchestration RPC error's shape. The service module hoist (orchestration/ThreadBackgroundLiveness.ts with inline interface, make, layer, Service["Service"], requirement kept on the consuming layers) and the workflowScriptQuery error/cause cleanup from earlier rounds all look right.

      Posted via Macroscope — Effect Service Conventions
    12. Actionable comments posted: 10

      🧹 Nitpick comments (10)
      apps/server/src/orchestration/workflowScriptQuery.ts (1)

      25-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Record the provider decision for the hardcoded Claude scripts root.

      scriptsRoot() returns ~/.claude/projects. Workflow scripts produced by other adapters resolve outside that root and fail with outside-root. This PR also adds Codex workflow observability, so the Agents "{} script" affordance will not work for Codex runs.

      State the intended behavior for Codex, Cursor, Grok, and OpenCode. If only Claude persists workflow scripts today, document that in the module header so the limitation is explicit.

      As per coding guidelines: "Provider-shaped features require a deliberate decision for each provider adapter: Codex, Claude, Cursor, Grok, and OpenCode."

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/orchestration/workflowScriptQuery.ts` around lines 25 - 27,
      Document the provider decision in the module header for the hardcoded
      scriptsRoot() path: explicitly state the intended workflow-script behavior for
      Codex, Claude, Cursor, Grok, and OpenCode, including that only Claude currently
      persists scripts if that is the supported behavior. Ensure the documentation
      makes clear which providers support the Agents “script” affordance and avoids
      implying that all adapters use ~/.claude/projects.

      Source: Coding guidelines

      apps/server/src/orchestration/workflowScriptQuery.test.ts (1)

      10-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Do not write test fixtures into the real home directory.

      Lines 10-13 create files inside the developer's or CI runner's actual ~/.claude/projects, which is the same directory the Claude harness uses. Line 14 uses a fixed name in os.tmpdir(). Two concurrent runs collide, and afterAll deletes state under the real home directory.

      Make the scripts root injectable in workflowScriptQuery.ts (for example an optional root parameter that defaults to scriptsRoot()), then point the test at a mkdtempSync directory. This also removes the need for the afterAll cleanup of real user state.

      Also applies to: 23-26

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/orchestration/workflowScriptQuery.test.ts` around lines 10 -
      15, The test currently writes fixtures into the real home directory and uses a
      colliding fixed temporary filename. Make the scripts root injectable in the
      relevant workflow script query API, defaulting to scriptsRoot(), then have the
      test create an isolated mkdtempSync directory and place both fixtures under it.
      Update calls and cleanup to use only this temporary directory, removing afterAll
      cleanup of real user state.
      apps/web/src/rightPanelStore.ts (1)

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

      Consider keeping the storage version at 7.

      The change adds one surface kind. migratePersistedRightPanelState already tolerates the previous shape, because it only rewrites file and terminal surfaces and passes other kinds through. Raising the version to 8 discards every user's open right-panel tabs on upgrade without a correctness benefit.

      If you keep version 8, that is a deliberate reset. If not, revert to 7.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/web/src/rightPanelStore.ts` at line 52, Revert
      RIGHT_PANEL_STORAGE_VERSION to 7 because migratePersistedRightPanelState already
      preserves the newly added surface kind and no reset is required.
      apps/web/src/components/chat/MessagesTimeline.logic.ts (1)

      531-533: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

      Compute onlyToolEntries from the hidden entries.

      The toggle describes the hidden rows. visibleGroupedEntries includes the pinned spawn entries, which are never hidden. A spawn entry that is not tool-like flips onlyToolEntries to false even when every hidden row is a tool call, which changes the toggle label.

      ♻️ Proposed change
      -              onlyToolEntries: visibleGroupedEntries.every((entry) =>
      -                workLogEntryIsToolLike(entry),
      -              ),
      +              onlyToolEntries: hiddenEntries.every((entry) => workLogEntryIsToolLike(entry)),
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/web/src/components/chat/MessagesTimeline.logic.ts` around lines 531 -
      533, The onlyToolEntries calculation currently uses visibleGroupedEntries, which
      includes pinned spawn entries; update the logic around onlyToolEntries to
      evaluate the hidden entries collection instead, while preserving the existing
      workLogEntryIsToolLike predicate and toggle behavior.
      apps/web/src/session-logic.ts (2)

      652-672: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Move the quiet-timeline doc block onto deriveWorkLogEntries.

      The comment at Lines 652-661 documents the work-log filtering contract of deriveWorkLogEntries. It now sits directly above isAgentTaskStartedActivity, which carries its own doc comment on Line 662. A reader (and any doc tooling) attaches the block to the wrong function.

      Move the block to Line 712, immediately above deriveWorkLogEntries.

      As per coding guidelines: "Use comments mainly to describe how a function is used; avoid annotating every line of behavior, and move comments when code moves."

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/web/src/session-logic.ts` around lines 652 - 672, Move the
      quiet-timeline guarantee doc block from above isAgentTaskStartedActivity to
      immediately above deriveWorkLogEntries, preserving its text unchanged; keep the
      separate isAgentTaskStartedActivity documentation directly above that function.

      Source: Coding guidelines


      882-895: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

      Carry parentAgentId into the derived entry and key by it.

      toDerivedWorkLogEntry stores taskId and agentSpawn.workflowId, but not parentAgentId. If parentAgentId exists without a legacy :wf: encoding, agentSpawnGroupKey falls through to direct:<turnId> and splits the same workflow members into separate chat CTA rows from what the Agents panel groups under one coordinator.

      Also update the :wf:-slot check only after copying the parent link so this only affects unencoded workflow members.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/web/src/session-logic.ts` around lines 882 - 895, Update
      DerivedWorkLogEntry and toDerivedWorkLogEntry to preserve parentAgentId, then
      update agentSpawnGroupKey to use the copied parentAgentId for workflow grouping
      when no legacy :wf: taskId encoding exists. Keep the existing :wf: parsing
      precedence unchanged, and apply the parent-link fallback before the coordinator
      and direct turnId cases.
      apps/server/src/provider/Layers/ClaudeAdapter.test.ts (1)

      1453-1601: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Add focused tests for task_updated and workflow member synthesis.

      The two new tests cover interrupt fan-out and model/effort inheritance. Two behaviors with more branching remain untested in this file:

      • task_updated: the CLAUDE_TASK_PATCH_STATUS mapping (killed → cancelled, paused → idle), removal from liveTaskIds on a terminal patch, and the endedAt conversion.
      • emitWorkflowMemberProgress: the <coordinatorTaskId>:wf:<index> member id, per-index dedupe, and workflowAgentStatus.

      Both are backend behavior changes, so the guidelines require focused tests. Do you want me to draft them in the same harness style?

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/provider/Layers/ClaudeAdapter.test.ts` around lines 1453 -
      1601, Add focused harness-style tests in ClaudeAdapter.test.ts for task_updated
      and workflow member synthesis. Cover killed→cancelled and paused→idle status
      mapping, terminal patch removal from liveTaskIds, endedAt conversion, and
      emitWorkflowMemberProgress behavior including <coordinatorTaskId>:wf:<index>
      IDs, per-index deduplication, and workflowAgentStatus.

      Source: Coding guidelines

      apps/server/src/orchestration/ActivityPayloadProjection.test.ts (1)

      5-15: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

      Set the activity kind per test so the task-lifecycle case is really exercised.

      The helper hardcodes kind: "tool.completed". The second test is named for task lifecycle payloads, but it still passes a tool activity. If projectActivityPayload branches on kind, this test never reaches the task branch and the regression tripwire described in the file comment does not fire.

      💚 Proposed change
      -function activity(payload: Record<string, unknown>): OrchestrationThreadActivity {
      +function activity(
      +  payload: Record<string, unknown>,
      +  kind = "tool.completed",
      +): OrchestrationThreadActivity {
         return {
           id: "activity-1",
           tone: "tool",
      -    kind: "tool.completed",
      +    kind,
           summary: "Tool",
           payload,
           turnId: null,
           createdAt: "2026-08-01T10:00:00.000Z",
         } as unknown as OrchestrationThreadActivity;
       }
      -    const source = activity({
      -      taskId: "task-9",
      +    const source = activity(
      +      {
      +        taskId: "task-9",
      ...
      -      timelineBypass: true,
      -    });
      +        timelineBypass: true,
      +      },
      +      "task.started",
      +    );

      Also applies to: 47-62

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/orchestration/ActivityPayloadProjection.test.ts` around lines
      5 - 15, The activity helper currently hardcodes the tool kind, preventing
      task-lifecycle tests from exercising the task branch. Update activity and its
      callers so each test supplies the appropriate activity kind, preserving
      tool.completed for tool tests and using the task lifecycle kind in the second
      test.
      apps/server/src/provider/Layers/ClaudeAdapter.ts (1)

      4358-4375: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

      Log stopTask failures instead of discarding them.

      Every stopTask rejection is swallowed twice: catch: () => undefined and Effect.ignore. A provider that refuses to stop background tasks then produces no signal at all, and users see agents keep burning tokens after pressing Stop. Keep the best-effort semantics, but record the failure.

      ♻️ Proposed change to keep failures observable
      -        yield* Effect.forEach(
      -          liveIds,
      -          (taskId) =>
      -            Effect.tryPromise({
      -              // Invoke through the query object: SDK methods rely on `this`.
      -              try: () => context.query.stopTask!(taskId),
      -              catch: () => undefined,
      -            }).pipe(Effect.ignore),
      -          { concurrency: 8, discard: true },
      -        );
      +        yield* Effect.forEach(
      +          liveIds,
      +          (taskId) =>
      +            Effect.tryPromise({
      +              // Invoke through the query object: SDK methods rely on `this`.
      +              try: () => context.query.stopTask!(taskId),
      +              catch: (cause) => cause,
      +            }).pipe(
      +              Effect.catchCause((cause) =>
      +                Effect.logWarning("claude.task.stop-failed", { threadId, taskId, cause }),
      +              ),
      +            ),
      +          { concurrency: 8, discard: true },
      +        );
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/provider/Layers/ClaudeAdapter.ts` around lines 4358 - 4375,
      Update the stop-task cleanup around context.query.stopTask to preserve
      best-effort per-task execution while logging each rejection or thrown failure
      with the taskId and error details. Replace the silent catch/ignore handling
      without allowing one failed stopTask call to prevent remaining tasks from being
      attempted or the subsequent interrupt from running.
      apps/server/src/provider/Layers/CodexAdapter.ts (1)

      760-766: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Record the intentional omission for Cursor, Grok, and OpenCode child task events.

      This PR adds task.* child events for Codex and Claude only, while Cursor, Grok, and OpenCode do not emit collabAgent/...* child events. Capture that decision in the PR description or a code comment so the provider-level behavior is explicit.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/provider/Layers/CodexAdapter.ts` around lines 760 - 766,
      Document in a nearby comment to mapToRuntimeEvents that Cursor, Grok, and
      OpenCode intentionally do not map collabAgent/... child task events because
      those providers do not emit them; clarify that task.* child events are currently
      supported only for Codex and Claude.

      Source: Coding guidelines

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@apps/server/src/orchestration/workflowScriptQuery.test.ts`:
      - Around line 16-21: Update the symlink setup and assertions in the workflow
      script query test around NodeFS.symlinkSync and readWorkflowScript: only
      tolerate an already-existing link, rethrow unexpected or permission errors,
      verify the link exists before querying, and assert that the returned Failure
      reason is the containment-specific value rather than checking only _tag.
      
      In `@apps/server/src/orchestration/workflowScriptQuery.ts`:
      - Around line 29-38: Update readWorkflowScript and getWorkflowScript to carry
      the caller’s threadId, then resolve the workflow script location recorded for
      that thread in runHandles.scriptPath before accepting the requested path hint.
      Require the resolved requested path to match the thread’s recorded script
      location, while retaining ~/.claude/projects as a secondary containment check.
      Reject mismatches through the existing invalid-path error flow.
      
      In `@apps/server/src/provider/Layers/CodexAdapter.ts`:
      - Around line 669-700: Update the token usage parsing in the
      collabAgent/tokenUsage case to define and reuse the existing count validator
      before validating totalTokens. Require totalTokens to pass count, return [] when
      it is undefined, and assign the validated value to RuntimeTaskUsage; reuse local
      validated values for the other fields instead of calling count repeatedly.
      
      In `@apps/server/src/provider/Layers/CodexSessionRuntime.ts`:
      - Around line 1109-1122: The interceptCollabChildNotification switch currently
      drops child error notifications, leaving the child marked running. Add a case
      for "error" that emits a collabAgent/statusChanged event with type "systemError"
      and the child identity/status payload required by mapCollabAgentEvent to produce
      a failed task update; preserve existing handling for closed and other
      notifications.
      
      In `@apps/web/src/components/chat/MessagesTimeline.logic.ts`:
      - Around line 504-512: Update the work-group entry selection around
      pinnedSpawnEntries, hiddenEntries, visibleEntries, and renderedEntries to
      preserve the original visibleGroupedEntries chronological order. Select retained
      entries by their indices rather than concatenating all spawn rows with the
      overflow tail, and ensure the expanded path renders the full ordered group while
      the collapsed path renders only the retained ordered entries.
      
      In `@apps/web/src/components/ChatView.tsx`:
      - Around line 4209-4224: Update handleStopBackgroundWork so every
      interruptThreadTurn failure resets isStoppingBackgroundWork, including when
      isAtomCommandInterrupted(result) is true, while preserving the existing
      error-setting path only for non-interrupted failures.
      
      In `@apps/web/src/components/Sidebar.logic.ts`:
      - Around line 443-450: Reorder the backgroundLiveness branches in both status
      resolvers in apps/web/src/components/Sidebar.logic.ts:443-450 and
      apps/web/src/components/Sidebar.logic.ts:626-646. In the first resolver, keep
      session?.status === "error" ahead of background statuses; in the second, keep
      hasPlanReadyPrompt ahead of the background-liveness pill branches so error and
      actionable states take precedence.
      - Line 135: Update the status priority mapping around Monitoring so Monitoring
      ranks below the active Working and Connecting statuses, or adjust
      resolveProjectStatusIndicator to break equal-priority ties in favor of active
      work. Preserve the existing project-group status resolution behavior for all
      other statuses.
      
      In `@apps/web/src/session-logic.ts`:
      - Around line 674-710: Update isAgentInternalActivity so agentId ownership alone
      does not classify nested agent task rows as internal; use
      isBackgroundTaskActivity() to distinguish shell-only background tasks from agent
      task activity. Preserve nested agent rows and their CTA anchors while keeping
      work-log, Agentic Activities, and spawn CTA classification consistent with the
      shared task-type contract.
      
      In `@packages/client-runtime/src/state/subagentRuntime.ts`:
      - Around line 469-473: Update the status resolution in the flow using
      TASK_COMPLETED_STATUS to validate that the looked-up value is a valid
      RuntimeSubagentStatus before passing it to applyStatus. Guard against inherited
      keys such as “toString” and “constructor” so invalid payload statuses fall back
      to “completed,” rather than relying on truthiness or nullish coalescing alone.
      
      ---
      
      Nitpick comments:
      In `@apps/server/src/orchestration/ActivityPayloadProjection.test.ts`:
      - Around line 5-15: The activity helper currently hardcodes the tool kind,
      preventing task-lifecycle tests from exercising the task branch. Update activity
      and its callers so each test supplies the appropriate activity kind, preserving
      tool.completed for tool tests and using the task lifecycle kind in the second
      test.
      
      In `@apps/server/src/orchestration/workflowScriptQuery.test.ts`:
      - Around line 10-15: The test currently writes fixtures into the real home
      directory and uses a colliding fixed temporary filename. Make the scripts root
      injectable in the relevant workflow script query API, defaulting to
      scriptsRoot(), then have the test create an isolated mkdtempSync directory and
      place both fixtures under it. Update calls and cleanup to use only this
      temporary directory, removing afterAll cleanup of real user state.
      
      In `@apps/server/src/orchestration/workflowScriptQuery.ts`:
      - Around line 25-27: Document the provider decision in the module header for the
      hardcoded scriptsRoot() path: explicitly state the intended workflow-script
      behavior for Codex, Claude, Cursor, Grok, and OpenCode, including that only
      Claude currently persists scripts if that is the supported behavior. Ensure the
      documentation makes clear which providers support the Agents “script” affordance
      and avoids implying that all adapters use ~/.claude/projects.
      
      In `@apps/server/src/provider/Layers/ClaudeAdapter.test.ts`:
      - Around line 1453-1601: Add focused harness-style tests in
      ClaudeAdapter.test.ts for task_updated and workflow member synthesis. Cover
      killed→cancelled and paused→idle status mapping, terminal patch removal from
      liveTaskIds, endedAt conversion, and emitWorkflowMemberProgress behavior
      including <coordinatorTaskId>:wf:<index> IDs, per-index deduplication, and
      workflowAgentStatus.
      
      In `@apps/server/src/provider/Layers/ClaudeAdapter.ts`:
      - Around line 4358-4375: Update the stop-task cleanup around
      context.query.stopTask to preserve best-effort per-task execution while logging
      each rejection or thrown failure with the taskId and error details. Replace the
      silent catch/ignore handling without allowing one failed stopTask call to
      prevent remaining tasks from being attempted or the subsequent interrupt from
      running.
      
      In `@apps/server/src/provider/Layers/CodexAdapter.ts`:
      - Around line 760-766: Document in a nearby comment to mapToRuntimeEvents that
      Cursor, Grok, and OpenCode intentionally do not map collabAgent/... child task
      events because those providers do not emit them; clarify that task.* child
      events are currently supported only for Codex and Claude.
      
      In `@apps/web/src/components/chat/MessagesTimeline.logic.ts`:
      - Around line 531-533: The onlyToolEntries calculation currently uses
      visibleGroupedEntries, which includes pinned spawn entries; update the logic
      around onlyToolEntries to evaluate the hidden entries collection instead, while
      preserving the existing workLogEntryIsToolLike predicate and toggle behavior.
      
      In `@apps/web/src/rightPanelStore.ts`:
      - Line 52: Revert RIGHT_PANEL_STORAGE_VERSION to 7 because
      migratePersistedRightPanelState already preserves the newly added surface kind
      and no reset is required.
      
      In `@apps/web/src/session-logic.ts`:
      - Around line 652-672: Move the quiet-timeline guarantee doc block from above
      isAgentTaskStartedActivity to immediately above deriveWorkLogEntries, preserving
      its text unchanged; keep the separate isAgentTaskStartedActivity documentation
      directly above that function.
      - Around line 882-895: Update DerivedWorkLogEntry and toDerivedWorkLogEntry to
      preserve parentAgentId, then update agentSpawnGroupKey to use the copied
      parentAgentId for workflow grouping when no legacy :wf: taskId encoding exists.
      Keep the existing :wf: parsing precedence unchanged, and apply the parent-link
      fallback before the coordinator and direct turnId cases.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 1ee12d61-2e8a-40e0-b88a-6979acf94b14

      📥 Commits

      Reviewing files that changed from the base of the PR and between 64bf0161919ec0e41470af3304928d9fc8711bf4 and 5ff16383e36fd2ad5b528abfb87bd38dfa4a0356.

      📒 Files selected for processing (39)
      • apps/mobile/src/lib/threadActivity.ts
      • apps/server/integration/OrchestrationEngineHarness.integration.ts
      • apps/server/src/auth/RpcAuthorization.ts
      • apps/server/src/orchestration/ActivityPayloadProjection.test.ts
      • apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
      • apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
      • apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts
      • apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
      • apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
      • apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      • apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
      • apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
      • apps/server/src/orchestration/ThreadBackgroundLiveness.test.ts
      • apps/server/src/orchestration/ThreadBackgroundLiveness.ts
      • apps/server/src/orchestration/runtimeLayer.ts
      • apps/server/src/orchestration/workflowScriptQuery.test.ts
      • apps/server/src/orchestration/workflowScriptQuery.ts
      • apps/server/src/provider/Layers/ClaudeAdapter.test.ts
      • apps/server/src/provider/Layers/ClaudeAdapter.ts
      • apps/server/src/provider/Layers/CodexAdapter.ts
      • apps/server/src/provider/Layers/CodexSessionRuntime.ts
      • apps/server/src/ws.ts
      • apps/web/src/components/AgentsPanel.tsx
      • apps/web/src/components/ChatView.tsx
      • apps/web/src/components/RightPanelTabs.tsx
      • apps/web/src/components/Sidebar.logic.ts
      • apps/web/src/components/SidebarV2.tsx
      • apps/web/src/components/chat/MessagesTimeline.logic.ts
      • apps/web/src/components/chat/MessagesTimeline.tsx
      • apps/web/src/rightPanelStore.ts
      • apps/web/src/session-logic.test.ts
      • apps/web/src/session-logic.ts
      • packages/client-runtime/package.json
      • packages/client-runtime/src/state/orchestration.ts
      • packages/client-runtime/src/state/subagentRuntime.test.ts
      • packages/client-runtime/src/state/subagentRuntime.ts
      • packages/contracts/src/orchestration.ts
      • packages/contracts/src/providerRuntime.ts
      • packages/contracts/src/rpc.ts

Sign in to join this conversation.