TypeScript
fix(web): a thread that left a shell running shows its unseen completion (#14910)
Igor Makowskif68e24fb419c
diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.tsindex 166baa9d2e4..3e60d44f73f 100644--- a/apps/mobile/src/features/threads/threadListV2.test.ts+++ b/apps/mobile/src/features/threads/threadListV2.test.ts@@ -1,3 +1,5 @@+import { presentThreadShell } from "@t3tools/client-runtime/state/models";+import * as DateTime from "effect/DateTime";import { planPinnedMove } from "@t3tools/client-runtime/state/thread-sort";import {createPendingThreadOrder,@@ -23,7 +25,7 @@ import {import { describe, expect, it, vi } from "vite-plus/test";import type { PendingNewTask } from "../../state/use-pending-new-tasks";-import { makeThreadShellFixture } from "../../test-fixtures";+import { makeRawThreadShell, makeThreadShellFixture } from "../../test-fixtures";import { threadJumpTarget } from "../keyboard/threadKeyboardShortcuts";import {buildThreadListV2Items,@@ -36,6 +38,7 @@ import {resolveThreadListV2SwipeActions,sortThreadsForListV2,threadListV2ListItemsAreEqual,+ threadHasUnseenCompletion,type ThreadListV2ListItem,} from "./threadListV2";@@ -160,9 +163,7 @@ describe("resolveThreadListV2Status", () => {makeThread({id: ThreadId.make("t"),title: "t",- pendingBackgroundTasks: [- { taskId: "bg-1", description: "Run Codex review", kind: "command" },- ],+ pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],runtime: {status: "idle",activeRunId: null,@@ -176,6 +177,28 @@ describe("resolveThreadListV2Status", () => {).toBe("waiting");});+ it.each([+ { kind: "command", status: "ready" },+ { kind: "monitor", status: "waiting" },+ ] as const)(+ "presents an unseen completion with a $kind roster as $status",+ ({ kind, status }) => {+ const thread = presentThreadShell(+ environmentId,+ makeRawThreadShell({+ latestRunId: RunId.make("run-background-completion"),+ status: "completed",+ latestRunCompletedAt: DateTime.makeUnsafe(NOW),+ lastVisitedAt: DateTime.makeUnsafe("2026-06-01T23:59:00.000Z"),+ pendingBackgroundTasks: [{ taskId: "background-work", kind }],+ }),+ );++ expect(resolveThreadListV2Status(thread)).toBe(status);+ expect(threadHasUnseenCompletion(thread)).toBe(true);+ },+ );+it("resolves ready for quiescent threads", () => {expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe("ready",diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.tsindex f0b2459301a..48f13e348b0 100644--- a/apps/mobile/src/features/threads/threadListV2.ts+++ b/apps/mobile/src/features/threads/threadListV2.ts@@ -62,7 +62,8 @@ export function resolveThreadListV2ProviderDrivers(* failures. Ready is the unlabeled resting state; waiting (runtime status "idle") is the agent* parked on open background tasks, grey like working rather than a false Done.* The orchestrator v2 presentation bridge parks runtime at idle when the- * post-settlement background roster is nonempty.+ * post-settlement background roster holds the run's completion (subagents,+ * monitors); commands left running, such as a dev server, read as ready.*/export type ThreadListV2Status =| "approval"diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex 33bdb2129bf..5b8b7688953 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -1,3 +1,5 @@+import { presentThreadShell } from "@t3tools/client-runtime/state/models";+import * as DateTime from "effect/DateTime";import { deriveActiveWorkStartedAt } from "../session-logic.ts";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";@@ -1254,7 +1256,7 @@ describe("resolveThreadStatusPill", () => {resolveThreadStatusPill({thread: {...baseThread,- pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20", kind: "command" }],+ pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],runtime: {...baseThread.runtime,status: "idle",@@ -2053,6 +2055,39 @@ describe("navigation after parking a thread", () => {);});+describe("unseen completion with background work", () => {+ it.each([+ { kind: "command", status: "ready", topStatus: "done", receded: false, pill: "Completed" },+ { kind: "monitor", status: "waiting", topStatus: "waiting", receded: true, pill: "Waiting" },+ ] as const)("presents a completed thread with a $kind roster", (expected) => {+ const thread = presentThreadShell(localEnvironmentId, {+ ...makeThreadFixture().source,+ latestRunId: RunId.make("run-background-completion"),+ status: "completed",+ latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),+ lastVisitedAt: DateTime.makeUnsafe("2026-06-20T00:59:00.000Z"),+ pendingBackgroundTasks: [{ taskId: "background-work", kind: expected.kind }],+ });+ const status = resolveSidebarThreadStatus(thread);+ const isUnread = hasUnseenCompletion(thread);++ expect(isUnread).toBe(true);+ expect(status).toBe(expected.status);+ expect(resolveSidebarV2TopStatus({ status, isUnread, isWoke: false })).toBe(expected.topStatus);+ expect(+ shouldRecedeSidebarThread({+ status,+ isUnread,+ isWoke: false,+ isActive: false,+ isSelected: false,+ }),+ ).toBe(expected.receded);+ expect(isSidebarThreadWorking(thread)).toBe(expected.receded);+ expect(resolveThreadStatusPill({ thread })).toMatchObject({ label: expected.pill });+ });+});+describe("Working shelf (beta)", () => {const runtime = {status: "running" as const,@@ -2062,7 +2097,7 @@ describe("Working shelf (beta)", () => {lastError: null,updatedAt: "2026-03-09T10:00:00.000Z",};- const backgroundTask = { taskId: "bg-1", description: "sleep 20", kind: "command" as const };+ const backgroundTask = { taskId: "bg-1", description: "Watch build", kind: "monitor" as const };const idle = {hasActionableProposedPlan: false,hasPendingApprovals: false,diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 4f504e286d0..5a579bc503a 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -1,4 +1,5 @@import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";+import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";import * as React from "react";import {@@ -910,9 +911,10 @@ export function resolveThreadRowClassName(input: {// (approval), "in motion" (working), and "broken" (failed). Ready is the// unlabeled resting state — the agent stopped and is waiting on the user,// whether it finished, asked a question, or proposed a plan. Waiting-// (runtime status "idle") is the agent stopped with background tasks still-// open: not the user's turn yet, so it renders grey like working, not as a-// false Done.+// (runtime status "idle") is the agent stopped with background work that will+// wake it (subagents, monitors): not the user's turn yet, so it renders grey+// like working, not as a false Done. Commands it left running, such as a dev+// server, do not hold the thread; it reads as ready.// Unread completion is tracked separately: it describes whether a ready// thread needs attention, not what the thread is currently doing.export type SidebarThreadStatus =@@ -1007,8 +1009,8 @@ export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolea}/** Working beta: threads busy with work that does not need the user fold into- the Working shelf: a running run, or one stopped with background tasks- still open. Approvals, questions, plan prompts, and failures stay in the+ the Working shelf: a running run, or one stopped with background work+ that will wake it. Approvals, questions, plan prompts, and failures stay in theinbox. */export function isSidebarThreadWorking(thread: ThreadStatusInput): boolean {const status = resolveSidebarThreadStatus(thread);@@ -1209,7 +1211,7 @@ export function resolveThreadStatusPill(input: {};}- if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) {+ if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) {return {label: "Waiting",colorClass: "text-sidebar-muted-foreground",diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsxindex e59099d62d4..741e850ca0d 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.tsx+++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx@@ -2,7 +2,6 @@ import { presentThreadShell } from "@t3tools/client-runtime/state/models";import { useAtomValue } from "@effect/atom-react";import { useNavigate, useParams } from "@tanstack/react-router";import type { EnvironmentId, ThreadId } from "@t3tools/contracts";-import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";import * as Option from "effect/Option";import {CircleAlertIcon,@@ -126,12 +125,11 @@ function EnvironmentNotifications({? `${thread.latestRun?.runId ?? ""}:${status}`: null;const completedAt = Date.parse(thread.latestRun?.completedAt ?? "");- // Waiting only on commands (a dev server) is done; subagents and monitors wake the agent.- const settled =- status === "ready" ||- (status === "waiting" && !backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks));+ // Commands left running (a dev server) read as ready; subagents and monitors wait.const completion =- settled && thread.latestRun?.status === "completed" && Number.isFinite(completedAt)+ status === "ready" &&+ thread.latestRun?.status === "completed" &&+ Number.isFinite(completedAt)? completedAt: (prior?.completion ?? null);next.set(thread.id, { attention, completion });diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.tsindex 736e05c8356..1a2581609bc 100644--- a/packages/client-runtime/src/state/entities.test.ts+++ b/packages/client-runtime/src/state/entities.test.ts@@ -2,8 +2,10 @@ import {EnvironmentId,MessageId,NodeId,+ ProviderDriverKind,ProviderInstanceId,ProviderSessionId,+ ProviderThreadId,RunId,RuntimeRequestId,TurnItemId,@@ -140,7 +142,7 @@ describe("V2 client presentation", () => {latestRunId: runId,activeRunId: null,status: "completed",- pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20", kind: "command" }],+ pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],});expect(shell.latestRun).toMatchObject({ runId, status: "completed" });@@ -149,10 +151,50 @@ describe("V2 client presentation", () => {activeRunId: null,});expect(shell.pendingBackgroundTasks).toEqual([- { taskId: "bg-1", description: "sleep 20", kind: "command" },+ { taskId: "bg-1", description: "Watch build", kind: "monitor" },]);});+ it.each([+ { kinds: ["command"], expected: "completed" },+ { kinds: ["command", "subagent"], expected: "idle" },+ { kinds: ["background_task"], expected: "idle" },+ ] as const)("presents a completed shell with $kinds as $expected", ({ kinds, expected }) => {+ const pendingBackgroundTasks = kinds.map((kind, index) => ({+ taskId: `bg-${index}`,+ kind,+ }));+ const shell = presentThreadShell(environmentId, {+ ...v2ThreadShell,+ latestRunId: RunId.make("run-completed"),+ activeRunId: null,+ status: "completed",+ pendingBackgroundTasks,+ });++ expect(shell.latestRun?.status).toBe("completed");+ expect(shell.runtime).toMatchObject({ status: expected, activeRunId: null });+ expect(shell.pendingBackgroundTasks).toEqual(pendingBackgroundTasks);+ });++ it.each(["running", "waiting"] as const)(+ "preserves shell %s while only commands remain in the roster",+ (status) => {+ const runId = RunId.make("run-command");+ const shell = presentThreadShell(environmentId, {+ ...v2ThreadShell,+ latestRunId: runId,+ activeRunId: runId,+ status,+ pendingBackgroundTasks: [{ taskId: "dev-server", kind: "command" }],+ });++ expect(shell.latestRun?.status).toBe(status);+ expect(shell.runtime).toMatchObject({ status, activeRunId: runId });+ expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "dev-server", kind: "command" }]);+ },+ );+it("keeps a failed latest run failed while background tasks are still pending", () => {const shell = presentThreadShell(environmentId, {...v2ThreadShell,@@ -160,7 +202,7 @@ describe("V2 client presentation", () => {activeRunId: null,status: "failed",lastError: "Provider turn failed",- pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20", kind: "command" }],+ pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],});// Sidebar and mobile list read runtime "idle" as Waiting before failure.@@ -286,7 +328,7 @@ describe("V2 client presentation", () => {// Stale: server already projected a post-settlement roster, but shell// status still says running (packaged orchestrator-v2 bug).status: "running",- pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20", kind: "command" }],+ pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],});expect(shell.latestRun).toMatchObject({ runId, status: "running" });@@ -295,7 +337,7 @@ describe("V2 client presentation", () => {activeRunId: runId,});expect(shell.pendingBackgroundTasks).toEqual([- { taskId: "bg-1", description: "sleep 20", kind: "command" },+ { taskId: "bg-1", description: "Watch build", kind: "monitor" },]);});@@ -307,7 +349,7 @@ describe("V2 client presentation", () => {activeRunId: runId,// Stale: checkpoint-oriented waiting masks post-settlement background work.status: "waiting",- pendingBackgroundTasks: [{ taskId: "bg-2", description: "background bash", kind: "command" }],+ pendingBackgroundTasks: [{ taskId: "bg-2", description: "Watch build", kind: "monitor" }],});expect(shell.latestRun).toMatchObject({ runId, status: "waiting" });@@ -316,7 +358,7 @@ describe("V2 client presentation", () => {activeRunId: runId,});expect(shell.pendingBackgroundTasks).toEqual([- { taskId: "bg-2", description: "background bash", kind: "command" },+ { taskId: "bg-2", description: "Watch build", kind: "monitor" },]);});@@ -443,7 +485,7 @@ describe("V2 client presentation", () => {contextHandoffId: null,};const backgroundItem = {- id: TurnItemId.make("item-background-command"),+ id: TurnItemId.make("item-background-subagent"),threadId: v2Projection.thread.id,runId,nodeId: null,@@ -453,12 +495,18 @@ describe("V2 client presentation", () => {parentItemId: null,ordinal: 0,status: "running" as const,- title: "Background command",+ title: "Background review",startedAt: now,completedAt: null,updatedAt: now,- type: "command_execution" as const,- input: "sleep 20",+ type: "subagent" as const,+ subagentId: NodeId.make("subagent-review"),+ origin: "provider_native" as const,+ driver: ProviderDriverKind.make("codex"),+ providerInstanceId: v2Projection.thread.providerInstanceId,+ childThreadId: null,+ prompt: "Review the changes",+ result: null,};expect(@@ -488,6 +536,59 @@ describe("V2 client presentation", () => {turnItems: [backgroundItem],}),).toMatchObject({ status: "failed", activeRunId: null });+ const commandItem = {+ ...backgroundItem,+ id: TurnItemId.make("item-background-command"),+ type: "command_execution" as const,+ input: "npm run dev",+ };+ expect(+ deriveThreadRuntime({ ...v2Projection, runs: [run], turnItems: [commandItem] }),+ ).toMatchObject({ status: "waiting", activeRunId: null });++ for (const [turnItems, status] of [+ [[commandItem], "completed"],+ [[backgroundItem], "idle"],+ [[commandItem, backgroundItem], "idle"],+ ] as const) {+ expect(+ deriveThreadRuntime({+ ...v2Projection,+ runs: [{ ...run, status: "completed", completedAt: now }],+ turnItems,+ }),+ ).toMatchObject({ status, activeRunId: null });+ }++ for (const kind of ["monitor", "background_task"] as const) {+ const providerThread = {+ id: ProviderThreadId.make("provider-thread-background"),+ driver: ProviderDriverKind.make("claudeCode"),+ providerInstanceId: v2Projection.thread.providerInstanceId,+ providerSessionId: null,+ appThreadId: v2Projection.thread.id,+ ownerNodeId: null,+ nativeThreadRef: null,+ nativeConversationHeadRef: null,+ status: "idle" as const,+ firstRunOrdinal: 1,+ lastRunOrdinal: 1,+ handoffIds: [],+ forkedFrom: null,+ pendingBackgroundTasks: [{ taskId: "background-task", kind }],+ createdAt: now,+ updatedAt: now,+ };+ for (const status of ["completed", "failed"] as const) {+ expect(+ deriveThreadRuntime({+ ...v2Projection,+ runs: [{ ...run, status, completedAt: now }],+ providerThreads: [providerThread],+ }),+ ).toMatchObject({ status: status === "failed" ? "failed" : "idle", activeRunId: null });+ }+ }});it("joins pending request entities to their native turn-item display data", () => {diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex 37b7b5b8e30..dc74aff6ff5 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -1,3 +1,4 @@+import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";import type {ThreadLinkedPullRequest,@@ -159,15 +160,19 @@ function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {);}-// Park runtime at idle when the post-settlement background roster is nonempty-// so #4415 waiting-presentation Waiting (session.idle) can consume CTM runtime.+// Park runtime at idle when the post-settlement background roster holds the+// run's completion, so #4415 waiting-presentation Waiting (session.idle) can+// consume CTM runtime. Only work that wakes the agent holds it: commands it+// left running, such as a dev server, present the run's own status (#14872).// The server suppresses the roster while an interruptible activity run exists,// so a remaining roster is stronger than checkpoint-oriented waiting.// latestRun keeps the latest run's status for history presentation.// A failed latest run outranks the roster, so the failure stays visible.function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;- const parkAtIdle = (thread.pendingBackgroundTasks?.length ?? 0) > 0 && thread.status !== "failed";+ const parkAtIdle =+ backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&+ thread.status !== "failed";const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);return {status,diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.tsindex 51321d72267..a7722af0391 100644--- a/packages/client-runtime/src/state/threadExecution.ts+++ b/packages/client-runtime/src/state/threadExecution.ts@@ -236,18 +236,21 @@ export function deriveThreadRuntime(if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;const activeRunId =latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;- const hasPendingBackgroundTasks =+ // Same rule as the shell runtime: only background work that holds the+ // completion parks the thread at idle; a dev server left running does not.+ const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(derivePendingBackgroundWork({latestRun: latestRunProjection,providerThreads: projection.providerThreads,turnItems: projection.turnItems,activeProviderThreadId: projection.thread.activeProviderThreadId,runs: projection.runs,- }).length > 0;+ }),+ );return {status: usageLimitedRun? "failed"- : hasPendingBackgroundTasks && latestRunProjection?.status !== "failed"+ : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"? "idle": (activityRun?.status ?? "idle"),activeRunId,