Compare commits

...
Author SHA1 Message Date
maria-rcks 355a1c5985 fix(server): dedupe codex subagent item events 2026-08-06 22:56:22 -04:00
Theo BrowneandClaude Fable 5 6b73b3defe feat: paginate thread loading with user-anchored turn windows (#5493)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 19:33:49 -07:00
Theo Browne 7aad7911f6 fix(server): let stopped threads settle immediately (#5553) 2026-08-06 18:43:13 -07:00
Theo Browne 6da92244cc fix(web): show one toast when snoozing threads in bulk (#5560) 2026-08-06 18:16:36 -07:00
Theo BrowneandClaude Fable 5 c471145e96 fix(server): stopping a Claude thread no longer shows an ede_diagnostic error (#5557)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:55:20 -07:00
Theo Browne 64a991ad45 fix(web): show remote environment for non-Git projects (#5555) 2026-08-06 17:55:00 -07:00
Theo BrowneandClaude Fable 5 0ec4fbc4a3 fix(server): stop showing commit/push/PR notices as errors in the work log (#5559)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:52:29 -07:00
Theo BrowneandClaude Fable 5 ea50b695a7 fix(web): update tooltip no longer dismisses when scrolling release notes (#5547)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:31:12 -07:00
Theo BrowneandClaude Fable 5 331c6dce7f fix(server): skip origin fetch when creating worktrees in repos without an origin remote (#5556)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 20:13:10 -04:00
Wout Stiens 4f5834ba72 fix(web): clear woke state on explicit thread actions (#5486) 2026-08-06 14:08:35 -04:00
Wout Stiens aa16c180e5 fix(web): align composer inline chips with prompt text (#5495) 2026-08-06 12:57:02 -04:00
Carlos Rico-OspinaandClaude Opus 5 470d4eb993 fix(mobile): stop thread messages reading through pending cards (#5450)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-06 12:56:01 -04:00
t3-code[bot] 99d91ddaa4 fix(acp): keep unknown approvals actionable (#5430)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:31 -04:00
t3-code[bot] ab3b55e29a fix(web): clarify auto permission fallback (#5431)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:00 -04:00
Theo BrowneandClaude Fable 5 e4abc31f1e docs(server): pin interleaved-collapse divergence as intentional with test
Bugbot flagged that clients collapse only adjacent lifecycle rows, so
dropping a superseded update separated by an interleaved parallel call
diverges from full-history rendering. Measured on a real database: 1.5%
of dropped rows (553/36,581), all pure in-flight state whose final result
the retained completion still shows, and zero dropped rows carry a
client-merged payload field their completion lacks (verified across all
49,515 update rows). Documents the tradeoff and adds a test pinning it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:24:08 -04:00
Theo BrowneandClaude Fable 5 b7d1981b57 fix(server): drop superseded tool updates from snapshots
A tool.updated row is the in-flight snapshot of a call; once the call
completes, the tool.completed row carries the final state and both
clients fold every matching update into it. Shipping the updates buys
nothing: 47k such rows exist in one real database, and a single thread
carries 3,291 of them.

Filter them out of thread snapshots, mirroring the existing
context-window dedup. Matching is per turn and only against a LATER
completion, so a revert that discards the completing turn cannot leave
a call unrepresented, and a later update under the same identity (the
next call, still in flight) survives. Live events are untouched.

Rows are matched on the same identity the clients collapse by: an
explicit data.toolCallId when the adapter emits one, otherwise the
itemType/title/detail triple. No tool lifecycle row in the real db
carries a toolCallId, so the fallback does the work.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:24:08 -04:00
Theo Browne 64a3cd6d7d fix(server): separate trial cleanup from handoff retention 2026-08-06 08:09:51 -04:00
Theo Browne 48e2c27f2f fix(web): make update version tooltips accessible 2026-08-06 08:09:51 -04:00
Theo Browne 8b2ea5721a fix(server): order explicit service shutdown 2026-08-06 08:09:51 -04:00
Theo Browne df2f1273e9 fix(server): clean up interrupted update trials 2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 f9e8236899 fix(server): release the tunnel when an explicit stop interrupts an update
A pending update in the launcher state is not proof a replacement
server is coming: `t3 service uninstall` or `systemctl stop` during
the pending window also tears the server down, permanently. The
launcher now writes a stop marker before signalling its child on an
explicit stop and clears it on the next start; the shutdown tunnel
release keeps the tunnel only for pending updates without the marker.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 8f341f20c9 test(server): use the launcher state writer in release tests
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 808d685355 fix(server): keep the managed tunnel across remote update restarts
Measured on a live update: the server was back in ~9s but stayed
unreachable for ~96s, because releasing the tunnel on shutdown forces
the replacement tunnel's hostname route through 1-2 minutes of edge
propagation. An update handoff always brings a server right back
(new version or rollback), so the tunnel is never orphaned; skip the
release when the launcher state file records a pending update. The
next boot respawns the connector from the stored config against the
same tunnel and is reachable as soon as it connects.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 80720ad592 fix(web): calm one-row server update status and banner
The version-skew banner is no longer an amber warning: it reads
"Server update available" with the raw versions (unreadable for
nightlies) moved to a tooltip. The in-flight rail (Download/Install/
Resume) becomes a single status row, "Downloading…" then
"Restarting…", since the wire installing stage is a sub-second
launcher handoff and "resuming" meant nothing to most people.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Hugo Blom a483337a02 fix: respect time format for sidebar snooze (#4438) 2026-08-06 11:40:58 +02:00
Theo BrowneandClaude Fable 5 1ffba7093a fix(web): closed plan sidebar stays closed when returning to a thread (#5484)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:37:27 -07:00
Theo BrowneandClaude Fable 5 3da315e7b5 perf(server): stop shipping full MCP tool results in thread payloads (#5482)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:34:27 -07:00
Theo BrowneandClaude Fable 5 a2ca89aa10 feat: native subagent & workflow observability (#5219)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 00:32:28 -04:00
Theo BrowneandClaude Fable 5 990bb0b689 fix: reconnect faster after remote server updates (#5404)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-05 19:12:52 -07:00
100 changed files with 10802 additions and 497 deletions

No files matched your search

@@ -17,7 +17,10 @@ import * as Schema from "effect/Schema";
import * as MobileDatabase from "../persistence/mobile-database";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
// makes pre-pagination clients discard the record instead of decoding a
// partial thread as complete (rollback safety).
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
@@ -14,8 +14,10 @@ export interface PendingApprovalCardProps {
}
export function PendingApprovalCard(props: PendingApprovalCardProps) {
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
// behind this card, so a translucent surface bleeds messages through it.
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
@@ -24,8 +24,11 @@ export interface PendingUserInputCardProps {
}
export function PendingUserInputCard(props: PendingUserInputCardProps) {
// The surface is opaque on purpose: the card floats over the thread feed
// with no blur behind it, so a translucent background renders the questions
// on top of whatever message happens to sit underneath.
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
@@ -61,6 +61,8 @@ export interface ThreadDetailScreenProps {
readonly connectionStateLabel: EnvironmentConnectionPhase;
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
@@ -371,6 +373,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
</View>
) : (
@@ -164,6 +164,11 @@ export interface ThreadFeedProps {
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: {
readonly loading: boolean;
readonly onLoadEarlier: () => void;
} | null;
}
function MessageAttachmentImage(props: {
@@ -1893,7 +1898,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
<>
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
{props.loadEarlier != null ? (
<Pressable
onPress={props.loadEarlier.onLoadEarlier}
disabled={props.loadEarlier.loading}
className="items-center py-2"
>
<Text className="text-xs text-foreground-secondary">
{props.loadEarlier.loading ? "Loading earlier turns…" : "Load earlier turns"}
</Text>
</Pressable>
) : null}
</>
}
contentContainerStyle={{
paddingTop: 12,
@@ -8,6 +8,10 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
import {
requestOlderThreadTurns,
threadHasOlderTurns,
} from "@t3tools/client-runtime/state/threads";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -190,6 +194,20 @@ function ThreadRouteContent(
useThreadSelection();
const selectedThreadDetailState = props.selectedThreadDetailState;
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
// "Load earlier turns" header state for windowed (paginated) thread loads.
const loadEarlierTurns = useMemo(() => {
if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
return null;
}
return {
loading:
selectedThreadDetailState.page._tag === "Some" &&
selectedThreadDetailState.page.value.loadingOlder,
onLoadEarlier: () => {
requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
},
};
}, [selectedThread, selectedThreadDetailState]);
const { selectedThreadCwd } = useSelectedThreadWorktree();
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
@@ -766,6 +784,7 @@ function ThreadRouteContent(
draftAttachments={composer.draftAttachments}
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
loadEarlier={loadEarlierTurns}
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
@@ -532,3 +532,39 @@ describe("buildThreadFeed", () => {
});
});
});
describe("quiet timeline: nested agents", () => {
it("keeps a nested agent's terminal row but hides its background work", () => {
const thread = makeThread({
id: ThreadId.make("thread-nested"),
projectId: ProjectId.make("project-1"),
title: "Nested agents",
activities: [
// A subagent's own shell: internal, covered by the owner's liveness.
makeActivity({
id: EventId.make("shell-done"),
kind: "task.completed",
summary: "Task completed",
createdAt: "2026-04-01T00:00:02.000Z",
payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },
}),
// A nested AGENT's completion: mobile has no Agents sheet, so this
// terminal row is the only signal it ever finished.
makeActivity({
id: EventId.make("nested-done"),
kind: "task.completed",
summary: "Task completed",
createdAt: "2026-04-01T00:00:03.000Z",
payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },
}),
],
});
const feed = buildThreadFeed(thread);
const ids = feed.flatMap((entry) =>
entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],
);
expect(ids).toContain("nested-done");
expect(ids).not.toContain("shell-done");
});
});
+93 -1
View File
@@ -80,6 +80,8 @@ interface WorkLogEntry {
interface DerivedWorkLogEntry extends WorkLogEntry {
activityKind: OrchestrationThreadActivity["kind"];
collapseKey?: string;
/** Grouping key for subagent lifecycle rows (one row per agent). */
taskId?: string;
}
type RawThreadFeedEntry =
@@ -235,6 +237,63 @@ function resolvePendingUserInputAnswer(
return normalizeDraftAnswer(draft?.selectedOptionLabel);
}
/** Codex children settle via task.updated (idle/failed/interrupted), never
* task.completed — these rows are mobile's only terminal signal for them. */
const MOBILE_TERMINAL_UPDATE_STATUSES: ReadonlySet<string> = new Set([
"idle",
"completed",
"failed",
"cancelled",
"interrupted",
]);
function isTerminalBypassUpdate(activity: OrchestrationThreadActivity): boolean {
if (activity.kind !== "task.updated") {
return false;
}
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
return (
payload?.timelineBypass === true &&
typeof payload.status === "string" &&
MOBILE_TERMINAL_UPDATE_STATUSES.has(payload.status)
);
}
/**
* Quiet-timeline guarantee (mirrors web's session-logic): agent-internal
* activity lives in the Agents sheet, not the work log. Terminal rows are
* kept — with no Agents surface on mobile they are the terminal signal
* (a surface that hides rows must keep its own terminal signal). That means
* task.completed (Claude) AND terminal bypassed task.updated (Codex, whose
* children never emit task.completed — review finding).
*/
function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
if (!payload) {
return false;
}
const isTerminalTaskRow = activity.kind === "task.completed" || isTerminalBypassUpdate(activity);
if (payload.timelineBypass === true && !isTerminalTaskRow) {
return true;
}
// agentId marks ownership, not "hide me": a NESTED AGENT's terminal row is
// the only signal mobile gets (no Agents sheet), so it stays. Only an
// agent's own background work (stamped "background") is internal — same
// rule as web (review finding: hiding on agentId alone dropped nested
// completions with no replacement UI).
const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
if (!ownedByAgent) {
return false;
}
return !(isTerminalTaskRow && payload.agentKind === "agent");
}
function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): DerivedWorkLogEntry[] {
@@ -243,9 +302,13 @@ function deriveWorkLogEntries(
for (const activity of ordered) {
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
// Terminal bypassed updates pass: Codex children's only terminal signal.
if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;
if (activity.kind === "tool.progress") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
if (isAgentInternalActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries);
@@ -271,7 +334,13 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
const commandPreview = extractToolCommand(payload);
const changedFiles = extractChangedFiles(payload);
const title = extractToolTitle(payload);
const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
// task.updated included: terminal bypassed updates (Codex children's only
// terminal signal) must carry task identity so they collapse per child
// instead of stacking anonymous "Task idle" rows.
const isTaskActivity =
activity.kind === "task.progress" ||
activity.kind === "task.completed" ||
activity.kind === "task.updated";
const taskSummary =
isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
? payload.summary
@@ -284,10 +353,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
? payload.detail
: null;
const taskLabel = taskSummary || taskDetailAsLabel;
const taskId =
isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0
? payload.taskId
: undefined;
const entry: DerivedWorkLogEntry = {
id: activity.id,
createdAt: activity.createdAt,
turnId: activity.turnId,
...(taskId ? { taskId } : {}),
label: taskLabel || activity.summary,
tone:
activity.kind === "task.progress"
@@ -352,7 +426,25 @@ function collapseDerivedWorkLogEntries(
entries: ReadonlyArray<DerivedWorkLogEntry>,
): DerivedWorkLogEntry[] {
const collapsed: DerivedWorkLogEntry[] = [];
// Subagent rows collapse by identity, not adjacency (quiet-timeline
// guarantee; mirrors web's session-logic).
const taskRowIndex = new Map<string, number>();
for (const entry of entries) {
const isTaskRow =
entry.taskId !== undefined &&
(entry.activityKind === "task.progress" ||
entry.activityKind === "task.completed" ||
entry.activityKind === "task.updated");
if (isTaskRow && entry.taskId !== undefined) {
const existingIndex = taskRowIndex.get(entry.taskId);
if (existingIndex !== undefined) {
collapsed[existingIndex] = mergeDerivedWorkLogEntries(collapsed[existingIndex]!, entry);
continue;
}
taskRowIndex.set(entry.taskId, collapsed.length);
collapsed.push(entry);
continue;
}
const previous = collapsed.at(-1);
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
@@ -50,6 +50,7 @@ import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityRe
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
@@ -305,7 +306,7 @@ export const makeOrchestrationIntegrationHarness = (
checkpointStoreLayer,
providerLayer,
RuntimeReceiptBusTest,
);
).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
+1
View File
@@ -22,6 +22,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
*/
export const RPC_REQUIRED_SCOPES = {
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
+1 -1
View File
@@ -31,7 +31,7 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
});
expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
expect(unit).toContain("KillMode=control-group");
expect(unit).toContain("KillMode=mixed");
expect(unit).not.toContain("versions/1.2.3");
});
+3 -1
View File
@@ -64,7 +64,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
"KillMode=control-group",
// Let the launcher mark an explicit stop before it signals the server.
// systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
"KillMode=mixed",
"Restart=always",
"RestartSec=5",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
+115
View File
@@ -1,7 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Tracer from "effect/Tracer";
import {
@@ -15,6 +18,14 @@ import { EnvironmentId } from "@t3tools/contracts";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfigModule from "../config.ts";
import { writeServiceState } from "../serviceLauncher.ts";
import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
type ServiceUpdateRecord,
} from "./serviceProtocol.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
@@ -24,6 +35,7 @@ import {
consumeCloudReplayGuards,
isSupportedLinkProviderKind,
linkProofScopes,
pendingServiceUpdateExists,
reconcileDesiredCloudLink,
releaseManagedTunnelOnShutdown,
} from "./http.ts";
@@ -256,6 +268,23 @@ describe("releaseManagedTunnelOnShutdown", () => {
readonly respond?: () => Response;
}
// Writes the launcher's durable state file into this test's baseDir with
// the launcher's own writer; the release reads it to detect an in-flight
// update handoff.
const writeLauncherState = (update: ServiceUpdateRecord) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const config = yield* ServerConfigModule.ServerConfig;
const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "0.0.30",
update,
}),
);
});
const provideReleaseHarness =
(harness: ReleaseHarness) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
@@ -306,6 +335,14 @@ describe("releaseManagedTunnelOnShutdown", () => {
}),
),
),
// The release consults the launcher state file under the configured
// baseDir, so every harness run gets a scoped temp baseDir.
Effect.provide(
ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
Layer.provideMerge(NodeServices.layer),
),
),
Effect.scoped,
);
// The persisted state of a CLI-managed link whose tunnel is releasable.
@@ -390,6 +427,84 @@ describe("releaseManagedTunnelOnShutdown", () => {
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
dbPath: "/tmp/state.sqlite",
status: "pending",
});
const released = yield* releaseManagedTunnelOnShutdown();
// The launcher restarts a server immediately, so the tunnel is not
// orphaned; keeping it avoids the hostname route re-propagation that
// dominates update downtime. The stored config must survive so the
// next boot respawns the connector against the same tunnel.
expect(released).toBe(false);
expect(applyConfigCalls).toEqual([]);
expect(requests).toEqual([]);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("still releases a pending update when the launcher is stopping", () => {
// `t3 service uninstall` or `systemctl stop` during the pending window:
// the launcher writes its stop marker before signalling the child, so no
// replacement server is coming and the tunnel must not be kept.
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
dbPath: "/tmp/state.sqlite",
status: "pending",
});
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfigModule.ServerConfig;
yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
expect(yield* pendingServiceUpdateExists).toBe(true);
const released = yield* releaseManagedTunnelOnShutdown();
expect(released).toBe(true);
expect(requests).toHaveLength(1);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("still releases when the recorded update already settled", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
status: "committed",
});
const released = yield* releaseManagedTunnelOnShutdown();
expect(released).toBe(true);
expect(requests).toHaveLength(1);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
+52
View File
@@ -46,7 +46,9 @@ import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
@@ -56,8 +58,14 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { requireEnvironmentScope } from "../auth/http.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import {
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
serviceStateHasPendingUpdate,
} from "./serviceProtocol.ts";
import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINKED_USER_ID,
@@ -627,6 +635,37 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
},
);
// The launcher owns this durable state, so read it directly both when a trial
// decides whether it owns pre-activation cleanup and while a server tears down.
export const pendingServiceUpdateExists = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runtimeDir = path.join(config.baseDir, "runtime");
const stateText = yield* fs
.readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
.pipe(Effect.option);
return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
});
// A pending update alone is not proof a replacement server is coming: an
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
// the pending window also tears this server down. The launcher marks that case
// just before it signals the child, so pending + no marker is the handoff.
const pendingUpdateHandoffExists = Effect.gen(function* () {
if (!(yield* pendingServiceUpdateExists)) {
return false;
}
const config = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runtimeDir = path.join(config.baseDir, "runtime");
const stopping = yield* fs
.exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
.pipe(Effect.orElseSucceed(() => false));
return !stopping;
});
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
// relay keeps the link and its hostname reservation, and the next startup's
@@ -649,6 +688,19 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
return false;
}
// A shutdown that hands off to a pending remote update is not the
// environment going offline: the launcher immediately brings a server back
// (the new version, or the old one after a rollback). Deleting the tunnel
// here forces that server to provision a replacement UUID, and the public
// hostname's route to the new tunnel takes 1-2 minutes to propagate — the
// dominant cost of an update restart. Keep the tunnel instead: the next
// boot respawns the connector from the stored config and is reachable as
// soon as it connects, and the reconcile confirms the still-live tunnel
// without replacing it.
if (yield* pendingUpdateHandoffExists) {
yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
return false;
}
const token = yield* dependencies.cliTokenManager.getExisting;
if (Option.isNone(token)) {
return false;
+4
View File
@@ -5,6 +5,10 @@ export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
export const SERVICE_STATE_FILE = "service-state.json";
/** Written by the launcher just before an explicit stop kills its child, so
the child can tell "the service is going away" from "the launcher is about
to start my replacement" while a pending update is recorded. */
export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
export interface PendingServiceUpdate {
readonly id: string;
@@ -69,6 +69,10 @@ export class GitWorkflowService extends Context.Service<
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<void, GitCommandError>;
readonly remoteExists: (input: {
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<boolean, GitCommandError>;
readonly resolveRemoteTrackingCommit: (input: {
readonly cwd: string;
readonly refName: string;
@@ -303,6 +307,10 @@ export const make = Effect.gen(function* () {
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
Effect.andThen(git.fetchRemote(input)),
),
remoteExists: (input) =>
ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
Effect.andThen(git.remoteExists(input)),
),
resolveRemoteTrackingCommit: (input) =>
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
@@ -0,0 +1,117 @@
import { describe, expect, it } from "vite-plus/test";
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
import { projectActivityPayload } from "./ActivityPayloadProjection.ts";
function activity(payload: Record<string, unknown>): OrchestrationThreadActivity {
return {
id: "activity-1",
tone: "tool",
kind: "tool.completed",
summary: "Tool",
payload,
turnId: null,
createdAt: "2026-08-01T10:00:00.000Z",
} as unknown as OrchestrationThreadActivity;
}
/**
* Wire-survival regression: the slimming pass rewrites payload.data but must
* never strip the top-level per-agent fields the subagent fold depends on.
* If slimming ever moves to an allowlist over the whole payload, these
* assertions are the tripwire.
*/
describe("projectActivityPayload agent-field survival", () => {
it("preserves tool attribution (agentId/parentToolUseId) through data slimming", () => {
const projected = projectActivityPayload(
activity({
itemType: "command_execution",
agentId: "task-123",
parentToolUseId: "toolu_abc",
data: {
toolName: "Bash",
input: { command: "ls" },
command: "ls",
rawOutput: { content: "x".repeat(10) },
somethingClientNeverReads: { big: "blob" },
},
}),
);
const payload = projected.payload as Record<string, unknown>;
expect(payload.agentId).toBe("task-123");
expect(payload.parentToolUseId).toBe("toolu_abc");
// Slimming itself still applies to data.
const data = payload.data as Record<string, unknown>;
expect(data.somethingClientNeverReads).toBeUndefined();
});
it("slims Codex-shaped mcp_tool_call items to rendered fields plus a result summary", () => {
const projected = projectActivityPayload(
activity({
itemType: "mcp_tool_call",
data: {
item: {
type: "mcpToolCall",
id: "item-1",
tool: "fetch_pr",
server: "github",
status: "completed",
arguments: { pr: 42 },
durationMs: 1200,
result: {
content: [{ type: "text", text: `PR body line one\n${"x".repeat(5000)}` }],
structuredContent: { huge: "y".repeat(5000) },
},
_meta: { internal: true },
},
},
}),
);
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
const item = data.item as Record<string, unknown>;
expect(item.tool).toBe("fetch_pr");
expect(item.server).toBe("github");
expect(item.arguments).toEqual({ pr: 42 });
expect(item._meta).toBeUndefined();
expect(item.result).toEqual({ content: "PR body line one" });
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
});
it("slims Claude-shaped mcp_tool_call data (toolName/input/result block)", () => {
const projected = projectActivityPayload(
activity({
itemType: "mcp_tool_call",
data: {
toolName: "mcp__github__fetch_pr",
input: { pr: 42 },
result: {
type: "tool_result",
tool_use_id: "toolu_1",
content: [{ type: "text", text: `first line of output\n${"z".repeat(5000)}` }],
},
},
}),
);
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
expect(data.toolName).toBe("mcp__github__fetch_pr");
expect(data.input).toEqual({ pr: 42 });
expect(data.result).toEqual({ content: "first line of output" });
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
});
it("passes task lifecycle payloads (no data field) through untouched", () => {
const source = activity({
taskId: "task-9",
title: "Audit auth",
role: "explorer",
model: "opus",
effort: "high",
workflowName: "audit-flow",
phases: [{ index: 0, title: "Audit" }],
typedUsage: { totalTokens: 1200 },
runHandles: { runId: "run-1", scriptPath: "/tmp/wf.js" },
timelineBypass: true,
});
const projected = projectActivityPayload(source);
expect(projected.payload).toEqual(source.payload);
});
});
@@ -123,6 +123,114 @@ function summarizeToolTextOutput(value: string): string | null {
return null;
}
/**
* Fields of an MCP tool-call item both clients render in the expanded
* work-log row. Everything else — notably `result`, which carries the full
* tool output and dominates wire size on MCP-heavy threads — is summarized
* or dropped. Full payloads remain in persistence.
*/
const MCP_ITEM_KEPT_FIELDS = [
"type",
"id",
"tool",
"server",
"status",
"arguments",
"appContext",
"error",
"durationMs",
] as const;
/**
* Pulls renderable text out of an MCP tool result: either a Codex-style
* `{content: [{type: "text", text}, ...]}` record or a raw Claude
* `tool_result` block whose `content` is a string or block array.
*/
function extractMcpResultText(result: unknown): string | null {
const record = asRecord(result);
if (!record) {
return typeof result === "string" ? result : null;
}
if (typeof record.content === "string") {
return record.content;
}
if (Array.isArray(record.content)) {
const texts: string[] = [];
for (const entry of record.content) {
const text = asRecord(entry)?.text;
if (typeof text === "string" && text.trim().length > 0) {
texts.push(text);
}
}
if (texts.length > 0) {
return texts.join("\n");
}
}
return null;
}
function summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {
if (result === undefined || result === null) {
return undefined;
}
const text = extractMcpResultText(result);
const summary = text ? summarizeToolTextOutput(text) : null;
return summary ? { content: summary } : undefined;
}
/**
* MCP tool calls carry full tool results (`data.item.result` on Codex,
* `data.result` on Claude/OpenCode) that used to bypass slimming entirely to
* keep the expanded-row UI working. Keep the fields the UI actually renders
* and summarize the result like regular tool output.
*/
function projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {
const projectedData: Record<string, unknown> = {};
const item = asRecord(data.item);
if (item) {
const projectedItem: Record<string, unknown> = {};
for (const key of MCP_ITEM_KEPT_FIELDS) {
if (key in item) {
projectedItem[key] = item[key];
}
}
const result = summarizeMcpResult(item.result);
if (result) {
projectedItem.result = result;
}
projectedData.item = projectedItem;
}
if ("toolName" in data) {
projectedData.toolName = data.toolName;
}
if ("input" in data) {
projectedData.input = data.input;
}
if (!item) {
const result = summarizeMcpResult(data.result);
if (result) {
projectedData.result = result;
}
}
if ("toolCallId" in data) {
projectedData.toolCallId = data.toolCallId;
}
if ("kind" in data) {
projectedData.kind = data.kind;
}
const changedFiles: string[] = [];
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
if (changedFiles.length > 0) {
projectedData.files = changedFiles.map((path) => ({ path }));
}
return projectedData;
}
function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
const rawOutput = asRecord(value);
if (!rawOutput) {
@@ -160,10 +268,20 @@ export function projectActivityPayload(
): OrchestrationThreadActivity {
const payload = asRecord(activity.payload);
const data = asRecord(payload?.data);
if (!payload || !data || payload.itemType === "mcp_tool_call") {
if (!payload || !data) {
return activity;
}
if (payload.itemType === "mcp_tool_call") {
return {
...activity,
payload: {
...payload,
data: projectMcpToolCallData(data),
},
};
}
const projectedData: Record<string, unknown> = {};
const item = projectCommandData(data);
if (item) {
@@ -247,6 +365,107 @@ function dropStaleContextWindowActivities(
);
}
/**
* Identity both clients use to fold a tool lifecycle row into the call it
* belongs to (`deriveToolLifecycleCollapseKey` in web's `session-logic` and
* mobile's `threadActivity`): an explicit `data.toolCallId` when the adapter
* emits one, otherwise the itemType/title/detail triple. Returns null for rows
* with no identity at all — those never collapse on the client either, so they
* must not be dropped here.
*/
function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {
const payload = asRecord(activity.payload);
if (!payload) {
return null;
}
const toolCallId = asTrimmedString(asRecord(payload.data)?.toolCallId);
if (toolCallId) {
return `id:${toolCallId}`;
}
const itemType = asTrimmedString(payload.itemType) ?? "";
// Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may
// gain a trailing "complete"/"completed" the in-flight updates lack.
const label = (asTrimmedString(payload.title) ?? activity.summary)
.replace(/\s+(?:complete|completed)\s*$/iu, "")
.trim();
const detail = asTrimmedString(payload.detail) ?? "";
if (itemType.length === 0 && label.length === 0 && detail.length === 0) {
return null;
}
return [itemType, label, detail].join("");
}
/**
* Drops `tool.updated` rows a `tool.completed` row already supersedes. An
* update is the in-flight snapshot of a call; once the call completes, the
* completion carries the final state and the clients fold every matching
* update into it, so shipping the updates buys nothing — 47k such rows exist
* in one real database, and a single thread carries 2,291 of them totalling
* ~1MB post-slimming.
*
* Matching is per turn for the same reason `dropStaleContextWindowActivities`
* retains per turn: a live `thread.reverted` makes the client discard whole
* turns, so a completion in a different turn could vanish and leave the
* dropped update unrepresented. The completion must also come *after* the
* update within the turn — a later update belongs to a subsequent call that
* reuses the same identity and is still in flight. Rows without a lifecycle
* identity pass through, matching the clients, which never collapse them.
* Live `thread.activity-appended` events are untouched: updates still stream
* in real time and the completion supersedes them on the client as before.
*
* Deliberate divergence from client collapse: clients fold only *adjacent*
* lifecycle rows, so a superseded update separated from its completion by an
* interleaved parallel call renders as its own row today, and this drop
* removes it. Measured against a real database, that affects 1.5% of dropped
* rows (553 of 36,581), all pure in-flight state whose final result the
* retained completion still shows. Dropping them is intentional; matching
* adjacency server-side would forfeit most of the win for parallel-heavy
* threads, which are exactly the heavy ones. Superseding completions always
* carry a payload superset of their updates (verified across all 49,515
* update rows: zero dropped rows held a client-merged field — detail, title,
* command, item, kind, files — their completion lacked), so no expanded-row
* content is lost.
*/
function dropSupersededToolUpdatedActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const completionIndicesByKey = new Map<string, number[]>();
for (let index = 0; index < activities.length; index += 1) {
const activity = activities[index]!;
if (activity.kind !== "tool.completed") {
continue;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
continue;
}
const key = `${activity.turnId ?? ""}${identity}`;
const indices = completionIndicesByKey.get(key);
if (indices) {
indices.push(index);
} else {
completionIndicesByKey.set(key, [index]);
}
}
if (completionIndicesByKey.size === 0) {
return activities;
}
return activities.filter((activity, index) => {
if (activity.kind !== "tool.updated") {
return true;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
return true;
}
const indices = completionIndicesByKey.get(`${activity.turnId ?? ""}${identity}`);
return !indices?.some((completionIndex) => completionIndex > index);
});
}
export function projectThreadDetailSnapshot(
snapshot: OrchestrationThreadDetailSnapshot,
): OrchestrationThreadDetailSnapshot {
@@ -254,9 +473,9 @@ export function projectThreadDetailSnapshot(
...snapshot,
thread: {
...snapshot.thread,
activities: dropStaleContextWindowActivities(snapshot.thread.activities).map(
projectActivityPayload,
),
activities: dropSupersededToolUpdatedActivities(
dropStaleContextWindowActivities(snapshot.thread.activities),
).map(projectActivityPayload),
},
};
}
@@ -39,6 +39,7 @@ import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -294,6 +295,7 @@ describe("CheckpointReactor", () => {
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -301,6 +303,7 @@ describe("CheckpointReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -31,6 +31,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
@@ -55,6 +56,7 @@ async function createOrchestrationSystem() {
),
OrchestrationProjectionSnapshotQueryLive,
).pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolver.layer),
@@ -817,6 +819,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -922,6 +925,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -1065,6 +1069,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -31,6 +31,7 @@ import {
OrchestrationProjectionPipelineLive,
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -1429,6 +1430,13 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
const threadRows = yield* sql<{ readonly latestTurnId: string | null }>`
SELECT latest_turn_id AS "latestTurnId"
FROM projection_threads
WHERE thread_id = ${threadId}
`;
assert.deepEqual(threadRows, [{ latestTurnId: turnId }]);
}),
);
@@ -2664,6 +2672,7 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -850,7 +850,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
latestTurnId: event.payload.session.activeTurnId,
// activeTurnId describes current work; a terminal session must not erase history.
latestTurnId: event.payload.session.activeTurnId ?? existingRow.value.latestTurnId,
updatedAt: event.occurredAt,
});
yield* refreshThreadShellSummary(event.payload.threadId);
@@ -17,7 +17,9 @@ import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { encodeThreadDetailPageCursor } from "../threadDetailCursor.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
@@ -27,6 +29,7 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(val
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
@@ -443,6 +446,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
backgroundLiveness: null,
},
]);
@@ -1825,6 +1829,7 @@ it.effect(
() => {
const resolveCalls: string[] = [];
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provideMerge(
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
resolve: (cwd: string) =>
@@ -1913,3 +1918,407 @@ it.effect(
}).pipe(Effect.provide(layer));
},
);
projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) => {
// A thread shaped like real fan-out usage: user turns interleaved with
// subagent turns (no user pending message), plus a turnless straggler user
// message and a turnless activity anchored between turns.
//
// row turn pending msg anchor (requested_at)
// 1 turn-1 user-msg-1 T00
// 2 turn-2 (subagent) T01
// 3 turn-3 (subagent) T02
// 4 turn-4 user-msg-4 T03
// 5 turn-5 user-msg-5 T04
//
// Straggler user message at T03.5 (turn_id NULL, not any pending_message_id)
// and a turnless activity at T03.6 — both belong to the page containing T03+.
const seedFanOutThread = Effect.fnUntraced(function* () {
const sql = yield* SqlClient.SqlClient;
// Tests in this block share one in-memory database; reset before seeding.
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at
)
VALUES ('project-w', 'Windowed', '/tmp/project-w', '[]',
'2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
latest_turn_id, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, deleted_at
)
VALUES ('thread-w', 'project-w', 'Windowed thread',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
'turn-5', 0, 0, 0, '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:10.000Z', NULL)
`;
const turns: ReadonlyArray<{
turn: string;
pendingMessage: string | null;
at: string;
}> = [
{ turn: "turn-1", pendingMessage: "user-msg-1", at: "2026-03-01T00:00:00.000Z" },
{ turn: "turn-2", pendingMessage: null, at: "2026-03-01T00:01:00.000Z" },
{ turn: "turn-3", pendingMessage: null, at: "2026-03-01T00:02:00.000Z" },
{ turn: "turn-4", pendingMessage: "user-msg-4", at: "2026-03-01T00:03:00.000Z" },
{ turn: "turn-5", pendingMessage: "user-msg-5", at: "2026-03-01T00:04:00.000Z" },
];
for (const { turn, pendingMessage, at } of turns) {
yield* sql`
INSERT INTO projection_turns (
thread_id, turn_id, pending_message_id, state, requested_at, started_at, completed_at,
checkpoint_files_json
)
VALUES ('thread-w', ${turn}, ${pendingMessage}, 'completed', ${at}, ${at}, ${at}, '[]')
`;
if (pendingMessage !== null) {
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES (${pendingMessage}, 'thread-w', NULL, 'user', ${"prompt for " + turn}, 0, ${at}, ${at})
`;
}
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES (${turn + "-reply"}, 'thread-w', ${turn}, 'assistant', ${"reply from " + turn}, 0, ${at}, ${at})
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
)
VALUES (${turn + "-activity"}, 'thread-w', ${turn}, 'tool', 'tool.completed',
'ran tool', '{"ok":true}', ${at})
`;
}
// Straggler user message sent while turn-4 ran: turn_id NULL and not any
// turn's pending_message_id.
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES ('user-msg-straggler', 'thread-w', NULL, 'user', 'while you are at it',
0, '2026-03-01T00:03:30.000Z', '2026-03-01T00:03:30.000Z')
`;
// Turnless activity in the same time range.
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
)
VALUES ('turnless-activity', 'thread-w', NULL, 'info', 'context-window.updated',
'usage', '{"usedTokens":1}', '2026-03-01T00:03:36.000Z')
`;
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES (${projector}, 42, '2026-03-01T00:00:10.000Z')
`;
}
});
const threadW = ThreadId.make("thread-w");
const messageIds = (snapshot: { thread: { messages: ReadonlyArray<{ id: string }> } }) =>
snapshot.thread.messages.map((message) => message.id).toSorted();
const activityIds = (snapshot: { thread: { activities: ReadonlyArray<{ id: string }> } }) =>
snapshot.thread.activities.map((activity) => activity.id).toSorted();
it.effect("returns the full thread with no page metadata when no window is requested", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW);
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.page, undefined);
assert.equal(snapshot.value.thread.messages.length, 9);
assert.equal(snapshot.value.thread.activities.length, 6);
assert.equal(snapshot.value.snapshotSequence, 42);
}
}),
);
it.effect("windows to the last N user-anchored turns with subagent turns riding along", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// turnLimit 2 walks back: turn-5 (user), turn-4 (user) -> window is
// rows 4..5. Subagent turns 2-3 are older than the 2nd user turn and
// stay out; the straggler message and turnless activity (T03.5/T03.6,
// after turn-4's anchor) ride along.
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), [
"turn-4-reply",
"turn-5-reply",
"user-msg-4",
"user-msg-5",
"user-msg-straggler",
]);
assert.deepEqual(activityIds(snapshot.value), [
"turn-4-activity",
"turn-5-activity",
"turnless-activity",
]);
assert.equal(snapshot.value.page?.hasMore, true);
assert.notEqual(snapshot.value.page?.beforeCursor, null);
assert.equal(snapshot.value.page?.snapshotSequence, 42);
}
}),
);
it.effect("subagent turns between user turns ride along inside the window", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// turnLimit 3 reaches user turn-1, dragging subagent turns 2-3 along:
// the full thread, so no further pages.
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 3 });
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.thread.messages.length, 9);
assert.equal(snapshot.value.thread.activities.length, 6);
assert.equal(snapshot.value.page?.hasMore, false);
assert.equal(snapshot.value.page?.beforeCursor, null);
}
}),
);
it.effect("cursors survive a projection rewrite that reassigns turn row ids", () =>
Effect.gen(function* () {
// The revert projector (and any projection rebuild) deletes and
// re-upserts projection_turns, assigning fresh autoincrement row ids.
// The keyset cursor is derived from event content, so a page cursor
// minted before the rewrite must keep working after it.
yield* seedFanOutThread();
const sql = yield* SqlClient.SqlClient;
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const cursor = firstPage.value.page?.beforeCursor;
assert.notEqual(cursor, null);
if (cursor === null || cursor === undefined) return;
// Simulate the rewrite: delete and re-insert every turn row with the
// same content, which reassigns all row ids.
const turnRows = yield* sql`
SELECT thread_id, turn_id, pending_message_id, state, requested_at, started_at,
completed_at, checkpoint_files_json
FROM projection_turns WHERE thread_id = 'thread-w' ORDER BY row_id
`;
yield* sql`DELETE FROM projection_turns WHERE thread_id = 'thread-w'`;
for (const row of turnRows) {
yield* sql`
INSERT INTO projection_turns (
thread_id, turn_id, pending_message_id, state, requested_at, started_at,
completed_at, checkpoint_files_json
)
VALUES (${row.thread_id as string}, ${row.turn_id as string},
${row.pending_message_id as string | null}, ${row.state as string},
${row.requested_at as string}, ${row.started_at as string},
${row.completed_at as string}, ${row.checkpoint_files_json as string})
`;
}
const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
beforeCursor: cursor,
});
assert.equal(olderPage._tag, "Some");
if (olderPage._tag === "Some") {
// Identical older slice to what the pre-rewrite cursor would return.
assert.deepEqual(messageIds(olderPage.value), [
"turn-1-reply",
"turn-2-reply",
"turn-3-reply",
"user-msg-1",
]);
assert.equal(olderPage.value.page?.hasMore, false);
}
}),
);
it.effect("beforeCursor returns the disjoint adjacent older slice", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const cursor = firstPage.value.page?.beforeCursor;
assert.notEqual(cursor, null);
assert.notEqual(cursor, undefined);
if (cursor === null || cursor === undefined) return;
// Older page: user turn-1 plus subagent turns 2-3 riding along. Disjoint
// from the first page: no turn-4/5 rows, no straggler.
const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
beforeCursor: cursor,
});
assert.equal(olderPage._tag, "Some");
if (olderPage._tag === "Some") {
assert.deepEqual(messageIds(olderPage.value), [
"turn-1-reply",
"turn-2-reply",
"turn-3-reply",
"user-msg-1",
]);
assert.deepEqual(activityIds(olderPage.value), [
"turn-1-activity",
"turn-2-activity",
"turn-3-activity",
]);
assert.equal(olderPage.value.page?.hasMore, false);
assert.equal(olderPage.value.page?.beforeCursor, null);
}
}),
);
it.effect("a cursor for a different thread degrades to the first page", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const foreign = encodeThreadDetailPageCursor({
threadId: ThreadId.make("thread-other"),
beforeAnchorAt: "2026-03-01T00:01:00.000Z",
beforeTurnId: "turn-2",
});
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 2,
beforeCursor: foreign,
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), messageIds(firstPage.value));
}
}),
);
it.effect("a malformed cursor degrades to the first page instead of failing", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 2,
beforeCursor: "not-a-cursor",
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.page?.hasMore, true);
assert.equal(snapshot.value.thread.messages.length, 5);
}
}),
);
it.effect("windows never split below the raw-turn ceiling boundary contiguously", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// Page repeatedly with turnLimit 1 and assert the union of all pages is
// exactly the full thread with no duplicates (disjointness + coverage).
const seenMessages: string[] = [];
const seenActivities: string[] = [];
let cursor: string | undefined;
for (let page = 0; page < 10; page += 1) {
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
...(cursor !== undefined ? { beforeCursor: cursor } : {}),
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag !== "Some") return;
seenMessages.push(...snapshot.value.thread.messages.map((message) => message.id));
seenActivities.push(...snapshot.value.thread.activities.map((activity) => activity.id));
const next = snapshot.value.page?.beforeCursor;
if (next === null || next === undefined) break;
cursor = next;
}
assert.equal(new Set(seenMessages).size, seenMessages.length);
assert.equal(new Set(seenActivities).size, seenActivities.length);
assert.equal(seenMessages.length, 9);
assert.equal(seenActivities.length, 6);
}),
);
it.effect("a thread with no turns returns its content unwindowed on the first page", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const snapshotQuery = yield* ProjectionSnapshotQuery;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at
)
VALUES ('project-e', 'Empty', '/tmp/project-e', '[]',
'2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
pending_approval_count, pending_user_input_count, has_actionable_proposed_plan,
created_at, updated_at, deleted_at
)
VALUES ('thread-e', 'project-e', 'Turnless thread',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
0, 0, 0, '2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES ('pre-turn-msg', 'thread-e', NULL, 'user', 'first prompt', 0,
'2026-03-02T00:00:01.000Z', '2026-03-02T00:00:01.000Z')
`;
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES (${projector}, 7, '2026-03-02T00:00:01.000Z')
`;
}
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(ThreadId.make("thread-e"), {
turnLimit: 5,
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), ["pre-turn-msg"]);
assert.equal(snapshot.value.page?.hasMore, false);
assert.equal(snapshot.value.page?.beforeCursor, null);
}
}),
);
});
@@ -43,6 +43,7 @@ import {
type ProjectionRepositoryError,
} from "../../persistence/Errors.ts";
import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";
import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
@@ -50,6 +51,10 @@ import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionTh
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
import {
decodeThreadDetailPageCursor,
encodeThreadDetailPageCursor,
} from "../threadDetailCursor.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
@@ -129,6 +134,36 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
// Windowed reads order turns by the stable keyset (anchor, turn key), where
// anchor is requested_at and turn key is
// COALESCE(turn_id, ''). Both are event-derived, so cursors survive the
// revert projector's row-id rewrite and full projection rebuilds.
const ThreadTurnWindowLookupInput = Schema.Struct({
threadId: ThreadId,
// Exclusive keyset upper bound. Sentinels "~"/"" mean unbounded ("~" sorts
// after every ISO timestamp).
beforeAnchorAt: Schema.String,
beforeTurnKey: Schema.String,
userTurnLimit: Schema.Number,
maxRawTurns: Schema.Number,
});
const ProjectionTurnWindowRowSchema = Schema.Struct({
// The turn's timeline anchor, used to bound rows that have no turn linkage
// (user messages and turnless activities) to the same page window.
anchorAt: Schema.String,
turnKey: Schema.String,
});
const ThreadTurnRangeLookupInput = Schema.Struct({
threadId: ThreadId,
// Turn-linked rows are bounded by the keyset range [min, before) over
// (anchor, turn key); turnless rows by the matching [minAnchorAt,
// beforeAnchorAt) time range. Unbounded ends use sentinels: "" for the
// lower bound, "~" (sorts after ISO dates) for the upper bound.
minAnchorAt: Schema.String,
minTurnKey: Schema.String,
beforeAnchorAt: Schema.String,
beforeTurnKey: Schema.String,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -308,6 +343,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
}
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const sql = yield* SqlClient.SqlClient;
const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
const repositoryIdentityResolutionConcurrency = 4;
@@ -1041,6 +1077,197 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Resolves a page of recent turns for a windowed thread detail read. Walks
// back from the exclusive (beforeAnchorAt, beforeTurnKey) keyset boundary
// (sentinels "~"/"" mean unbounded, i.e. the first page) until it has seen
// `userTurnLimit` user-anchored turns — turns whose pending message is a
// user message; subagent/fan-out turns between them ride along — or hits the
// `maxRawTurns` ceiling that bounds pathological fan-out. The `candidates`
// CTE applies the keyset bound and LIMIT before the window functions run;
// its ORDER BY uses raw columns so the migration-037
// (thread_id, requested_at, turn_id) index serves both range and order with
// no temp B-tree — the scan is genuinely bounded by the LIMIT. (Raw
// turn_id DESC places NULLs exactly where COALESCE-to-'' would, below every
// real id.) The caller derives the continuation cursor from the oldest
// returned row.
// Highest thread-DETAIL event sequence for this thread that the projection
// has applied (bounded by the global snapshot sequence read in the same
// transaction). This is the thread-scoped watermark a windowed page carries
// so clients can defer merging until their live subscription has caught up;
// the global sequence is not waitable per-thread. The event_type filter
// must match ws.ts's isThreadDetailEvent exactly: the subscription only
// delivers these types, so a watermark counting any other event could
// never be reached by the client and would park the page forever. Served
// by the event store's (aggregate_kind, stream_id, sequence) index.
const getThreadEventWatermarkRow = SqlSchema.findOneOption({
Request: Schema.Struct({ threadId: ThreadId, maxSequence: Schema.Number }),
Result: Schema.Struct({ threadSequence: Schema.NullOr(Schema.Number) }),
execute: ({ threadId, maxSequence }) =>
sql`
SELECT MAX(sequence) AS "threadSequence"
FROM orchestration_events
WHERE aggregate_kind = 'thread'
AND stream_id = ${threadId}
AND sequence <= ${maxSequence}
AND event_type IN (
'thread.message-sent',
'thread.proposed-plan-upserted',
'thread.activity-appended',
'thread.turn-diff-completed',
'thread.reverted',
'thread.session-set'
)
`,
});
const listTurnWindowRows = SqlSchema.findAll({
Request: ThreadTurnWindowLookupInput,
Result: ProjectionTurnWindowRowSchema,
execute: ({ threadId, beforeAnchorAt, beforeTurnKey, userTurnLimit, maxRawTurns }) =>
sql`
WITH candidates AS (
SELECT
turns.requested_at AS anchor_at,
COALESCE(turns.turn_id, '') AS turn_key,
turns.pending_message_id
FROM projection_turns AS turns
WHERE turns.thread_id = ${threadId}
AND (
turns.requested_at < ${beforeAnchorAt}
OR (
turns.requested_at = ${beforeAnchorAt}
AND COALESCE(turns.turn_id, '') < ${beforeTurnKey}
)
)
ORDER BY turns.requested_at DESC, turns.turn_id DESC
LIMIT ${maxRawTurns}
),
walked AS (
SELECT
candidates.anchor_at,
candidates.turn_key,
CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END AS is_user_turn,
SUM(CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END) OVER (
ORDER BY candidates.anchor_at DESC, candidates.turn_key DESC
) AS user_turns_seen
FROM candidates
LEFT JOIN projection_thread_messages AS messages
ON messages.message_id = candidates.pending_message_id
)
SELECT
anchor_at AS "anchorAt",
turn_key AS "turnKey"
FROM walked
WHERE user_turns_seen < ${userTurnLimit}
OR (user_turns_seen = ${userTurnLimit} AND is_user_turn = 1)
ORDER BY anchor_at ASC, turn_key ASC
`,
});
// Windowed variants of the two heavy collections. Turn-linked rows are
// bounded by the page's (anchor, turn key) keyset range over
// projection_turns; rows with no turn linkage (user messages always, and
// turnless activities like pre-turn context-window updates) are bounded by
// the matching turn-anchor time range so they land on the same page as the
// turns around them. Proposed plans and checkpoints stay unwindowed: they
// are metadata-scale.
const listThreadMessageRowsByThreadWindow = SqlSchema.findAll({
Request: ThreadTurnRangeLookupInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE thread_id = ${threadId}
AND (
turn_id IN (
SELECT turn_id FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NOT NULL
AND (
requested_at > ${minAnchorAt}
OR (
requested_at = ${minAnchorAt}
AND turn_id >= ${minTurnKey}
)
)
AND (
requested_at < ${beforeAnchorAt}
OR (
requested_at = ${beforeAnchorAt}
AND turn_id < ${beforeTurnKey}
)
)
)
OR (
turn_id IS NULL
AND created_at >= ${minAnchorAt}
AND created_at < ${beforeAnchorAt}
)
)
ORDER BY created_at ASC, message_id ASC
`,
});
const listThreadActivityRowsByThreadWindow = SqlSchema.findAll({
Request: ThreadTurnRangeLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND (
turn_id IN (
SELECT turn_id FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NOT NULL
AND (
requested_at > ${minAnchorAt}
OR (
requested_at = ${minAnchorAt}
AND turn_id >= ${minTurnKey}
)
)
AND (
requested_at < ${beforeAnchorAt}
OR (
requested_at = ${beforeAnchorAt}
AND turn_id < ${beforeTurnKey}
)
)
)
OR (
turn_id IS NULL
AND created_at >= ${minAnchorAt}
AND created_at < ${beforeAnchorAt}
)
)
ORDER BY
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
const getFullThreadDiffContextRow = SqlSchema.findOneOption({
Request: FullThreadDiffContextLookupInput,
Result: ProjectionFullThreadDiffContextRowSchema,
@@ -1678,6 +1905,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
@@ -1818,6 +2048,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
@@ -2090,10 +2323,23 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
threadRow.value.threadId,
),
} satisfies OrchestrationThreadShell);
});
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
// Contiguous turn range bounding a windowed detail read; undefined loads the
// full thread. Resolved from a window request inside the snapshot
// transaction (see getThreadDetailSnapshot).
interface ThreadDetailBounds {
readonly minAnchorAt: string;
readonly minTurnKey: string;
readonly beforeAnchorAt: string;
readonly beforeTurnKey: string;
}
const getThreadDetailByIdBounded = (threadId: ThreadId, bounds: ThreadDetailBounds | undefined) =>
Effect.gen(function* () {
const [
threadRow,
@@ -2112,7 +2358,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadMessageRowsByThread({ threadId }).pipe(
(bounds === undefined
? listThreadMessageRowsByThread({ threadId })
: listThreadMessageRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query",
@@ -2128,7 +2377,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadActivityRowsByThread({ threadId }).pipe(
(bounds === undefined
? listThreadActivityRowsByThread({ threadId })
: listThreadActivityRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
@@ -2238,23 +2490,139 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
);
});
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
getThreadDetailByIdBounded(threadId, undefined);
// Bounds pathological fan-out: one user turn that spawned hundreds of
// subagent turns still pages in bounded chunks, at the cost of splitting the
// fan-out group across pages (the cursor continues the same group). Also
// structurally bounds the window scan via the candidates CTE's LIMIT.
const THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE = 150;
// Sentinels for unbounded keyset ends; "~" sorts after any ISO timestamp.
const ANCHOR_UNBOUNDED = "~";
const getThreadDetailSnapshot: ProjectionSnapshotQueryShape["getThreadDetailSnapshot"] = (
threadId,
window,
) =>
// Read the thread detail and the snapshot sequence within a single
// transaction so the sequence is consistent with the returned state; a
// projector update landing between two separate reads could otherwise return
// a sequence ahead of the thread detail, causing the client to resume from
// too far and drop events.
// too far and drop events. Window resolution runs inside the same
// transaction so the page boundary is consistent with the returned rows.
sql
.withTransaction(
Effect.gen(function* () {
const thread = yield* getThreadDetailById(threadId);
if (window?.turnLimit === undefined) {
const thread = yield* getThreadDetailById(threadId);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
}
// A malformed or foreign-thread cursor falls back to the first page
// rather than failing: the client's stale cursor after a revert or
// reconnect should degrade to "reload recent history", not error.
const decodedCursor =
window.beforeCursor === undefined
? null
: decodeThreadDetailPageCursor(window.beforeCursor);
const cursor = decodedCursor?.threadId === threadId ? decodedCursor : null;
const windowRows = yield* listTurnWindowRows({
threadId,
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
beforeTurnKey: cursor?.beforeTurnId ?? "",
userTurnLimit: window.turnLimit,
maxRawTurns: THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:decodeRows",
),
),
);
const oldest = windowRows[0];
// An empty window (no turns before the cursor, or a thread with no
// turns at all) still returns thread metadata with empty collections
// for turn-linked rows; turnless rows are bounded to the same empty
// range. The first page of a turnless thread stays unwindowed so
// pre-turn content (e.g. a just-created thread) is not hidden.
const bounds: ThreadDetailBounds | undefined =
oldest === undefined && cursor === null
? undefined
: {
minAnchorAt: oldest?.anchorAt ?? "",
minTurnKey: oldest?.turnKey ?? "",
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
beforeTurnKey: cursor?.beforeTurnId ?? "",
};
// Empty window behind a cursor: nothing older remains.
const emptyBounds =
oldest === undefined && cursor !== null
? { minAnchorAt: "", minTurnKey: "", beforeAnchorAt: "", beforeTurnKey: "" }
: undefined;
const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const hasMore =
oldest !== undefined &&
(yield* listTurnWindowRows({
threadId,
beforeAnchorAt: oldest.anchorAt,
beforeTurnKey: oldest.turnKey,
userTurnLimit: 1,
maxRawTurns: 1,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:decodeRows",
),
),
)).length > 0;
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
const watermarkRow = yield* getThreadEventWatermarkRow({
threadId,
maxSequence: snapshotSequence,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:decodeRow",
),
),
);
const threadSequence = Option.match(watermarkRow, {
onNone: () => 0,
onSome: (row) => row.threadSequence ?? 0,
});
return Option.some({
snapshotSequence,
thread: thread.value,
page: {
beforeCursor:
hasMore && oldest !== undefined
? encodeThreadDetailPageCursor({
threadId,
beforeAnchorAt: oldest.anchorAt,
beforeTurnId: oldest.turnKey,
})
: null,
hasMore,
snapshotSequence,
threadSequence,
},
});
}),
)
.pipe(
@@ -48,6 +48,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import {
providerErrorLabel,
providerErrorLabelFromInstanceHint,
@@ -345,6 +346,7 @@ describe("ProviderCommandReactor", () => {
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -352,6 +354,7 @@ describe("ProviderCommandReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -44,6 +44,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
@@ -237,6 +238,9 @@ describe("ProviderRuntimeIngestion", () => {
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
// Single shared liveness instance across ingestion (writer), the
// engine, and the snapshot query (reader).
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
@@ -3143,7 +3147,8 @@ describe("ProviderRuntimeIngestion", () => {
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-started",
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:turn-task-1",
);
const completed = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-completed",
@@ -3227,7 +3232,8 @@ describe("ProviderRuntimeIngestion", () => {
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:named-task-1",
);
const completed = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-completed",
@@ -3318,7 +3324,8 @@ describe("ProviderRuntimeIngestion", () => {
await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:swept-task-1",
),
);
@@ -7,6 +7,8 @@ import {
type OrchestrationMessage,
type OrchestrationProposedPlanId,
CheckpointRef,
classifyTaskAgentKind,
EventId,
isToolLifecycleItemType,
ThreadId,
type ThreadTokenUsageSnapshot,
@@ -32,6 +34,7 @@ import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionT
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
ProviderRuntimeIngestionService,
@@ -307,6 +310,52 @@ function requestKindFromCanonicalRequestType(
}
}
/**
* Copies the optional TaskAgentLinkage bundle from a task.* runtime payload
* into the persisted activity payload. Identity fields ride on every row so
* client folds survive activity retention; absent fields stay absent.
*/
function taskLinkageActivityFields(payload: Record<string, unknown>): Record<string, unknown> {
const fields: Record<string, unknown> = {
// Server-stamped classification: persisted rows are self-describing, so
// clients trust the stamp instead of re-deriving agent-vs-background
// from taskType denylists and marker heuristics (legacy rows without a
// stamp keep the client fallback).
agentKind: classifyTaskAgentKind({
taskType: typeof payload.taskType === "string" ? payload.taskType : undefined,
agentId: typeof payload.agentId === "string" ? payload.agentId : undefined,
}),
};
for (const key of [
"taskType",
"agentId",
"title",
"role",
"model",
"effort",
"toolUseId",
"parentAgentId",
"workflowName",
"agentIndex",
"phaseIndex",
"phaseTitle",
"phases",
"attempt",
"runHandles",
"outputFile",
"agentPath",
"timelineBypass",
"typedUsage",
"status",
"error",
] as const) {
if (payload[key] !== undefined) {
fields[key] = payload[key];
}
}
return fields;
}
export function runtimeEventToActivities(
event: ProviderRuntimeEvent,
taskTitle?: string,
@@ -505,6 +554,7 @@ export function runtimeEventToActivities(
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -515,7 +565,16 @@ export function runtimeEventToActivities(
case "task.progress": {
return [
{
id: event.eventId,
// Stable per-task id: progress is "latest state", not history, so
// each tick REPLACES the last via the activity upsert (PK + the
// replace-by-id apply in projector and client reducer). Keeps one
// progress row per task instead of thousands, so a large fleet's
// ticks can no longer evict its own start/terminal rows out of
// the 500-row retention window. Thread-scoped: activity_id is a
// GLOBAL primary key and Claude task ids are session-local, so a
// bare taskId could collide across threads and steal another
// thread's row (review finding).
id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info",
kind: "task.progress",
@@ -532,6 +591,71 @@ export function runtimeEventToActivities(
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "task.updated": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: event.payload.status === "failed" ? "error" : "info",
kind: "task.updated",
summary:
event.payload.status === "failed"
? "Task failed"
: event.payload.status
? `Task ${event.payload.status}`
: "Task updated",
payload: {
taskId: event.payload.taskId,
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
...(event.payload.endedAt ? { endedAt: event.payload.endedAt } : {}),
...(event.payload.isBackgrounded !== undefined
? { isBackgrounded: event.payload.isBackgrounded }
: {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "tool.progress": {
// Only agent-owned heartbeats are persisted: they feed the owning
// agent's activity line. Parent-conversation tool progress stays
// ephemeral (item lifecycle already covers it).
if (event.payload.taskId === undefined) {
return [];
}
return [
{
// Same stable-id treatment as task.progress: a heartbeat is
// "what is this agent doing right now", so one row per task
// (thread-scoped for the same global-PK collision reason).
id: EventId.make(`tool-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info",
kind: "tool.progress",
summary: event.payload.toolName ?? "Tool progress",
payload: {
taskId: event.payload.taskId,
...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
...(event.payload.elapsedSeconds !== undefined
? { elapsedSeconds: event.payload.elapsedSeconds }
: {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -565,6 +689,7 @@ export function runtimeEventToActivities(
}
: {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -630,6 +755,10 @@ export function runtimeEventToActivities(
...(event.payload.status ? { status: event.payload.status } : {}),
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -652,6 +781,10 @@ export function runtimeEventToActivities(
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -673,6 +806,10 @@ export function runtimeEventToActivities(
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -688,6 +825,7 @@ export function runtimeEventToActivities(
}
const make = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
@@ -1756,6 +1894,43 @@ const make = Effect.gen(function* () {
yield* rememberTaskDescription(thread.id, event.payload.taskId, description);
}
}
// Sidebar background liveness: fed from the same lifecycle stream,
// read by the shell query at mapping time (no persistence).
switch (event.type) {
case "task.started":
case "task.progress":
case "task.updated":
case "task.completed": {
const payload = event.payload as {
taskId: string;
taskType?: string;
status?: string;
agentId?: string;
};
threadBackgroundLiveness.recordTaskLiveness({
threadId: thread.id,
taskId: payload.taskId,
taskType: payload.taskType,
status: payload.status,
agentId: payload.agentId,
kind:
event.type === "task.started"
? "started"
: event.type === "task.progress"
? "progress"
: event.type === "task.updated"
? "updated"
: "completed",
});
break;
}
case "session.exited":
threadBackgroundLiveness.clearThreadLiveness(thread.id);
break;
default:
break;
}
let taskTitle: string | undefined;
if (event.type === "task.completed") {
taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);
@@ -17,6 +17,7 @@ import type {
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
OrchestrationThreadDetailWindow,
OrchestrationThreadShell,
ProjectId,
ThreadId,
@@ -174,9 +175,16 @@ export interface ProjectionSnapshotQueryShape {
* sequence in one consistent transaction, so the returned `snapshotSequence`
* exactly matches the state reflected in `thread` (no interleaving projector
* update between the two reads).
*
* When `window` is provided, the thread's messages, activities, proposed
* plans, and checkpoints are bounded to a page of recent turns and the
* response carries `page` metadata (see `OrchestrationThreadDetailWindow`).
* Without a window the full thread is returned with no `page` field —
* pagination is strictly opt-in.
*/
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
window?: OrchestrationThreadDetailWindow,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
}
@@ -0,0 +1,173 @@
import { describe, expect, it } from "vite-plus/test";
import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
describe("ThreadBackgroundLiveness", () => {
it("agents present as working; monitors as monitoring; agents win", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-1";
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: undefined,
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
liveness.recordTaskLiveness({
threadId,
taskId: "a1",
taskType: "subagent",
status: undefined,
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "a1",
taskType: "subagent",
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("terminal rows without a taskType still clear monitor entries", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-2";
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: undefined,
kind: "started",
});
// Terminal tick arrives with no taskType (common on task.completed).
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: undefined,
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("nested agents (agentId + agent taskType) still count toward liveness", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-nested";
liveness.recordTaskLiveness({
threadId,
taskId: "n1",
taskType: "local_agent",
status: undefined,
kind: "started",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "n1",
taskType: "local_agent",
status: "completed",
kind: "completed",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("untyped rows count as agents; idle is not live; agent-owned tasks are ignored", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-3";
liveness.recordTaskLiveness({
threadId,
taskId: "wf:1",
taskType: undefined,
status: "running",
kind: "progress",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "wf:1",
taskType: undefined,
status: "idle",
kind: "updated",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
liveness.recordTaskLiveness({
threadId,
taskId: "sh:1",
taskType: "local_bash",
status: undefined,
kind: "started",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("reclassification moves a task between buckets instead of duplicating it", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-reclass";
// First seen without a taskType: counts as an agent.
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: undefined,
status: "running",
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
// Later transition reveals it's a shell: downgrade to monitoring, not
// a stale duplicate pinning "working".
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: "local_bash",
status: "running",
kind: "progress",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
// Turning out to be inert or agent-owned drops the prior entry too.
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: "local_bash",
status: "running",
kind: "progress",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("plan tasks are inert; clear removes everything; instances are isolated", () => {
const a = ThreadBackgroundLiveness.make();
const b = ThreadBackgroundLiveness.make();
a.recordTaskLiveness({
threadId: "t",
taskId: "p1",
taskType: "plan",
status: undefined,
kind: "started",
});
expect(a.getThreadBackgroundLiveness("t")).toBeNull();
a.recordTaskLiveness({
threadId: "t",
taskId: "a1",
taskType: "local_workflow",
status: undefined,
kind: "started",
});
expect(a.getThreadBackgroundLiveness("t")).toBe("working");
expect(b.getThreadBackgroundLiveness("t")).toBeNull();
a.clearThreadLiveness("t");
expect(a.getThreadBackgroundLiveness("t")).toBeNull();
});
});
@@ -0,0 +1,160 @@
/**
* ThreadBackgroundLivenessService - in-memory per-thread background liveness
* for the sidebar status pill.
*
* The turn can settle while native background work runs on (subagent fleets,
* workflow runs, Monitor watch loops); the shell previously showed nothing.
* Ingestion records task lifecycle transitions and the shell query reads the
* derived state at mapping time — no persistence, no migration. After a
* server restart the registry is empty until new task events arrive, which
* matches reality: orphaned background work is not live.
*
* "monitoring" is reserved for watch loops (monitor tasks and background
* shells) when they are the ONLY live work; any agent work presents as
* "working".
*
* @module ThreadBackgroundLivenessService
*/
import { INERT_TASK_TYPES, MONITOR_TASK_TYPES } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export type ThreadBackgroundLiveness = "working" | "monitoring" | null;
interface ThreadLivenessState {
readonly agents: Set<string>;
readonly monitors: Set<string>;
}
// Classification sets are the shared contracts copies (MONITOR_TASK_TYPES:
// watch loops — monitor tasks plus background shells, which in practice are
// PR babysitting/log tails since pacing sleeps complete inside the turn;
// INERT_TASK_TYPES: plan-mode bookkeeping) so this registry, ingestion's
// agentKind stamp, and the client fold can never drift apart.
const TERMINAL_STATUSES: ReadonlySet<string> = new Set([
"completed",
"failed",
"stopped",
"cancelled",
"interrupted",
]);
export class ThreadBackgroundLivenessService extends Context.Service<
ThreadBackgroundLivenessService,
{
/**
* Feed one task lifecycle transition. taskType may be absent on
* synthesized rows (workflow members, Codex children) — those count as
* agents. agentId marks a task launched from inside a subagent: its
* internal shells are covered by the owning agent's liveness, but a
* NESTED AGENT (agentId + agent-flavored taskType) still counts — it
* can outlive its parent and must keep the thread Working.
*/
readonly recordTaskLiveness: (input: {
readonly threadId: string;
readonly taskId: string;
readonly taskType: string | undefined;
readonly status: string | undefined;
readonly kind: "started" | "progress" | "updated" | "completed";
readonly agentId?: string | undefined;
}) => void;
/** Session death orphans all of a thread's background work. */
readonly clearThreadLiveness: (threadId: string) => void;
/**
* Two-state vocabulary by design: any live agent work is "working";
* "monitoring" only when watch loops are the ONLY live work.
*/
readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;
}
>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}
export function make(): ThreadBackgroundLivenessService["Service"] {
const stateByThreadId = new Map<string, ThreadLivenessState>();
const stateFor = (threadId: string): ThreadLivenessState => {
const existing = stateByThreadId.get(threadId);
if (existing) {
return existing;
}
const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };
stateByThreadId.set(threadId, created);
return created;
};
// Classification is per-transition, not sticky: a task first seen without
// a taskType may later reveal itself as a shell, become inert, or turn out
// to be agent-owned. Every path drops any prior entry for the taskId so a
// stale bucket assignment can't pin the thread's status (review finding).
const drop = (threadId: string, taskId: string) => {
const state = stateByThreadId.get(threadId);
if (!state) {
return;
}
state.agents.delete(taskId);
state.monitors.delete(taskId);
if (state.agents.size === 0 && state.monitors.size === 0) {
stateByThreadId.delete(threadId);
}
};
return {
recordTaskLiveness: (input) => {
const taskType = input.taskType;
if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {
drop(input.threadId, input.taskId);
return;
}
// A subagent's internal non-agent work (its own shells/monitors) is
// covered by the owning agent's liveness. Nested agents fall through:
// they can outlive their parent (review finding).
if (
input.agentId !== undefined &&
(taskType === undefined || MONITOR_TASK_TYPES.has(taskType))
) {
drop(input.threadId, input.taskId);
return;
}
// Idle counts as not-live: a resting (resumable) Codex child isn't
// doing anything, and an all-idle fleet must not pin Working.
const terminal =
input.kind === "completed" ||
input.status === "idle" ||
(input.status !== undefined && TERMINAL_STATUSES.has(input.status));
if (terminal) {
drop(input.threadId, input.taskId);
return;
}
drop(input.threadId, input.taskId);
const state = stateFor(input.threadId);
const bucket =
taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;
bucket.add(input.taskId);
},
clearThreadLiveness: (threadId) => {
stateByThreadId.delete(threadId);
},
getThreadBackgroundLiveness: (threadId) => {
const state = stateByThreadId.get(threadId);
if (!state) {
return null;
}
if (state.agents.size > 0) {
return "working";
}
if (state.monitors.size > 0) {
return "monitoring";
}
return null;
},
};
}
export const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));
+11 -1
View File
@@ -66,7 +66,17 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(args.params.threadId)
.getThreadDetailSnapshot(
args.params.threadId,
args.payload.turnLimit === undefined
? undefined
: {
turnLimit: args.payload.turnLimit,
...(args.payload.beforeCursor !== undefined
? { beforeCursor: args.payload.beforeCursor }
: {}),
},
)
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_thread_snapshot_failed", cause),
@@ -5,6 +5,7 @@ import { OrchestrationEventStoreLive } from "../persistence/Layers/Orchestration
import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
@@ -19,7 +20,10 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
);
// Shared background-liveness registry: written by runtime ingestion,
// read by the snapshot query. provideMerge feeds the same instance to
// the snapshot query here and re-exports it for runtime ingestion.
).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));
export const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
@@ -0,0 +1,44 @@
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import {
decodeThreadDetailPageCursor,
encodeThreadDetailPageCursor,
} from "./threadDetailCursor.ts";
describe("threadDetailCursor", () => {
it("round-trips a cursor", () => {
const cursor = {
threadId: ThreadId.make("thread-1"),
beforeAnchorAt: "2026-08-01T00:00:00.000Z",
beforeTurnId: "turn-9",
};
expect(decodeThreadDetailPageCursor(encodeThreadDetailPageCursor(cursor))).toEqual(cursor);
});
it("round-trips empty boundary values", () => {
// The anchor is COALESCE(requested_at, started_at, '') and the turn key
// is COALESCE(turn_id, ''), so a server-minted cursor can legitimately
// carry empty strings; rejecting them would degrade a valid cursor to a
// first-page request that repeats recent history (review finding).
const cursor = {
threadId: ThreadId.make("thread-1"),
beforeAnchorAt: "",
beforeTurnId: "",
};
expect(decodeThreadDetailPageCursor(encodeThreadDetailPageCursor(cursor))).toEqual(cursor);
});
it("rejects malformed input", () => {
expect(decodeThreadDetailPageCursor("not-base64-json")).toBeNull();
expect(decodeThreadDetailPageCursor(Buffer.from("[]").toString("base64url"))).toBeNull();
expect(
decodeThreadDetailPageCursor(Buffer.from(JSON.stringify({ t: "" })).toString("base64url")),
).toBeNull();
expect(
decodeThreadDetailPageCursor(
Buffer.from(JSON.stringify({ t: "thread-1", a: 5, i: "x" })).toString("base64url"),
),
).toBeNull();
});
});
@@ -0,0 +1,62 @@
import type { ThreadId } from "@t3tools/contracts";
/**
* Opaque, exclusive cursor for windowed thread detail reads. Encodes the thread
* id and the keyset boundary of an already-delivered page: the boundary turn's
* anchor timestamp (`COALESCE(requested_at, started_at, '')`) and turn id.
* Passing it back requests the adjacent disjoint slice of strictly older turns
* under `(anchor, turn_id)` ordering.
*
* The boundary is deliberately NOT a `projection_turns.row_id`: row ids are
* rewritten by the revert projector (delete + re-upsert) and by projection
* rebuilds, which would silently invalidate every persisted cursor with no
* event emitted. The (anchor, turnId) pair is derived from event content, so
* cursors survive both and no client-side refresh machinery is needed. The
* anchor doubles as the time bound for rows with no turn linkage (straggler
* user messages, turnless activities). The thread id is embedded so a cursor
* can never be replayed against a different thread. Clients must treat the
* string as opaque.
*/
export interface ThreadDetailPageCursor {
readonly threadId: ThreadId;
readonly beforeAnchorAt: string;
/** Boundary turn id; "" for the rare turn row with a null turn_id. */
readonly beforeTurnId: string;
}
export function encodeThreadDetailPageCursor(cursor: ThreadDetailPageCursor): string {
return Buffer.from(
JSON.stringify({ t: cursor.threadId, a: cursor.beforeAnchorAt, i: cursor.beforeTurnId }),
).toString("base64url");
}
/**
* Returns null for anything that is not a well-formed cursor. Callers degrade
* a malformed or foreign-thread cursor to a first-page request.
*/
export function decodeThreadDetailPageCursor(encoded: string): ThreadDetailPageCursor | null {
let parsed: unknown;
try {
parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
} catch {
return null;
}
if (parsed === null || typeof parsed !== "object") {
return null;
}
const record = parsed as Record<string, unknown>;
if (typeof record.t !== "string" || record.t.length === 0) {
return null;
}
// Empty strings are valid boundary values, not malformed input: the anchor
// is COALESCE(requested_at, started_at, ''), so a boundary turn with no
// timestamps encodes a: "" (and sorts before every real anchor, correctly
// ending the walk); the turn key is "" for a null turn_id.
if (typeof record.a !== "string") {
return null;
}
if (typeof record.i !== "string") {
return null;
}
return { threadId: record.t as ThreadId, beforeAnchorAt: record.a, beforeTurnId: record.i };
}
@@ -0,0 +1,75 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { it as effectIt } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterAll, assert, describe } from "vite-plus/test";
import { readWorkflowScript } from "./workflowScriptQuery.ts";
const root = NodePath.join(NodeOS.homedir(), ".claude", "projects", "__wf_script_test__");
NodeFS.mkdirSync(root, { recursive: true });
const scriptPath = NodePath.join(root, "run.js");
NodeFS.writeFileSync(scriptPath, "export const meta = {};\n");
const outside = NodePath.join(NodeOS.tmpdir(), "wf-outside.js");
NodeFS.writeFileSync(outside, "evil\n");
const link = NodePath.join(root, "sneaky.js");
try {
NodeFS.symlinkSync(outside, link);
} catch (error) {
// Tolerate only "already exists" from a prior run — any other failure
// (EPERM etc.) must fail setup, or the escape test below would pass
// vacuously on "not-found" without testing containment.
if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
throw error;
}
}
if (!NodeFS.lstatSync(link).isSymbolicLink()) {
throw new Error("test setup: sneaky.js must be a symlink");
}
afterAll(() => {
NodeFS.rmSync(root, { recursive: true, force: true });
NodeFS.rmSync(outside, { force: true });
});
describe("readWorkflowScript containment", () => {
effectIt.effect("serves a real script under the projects root", () =>
Effect.gen(function* () {
const result = yield* readWorkflowScript({ scriptPath });
assert.include(result.contents, "export const meta");
assert.equal(result.truncated, false);
}),
);
effectIt.effect("rejects relative and non-js paths", () =>
Effect.gen(function* () {
const relative = yield* Effect.exit(readWorkflowScript({ scriptPath: "run.js" }));
assert.equal(relative._tag, "Failure");
const nonJs = yield* Effect.exit(
readWorkflowScript({ scriptPath: scriptPath.replace(".js", ".ts") }),
);
assert.equal(nonJs._tag, "Failure");
}),
);
effectIt.effect("rejects paths outside the root and symlink escapes", () =>
Effect.gen(function* () {
const escaped = yield* Effect.exit(readWorkflowScript({ scriptPath: outside }));
assert.equal(escaped._tag, "Failure");
// A symlink INSIDE the root pointing outside must fail specifically on
// realpath re-containment — a "not-found" would mean the link was
// never exercised and the assertion proves nothing.
const sneaky = yield* Effect.exit(
readWorkflowScript({ scriptPath: link }).pipe(
Effect.flip,
Effect.map((error) => error.reason),
),
);
assert.equal(sneaky._tag, "Success");
if (sneaky._tag === "Success") {
assert.equal(sneaky.value, "outside-root");
}
}),
);
});
@@ -0,0 +1,124 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Read-only access to persisted workflow scripts for the Agents surface's
* "{} script" affordance.
*
* Containment rules (lifted from the reviewed #3650 inspection service):
* - the resolved realpath must live under ~/.claude/projects (where the
* Claude harness persists workflow scripts) — realpath re-containment
* defeats symlink escapes, including a symlinked leaf file;
* - only .js leaf files are served;
* - reads are size-capped rather than failed, with a truncation marker.
*
* The client-supplied path is a hint from the workflow's runHandles; it is
* never trusted beyond these checks.
*/
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { OrchestrationGetWorkflowScriptError } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
const SCRIPT_BYTE_CAP = 256 * 1024;
function scriptsRoot(): string {
return NodePath.join(NodeOS.homedir(), ".claude", "projects");
}
export const readWorkflowScript = Effect.fn("orchestration.readWorkflowScript")(function* (input: {
readonly scriptPath: string;
}) {
const requested = input.scriptPath;
if (!NodePath.isAbsolute(requested) || NodePath.extname(requested) !== ".js") {
return yield* Effect.fail(
new OrchestrationGetWorkflowScriptError({ reason: "invalid-path", scriptPath: requested }),
);
}
const root = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(scriptsRoot()),
catch: (cause) =>
new OrchestrationGetWorkflowScriptError({
reason: "root-unavailable",
scriptPath: requested,
cause,
}),
});
// Realpath the FILE itself (not just its directory): a symlink named
// like a script inside a contained directory must not escape.
const resolved = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(requested),
catch: (cause) =>
new OrchestrationGetWorkflowScriptError({
reason: "not-found",
scriptPath: requested,
cause,
}),
});
if (resolved !== root && !resolved.startsWith(`${root}${NodePath.sep}`)) {
return yield* Effect.fail(
new OrchestrationGetWorkflowScriptError({ reason: "outside-root", scriptPath: resolved }),
);
}
if (NodePath.extname(resolved) !== ".js") {
return yield* Effect.fail(
new OrchestrationGetWorkflowScriptError({ reason: "not-js", scriptPath: resolved }),
);
}
// TOCTOU-safe read (review finding): open FIRST, then verify what was
// actually opened via the file descriptor. Re-checking the path after
// open would race against a swap; fstat on the handle cannot. The two
// containment checks fail with their own tagged reasons (not manufactured
// Errors folded into read-failed); "read-failed" is reserved for genuine
// platform failures with the real cause attached.
const read = yield* Effect.tryPromise({
try: async () => {
const handle = await NodeFSP.open(resolved, "r");
try {
const stat = await handle.stat();
if (!stat.isFile()) {
return { failure: "not-regular-file" as const };
}
// The opened inode must be the same one realpath resolved to: a
// process swapping the path between realpath and open changes the
// inode, which this comparison catches.
const pathStat = await NodeFSP.lstat(resolved);
if (stat.ino !== pathStat.ino || stat.dev !== pathStat.dev) {
return { failure: "changed-during-read" as const };
}
const truncated = stat.size > SCRIPT_BYTE_CAP;
const buffer = Buffer.alloc(Math.min(stat.size, SCRIPT_BYTE_CAP));
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
return {
contents: buffer.subarray(0, bytesRead).toString("utf8"),
truncated,
};
} finally {
await handle.close();
}
},
catch: (cause) =>
new OrchestrationGetWorkflowScriptError({
reason: "read-failed",
scriptPath: resolved,
cause,
}),
});
if ("failure" in read) {
return yield* new OrchestrationGetWorkflowScriptError({
reason: read.failure,
scriptPath: resolved,
});
}
return {
scriptPath: resolved,
contents: read.contents,
truncated: read.truncated,
};
});
@@ -49,6 +49,7 @@ import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
/**
* Migration loader with all migrations defined inline.
@@ -97,6 +98,7 @@ export const migrationEntries = [
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
[37, "ProjectionTurnsKeysetIndex", Migration0037],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,17 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
/**
* Composite index for windowed thread detail reads. Pagination orders turns by
* the stable keyset (requested_at, turn_id); the pre-existing
* (thread_id, requested_at) index cannot serve the tiebreak order, forcing a
* temp B-tree over all of a thread's turns before the page LIMIT applies.
* With this index the candidates scan is genuinely bounded by the page size.
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_keyset
ON projection_turns(thread_id, requested_at, turn_id)
`;
});
@@ -55,6 +55,7 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
private failure: unknown | undefined;
public readonly interruptCalls: Array<void> = [];
public readonly stopTaskCalls: Array<string> = [];
public readonly setModelCalls: Array<string | undefined> = [];
public readonly setPermissionModeCalls: Array<string> = [];
public readonly setMaxThinkingTokensCalls: Array<number | null> = [];
@@ -98,6 +99,10 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
this.interruptCalls.push(undefined);
};
readonly stopTask = async (taskId: string): Promise<void> => {
this.stopTaskCalls.push(taskId);
};
readonly setModel = async (model?: string): Promise<void> => {
this.setModelCalls.push(model);
};
@@ -1445,6 +1450,304 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("treats aborted_tools results as interrupted and hides ede_diagnostic errors", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
// Exact shape the CLI emits when Stop lands mid-tool-call: is_error
// is true and the only error is internal diagnostic telemetry.
harness.query.emit({
type: "result",
subtype: "error_during_execution",
is_error: true,
errors: ["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],
stop_reason: "tool_use",
terminal_reason: "aborted_tools",
session_id: "sdk-session-abort-tools",
uuid: "result-abort-tools",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"turn.completed",
],
);
const turnCompleted = runtimeEvents[runtimeEvents.length - 1];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "interrupted");
assert.equal(turnCompleted.payload.errorMessage, undefined);
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("interruptTurn stops every live task before interrupting the turn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
// Wait for the three task.* runtime events to prove the lifecycle
// handlers processed the emissions (no wall-clock sleeps under the
// test clock).
const taskEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type.startsWith("task.")),
Stream.take(3),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "spawn agents",
attachments: [],
});
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "task-live",
description: "Agent A",
task_type: "local_agent",
uuid: "task-live-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "task-settled",
description: "Agent B",
task_type: "local_agent",
uuid: "task-settled-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_notification",
task_id: "task-settled",
status: "completed",
output_file: "/tmp/task-settled.jsonl",
summary: "done",
uuid: "task-settled-done-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
yield* Fiber.join(taskEventsFiber);
yield* adapter.interruptTurn(session.threadId);
// Only the still-live task is stopped; interrupt always fires after.
assert.deepEqual(harness.query.stopTaskCalls, ["task-live"]);
assert.equal(harness.query.interruptCalls.length, 1);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("workflow member coalescing: identical snapshots suppress, changes emit", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
// Collect task.progress until member-0's tick-3 emission lands, then
// evaluate member emissions.
const progressFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type === "task.progress"),
Stream.takeUntil(
// Sentinel: member-0's tick-3 emission (tokens 20) — members are
// emitted after the coordinator row within a tick.
(event) =>
(event.payload as { taskId?: string }).taskId === "wf-coalesce:wf:0" &&
(event.payload as { typedUsage?: { totalTokens?: number } }).typedUsage?.totalTokens ===
20,
),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "run workflow",
attachments: [],
});
const memberSnapshot = (tokens: number) => [
{ type: "workflow_phase", index: 0, title: "Work" },
{
type: "workflow_agent",
index: 0,
state: "running",
label: "member-0",
phaseIndex: 0,
tokens,
},
{
type: "workflow_agent",
index: 1,
state: "running",
label: "member-1",
phaseIndex: 0,
tokens: 50,
},
];
const tick = (usageTotal: number, snapshot: ReturnType<typeof memberSnapshot>) =>
harness.query.emit({
type: "system",
subtype: "task_progress",
task_id: "wf-coalesce",
description: "Coalescing workflow",
usage: { total_tokens: usageTotal, tool_uses: 1, duration_ms: 10 },
workflow_progress: snapshot,
uuid: `wf-tick-${usageTotal}`,
session_id: "sdk-session",
} as unknown as SDKMessage);
// Tick 1: both members are new -> 2 member events.
tick(100, memberSnapshot(10));
// Tick 2: IDENTICAL member snapshot -> 0 member events (coordinator
// usage changed, but members did not).
tick(200, memberSnapshot(10));
// Tick 3: member-0's tokens advanced -> exactly 1 member event.
tick(300, memberSnapshot(20));
const progressEvents = Array.from(yield* Fiber.join(progressFiber));
const byMember = new Map<string, number>();
for (const event of progressEvents) {
const taskId = (event.payload as { taskId: string }).taskId;
if (!taskId.includes(":wf:")) continue;
byMember.set(taskId, (byMember.get(taskId) ?? 0) + 1);
}
// member-0: tick 1 + tick 3. member-1: tick 1 only (tick 2 identical,
// tick 3 unchanged).
assert.equal(byMember.get("wf-coalesce:wf:0"), 2);
assert.equal(byMember.get("wf-coalesce:wf:1"), 1);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("task.started carries model/effort; subagent snapshots refine the model", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const taskEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type.startsWith("task.")),
Stream.take(2),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "effort", value: "max" }],
),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "spawn an agent",
attachments: [],
});
// No explicit model/effort on the launch input: the task inherits the
// session's selection.
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "task-model",
description: "Agent M",
task_type: "local_agent",
tool_use_id: "toolu_agent_m",
uuid: "task-model-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
// The subagent's assistant snapshot carries the authoritative API
// model id, which refines the linkage on later rows.
harness.query.emit({
type: "assistant",
parent_tool_use_id: "toolu_agent_m",
message: {
model: "claude-sonnet-5[1m]",
content: [],
},
uuid: "subagent-snapshot-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_progress",
task_id: "task-model",
description: "Agent M",
usage: { total_tokens: 100, tool_uses: 1, duration_ms: 10 },
uuid: "task-model-progress-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
const taskEvents = Array.from(yield* Fiber.join(taskEventsFiber));
const started = taskEvents[0];
assert.equal(started?.type, "task.started");
if (started?.type === "task.started") {
assert.equal(started.payload.model, "claude-opus-4-6");
assert.equal(started.payload.effort, "max");
}
const progress = taskEvents[1];
assert.equal(progress?.type, "task.progress");
if (progress?.type === "task.progress") {
assert.equal(progress.payload.model, "claude-sonnet-5[1m]");
assert.equal(progress.payload.effort, "max");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1779,6 +2082,24 @@ describe("ClaudeAdapterLive", () => {
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "vcs_state_changed",
kind: "push",
cwd: "/tmp/worktree",
session_id: "session",
uuid: "vcs",
},
{
type: "system",
subtype: "code_change_published",
provider: "github",
url: "https://github.com/pingdotgg/t3code/pull/1",
repo: "pingdotgg/t3code",
identifier: "1",
session_id: "session",
uuid: "ccp",
},
{
type: "system",
subtype: "task_updated",
+619 -17
View File
@@ -42,6 +42,10 @@ import {
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
type RuntimeTaskStatus,
type RuntimeTaskUsage,
type TaskAgentLinkage,
type TaskRunHandles,
ThreadId,
TurnId,
type UserInputQuestion,
@@ -169,6 +173,9 @@ interface ToolInFlight {
readonly input: Record<string, unknown>;
readonly partialInputJson: string;
readonly lastEmittedInputFingerprint?: string;
/** Owning agent when this tool ran inside a subagent (see attribution note). */
readonly agentId?: string;
readonly parentToolUseId?: string;
}
interface ClaudeTaskState {
@@ -178,6 +185,28 @@ interface ClaudeTaskState {
readonly blockedBy: Set<string>;
}
/**
* Agent identity captured from task_started and repeated on every subsequent
* task.* payload, so client folds can reconstruct an agent even when its
* start row aged out of activity retention.
*/
interface ClaudeTaskAgentState {
readonly taskId: string;
toolUseId: string | undefined;
description: string | undefined;
subagentType: string | undefined;
taskType: string | undefined;
workflowName: string | undefined;
skipTranscript: boolean;
runHandles: TaskRunHandles | undefined;
/** Set when this task was launched from inside a subagent. */
owningAgentId: string | undefined;
/** Seeded from the launching tool's input; refined by the subagent's own
* assistant snapshots (authoritative API model). */
model: string | undefined;
effort: string | undefined;
}
interface ClaudeSessionContext {
session: ProviderSession;
readonly promptQueue: Queue.Queue<PromptQueueItem>;
@@ -186,6 +215,9 @@ interface ClaudeSessionContext {
readonly startedAt: string;
readonly basePermissionMode: PermissionMode | undefined;
currentApiModelId: string | undefined;
/** Effective effort for the session's turns; subagents without an explicit
* effort override inherit this. */
currentEffort: string | undefined;
resumeSessionId: string | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
@@ -195,6 +227,17 @@ interface ClaudeSessionContext {
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
readonly claudeTasks: Map<string, ClaudeTaskState>;
readonly taskAgents: Map<string, ClaudeTaskAgentState>;
/**
* Last emitted workflow-member fingerprint per member slot. A coordinator
* task_progress repeats the FULL member array every tick; without a
* material-transition filter one provider tick fans out into up to 100
* runtime events (event-log writes, queue pressure, client reducer work)
* even when nothing changed for most members.
*/
readonly workflowMemberFingerprints: Map<string, string>;
/** Task ids that have started and not yet reached a terminal state. */
readonly liveTaskIds: Set<string>;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
@@ -206,6 +249,8 @@ interface ClaudeSessionContext {
interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly interrupt: () => Promise<void>;
/** SDK Query.stopTask — present on real queries; optional for test doubles. */
readonly stopTask?: (taskId: string) => Promise<void>;
readonly setModel: (model?: string) => Promise<void>;
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
@@ -303,7 +348,29 @@ function resultErrorsText(result: SDKResultMessage): string {
: "";
}
/**
* First user-facing error from a non-success result. "[ede_diagnostic] ..."
* entries are CLI-internal telemetry (the CLI hides them from its own UI too),
* so they must never become the error banner.
*/
function resultUserFacingError(result: SDKResultMessage): string | undefined {
if (result.subtype === "success" || !Array.isArray(result.errors)) {
return undefined;
}
return result.errors.find((error) => !error.startsWith("[ede_diagnostic]"));
}
function isInterruptedResult(result: SDKResultMessage): boolean {
// The CLI stamps user aborts explicitly: interrupting mid-tool-call yields
// "aborted_tools" (with an internal "[ede_diagnostic] ..." error and
// is_error: true), interrupting mid-stream yields "aborted_streaming".
if (
result.terminal_reason === "aborted_tools" ||
result.terminal_reason === "aborted_streaming"
) {
return true;
}
const errors = resultErrorsText(result);
if (errors.includes("interrupt")) {
return true;
@@ -826,6 +893,225 @@ function planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep
});
}
/** Only http/https survive; anything else (javascript:, file:, …) is dropped. */
function sanitizeSessionUrl(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const trimmed = value.trim();
if (!/^https?:\/\//i.test(trimmed)) {
return undefined;
}
return trimmed;
}
function nonNegativeInt(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value >= 0
? Math.floor(value)
: undefined;
}
function trimmedString(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
/**
* SDK task usage ({total_tokens, tool_uses, duration_ms}, sometimes with
* input/output/cache breakdowns) → the typed contract shape. Unknown or
* malformed input yields undefined rather than a partial guess.
*/
function normalizeTaskUsage(usage: unknown): RuntimeTaskUsage | undefined {
if (typeof usage !== "object" || usage === null) {
return undefined;
}
const record = usage as Record<string, unknown>;
const totalTokens = nonNegativeInt(record.total_tokens);
if (totalTokens === undefined) {
return undefined;
}
const inputTokens = nonNegativeInt(record.input_tokens);
const cachedInputTokens = nonNegativeInt(record.cache_read_input_tokens);
const outputTokens = nonNegativeInt(record.output_tokens);
const toolUses = nonNegativeInt(record.tool_uses);
const durationMs = nonNegativeInt(record.duration_ms);
return {
totalTokens,
...(inputTokens !== undefined ? { inputTokens } : {}),
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(outputTokens !== undefined ? { outputTokens } : {}),
...(toolUses !== undefined ? { toolUses } : {}),
...(durationMs !== undefined ? { durationMs } : {}),
};
}
/** SDK task_updated patch status → the shared wire vocabulary. */
const CLAUDE_TASK_PATCH_STATUS: Record<string, RuntimeTaskStatus> = {
pending: "pending",
running: "running",
completed: "completed",
failed: "failed",
killed: "cancelled",
paused: "idle",
};
/**
* Resolves a stream message's parent_tool_use_id to the owning agent's
* taskId. The Task tool's tool_use_id is remembered on task_started; any
* subagent-forwarded block carries that id as its parent. Returns undefined
* for parent-conversation traffic.
*/
function agentIdForParentToolUse(
agents: Map<string, ClaudeTaskAgentState>,
parentToolUseId: string | null | undefined,
): string | undefined {
if (parentToolUseId === null || parentToolUseId === undefined) {
return undefined;
}
for (const agent of agents.values()) {
if (agent.toolUseId === parentToolUseId) {
return agent.taskId;
}
}
return undefined;
}
/**
* Linkage bundle repeated on every task.* payload for `taskId`. Reads the
* remembered identity (from task_started) so progress/terminal rows are
* self-describing even when the start row ages out of activity retention.
*/
function taskLinkageFor(
agents: Map<string, ClaudeTaskAgentState>,
taskId: string,
): TaskAgentLinkage {
const agent = agents.get(taskId);
if (!agent) {
return {};
}
return {
...(agent.taskType ? { taskType: agent.taskType } : {}),
...(agent.owningAgentId ? { agentId: agent.owningAgentId } : {}),
...(agent.description ? { title: agent.description } : {}),
...(agent.subagentType ? { role: agent.subagentType } : {}),
...(agent.model ? { model: agent.model } : {}),
...(agent.effort ? { effort: agent.effort } : {}),
...(agent.toolUseId ? { toolUseId: agent.toolUseId } : {}),
...(agent.workflowName ? { workflowName: agent.workflowName } : {}),
...(agent.runHandles ? { runHandles: agent.runHandles } : {}),
};
}
const WORKFLOW_PHASE_CAP = 64;
const WORKFLOW_AGENT_CAP = 100;
interface ClaudeWorkflowAgentEntry {
readonly index: number;
readonly state: string;
readonly label: string | undefined;
readonly phaseIndex: number | undefined;
readonly phaseTitle: string | undefined;
readonly model: string | undefined;
readonly attempt: number | undefined;
readonly lastToolName: string | undefined;
readonly startedAt: string | undefined;
readonly error: string | undefined;
readonly tokens: number | undefined;
readonly toolCalls: number | undefined;
}
interface ClaudeWorkflowProgress {
readonly phases: ReadonlyArray<{ index: number; title: string }>;
readonly agents: ReadonlyArray<ClaudeWorkflowAgentEntry>;
}
/**
* Defensive parse of the SDK's undeclared-but-real workflow_progress array on
* task_progress messages (wire-confirmed; absent from sdk.d.ts). Unknown
* shapes are skipped per-entry; phases and agents dedupe by index before
* caps; a vanished field never throws. If the array disappears upstream the
* caller keeps the coordinator row and plain task lifecycle.
*/
function parseWorkflowProgress(value: unknown): ClaudeWorkflowProgress | undefined {
if (!Array.isArray(value) || value.length === 0) {
return undefined;
}
const phasesByIndex = new Map<number, string>();
const agentsByIndex = new Map<number, ClaudeWorkflowAgentEntry>();
for (const entry of value) {
if (typeof entry !== "object" || entry === null) {
continue;
}
const record = entry as Record<string, unknown>;
const entryType = trimmedString(record.type);
if (entryType === "workflow_phase") {
const index = nonNegativeInt(record.index);
const title = trimmedString(record.title);
if (index !== undefined && title && !phasesByIndex.has(index)) {
phasesByIndex.set(index, title);
}
continue;
}
if (entryType !== "workflow_agent") {
continue;
}
const index = nonNegativeInt(record.index);
const state = trimmedString(record.state);
if (index === undefined || !state || agentsByIndex.has(index)) {
continue;
}
agentsByIndex.set(index, {
index,
state,
label: trimmedString(record.label),
phaseIndex: nonNegativeInt(record.phaseIndex),
phaseTitle: trimmedString(record.phaseTitle),
model: trimmedString(record.model),
attempt: nonNegativeInt(record.attempt),
lastToolName: trimmedString(record.lastToolName),
startedAt: trimmedString(record.startedAt),
error: trimmedString(record.error),
tokens: nonNegativeInt(record.tokens),
toolCalls: nonNegativeInt(record.toolCalls),
});
}
if (phasesByIndex.size === 0 && agentsByIndex.size === 0) {
return undefined;
}
const phases = Array.from(phasesByIndex.entries())
.map(([index, title]) => ({ index, title }))
.toSorted((a, b) => a.index - b.index)
.slice(0, WORKFLOW_PHASE_CAP);
const agents = Array.from(agentsByIndex.values())
.toSorted((a, b) => a.index - b.index)
.slice(0, WORKFLOW_AGENT_CAP);
return { phases, agents };
}
/**
* Workflow member states from workflow_progress → shared task status.
* Unknown states read running after startedAt, pending before it.
*/
function workflowAgentStatus(entry: ClaudeWorkflowAgentEntry): RuntimeTaskStatus {
switch (entry.state) {
case "queued":
case "pending":
return "pending";
case "start":
case "running":
return entry.startedAt === undefined ? "pending" : "running";
case "done":
return "completed";
case "error":
return "failed";
default:
return entry.startedAt === undefined ? "pending" : "running";
}
}
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
const commandValue = input.command ?? input.cmd;
const command = typeof commandValue === "string" ? commandValue : undefined;
@@ -833,17 +1119,17 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
return `${toolName}: ${command.trim().slice(0, 400)}`;
}
// For agent/subagent tools, prefer human-readable description or prompt over raw JSON
// For agent/subagent tools, prefer the human-readable description or prompt
// over raw JSON. The structured subagent_type is carried separately on the
// task.* payloads (role) — the label is display-only.
const itemType = classifyToolItemType(toolName);
if (itemType === "collab_agent_tool_call") {
const description =
typeof input.description === "string" ? input.description.trim() : undefined;
const prompt = typeof input.prompt === "string" ? input.prompt.trim() : undefined;
const subagentType =
typeof input.subagent_type === "string" ? input.subagent_type.trim() : undefined;
const label = description || (prompt ? prompt.slice(0, 200) : undefined);
if (label) {
return subagentType ? `${subagentType}: ${label}` : label;
return label;
}
}
@@ -2078,6 +2364,32 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const { event } = message;
// Subagent-owned stream traffic (parent_tool_use_id set) must not write
// into the parent transcript: with forwardSubagentText off the SDK still
// forwards subagent tool_use/tool_result blocks and their wrapping
// text/thinking deltas, and emitting them interleaved N subagents'
// narration into the chat (live-test finding). Their results reach the
// UI via the task.* lifecycle; their tool blocks are attributed and
// re-homed by the quiet-timeline filter.
const streamParentToolUseId = (message as { parent_tool_use_id?: string | null })
.parent_tool_use_id;
if (streamParentToolUseId !== null && streamParentToolUseId !== undefined) {
// Drop only the subagent's narration (text/thinking); tool_use blocks
// and their input_json_delta frames must flow so attributed tool items
// keep their inputs (review finding: dropping deltas emptied inputs).
const dropStart =
event.type === "content_block_start" &&
event.content_block.type !== "tool_use" &&
event.content_block.type !== "server_tool_use" &&
event.content_block.type !== "mcp_tool_use";
const dropDelta =
event.type === "content_block_delta" &&
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta");
if (dropStart || dropDelta) {
return;
}
}
if (event.type === "message_delta") {
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
return;
@@ -2205,6 +2517,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: "inProgress",
title: nextTool.title,
...(nextTool.detail ? { detail: nextTool.detail } : {}),
...(nextTool.agentId ? { agentId: nextTool.agentId } : {}),
...(nextTool.parentToolUseId ? { parentToolUseId: nextTool.parentToolUseId } : {}),
data: {
toolName: nextTool.toolName,
input: nextTool.input,
@@ -2274,6 +2588,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const inputFingerprint =
Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;
// Attribute tools that ran inside a subagent to their owning agent so
// clients can re-home them out of the main timeline (quiet-timeline
// guarantee): the SDK forwards subagent tool_use blocks tagged with the
// spawning Task tool's id as parent_tool_use_id.
const parentToolUseId =
(message as { parent_tool_use_id?: string | null }).parent_tool_use_id ?? undefined;
const owningAgentId = agentIdForParentToolUse(context.taskAgents, parentToolUseId);
const tool: ToolInFlight = {
itemId,
itemType,
@@ -2283,6 +2605,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: toolInput,
partialInputJson: "",
...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),
...(owningAgentId ? { agentId: owningAgentId } : {}),
...(parentToolUseId ? { parentToolUseId } : {}),
};
context.inFlightTools.set(index, tool);
@@ -2300,6 +2624,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: "inProgress",
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
...(tool.agentId ? { agentId: tool.agentId } : {}),
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
data: {
toolName: tool.toolName,
input: toolInput,
@@ -2378,6 +2704,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: toolResult.isError ? "failed" : "inProgress",
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
...(tool.agentId ? { agentId: tool.agentId } : {}),
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
@@ -2430,6 +2758,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: itemStatus,
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
...(tool.agentId ? { agentId: tool.agentId } : {}),
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
@@ -2442,6 +2772,43 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
// The Workflow tool's result carries the run handles (runId, scriptPath,
// transcriptDir, sessionUrl). Attach them to the workflow's task agent so
// the next task.* payload advertises them to clients.
if (!toolResult.isError && tool.toolName.toLowerCase() === "workflow" && toolUseResult) {
const workflowTaskId = trimmedString(toolUseResult.taskId);
if (workflowTaskId) {
const runHandles: TaskRunHandles = {
...(trimmedString(toolUseResult.runId)
? { runId: trimmedString(toolUseResult.runId) }
: {}),
...(trimmedString(toolUseResult.scriptPath)
? { scriptPath: trimmedString(toolUseResult.scriptPath) }
: {}),
...(trimmedString(toolUseResult.transcriptDir)
? { transcriptDir: trimmedString(toolUseResult.transcriptDir) }
: {}),
...(sanitizeSessionUrl(toolUseResult.sessionUrl)
? { sessionUrl: sanitizeSessionUrl(toolUseResult.sessionUrl) }
: {}),
};
const existing = context.taskAgents.get(workflowTaskId);
context.taskAgents.set(workflowTaskId, {
taskId: workflowTaskId,
toolUseId: existing?.toolUseId ?? tool.itemId,
description: existing?.description,
subagentType: existing?.subagentType,
taskType: existing?.taskType ?? "local_workflow",
workflowName: existing?.workflowName,
skipTranscript: existing?.skipTranscript ?? false,
runHandles,
owningAgentId: existing?.owningAgentId,
model: existing?.model,
effort: existing?.effort,
});
}
}
if (
!toolResult.isError &&
applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)
@@ -2465,6 +2832,26 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
}
// Subagent-owned assistant snapshots (parent_tool_use_id set) are the
// subagent's own conversation, not the parent's. Emitting them created
// interleaved "Agent N done"-adjacent leak messages and spawned synthetic
// turns per subagent completion (which also reset the Working timer).
const assistantParentToolUseId = (message as { parent_tool_use_id?: string | null })
.parent_tool_use_id;
if (assistantParentToolUseId !== null && assistantParentToolUseId !== undefined) {
// The snapshot's message.model is the authoritative API model the
// subagent actually ran on — refine the seeded launch-time value.
const owningTaskId = agentIdForParentToolUse(context.taskAgents, assistantParentToolUseId);
const snapshotModel = trimmedString(message.message.model);
const owningAgent = owningTaskId ? context.taskAgents.get(owningTaskId) : undefined;
if (owningAgent && snapshotModel) {
owningAgent.model = snapshotModel;
}
context.lastAssistantUuid = message.uuid;
yield* updateResumeCursor(context);
return;
}
// Auto-start a synthetic turn for assistant messages that arrive without
// an active turn (e.g., background agent/subagent responses between user prompts).
if (!context.turnState) {
@@ -2554,7 +2941,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
const status = turnStatusFromResult(message);
const errorMessage = message.subtype === "success" ? undefined : message.errors[0];
const errorMessage = resultUserFacingError(message);
if (status === "failed") {
yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed.");
@@ -2563,6 +2950,82 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
yield* completeTurn(context, status, errorMessage, message);
});
/**
* Synthesizes per-member task.progress rows from the coordinator's
* workflow_progress array. Member identity is the stable slot
* `<coordinatorTaskId>:wf:<index>` (never the per-attempt agent id, which
* changes on retry and would split one member into duplicate rows).
* timelineBypass keeps these out of the parent chat; the Agents surface and
* workflow card consume them.
*/
const emitWorkflowMemberProgress = Effect.fn("emitWorkflowMemberProgress")(function* (
context: ClaudeSessionContext,
base: Omit<ProviderRuntimeEvent, "type" | "payload">,
message: Extract<SDKMessage, { type: "system"; subtype: "task_progress" }>,
) {
const progress = parseWorkflowProgress(
(message as unknown as Record<string, unknown>).workflow_progress,
);
if (!progress) {
return;
}
const coordinatorId = message.task_id;
for (const entry of progress.agents) {
const memberTaskId = `${coordinatorId}:wf:${entry.index}`;
const status = workflowAgentStatus(entry);
// Material-transition filter: the wire repeats every member each tick.
// Emit only when something the client renders actually changed, so a
// 100-agent fleet costs ~1 event per changed member instead of 100
// per tick (review finding: unbounded event amplification).
const fingerprint = [
status,
entry.label ?? "",
entry.model ?? "",
entry.lastToolName ?? "",
entry.error ?? "",
entry.tokens ?? "",
entry.toolCalls ?? "",
entry.phaseIndex ?? "",
entry.phaseTitle ?? "",
entry.attempt ?? "",
].join("\u001f");
if (context.workflowMemberFingerprints.get(memberTaskId) === fingerprint) {
continue;
}
context.workflowMemberFingerprints.set(memberTaskId, fingerprint);
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: stamp.eventId,
createdAt: stamp.createdAt,
type: "task.progress",
payload: {
taskId: RuntimeTaskId.make(memberTaskId),
description: entry.label ?? `agent ${entry.index}`,
status,
...(entry.error ? { error: entry.error } : {}),
...(entry.label ? { title: entry.label } : {}),
...(entry.model ? { model: entry.model } : {}),
...(entry.lastToolName ? { lastToolName: entry.lastToolName } : {}),
...(entry.tokens !== undefined
? {
typedUsage: {
totalTokens: entry.tokens,
...(entry.toolCalls !== undefined ? { toolUses: entry.toolCalls } : {}),
},
}
: {}),
parentAgentId: coordinatorId,
agentIndex: entry.index,
...(entry.phaseIndex !== undefined ? { phaseIndex: entry.phaseIndex } : {}),
...(entry.phaseTitle ? { phaseTitle: entry.phaseTitle } : {}),
...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),
timelineBypass: true,
},
});
}
});
const handleSystemMessage = Effect.fn("handleSystemMessage")(function* (
context: ClaudeSessionContext,
message: SDKMessage,
@@ -2593,9 +3056,15 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
// error rows in client work logs. `background_tasks_changed` is a roster
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
// authoritative per-agent data and the typed background_tasks control
// request is the reconciliation source.
if ((message.subtype as string) === "background_tasks_changed") {
return;
// request is the reconciliation source. `vcs_state_changed`
// ({kind: commit|push|rebase}) and `code_change_published`
// ({provider, url, repo}) are informational CLI notices; the work log
// already shows the underlying git/gh tool calls.
switch (message.subtype as string) {
case "background_tasks_changed":
case "vcs_state_changed":
case "code_change_published":
return;
}
switch (message.subtype) {
@@ -2678,7 +3147,46 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
case "task_started":
case "task_started": {
// A task launched by a tool that itself ran inside a subagent (the
// in-flight tool carries agentId from parent_tool_use_id) is
// agent-internal: a subagent's background shell, not parent work.
const launchingTool = message.tool_use_id
? Array.from(context.inFlightTools.values()).find(
(tool) => tool.itemId === message.tool_use_id,
)
: undefined;
const owningAgentId = launchingTool?.agentId;
// Model/effort: the Agent tool's input carries explicit overrides;
// absent ones inherit the session's selection (SDK behavior).
// Subagent assistant snapshots later refine model with the
// authoritative API id. AgentInput.effort may be a named level or an
// integer.
const launchInput = launchingTool?.input;
const model =
trimmedString(launchInput?.model) ?? trimmedString(context.session.model ?? undefined);
const rawLaunchEffort = launchInput?.effort;
const effort =
trimmedString(rawLaunchEffort) ??
(typeof rawLaunchEffort === "number" && Number.isFinite(rawLaunchEffort)
? String(rawLaunchEffort)
: context.currentEffort);
// Remember the agent identity so every later task.* payload for this
// taskId is self-describing (identity must survive activity retention).
context.taskAgents.set(message.task_id, {
taskId: message.task_id,
toolUseId: message.tool_use_id,
description: message.description,
subagentType: message.subagent_type,
taskType: message.task_type,
workflowName: message.workflow_name,
skipTranscript: message.skip_transcript === true,
runHandles: context.taskAgents.get(message.task_id)?.runHandles,
owningAgentId,
model,
effort,
});
context.liveTaskIds.add(message.task_id);
yield* offerRuntimeEvent({
...base,
type: "task.started",
@@ -2686,10 +3194,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
taskId: RuntimeTaskId.make(message.task_id),
description: message.description,
...(message.task_type ? { taskType: message.task_type } : {}),
...(owningAgentId ? { agentId: owningAgentId } : {}),
...(message.description ? { title: message.description } : {}),
...(message.subagent_type ? { role: message.subagent_type } : {}),
...(model ? { model } : {}),
...(effort ? { effort } : {}),
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
...(message.workflow_name ? { workflowName: message.workflow_name } : {}),
},
});
return;
case "task_progress":
}
case "task_progress": {
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2698,6 +3214,15 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
rawPayload: message,
},
);
const linkage = taskLinkageFor(context.taskAgents, message.task_id);
const typedUsage = normalizeTaskUsage(message.usage);
// Phases ride on the coordinator's ONE progress row per tick. A
// separate phases-only row shared the stable ingestion activity id
// with this full row, and the thinner upsert overwrote usage and
// progress text (review finding).
const workflowPhases = parseWorkflowProgress(
(message as unknown as Record<string, unknown>).workflow_progress,
)?.phases;
yield* offerRuntimeEvent({
...base,
type: "task.progress",
@@ -2706,16 +3231,48 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
description: message.description,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(typedUsage ? { typedUsage } : {}),
...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
...(workflowPhases && workflowPhases.length > 0 ? { phases: workflowPhases } : {}),
...linkage,
...(message.subagent_type ? { role: message.subagent_type } : {}),
},
});
yield* emitWorkflowMemberProgress(context, base, message);
return;
}
case "task_updated": {
// Status patch (killed/paused/backgrounded/end_time/error) — main
// previously dropped this on the floor, losing all transitions.
const patch = message.patch;
const status =
patch.status !== undefined ? CLAUDE_TASK_PATCH_STATUS[patch.status] : undefined;
if (status === "completed" || status === "failed" || status === "cancelled") {
context.liveTaskIds.delete(message.task_id);
}
const endedAt =
typeof patch.end_time === "number" && Number.isFinite(patch.end_time)
? DateTime.formatIso(DateTime.makeUnsafe(patch.end_time))
: undefined;
yield* offerRuntimeEvent({
...base,
type: "task.updated",
payload: {
taskId: RuntimeTaskId.make(message.task_id),
...(status ? { status } : {}),
...(patch.description ? { description: patch.description } : {}),
...(patch.error ? { error: patch.error } : {}),
...(endedAt ? { endedAt } : {}),
...(patch.is_backgrounded !== undefined
? { isBackgrounded: patch.is_backgrounded }
: {}),
...taskLinkageFor(context.taskAgents, message.task_id),
},
});
return;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
}
case "task_notification": {
context.liveTaskIds.delete(message.task_id);
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2724,6 +3281,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
rawPayload: message,
},
);
const typedUsage = normalizeTaskUsage(message.usage);
yield* offerRuntimeEvent({
...base,
type: "task.completed",
@@ -2732,9 +3290,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: message.status,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(typedUsage ? { typedUsage } : {}),
...(message.output_file ? { outputFile: message.output_file } : {}),
...taskLinkageFor(context.taskAgents, message.task_id),
},
});
return;
}
case "files_persisted":
yield* offerRuntimeEvent({
...base,
@@ -2870,7 +3432,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
toolUseId: message.tool_use_id,
toolName: message.tool_name,
elapsedSeconds: message.elapsed_time_seconds,
...(message.task_id ? { summary: `task:${message.task_id}` } : {}),
...(message.task_id ? { taskId: RuntimeTaskId.make(message.task_id) } : {}),
...(message.parent_tool_use_id !== null
? { parentToolUseId: message.parent_tool_use_id }
: {}),
},
});
return;
@@ -3192,6 +3757,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const inFlightTools = new Map<number, ToolInFlight>();
const claudeTasks = new Map<string, ClaudeTaskState>();
const taskAgents = new Map<string, ClaudeTaskAgentState>();
const workflowMemberFingerprints = new Map<string, string>();
const liveTaskIds = new Set<string>();
const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
@@ -3628,12 +4196,16 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
startedAt,
basePermissionMode: permissionMode,
currentApiModelId: apiModelId,
currentEffort: effectiveEffort ?? undefined,
resumeSessionId: sessionId,
pendingApprovals,
pendingUserInputs,
turns: [],
inFlightTools,
claudeTasks,
taskAgents,
workflowMemberFingerprints,
liveTaskIds,
turnState: undefined,
lastKnownContextWindow: initialContextWindow,
lastKnownTokenUsage: undefined,
@@ -3750,6 +4322,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...context.session,
model: modelSelection.model,
};
const turnCaps = getClaudeModelCapabilities(modelSelection.model);
const turnEffort = resolveClaudeEffort(
turnCaps,
getModelSelectionStringOptionValue(modelSelection, "effort"),
);
context.currentEffort =
getEffectiveClaudeAgentEffort(turnEffort ?? null, modelSelection.model) ?? undefined;
}
// Apply interaction mode by switching the SDK's permission mode.
@@ -3825,6 +4404,29 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (threadId, _turnId) {
const context = yield* requireSession(threadId);
// Stop-everything semantics: users reach for Stop precisely when a
// fleet ran away. interrupt() alone only ends the parent turn —
// background subagents/shells keep running and keep burning tokens.
// Stop every live task first (best-effort per task: one refusal must
// not strand the rest or block the turn interrupt), then interrupt.
if (context.query.stopTask && context.liveTaskIds.size > 0) {
const liveIds = Array.from(context.liveTaskIds);
// Bounded: a wedged child's stopTask promise may never settle
// (Effect.ignore handles rejection, not non-resolution), and the
// parent interrupt below MUST still run — Stop matters most during
// runaway fleets (review finding). Per-task timeout keeps one hung
// child from consuming the whole budget.
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.timeoutOption("3 seconds"), Effect.ignore),
{ concurrency: 8, discard: true },
).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);
}
yield* Effect.tryPromise({
try: () => context.query.interrupt(),
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
@@ -20,6 +20,8 @@ import {
type ProviderUserInputAnswers,
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
type RuntimeTaskUsage,
ProviderApprovalDecision,
ThreadId,
ProviderSendTurnInput,
@@ -494,10 +496,276 @@ function mapItemLifecycle(
};
}
/**
* Maps the session runtime's synthetic `collabAgent/*` events (native
* multi-agent v2 child-thread signals) into the shared task.* lifecycle.
* Agent identity = child thread id; nickname is the display title, role is
* agentRole (fallback: last agentPath segment, then "general-purpose").
* A completed child turn is idle (resumable), not terminal. timelineBypass
* keeps these rows out of the parent chat.
*/
function mapCollabAgentEvent(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): ReadonlyArray<ProviderRuntimeEvent> {
const payload =
typeof event.payload === "object" && event.payload !== null
? (event.payload as Record<string, unknown>)
: undefined;
const agentThreadId = typeof payload?.agentThreadId === "string" ? payload.agentThreadId : "";
if (!payload || agentThreadId.length === 0) {
return [];
}
const base = runtimeEventBase(event, canonicalThreadId);
const taskId = RuntimeTaskId.make(agentThreadId);
const agentPath = typeof payload.agentPath === "string" ? payload.agentPath : undefined;
const pathLeaf = agentPath?.split("/").findLast((segment) => segment.length > 0);
const nickname = typeof payload.nickname === "string" ? payload.nickname : undefined;
const role =
(typeof payload.role === "string" ? payload.role : undefined) ?? pathLeaf ?? "general-purpose";
// A bare thread id is not a name. Omitting the title lets the client fold
// keep the real one from task.started instead of clobbering it (probe
// finding: progress rows renamed math_one to its UUID).
const knownName = nickname ?? pathLeaf;
const title = knownName ?? agentThreadId;
// Identity repeated on every status patch so rows are self-describing when
// the start row ages out of activity retention (review finding: a
// reconstructed agent had a UUID name and no role/path).
const statusLinkage = {
role,
...(knownName ? { title: knownName } : {}),
...(agentPath ? { agentPath } : {}),
timelineBypass: true,
} as const;
switch (event.method) {
case "collabAgent/started":
return [
{
...base,
type: "task.started",
payload: {
taskId,
description: title,
title,
role,
...(agentPath ? { agentPath } : {}),
...(typeof payload.parentThreadId === "string"
? { parentAgentId: payload.parentThreadId }
: {}),
timelineBypass: true,
},
},
];
case "collabAgent/activity": {
const activityKind = typeof payload.activityKind === "string" ? payload.activityKind : "";
if (activityKind === "interrupted") {
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "interrupted", ...statusLinkage },
},
];
}
if (activityKind === "started") {
// Wire-probe finding: children often register via subAgentActivity
// alone (no thread/started with a spawn source), so this is the one
// shot at a task.started with a real name — agentPath leaf beats a
// bare thread-id title.
return [
{
...base,
type: "task.started",
payload: {
taskId,
description: title,
title,
role,
...(agentPath ? { agentPath } : {}),
timelineBypass: true,
},
},
];
}
// interacted → the child is (again) actively driven.
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "running", ...statusLinkage },
},
];
}
case "collabAgent/turnStarted":
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "running", ...statusLinkage },
},
];
case "collabAgent/turnCompleted": {
// Idle, not terminal: the identity is resumable via sendInput/resume.
const turn =
typeof payload.turn === "object" && payload.turn !== null
? (payload.turn as Record<string, unknown>)
: undefined;
const turnStatus = typeof turn?.status === "string" ? turn.status : undefined;
const status =
turnStatus === "failed"
? ("failed" as const)
: turnStatus === "interrupted"
? ("interrupted" as const)
: ("idle" as const);
return [
{
...base,
type: "task.updated",
payload: { taskId, status, ...statusLinkage },
},
];
}
case "collabAgent/statusChanged": {
const status =
typeof payload.status === "object" && payload.status !== null
? (payload.status as Record<string, unknown>)
: undefined;
const statusType = typeof status?.type === "string" ? status.type : undefined;
if (statusType === "systemError") {
// Silently dropping this once left children stuck running forever.
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "failed", ...statusLinkage },
},
];
}
if (statusType === "active") {
const flags = Array.isArray(status?.activeFlags) ? status.activeFlags : [];
const waiting = flags.some(
(flag) => flag === "waitingOnApproval" || flag === "waitingOnUserInput",
);
return [
{
...base,
type: "task.updated",
payload: { taskId, status: waiting ? "waiting" : "running", ...statusLinkage },
},
];
}
if (statusType === "idle") {
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "idle", ...statusLinkage },
},
];
}
return [];
}
case "collabAgent/tokenUsage": {
// Cumulative per child thread: always the `total` breakdown, never
// `last` (which shrinks on follow-ups). Client folds max-merge.
const tokenUsage =
typeof payload.tokenUsage === "object" && payload.tokenUsage !== null
? (payload.tokenUsage as Record<string, unknown>)
: undefined;
const total =
typeof tokenUsage?.total === "object" && tokenUsage.total !== null
? (tokenUsage.total as Record<string, unknown>)
: undefined;
const count = (value: unknown): number | undefined =>
typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
// Same validation as every other field: RuntimeTaskUsage.totalTokens
// is NonNegativeInt, so NaN/Infinity/negative wire values must miss.
const totalTokens = count(total?.totalTokens);
if (totalTokens === undefined) {
return [];
}
const typedUsage: RuntimeTaskUsage = {
totalTokens,
...(count(total?.inputTokens) !== undefined
? { inputTokens: count(total?.inputTokens) }
: {}),
...(count(total?.cachedInputTokens) !== undefined
? { cachedInputTokens: count(total?.cachedInputTokens) }
: {}),
...(count(total?.outputTokens) !== undefined
? { outputTokens: count(total?.outputTokens) }
: {}),
...(count(total?.reasoningOutputTokens) !== undefined
? { reasoningOutputTokens: count(total?.reasoningOutputTokens) }
: {}),
};
return [
{
...base,
type: "task.progress",
payload: {
taskId,
description: title,
...(knownName ? { title: knownName } : {}),
typedUsage,
timelineBypass: true,
},
},
];
}
case "collabAgent/item": {
const item =
typeof payload.item === "object" && payload.item !== null
? (payload.item as Record<string, unknown>)
: undefined;
const itemTypeRaw = typeof item?.type === "string" ? item.type : undefined;
if (!itemTypeRaw) {
return [];
}
// A loose summary from the raw item: the child stream is untyped at
// this boundary (synthetic event payload), so read best-effort fields
// rather than force a schema decode.
const looseSummary =
(typeof item?.command === "string" ? item.command : undefined) ??
(typeof item?.title === "string" ? item.title : undefined) ??
(typeof item?.query === "string" ? item.query : undefined);
const canonical = toCanonicalItemType(itemTypeRaw);
const summary = looseSummary ?? canonical.replaceAll("_", " ");
return [
{
...base,
type: "task.progress",
payload: {
taskId,
description: title,
...(knownName ? { title: knownName } : {}),
summary,
timelineBypass: true,
},
},
];
}
case "collabAgent/closed":
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "interrupted", ...statusLinkage },
},
];
default:
return [];
}
}
function mapToRuntimeEvents(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): ReadonlyArray<ProviderRuntimeEvent> {
if (event.kind === "notification" && event.method.startsWith("collabAgent/")) {
return mapCollabAgentEvent(event, canonicalThreadId);
}
if (event.kind === "error") {
if (!event.message) {
return [];
@@ -0,0 +1,314 @@
/**
* Runtime-level collab regression: boots the REAL CodexSessionRuntime against
* a scripted mock app-server peer that replays the captured multi-agent wire
* sequence (codexMultiAgentWire.json) plus the shapes the capture alone can't
* script (receiver-turn bookkeeping via collabAgentToolCall, child terminal
* lifecycle, approval pass-through). This is the layer the pure routing-table
* test can't reach: ordering between the legacy receiver-turn suppressor and
* v2 interception, registration state, and synthetic event emission.
*/
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Stream from "effect/Stream";
import { assert, describe } from "vite-plus/test";
import wireFixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
import { makeCodexSessionRuntime } from "./CodexSessionRuntime.ts";
const ROOT = wireFixture.rootThreadId;
const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
/**
* The captured sequence, extended with the shapes the live capture didn't
* include: a collabAgentToolCall with receiverThreadIds (feeds the legacy
* receiver-turn map, so ordering vs. v2 interception is exercised), child
* terminal lifecycle, and a serverRequest/resolved addressed to a child
* (must pass through to the parent path, not vanish).
*/
function buildScript() {
const captured = wireFixture.notifications;
// Re-address the capture's schema-valid tool lifecycle pair to child A.
// Hand-written item shapes can drift from the generated Codex schema.
const childToolLifecycle = captured
.filter(
(entry) =>
(entry.method === "item/started" || entry.method === "item/completed") &&
(entry.params as { item?: { type?: string } }).item?.type === "collabAgentToolCall",
)
.map((entry) => {
const params = entry.params as {
readonly threadId: string;
readonly turnId: string;
readonly item: Record<string, unknown>;
};
return {
...entry,
params: {
...params,
threadId: CHILD_A,
turnId: `${CHILD_A}-turn-1`,
item: {
...params.item,
id: "call_fixture_child_tool",
senderThreadId: CHILD_A,
},
},
};
});
const childCompletionOnly = childToolLifecycle.find((entry) => entry.method === "item/completed");
assert.isDefined(childCompletionOnly);
const extras = [
{
method: "item/completed",
params: {
threadId: ROOT,
item: {
type: "collabAgentToolCall",
id: "call_fixture_wait",
tool: "wait",
status: "completed",
senderThreadId: ROOT,
receiverThreadIds: [CHILD_A, CHILD_B],
},
},
},
// Codex emits started + completed for one child item. They are one
// logical activity and must not become two synthetic agent updates.
...childToolLifecycle,
{
...childCompletionOnly,
params: {
...childCompletionOnly.params,
item: {
...childCompletionOnly.params.item,
id: "call_fixture_child_completion_only",
},
},
},
// Child terminal lifecycle AFTER the receiver map knows the children —
// pre-fix, the legacy suppressor dropped these before interception saw
// them, so no synthetic agent events were emitted.
{
method: "turn/completed",
params: {
threadId: CHILD_A,
turn: { id: `${CHILD_A}-turn-1`, status: "completed", items: [] },
},
},
{ method: "thread/closed", params: { threadId: CHILD_B } },
// Parent-owned traffic addressed to a child conversation: must reach the
// parent path (approval correlation cleanup), not be swallowed.
{ method: "serverRequest/resolved", params: { threadId: CHILD_A, requestId: "req-1" } },
];
return {
rootThreadId: ROOT,
notifications: [...captured.filter((entry) => entry.method !== "turn/completed"), ...extras],
};
}
const scriptPath = NodePath.join(import.meta.dirname, "../testFixtures/.collab-script.json");
const peerPath = NodePath.join(import.meta.dirname, "../testFixtures/codexCollabMockPeer.sh");
describe("CodexSessionRuntime collab integration", () => {
it.effect("replays the captured fan-out into synthetic agent events without child leaks", () =>
Effect.gen(function* () {
// @effect-diagnostics-next-line preferSchemaOverJson:off
NodeFS.writeFileSync(scriptPath, JSON.stringify(buildScript()), "utf8");
yield* Effect.addFinalizer(() =>
Effect.sync(() => NodeFS.rmSync(scriptPath, { force: true })),
);
const runtime = yield* makeCodexSessionRuntime({
threadId: ThreadId.make("thread-collab-integration"),
binaryPath: peerPath,
cwd: "/tmp",
runtimeMode: "full-access",
environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
});
const eventsFiber = yield* runtime.events.pipe(
Stream.takeUntil((event) => event.method === "turn/completed"),
Stream.runCollect,
Effect.forkScoped,
);
yield* runtime.start();
yield* runtime.sendTurn({ input: "fan out" });
const events = Array.from(yield* Fiber.join(eventsFiber));
const methods = events.map((event) => event.method);
// Children registered from subAgentActivity become synthetic agent
// lifecycle — including terminal rows that arrive AFTER the receiver
// map knows them (the ordering this test exists to pin).
assert.include(methods, "collabAgent/activity");
assert.include(methods, "collabAgent/turnCompleted");
assert.include(methods, "collabAgent/closed");
const childTurnCompleted = events.find(
(event) =>
event.method === "collabAgent/turnCompleted" &&
(event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
);
assert.isDefined(childTurnCompleted, "child A's turn completion becomes an agent event");
const childClosed = events.find(
(event) =>
event.method === "collabAgent/closed" &&
(event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
);
assert.isDefined(childClosed, "child B's close becomes an agent event");
const childToolItems = events.filter(
(event) =>
event.method === "collabAgent/item" &&
(event.payload as { item?: { id?: string } }).item?.id === "call_fixture_child_tool",
);
assert.lengthOf(childToolItems, 1, "one child item must emit one agent activity");
assert.equal(childToolItems[0]?.itemId, "call_fixture_child_tool");
assert.equal(
(childToolItems[0]?.payload as { itemLifecycle?: string }).itemLifecycle,
"started",
);
const completionOnly = events.find(
(event) =>
event.method === "collabAgent/item" &&
(event.payload as { item?: { id?: string } }).item?.id ===
"call_fixture_child_completion_only",
);
assert.equal(
(completionOnly?.payload as { itemLifecycle?: string }).itemLifecycle,
"completed",
);
// Parent-owned resolution passes through — not swallowed, not
// re-labelled as an agent event.
assert.include(methods, "serverRequest/resolved");
// The root's own subAgentActivity about "/root" must NOT register the
// root as a child: the parent turn completion still flows.
assert.include(methods, "turn/completed");
// No raw child conversation methods leak onto the parent stream.
const leaked = events.filter((event) => {
const payload = event.payload as { threadId?: string } | undefined;
const addressedToChild = payload?.threadId === CHILD_A || payload?.threadId === CHILD_B;
return addressedToChild && (event.method?.startsWith("thread/") ?? false);
});
assert.deepEqual(
leaked.map((event) => event.method),
[],
"child thread/* lifecycle must not appear as parent events",
);
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// it.live: the runtime talks to a real child process; under it.effect's
// TestClock the internal timers freeze and the join never completes.
it.live("Stop interrupts every live child regardless of registration timing", () =>
Effect.gen(function* () {
// Ordering + liveness torture for stop-everything: child A's
// turn/started arrives BEFORE anything registers it (foreign
// suppression path must record the live turn); child B's arrives after
// registration; child A's interrupt HANGS (RPC never settles — worse
// than rejecting) and the bounded deadline must still deliver B's and
// the parent's interrupts. The turn stays open so children are live
// when Stop fires.
// Build from REAL captured rows (hand-written shapes fail notification
// schema validation and are silently dropped): reorder so child A's
// turn/started precedes its registration, and drop terminal rows so
// children stay live when Stop fires.
const byIndex = wireFixture.notifications;
const isTurnStarted = (entry: (typeof byIndex)[number], child: string) =>
entry.method === "turn/started" &&
(entry.params as { threadId?: string }).threadId === child;
const isRegistration = (entry: (typeof byIndex)[number], child: string) => {
const item = (entry.params as { item?: { type?: string; agentThreadId?: string } }).item;
return item?.type === "subAgentActivity" && item.agentThreadId === child;
};
const turnStartedA = byIndex.find((entry) => isTurnStarted(entry, CHILD_A));
const turnStartedB = byIndex.find((entry) => isTurnStarted(entry, CHILD_B));
const registrationA = byIndex.find((entry) => isRegistration(entry, CHILD_A));
const registrationB = byIndex.find((entry) => isRegistration(entry, CHILD_B));
assert.isDefined(turnStartedA);
assert.isDefined(turnStartedB);
assert.isDefined(registrationA);
assert.isDefined(registrationB);
const script = {
rootThreadId: ROOT,
holdTurnOpen: true,
hangInterruptFor: CHILD_A,
notifications: [turnStartedA, registrationA, registrationB, turnStartedB],
};
// @effect-diagnostics-next-line preferSchemaOverJson:off
NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
const interruptsPath = `${scriptPath}.interrupts`;
NodeFS.rmSync(interruptsPath, { force: true });
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
NodeFS.rmSync(scriptPath, { force: true });
NodeFS.rmSync(interruptsPath, { force: true });
}),
);
const runtime = yield* makeCodexSessionRuntime({
threadId: ThreadId.make("thread-collab-stop"),
binaryPath: peerPath,
cwd: "/tmp",
runtimeMode: "full-access",
environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
});
// Wait for both children's turnStarted signals to be processed before
// stopping (B via the registered-child path; A only produces live-turn
// bookkeeping, so key on B's synthetic event).
const childBStartedFiber = yield* runtime.events.pipe(
Stream.filter(
(event) =>
event.method === "collabAgent/turnStarted" &&
(event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
),
Stream.take(1),
Stream.runCollect,
Effect.forkScoped,
);
yield* runtime.start();
yield* runtime.sendTurn({ input: "fan out and hang" });
const childBStarted = yield* Fiber.join(childBStartedFiber).pipe(
Effect.timeoutOption("15 seconds"),
);
assert.isTrue(childBStarted._tag === "Some", "child B turnStarted never arrived");
// Stop everything. A's interrupt hangs forever — the bounded child
// deadline must expire and the parent interrupt must still be sent.
yield* runtime.interruptTurn();
const parseInterruptLine = (line: string) => JSON.parse(line) as { threadId?: string };
const interrupted = NodeFS.readFileSync(interruptsPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map(parseInterruptLine);
const interruptedThreads = new Set(interrupted.map((entry) => entry.threadId));
assert.isTrue(
interruptedThreads.has(CHILD_A),
"pre-registration child A must still receive the interrupt RPC",
);
assert.isTrue(interruptedThreads.has(CHILD_B), "registered child B must be interrupted");
assert.isTrue(interruptedThreads.has(ROOT), "parent turn must be interrupted last");
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -0,0 +1,180 @@
/**
* Codex multi-agent wire fixtures.
*
* The child-interception path is the highest-blast-radius code in the
* subagent stack: it decides, per notification, whether traffic reaches the
* parent timeline at all. Three shipped bugs came from that decision being
* implicit (root thread registered as its own child; `error` and
* `serverRequest/resolved` swallowed by a catch-all). These tests pin the
* decision against a REAL capture rather than hand-written shapes.
*
* Fixture provenance: codex-cli 0.145.0 driven directly over stdio with
* gpt-5.6-luna at low effort, prompting a two-child fan-out (alpha, beta).
* See codexMultiAgentWire.json.
*/
import { assert, describe, it } from "vite-plus/test";
import fixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
import { routeCodexChildNotification } from "./CodexSessionRuntime.ts";
interface WireNotification {
readonly method: string;
readonly params: Record<string, unknown>;
}
const notifications = fixture.notifications as ReadonlyArray<WireNotification>;
const rootThreadId = fixture.rootThreadId;
const childThreadIds = new Set(fixture.childThreadIds);
/** Mirrors readNotificationThreadId's addressing for the captured methods. */
function notificationThreadId(entry: WireNotification): string | undefined {
const params = entry.params;
const thread = params.thread;
if (
typeof thread === "object" &&
thread !== null &&
typeof (thread as { id?: unknown }).id === "string"
) {
return (thread as { id: string }).id;
}
return typeof params.threadId === "string" ? params.threadId : undefined;
}
function subAgentActivityItems(): ReadonlyArray<Record<string, unknown>> {
return notifications.flatMap((entry) => {
const item = entry.params.item;
if (typeof item !== "object" || item === null) return [];
const record = item as Record<string, unknown>;
return record.type === "subAgentActivity" ? [record] : [];
});
}
describe("codex multi-agent wire capture", () => {
it("captures a real two-child fan-out", () => {
assert.equal(fixture.capturedWith.model, "gpt-5.6-luna");
assert.equal(childThreadIds.size, 2);
const paths = subAgentActivityItems().map((item) => item.agentPath);
assert.include(paths, "/root/alpha");
assert.include(paths, "/root/beta");
});
it("emits child traffic BEFORE the item that registers the child", () => {
// Ordering hazard: the child's own thread/status/changed arrives before
// the parent-side subAgentActivity naming it. Registration must tolerate
// child-first arrival, so unregistered child traffic passes through
// rather than being eaten (no regression vs. pre-feature behavior).
const firstChildTraffic = notifications.findIndex((entry) => {
const threadId = notificationThreadId(entry);
return threadId !== undefined && childThreadIds.has(threadId);
});
const firstRegistration = notifications.findIndex((entry) => {
const item = entry.params.item;
if (typeof item !== "object" || item === null) return false;
const record = item as Record<string, unknown>;
return record.type === "subAgentActivity" && record.kind === "started";
});
assert.isAtLeast(firstChildTraffic, 0);
assert.isAtLeast(firstRegistration, 0);
assert.isBelow(
firstChildTraffic,
firstRegistration,
"capture should exercise child-first ordering",
);
});
it("contains a /root self-activity emitted from a CHILD thread", () => {
// The bug this guards: the wire reports subAgentActivity about the ROOT
// (agentPath "/root"). Registering it made the runtime intercept the
// parent's own final message and turn/completed, so the thread hung
// "working" forever. The root guard must key on agentPath/thread id,
// never on which thread the notification arrived from.
const rootSelfActivity = subAgentActivityItems().find((item) => item.agentPath === "/root");
assert.isDefined(rootSelfActivity, "capture should contain a /root self-activity");
assert.equal(rootSelfActivity?.agentThreadId, rootThreadId);
});
it("routes every captured child method to a defined disposition", () => {
const childMethods = new Set(
notifications
.filter((entry) => {
const threadId = notificationThreadId(entry);
return threadId !== undefined && childThreadIds.has(threadId);
})
.map((entry) => entry.method),
);
assert.isAbove(childMethods.size, 0);
for (const method of childMethods) {
const route = routeCodexChildNotification(method);
// Child lifecycle traffic must become agent events — never silently
// dropped, never leaked to the parent timeline.
assert.equal(route, "agent-event", `${method} should map to an agent event`);
}
});
});
describe("routeCodexChildNotification", () => {
it("maps child lifecycle to agent events", () => {
for (const method of [
"turn/started",
"turn/completed",
"thread/status/changed",
"thread/tokenUsage/updated",
"item/started",
"item/completed",
"thread/closed",
"error",
]) {
assert.equal(routeCodexChildNotification(method), "agent-event", method);
}
});
it("drops only enumerated child chatter", () => {
for (const method of [
"item/agentMessage/delta",
"item/reasoning/textDelta",
"item/commandExecution/outputDelta",
"turn/plan/updated",
"thread/name/updated",
]) {
assert.equal(routeCodexChildNotification(method), "drop", method);
}
});
it("never routes child-owned thread lifecycle to the parent", () => {
// These mutate PARENT thread state in CodexAdapter (archived/compacted),
// so a child emitting them must never reach the parent path. This list
// mirrors shouldSuppressChildConversationNotification (the v1 collab
// suppressor) — the two must not drift (review finding: the router
// initially omitted them and they leaked).
for (const method of [
"thread/started",
"thread/status/changed",
"thread/archived",
"thread/unarchived",
"thread/closed",
"thread/compacted",
"thread/name/updated",
"thread/tokenUsage/updated",
"turn/started",
"turn/completed",
"turn/plan/updated",
"item/plan/delta",
]) {
assert.notEqual(
routeCodexChildNotification(method),
"parent",
`${method} is child-owned and must not reach the parent path`,
);
}
});
it("sends parent-owned and UNKNOWN methods to the parent path", () => {
// serverRequest/resolved clears the parent's approval correlation:
// swallowing it left approvals stuck (shipped bug). Unknown methods take
// the same route by design — a codex update that adds a notification
// must degrade to "parent sees it", never to silent loss.
assert.equal(routeCodexChildNotification("serverRequest/resolved"), "parent");
assert.equal(routeCodexChildNotification("thread/somethingBrandNew"), "parent");
assert.equal(routeCodexChildNotification("account/rateLimits/updated"), "parent");
});
});
@@ -600,6 +600,71 @@ function readRouteFields(notification: CodexServerNotification): {
}
}
/**
* Native collab child-agent tracking (multi-agent v2). Under v2 subagents are
* full app-server threads: identity arrives on `thread/started` with
* source.subAgent.thread_spawn, lifecycle on `subAgentActivity` items and the
* child thread's own turn/status/tokenUsage notifications. The runtime
* registers children from those explicit signals, intercepts their
* notifications before parent-timeline mapping, and re-emits them as
* synthetic `collabAgent/*` provider events the adapter turns into task.*
* runtime events (timelineBypass keeps them out of the parent chat).
*
* WIP, probe-gated: registration is deliberately explicit-signals-only. The
* spec's "provisionally treat unknown foreign thread ids as v2 children" rule
* needs a live wire capture of the packaged binary before it lands — blind
* capture risks eating unrelated traffic. Until then a child whose first
* notification precedes registration passes through as today (no regression
* vs main, which passes everything through).
*/
interface CollabChildAgentState {
readonly agentThreadId: string;
readonly nickname: string | undefined;
readonly role: string | undefined;
readonly agentPath: string | undefined;
readonly depth: number | undefined;
readonly parentThreadId: string | undefined;
/**
* Parent canonical turn active when the child registered. Stamped on every
* synthetic collabAgent/* event so clients can batch a fleet by its spawn
* turn — without it, separate fleets in one thread collapsed into a single
* "direct:no-turn" CTA (review finding).
*/
readonly spawnTurnId: TurnId | undefined;
}
function readThreadSpawnSource(thread: { readonly source: unknown }):
| {
nickname: string | undefined;
role: string | undefined;
agentPath: string | undefined;
depth: number | undefined;
parentThreadId: string | undefined;
}
| undefined {
const source = thread.source;
if (typeof source !== "object" || source === null || !("subAgent" in source)) {
return undefined;
}
const subAgent = (source as { subAgent: unknown }).subAgent;
if (typeof subAgent !== "object" || subAgent === null || !("thread_spawn" in subAgent)) {
return undefined;
}
const spawn = (subAgent as { thread_spawn: unknown }).thread_spawn;
if (typeof spawn !== "object" || spawn === null) {
return undefined;
}
const record = spawn as Record<string, unknown>;
return {
nickname: typeof record.agent_nickname === "string" ? record.agent_nickname : undefined,
role: typeof record.agent_role === "string" ? record.agent_role : undefined,
agentPath: typeof record.agent_path === "string" ? record.agent_path : undefined,
depth: typeof record.depth === "number" ? record.depth : undefined,
parentThreadId:
typeof record.parent_thread_id === "string" ? record.parent_thread_id : undefined,
};
}
function rememberCollabReceiverTurns(
collabReceiverTurns: Map<string, TurnId>,
notification: CodexServerNotification,
@@ -641,6 +706,72 @@ function shouldSuppressChildConversationNotification(
);
}
/**
* How a notification addressed to a REGISTERED child thread is handled.
*
* Exported and pure so the routing table can be asserted against captured
* wire traces (see codexMultiAgentWire.json) rather than only read.
*
* - "agent-event": map to a synthetic collabAgent/* event (Agents surface).
* - "parent": pass through to the parent path — it carries state the parent
* still owns (approval correlation cleanup).
* - "drop": genuine child chatter with no parent meaning (deltas, name and
* plan updates).
*
* Default is "drop" ONLY for the enumerated chatter; anything unrecognized
* routes to "parent" so new wire methods surface instead of vanishing
* (two shipped bugs came from a catch-all that swallowed everything).
*/
export type CodexChildNotificationRoute = "agent-event" | "parent" | "drop";
const CHILD_AGENT_EVENT_METHODS: ReadonlySet<string> = new Set([
"turn/started",
"turn/completed",
"thread/status/changed",
"thread/tokenUsage/updated",
"item/started",
"item/completed",
"thread/closed",
"error",
]);
const CHILD_CHATTER_METHODS: ReadonlySet<string> = new Set([
"item/agentMessage/delta",
"item/reasoning/textDelta",
"item/reasoning/summaryTextDelta",
"item/reasoning/summaryPartAdded",
"item/commandExecution/outputDelta",
"item/fileChange/outputDelta",
"item/fileChange/patchUpdated",
"item/plan/delta",
"turn/plan/updated",
"turn/diff/updated",
"thread/name/updated",
"thread/settings/updated",
"rawResponseItem/completed",
// Child-owned thread lifecycle: the parent adapter maps these onto the
// PARENT thread (archived/compacted state), so a child compacting would
// rewrite the parent. Mirrors the v1 suppressor list — dropping them is
// the pre-existing behavior for collab children (review finding).
"thread/archived",
"thread/unarchived",
"thread/compacted",
// Registration path 1 handles a child's first thread/started; a repeat
// must not reach the parent (it would restart the parent's thread state).
"thread/started",
]);
export function routeCodexChildNotification(method: string): CodexChildNotificationRoute {
if (CHILD_AGENT_EVENT_METHODS.has(method)) {
return "agent-event";
}
if (CHILD_CHATTER_METHODS.has(method)) {
return "drop";
}
// Unknown or parent-owned (serverRequest/resolved, approvals, …).
return "parent";
}
function toCodexUserInputAnswer(
questionId: string,
value: ProviderUserInputAnswers[string],
@@ -723,6 +854,11 @@ export const makeCodexSessionRuntime = (
const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());
const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgentState>());
/** Child provider-thread id → item ids already emitted during its lifetime. */
const collabChildSeenItemsRef = yield* Ref.make(new Map<string, ReadonlySet<string>>());
/** Child provider-thread id → its currently running provider turn id. */
const collabChildLiveTurnsRef = yield* Ref.make(new Map<string, string>());
const closedRef = yield* Ref.make(false);
// `~` is not shell-expanded when env vars are set via
@@ -839,6 +975,305 @@ export const makeCodexSessionRuntime = (
),
);
/**
* Registers v2 collab children and re-emits their notifications as
* synthetic `collabAgent/*` events for the adapter's task.* synthesis.
* Returns true when the notification was fully handled (must not reach
* parent-timeline mapping).
*/
const interceptCollabChildNotification = (notification: CodexServerNotification) =>
Effect.gen(function* () {
// Registration path 1: child thread announces itself with a
// subAgent thread_spawn source.
if (notification.method === "thread/started") {
const thread = notification.params.thread;
const spawn = readThreadSpawnSource(thread);
if (!spawn) {
return false;
}
// Merge with any subAgentActivity registration that got here
// first. spawnTurnId is REGISTRATION-time-only on both paths: for
// an already-known child we keep its value (set or unset) — a
// later thread/started during an unrelated parent turn must not
// backfill that turn as the spawn batch, which would stamp an old
// child onto a new fleet's CTA (review finding). Only a genuinely
// new registration captures the current turn.
const existingChild = (yield* Ref.get(collabChildAgentsRef)).get(thread.id);
const spawnTurnId = existingChild
? existingChild.spawnTurnId
: ((yield* Ref.get(sessionRef)).activeTurnId ?? undefined);
const state: CollabChildAgentState = {
agentThreadId: thread.id,
nickname: spawn.nickname ?? thread.agentNickname ?? existingChild?.nickname,
role: spawn.role ?? thread.agentRole ?? existingChild?.role,
agentPath: spawn.agentPath ?? existingChild?.agentPath,
depth: spawn.depth ?? existingChild?.depth,
parentThreadId:
spawn.parentThreadId ?? thread.parentThreadId ?? existingChild?.parentThreadId,
spawnTurnId,
};
yield* Ref.update(collabChildAgentsRef, (current) => {
const next = new Map(current);
next.set(thread.id, state);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
method: "collabAgent/started",
...(state.spawnTurnId ? { turnId: state.spawnTurnId } : {}),
payload: {
agentThreadId: state.agentThreadId,
...(state.nickname ? { nickname: state.nickname } : {}),
...(state.role ? { role: state.role } : {}),
...(state.agentPath ? { agentPath: state.agentPath } : {}),
...(state.depth !== undefined ? { depth: state.depth } : {}),
...(state.parentThreadId ? { parentThreadId: state.parentThreadId } : {}),
},
});
return true;
}
// Registration path 2: parent-side subAgentActivity item names the
// child thread (may arrive before or after thread/started).
if (
(notification.method === "item/started" || notification.method === "item/completed") &&
notification.params.item.type === "subAgentActivity"
) {
const item = notification.params.item;
// Never register the session's ROOT thread as its own child. The
// wire emits subAgentActivity {agentPath: "/root", interacted}
// about the root during collab runs; registering it intercepted
// every subsequent root notification — including the final
// assistant message and turn/completed — so the thread hung
// "working" after all subagents finished (live-probe finding).
const rootProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
if (
item.agentThreadId === rootProviderThreadId ||
item.agentPath === "/root" ||
item.agentPath === "/"
) {
return false;
}
const activitySpawnTurnId = (yield* Ref.get(sessionRef)).activeTurnId ?? undefined;
yield* Ref.update(collabChildAgentsRef, (current) => {
const existing = current.get(item.agentThreadId);
const next = new Map(current);
// Merge-late semantics: when thread/started registered first, a
// later subAgentActivity still carries the real agentPath (and a
// derived nickname) — fill missing fields, never clobber known
// ones. spawnTurnId is registration-time-only: for an already
// registered child, a later activity during an UNRELATED turn
// must not backfill that turn as the spawn batch (review
// finding); an unset spawn turn stays unset.
next.set(item.agentThreadId, {
agentThreadId: item.agentThreadId,
nickname:
existing?.nickname ??
item.agentPath.split("/").findLast((segment) => segment.length > 0),
role: existing?.role,
agentPath: existing?.agentPath ?? item.agentPath,
depth: existing?.depth,
parentThreadId: existing?.parentThreadId,
spawnTurnId: existing ? existing.spawnTurnId : activitySpawnTurnId,
});
return next;
});
const registeredChild = (yield* Ref.get(collabChildAgentsRef)).get(item.agentThreadId);
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
method: "collabAgent/activity",
...(registeredChild?.spawnTurnId ? { turnId: registeredChild.spawnTurnId } : {}),
payload: {
agentThreadId: item.agentThreadId,
agentPath: item.agentPath,
activityKind: item.kind,
},
});
return true;
}
// Interception: notifications addressed to a registered child thread
// become agent-scoped synthetic events instead of parent chatter.
const providerConversationId = readNotificationThreadId(notification);
if (!providerConversationId) {
return false;
}
// Belt-and-braces: the root thread's traffic must never be
// intercepted, whatever the registry says.
const interceptRootId = currentProviderThreadId(yield* Ref.get(sessionRef));
if (providerConversationId === interceptRootId) {
return false;
}
const children = yield* Ref.get(collabChildAgentsRef);
const child = children.get(providerConversationId);
if (!child) {
return false;
}
const childIdentity = {
agentThreadId: child.agentThreadId,
...(child.nickname ? { nickname: child.nickname } : {}),
...(child.role ? { role: child.role } : {}),
...(child.agentPath ? { agentPath: child.agentPath } : {}),
};
switch (notification.method) {
case "turn/started": {
const childTurnId =
typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === "string"
? ((notification.params as { turn: { id: string } }).turn.id as string)
: undefined;
if (childTurnId) {
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.set(child.agentThreadId, childTurnId);
return next;
});
}
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/turnStarted",
payload: childIdentity,
});
return true;
}
case "turn/completed":
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/turnCompleted",
payload: {
...childIdentity,
turn: notification.params.turn,
},
});
return true;
case "thread/status/changed":
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/statusChanged",
payload: {
...childIdentity,
status: notification.params.status,
},
});
return true;
case "thread/tokenUsage/updated":
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/tokenUsage",
payload: {
...childIdentity,
tokenUsage: notification.params.tokenUsage,
},
});
return true;
case "item/started":
case "item/completed": {
const item = notification.params.item;
const shouldEmit = yield* Ref.modify(collabChildSeenItemsRef, (current) => {
const seen = current.get(child.agentThreadId);
if (seen?.has(item.id) === true) {
return [false, current];
}
const next = new Map(current);
next.set(child.agentThreadId, new Set([...(seen ?? []), item.id]));
return [true, next];
});
// Codex emits both lifecycle notifications for the same child
// tool item. The adapter turns each synthetic event into agent
// activity, so only the first one is useful; completion-only
// items still pass through when no start was observed.
if (!shouldEmit) {
return true;
}
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
itemId: ProviderItemId.make(item.id),
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/item",
payload: {
...childIdentity,
itemLifecycle: notification.method === "item/started" ? "started" : "completed",
item,
},
});
return true;
}
case "thread/closed":
// The child is gone: drop its live-turn entry so a later Stop
// doesn't waste a turn/interrupt RPC on a closed thread before
// reaching the parent (review finding).
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* Ref.update(collabChildSeenItemsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/closed",
payload: childIdentity,
});
return true;
case "error": {
// A child error must surface as a failed agent, not vanish into
// the default swallow (review finding: the child stayed
// "running" forever). Retryable errors (willRetry) keep the
// child RUNNING and interruptible — mirroring the root error
// handler; settling it would orphan a still-live child from
// Stop (review finding). Terminal errors clean up the live turn
// like thread/closed and reuse the statusChanged systemError
// path.
const willRetry = (notification.params as { willRetry?: boolean }).willRetry === true;
if (willRetry) {
return true;
}
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/statusChanged",
payload: {
...childIdentity,
status: { type: "systemError" },
},
});
return true;
}
default:
// Routing table decides (single source of truth, asserted
// against captured wire traces): enumerated chatter is dropped,
// everything else — including methods this build has never seen
// — falls through to the parent path rather than vanishing.
return routeCodexChildNotification(notification.method) === "drop";
}
});
const handleRawNotification = (notification: CodexServerNotification) =>
Effect.gen(function* () {
const payload = notification.params;
@@ -852,7 +1287,68 @@ export const makeCodexSessionRuntime = (
})();
rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);
if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) {
// Interception FIRST: a registered v2 child is usually also in the
// receiver-turn map (collabAgentToolCall.receiverThreadIds), and the
// legacy suppressor below would drop its lifecycle before it could
// become synthetic collabAgent events (review finding). The
// suppressor still covers UNREGISTERED children.
if (yield* interceptCollabChildNotification(notification)) {
yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
return;
}
// Suppression applies to receiver-map children (v1) AND to any
// conversation that is not the root thread. The live capture
// (codexMultiAgentWire.json) shows a child's thread/status/changed
// arriving BEFORE anything registers the child — pre-registration
// lifecycle must not reach the parent path, where the adapter maps
// thread/* onto parent session state. Root-id-known guard keeps the
// root's own early notifications flowing during session open.
const suppressRootId = currentProviderThreadId(yield* Ref.get(sessionRef));
const foreignConversation = (() => {
const providerConversationId = readNotificationThreadId(notification);
return (
providerConversationId !== undefined &&
suppressRootId !== undefined &&
providerConversationId !== suppressRootId
);
})();
if (
(childParentTurnId !== undefined || foreignConversation) &&
shouldSuppressChildConversationNotification(notification.method)
) {
// Stop-everything must not depend on registration timing: a
// child's turn/started can arrive before the subAgentActivity that
// registers it (captured ordering), and suppressing it without
// remembering the live turn would leave that child running after
// Stop (review finding). Track live turns for ANY foreign
// conversation; interrupts are best-effort per child, so a
// false-positive entry costs one ignored RPC at worst.
const foreignThreadId = readNotificationThreadId(notification);
if (foreignThreadId !== undefined) {
if (notification.method === "turn/started") {
const foreignTurnId =
typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === "string"
? (notification.params as { turn: { id: string } }).turn.id
: undefined;
if (foreignTurnId) {
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.set(foreignThreadId, foreignTurnId);
return next;
});
}
} else if (
notification.method === "turn/completed" ||
notification.method === "thread/closed"
) {
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(foreignThreadId);
return next;
});
}
}
yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
return;
}
@@ -1331,6 +1827,26 @@ export const makeCodexSessionRuntime = (
Effect.gen(function* () {
const providerThreadId = yield* readProviderThreadId;
const session = yield* Ref.get(sessionRef);
// Stop-everything: children are full threads with their own turns;
// interrupting only the parent leaves the fleet running. Interrupt
// each live child turn first, best-effort per child, BOUNDED: the
// transport awaits an unbounded Deferred per request, so a wedged
// child would otherwise block the parent interrupt forever —
// exactly during the runaway fleet where Stop matters most
// (review finding). Per-child and overall deadlines guarantee the
// parent interrupt below always runs.
const liveChildTurns = yield* Ref.get(collabChildLiveTurnsRef);
yield* Effect.forEach(
Array.from(liveChildTurns.entries()),
([childThreadId, childTurnId]) =>
client
.request("turn/interrupt", {
threadId: childThreadId,
turnId: childTurnId,
})
.pipe(Effect.timeoutOption("3 seconds"), Effect.ignore),
{ concurrency: 8, discard: true },
).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);
const effectiveTurnId = turnId ?? session.activeTurnId;
if (!effectiveTurnId) {
return;
@@ -68,6 +68,46 @@ describe("AcpCoreRuntimeEvents", () => {
});
});
it("maps generic ACP permission kinds to dynamic tool approvals", () => {
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
for (const kind of ["search", "fetch", "other", "unknown", "future-tool-kind"]) {
const permissionRequest = { kind };
const request = {
stamp,
provider: ProviderDriverKind.make("cursor"),
threadId: "thread-1" as never,
turnId: TurnId.make("turn-1"),
requestId: RuntimeRequestId.make(`request-${kind}`),
permissionRequest,
};
expect(
makeAcpRequestOpenedEvent({
...request,
detail: kind,
args: {},
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: { sessionId: "session-1" },
}),
).toMatchObject({
type: "request.opened",
payload: { requestType: "dynamic_tool_call" },
});
expect(
makeAcpRequestResolvedEvent({
...request,
decision: "accept",
}),
).toMatchObject({
type: "request.resolved",
payload: { requestType: "dynamic_tool_call" },
});
}
});
it("maps ACP core plan, tool-call, and content updates", () => {
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
const turnId = TurnId.make("turn-1");
@@ -26,7 +26,7 @@ interface AcpEventStamp {
type AcpCanonicalRequestType = Extract<
CanonicalRequestType,
"exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown"
"exec_command_approval" | "file_read_approval" | "file_change_approval" | "dynamic_tool_call"
>;
function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonicalRequestType {
@@ -40,7 +40,7 @@ function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonical
case "move":
return "file_change_approval";
default:
return "unknown";
return "dynamic_tool_call";
}
}
@@ -0,0 +1,93 @@
// Minimal codex app-server stand-in for runtime-level collab tests.
// Speaks just enough of the protocol for CodexSessionRuntime to start a
// session, using REAL captured responses (codexMultiAgentWire.json), then
// replays a scripted multi-agent notification sequence read from the
// T3_CODEX_COLLAB_SCRIPT env var (a JSON file path) when the first turn
// starts. Runs as a plain Node process — stdlib only.
import * as NodeFS from "node:fs";
import * as NodeReadline from "node:readline";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
const here = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const fixture = JSON.parse(
NodeFS.readFileSync(NodePath.join(here, "codexMultiAgentWire.json"), "utf8"),
);
const script = JSON.parse(NodeFS.readFileSync(process.env.T3_CODEX_COLLAB_SCRIPT, "utf8"));
const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
const rl = NodeReadline.createInterface({ input: process.stdin });
rl.on("line", (line) => {
let message;
try {
message = JSON.parse(line);
} catch {
return;
}
const { id, method } = message;
if (method === "initialize") {
write({
id,
result: {
userAgent: "t3-collab-mock/0.0.0",
codexHome: "/tmp",
platformFamily: "unix",
platformOs: "linux",
},
});
return;
}
if (method === "thread/start" || method === "thread/resume") {
write({ id, result: fixture.responses.threadStart });
return;
}
if (method === "turn/start") {
write({ id, result: fixture.responses.turnStart });
const rootThreadId = script.rootThreadId;
const turn = fixture.responses.turnStart.turn;
write({
jsonrpc: "2.0",
method: "turn/started",
params: { threadId: rootThreadId, turn },
});
for (const notification of script.notifications) {
write({ jsonrpc: "2.0", method: notification.method, params: notification.params });
}
if (script.holdTurnOpen !== true) {
write({
jsonrpc: "2.0",
method: "turn/completed",
params: {
threadId: rootThreadId,
turn: { ...turn, status: "completed" },
},
});
}
return;
}
if (method === "turn/interrupt") {
// Record which thread/turn was interrupted (append-only sidecar file the
// test reads) so Stop coverage can assert every live child was reached.
// failInterruptFor simulates a dead child whose interrupt errors.
const target = message.params?.threadId;
NodeFS.appendFileSync(
`${process.env.T3_CODEX_COLLAB_SCRIPT}.interrupts`,
`${JSON.stringify({ threadId: target, turnId: message.params?.turnId })}\n`,
);
if (script.failInterruptFor && script.failInterruptFor === target) {
write({ id, error: { code: -32000, message: "thread already closed" } });
return;
}
if (script.hangInterruptFor && script.hangInterruptFor === target) {
// Never respond: simulates a wedged child whose RPC neither resolves
// nor rejects. The runtime's bounded deadline must move on.
return;
}
write({ id, result: {} });
return;
}
if (id !== undefined) {
write({ id, result: {} });
}
});
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Wrapper so CodexSessionRuntime can spawn the mock peer: the runtime always
# passes "app-server" as the first argument (real codex CLI subcommand);
# discard it and exec node on the .mjs peer.
shift
exec node "$(dirname "$0")/codexCollabMockPeer.mjs" "$@"
@@ -0,0 +1,445 @@
{
"capturedWith": {
"cli": "codex-cli 0.145.0",
"model": "gpt-5.6-luna",
"effort": "low"
},
"rootThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"childThreadIds": [
"019fcfd6-2883-77e0-9013-4410ede70371",
"019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf"
],
"notifications": [
{
"method": "thread/started",
"params": {
"thread": {
"id": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"extra": null,
"sessionId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"forkedFromId": null,
"parentThreadId": null,
"preview": "",
"ephemeral": false,
"historyMode": "legacy",
"modelProvider": "openai",
"createdAt": 1785898342,
"updatedAt": 1785898342,
"recencyAt": 1785898342,
"status": {
"type": "idle"
},
"path": "/fixtures/codex/rollout.jsonl",
"cwd": "/workspace/repo",
"cliVersion": "0.145.0",
"source": "vscode",
"canAcceptDirectInput": true,
"threadSource": null,
"agentNickname": null,
"agentRole": null,
"gitInfo": null,
"name": null,
"turns": []
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"status": {
"type": "active",
"activeFlags": []
}
}
},
{
"method": "turn/started",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turn": {
"id": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": 1785898342,
"completedAt": null,
"durationMs": null
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"status": {
"type": "idle"
}
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "subAgentActivity",
"id": "call_S2JPiq0sMnJYS7kswVdvzEjB",
"kind": "started",
"agentThreadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"agentPath": "/root/alpha"
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"completedAtMs": 1785898346687
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"tokenUsage": {
"total": {
"totalTokens": 18261,
"inputTokens": 18228,
"cachedInputTokens": 11008,
"cacheWriteInputTokens": 0,
"outputTokens": 33,
"reasoningOutputTokens": 0
},
"last": {
"totalTokens": 18261,
"inputTokens": 18228,
"cachedInputTokens": 11008,
"cacheWriteInputTokens": 0,
"outputTokens": 33,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"status": {
"type": "active",
"activeFlags": []
}
}
},
{
"method": "turn/started",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turn": {
"id": "019fcfd6-28bf-7e00-a873-4554526dc845",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": 1785898346,
"completedAt": null,
"durationMs": null
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"status": {
"type": "idle"
}
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "subAgentActivity",
"id": "call_A2U7sfjmdGlUn5bn6gUNI0rl",
"kind": "started",
"agentThreadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"agentPath": "/root/beta"
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"completedAtMs": 1785898348329
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"status": {
"type": "active",
"activeFlags": []
}
}
},
{
"method": "turn/started",
"params": {
"threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"turn": {
"id": "019fcfd6-2f29-79e3-aa6a-c5836a519d3f",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": 1785898348,
"completedAt": null,
"durationMs": null
}
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"tokenUsage": {
"total": {
"totalTokens": 36576,
"inputTokens": 36510,
"cachedInputTokens": 28160,
"cacheWriteInputTokens": 0,
"outputTokens": 66,
"reasoningOutputTokens": 0
},
"last": {
"totalTokens": 18315,
"inputTokens": 18282,
"cachedInputTokens": 17152,
"cacheWriteInputTokens": 0,
"outputTokens": 33,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "subAgentActivity",
"id": "call_2W1NboHClVo0VqAf1y3ZFinO",
"kind": "interacted",
"agentThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"agentPath": "/root"
},
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",
"completedAtMs": 1785898349265
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",
"tokenUsage": {
"total": {
"totalTokens": 20756,
"inputTokens": 20713,
"cachedInputTokens": 5888,
"cacheWriteInputTokens": 0,
"outputTokens": 43,
"reasoningOutputTokens": 11
},
"last": {
"totalTokens": 20756,
"inputTokens": 20713,
"cachedInputTokens": 5888,
"cacheWriteInputTokens": 0,
"outputTokens": 43,
"reasoningOutputTokens": 11
},
"modelContextWindow": 258400
}
}
},
{
"method": "item/started",
"params": {
"item": {
"type": "collabAgentToolCall",
"id": "call_XGMDYMm4O8ne7vg3Y6p4eSqz",
"tool": "wait",
"status": "inProgress",
"senderThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"receiverThreadIds": [],
"prompt": null,
"model": null,
"reasoningEffort": null,
"agentsStates": {}
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"startedAtMs": 1785898349931
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "collabAgentToolCall",
"id": "call_XGMDYMm4O8ne7vg3Y6p4eSqz",
"tool": "wait",
"status": "completed",
"senderThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"receiverThreadIds": [],
"prompt": null,
"model": null,
"reasoningEffort": null,
"agentsStates": {}
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"completedAtMs": 1785898349931
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"tokenUsage": {
"total": {
"totalTokens": 54933,
"inputTokens": 54846,
"cachedInputTokens": 45312,
"cacheWriteInputTokens": 0,
"outputTokens": 87,
"reasoningOutputTokens": 0
},
"last": {
"totalTokens": 18357,
"inputTokens": 18336,
"cachedInputTokens": 17152,
"cacheWriteInputTokens": 0,
"outputTokens": 21,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",
"tokenUsage": {
"total": {
"totalTokens": 41529,
"inputTokens": 41481,
"cachedInputTokens": 26112,
"cacheWriteInputTokens": 0,
"outputTokens": 48,
"reasoningOutputTokens": 11
},
"last": {
"totalTokens": 20773,
"inputTokens": 20768,
"cachedInputTokens": 20224,
"cacheWriteInputTokens": 0,
"outputTokens": 5,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"status": {
"type": "idle"
}
}
},
{
"method": "turn/completed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turn": {
"id": "019fcfd6-28bf-7e00-a873-4554526dc845",
"items": [],
"itemsView": "notLoaded",
"status": "completed",
"error": null,
"startedAt": 1785898346,
"completedAt": 1785898350,
"durationMs": 3792
}
}
}
],
"responses": {
"threadStart": {
"thread": {
"id": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"extra": null,
"sessionId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"forkedFromId": null,
"parentThreadId": null,
"preview": "",
"ephemeral": false,
"historyMode": "legacy",
"modelProvider": "openai",
"createdAt": 1785898342,
"updatedAt": 1785898342,
"recencyAt": 1785898342,
"status": {
"type": "idle"
},
"path": "/fixtures/codex/rollout.jsonl",
"cwd": "/workspace/repo",
"cliVersion": "0.145.0",
"source": "vscode",
"canAcceptDirectInput": true,
"threadSource": null,
"agentNickname": null,
"agentRole": null,
"gitInfo": null,
"name": null,
"turns": []
},
"model": "gpt-5.6-sol",
"modelProvider": "openai",
"serviceTier": "default",
"cwd": "/workspace/repo",
"runtimeWorkspaceRoots": ["/workspace/repo"],
"instructionSources": ["/fixtures/scrubbed", "/workspace/repo/AGENTS.md"],
"approvalPolicy": "on-request",
"approvalsReviewer": "auto_review",
"sandbox": {
"type": "workspaceWrite",
"writableRoots": [],
"networkAccess": false,
"excludeTmpdirEnvVar": false,
"excludeSlashTmp": false
},
"activePermissionProfile": null,
"reasoningEffort": "high",
"multiAgentMode": "explicitRequestOnly"
},
"turnStart": {
"turn": {
"id": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": null,
"completedAt": null,
"durationMs": null
}
}
}
}
+113
View File
@@ -7134,6 +7134,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
pr: null,
}),
);
const remoteExists = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["remoteExists"]>[0]) =>
Effect.sync(() => {
bootstrapGitOperations.push("remote-exists");
return true;
}),
);
const fetchRemote = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"]>[0]) =>
Effect.sync(() => {
@@ -7181,6 +7188,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitVcsDriver: {
remoteExists,
fetchRemote,
resolveRemoteTrackingCommit,
createWorktree,
@@ -7271,6 +7279,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fallbackRemoteName: "origin",
});
assert.deepEqual(bootstrapGitOperations, [
"remote-exists",
"fetch",
"resolve-remote-commit",
"create-worktree",
@@ -7299,6 +7308,110 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"falls back to the local base branch when startFromOrigin is set but no origin remote exists",
() =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const remoteExists = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["remoteExists"]>[0]) =>
Effect.succeed(false),
);
const fetchRemote = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"]>[0]) => Effect.void,
);
const resolveRemoteTrackingCommit = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["resolveRemoteTrackingCommit"]>[0]) =>
Effect.succeed({
commitSha: "0123456789abcdef0123456789abcdef01234567",
remoteRefName: "origin/main",
}),
);
const createWorktree = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
refName: "t3code/bootstrap-refName",
path: "/tmp/bootstrap-worktree",
},
}),
);
yield* buildAppUnderTest({
layers: {
gitVcsDriver: {
remoteExists,
fetchRemote,
resolveRemoteTrackingCommit,
createWorktree,
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
return { sequence: dispatchedCommands.length };
}),
readEvents: () => Stream.empty,
},
},
});
const createdAt = "2026-01-01T00:00:00.000Z";
const wsUrl = yield* getWsServerUrl("/ws");
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.make("cmd-bootstrap-turn-start-no-origin"),
threadId: ThreadId.make("thread-bootstrap-no-origin"),
message: {
messageId: MessageId.make("msg-bootstrap-no-origin"),
role: "user",
text: "hello",
attachments: [],
},
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: defaultProjectId,
title: "Bootstrap Thread",
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt,
},
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-refName",
startFromOrigin: true,
},
},
createdAt,
}),
),
);
assert.deepEqual(remoteExists.mock.calls[0]?.[0], {
cwd: "/tmp/project",
remoteName: "origin",
});
assert.equal(fetchRemote.mock.calls.length, 0);
assert.equal(resolveRemoteTrackingCommit.mock.calls.length, 0);
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
cwd: "/tmp/project",
refName: "main",
newRefName: "t3code/bootstrap-refName",
baseRefName: "main",
path: null,
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
+34 -20
View File
@@ -83,6 +83,7 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
connectHttpApiLayer,
pendingServiceUpdateExists,
reconcileDesiredCloudLink,
releaseManagedTunnelOnShutdown,
} from "./cloud/http.ts";
@@ -559,32 +560,45 @@ export const makeServerLayer = Layer.unwrap(
yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
return;
}
const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
),
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to release the managed tunnel on shutdown; the next link reuses it",
{ cause },
),
),
Effect.asVoid,
);
// A launcher trial can be stopped before activation. The previous
// server is already gone, so the trial owns cleanup immediately; the
// pending-state check keeps the tunnel for normal commit or rollback,
// while the launcher's explicit-stop marker allows it to be released.
// Other runtimes wait for activation so a failed standby cannot tear
// down the active runtime's tunnel.
const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
if (cleanupBeforeActivation) {
yield* Effect.addFinalizer(() => releaseManagedTunnel);
}
yield* forkParked(
Effect.gen(function* () {
// Only an activated runtime owns the tunnel cleanup finalizer.
yield* Effect.addFinalizer(() =>
releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released
? Effect.logInfo("Released the managed tunnel on shutdown")
: Effect.void,
),
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to release the managed tunnel on shutdown; the next link reuses it",
{ cause },
),
),
Effect.asVoid,
),
);
if (!cleanupBeforeActivation) {
yield* Effect.addFinalizer(() => releaseManagedTunnel);
}
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
yield* Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
// No settling delay before the first attempt: routes are already
// serving by the time activation opens this gate (the startup
// sequence awaits routesReady), and the retry schedule below
// covers anything this sleep used to hedge against. Every
// millisecond here is dead time on the path to remote
// reachability after a restart.
yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
+7 -1
View File
@@ -10,6 +10,7 @@ import {
decodeServiceState,
isExactServiceVersion,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STOP_MARKER_FILE,
} from "./cloud/serviceProtocol.ts";
it("accepts only exact semantic versions", () => {
@@ -111,7 +112,12 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
const running = launcher.run();
yield* Effect.promise(() => launcher.stop("SIGTERM"));
const stopping = launcher.stop("SIGTERM");
// An explicit stop leaves the marker that tells a child shutting down
// mid-update that no replacement server is coming. It is present as
// soon as stop() returns its promise, before queued transitions run.
assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE)));
yield* Effect.promise(() => stopping);
yield* Effect.promise(() => running);
}),
);
+25 -2
View File
@@ -5,6 +5,7 @@
// `t3 service update`. Keep runtime imports limited to Node built-ins.
import * as NodeChildProcess from "node:child_process";
import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
@@ -24,6 +25,7 @@ import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
} from "./cloud/serviceProtocol.ts";
const HANDOFF_DELAY_MS = 2_000;
@@ -257,6 +259,9 @@ async function terminateChild(
}
}
const stopMarkerPath = (baseDir: string) =>
NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
export class Launcher {
readonly #baseDir: string;
readonly #statePath: string;
@@ -264,6 +269,7 @@ export class Launcher {
#child: ManagedChild | null = null;
#timer: NodeJS.Timeout | undefined;
#transitions: Promise<void> = Promise.resolve();
#stopRequested = false;
#stopping = false;
#done = false;
readonly #completion = Promise.withResolvers<void>();
@@ -308,13 +314,26 @@ export class Launcher {
}
async stop(signal: NodeJS.Signals): Promise<void> {
if (this.#stopping) {
// This must happen synchronously at signal receipt. A queued update
// transition may already be terminating the active child, and that child
// needs to see the marker in its shutdown finalizer. KillMode=mixed also
// ensures systemd signals the launcher before the rest of the cgroup.
try {
NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
} catch {
// Err toward keeping the tunnel; the next link or unlink reconciles it.
}
if (this.#stopRequested || this.#stopping) {
await this.#completion.promise.catch(() => undefined);
return;
}
this.#stopping = true;
this.#stopRequested = true;
this.#clearTimer();
this.#enqueue(async () => {
// Let an update transition already in progress start its replacement
// before this queued stop tears it down. That replacement owns the
// pre-activation tunnel cleanup path and observes the marker above.
this.#stopping = true;
const child = this.#child?.process;
this.#child = null;
if (child !== undefined) await terminateChild(child, signal);
@@ -330,6 +349,10 @@ export class Launcher {
}
async #recover(): Promise<void> {
// A fresh launcher means servers are running again: any stop marker from
// a previous explicit stop is stale and must not make a future update
// handoff release its tunnel.
await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
const update = this.#state.update;
if (update?.status !== "pending") {
if (update !== undefined) {
+6
View File
@@ -168,6 +168,11 @@ export interface GitFetchRemoteInput {
remoteName: string;
}
export interface GitRemoteExistsInput {
cwd: string;
remoteName: string;
}
export interface GitResolveRemoteTrackingCommitInput {
cwd: string;
refName: string;
@@ -243,6 +248,7 @@ export class GitVcsDriver extends Context.Service<
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
readonly resolveRemoteTrackingCommit: (
input: GitResolveRemoteTrackingCommitInput,
) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
+6 -2
View File
@@ -1284,11 +1284,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
},
).pipe(Effect.map((result) => result.exitCode === 0));
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
executeGit("GitVcsDriver.originRemoteExists", cwd, ["remote", "get-url", "origin"], {
const remoteExists: GitVcsDriver.GitVcsDriver["Service"]["remoteExists"] = (input) =>
executeGit("GitVcsDriver.remoteExists", input.cwd, ["remote", "get-url", input.remoteName], {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.exitCode === 0));
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
remoteExists({ cwd, remoteName: "origin" });
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
runGitStdout("GitVcsDriver.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map(parseRemoteNamesInGitOrder),
@@ -3071,6 +3074,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)),
resolvePrimaryRemoteName,
fetchRemote: (input) => withListRefsInvalidation(input.cwd, fetchRemote(input)),
remoteExists,
resolveRemoteTrackingCommit,
fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)),
fetchRemoteTrackingBranch: (input) =>
+26 -2
View File
@@ -91,6 +91,7 @@ import { issueAssetUrl } from "./assets/AssetAccess.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
import { readWorkflowScript } from "./orchestration/workflowScriptQuery.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
@@ -907,7 +908,16 @@ const makeWsRpcLayer = (
if (bootstrap?.prepareWorktree) {
let worktreeBaseRef = bootstrap.prepareWorktree.baseBranch;
if (bootstrap.prepareWorktree.startFromOrigin) {
// "Start from origin" is a stored default; repos without an
// origin remote fall back to the local base branch instead of
// failing the whole bootstrap on `git fetch origin`.
const startFromOrigin =
bootstrap.prepareWorktree.startFromOrigin === true &&
(yield* gitWorkflow.remoteExists({
cwd: bootstrap.prepareWorktree.projectCwd,
remoteName: "origin",
}));
if (startFromOrigin) {
yield* gitWorkflow.fetchRemote({
cwd: bootstrap.prepareWorktree.projectCwd,
remoteName: "origin",
@@ -1009,6 +1019,7 @@ const makeWsRpcLayer = (
settings,
shellResumeCompletionMarker: true,
threadResumeCompletionMarker: true,
threadSnapshotPagination: true,
};
});
@@ -1084,6 +1095,12 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getWorkflowScript,
readWorkflowScript({ scriptPath: input.scriptPath }),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getTurnDiff,
@@ -1335,7 +1352,14 @@ const makeWsRpcLayer = (
}
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(input.threadId)
.getThreadDetailSnapshot(
input.threadId,
// Windowing the fallback snapshot is opt-in per subscription:
// clients that don't send turnLimit (including all
// pre-pagination clients) get the full thread, since they
// have no way to load older pages.
input.turnLimit === undefined ? undefined : { turnLimit: input.turnLimit },
)
.pipe(
Effect.mapError(
(cause) =>
@@ -117,9 +117,9 @@ const fixtures = [
server: "repository",
tool: "search",
arguments: { query: "activity projection" },
aggregatedOutput: "mcp payload remains available",
aggregatedOutput: "mcp bulk is dropped",
},
ignored: "MCP data is rendered verbatim",
ignored: "top-level bulk",
}),
makeActivity("search", "web_search", {
rawOutput: {
@@ -184,13 +184,37 @@ describe("projectActivityPayload", () => {
});
});
it("passes MCP tool data through unchanged", () => {
expect(projectActivityPayload(fixtures[4]!)).toBe(fixtures[4]);
it("slims MCP tool data to the fields the expanded row renders", () => {
expect(projectActivityPayload(fixtures[4]!).payload).toEqual({
itemType: "mcp_tool_call",
title: "mcp_tool_call",
detail: "mcp_tool_call detail",
status: "completed",
requestKind: "command",
data: {
item: {
server: "repository",
tool: "search",
arguments: { query: "activity projection" },
},
},
});
});
it("keeps current web and mobile derived output identical for every tool item type", () => {
for (const activity of fixtures) {
const projected = projectActivityPayload(activity);
if (activity === fixtures[4]) {
// MCP is the one deliberate difference: the expanded row's toolData
// loses result bulk but keeps the rendered identity fields.
const [entry] = deriveWorkLogEntries([projected]);
expect(entry?.toolData).toEqual({
server: "repository",
tool: "search",
arguments: { query: "activity projection" },
});
continue;
}
expect(deriveWorkLogEntries([projected])).toEqual(deriveWorkLogEntries([activity]));
expect(comparableThreadFeed([projected])).toEqual(comparableThreadFeed([activity]));
}
@@ -233,6 +257,179 @@ describe("projectActivityPayload", () => {
});
});
describe("superseded tool.updated snapshot dedup", () => {
function makeToolLifecycleActivity(
id: string,
kind: "tool.updated" | "tool.completed",
options: {
readonly turn?: string;
readonly title?: string;
readonly detail?: string;
readonly toolCallId?: string;
} = {},
): OrchestrationThreadActivity {
const { turn = "turn-a", title = "File change", detail, toolCallId } = options;
return {
id: EventId.make(id),
tone: "tool",
kind,
summary: title,
payload: {
itemType: "file_change",
title,
...(detail ? { detail } : {}),
data: {
...(toolCallId ? { toolCallId } : {}),
toolName: "Edit",
input: { file_path: "src/app.ts" },
},
},
turnId: TurnId.make(turn),
createdAt: "2026-07-27T00:00:00.000Z",
};
}
function projectedIds(activities: ReadonlyArray<OrchestrationThreadActivity>) {
return projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread(activities),
}).thread.activities.map((activity) => activity.id);
}
it("drops updates a later completion supersedes in the same turn", () => {
const update1 = makeToolLifecycleActivity("upd-1", "tool.updated");
const update2 = makeToolLifecycleActivity("upd-2", "tool.updated");
const completed = makeToolLifecycleActivity("done-1", "tool.completed");
expect(projectedIds([update1, update2, completed])).toEqual([completed.id]);
});
it("matches on toolCallId when the adapter emits one", () => {
const otherCall = makeToolLifecycleActivity("upd-other", "tool.updated", {
toolCallId: "call-b",
});
const update = makeToolLifecycleActivity("upd-a", "tool.updated", { toolCallId: "call-a" });
const completed = makeToolLifecycleActivity("done-a", "tool.completed", {
toolCallId: "call-a",
});
// Same itemType/title, different call: only call-a's update is superseded.
expect(projectedIds([otherCall, update, completed])).toEqual([otherCall.id, completed.id]);
});
it("keeps updates with no matching completion", () => {
const inFlight = makeToolLifecycleActivity("upd-live", "tool.updated", { title: "Running" });
const other = makeToolLifecycleActivity("upd-other", "tool.updated", { title: "Reading" });
const completed = makeToolLifecycleActivity("done-other", "tool.completed", {
title: "Reading",
});
expect(projectedIds([inFlight, other, completed])).toEqual([inFlight.id, completed.id]);
});
it("drops interleaved superseded updates even when a parallel call separates them", () => {
// Deliberate divergence from the clients' adjacency-based collapse: a
// superseded update separated from its completion by an interleaved
// parallel call renders as its own in-flight row on full history, and the
// snapshot omits it. Its final state still shows via the retained
// completion (1.5% of dropped rows on real data; see the projection's doc
// comment).
const updateA = makeToolLifecycleActivity("upd-a", "tool.updated", { toolCallId: "call-a" });
const updateB = makeToolLifecycleActivity("upd-b", "tool.updated", { toolCallId: "call-b" });
const completedA = makeToolLifecycleActivity("done-a", "tool.completed", {
toolCallId: "call-a",
});
const completedB = makeToolLifecycleActivity("done-b", "tool.completed", {
toolCallId: "call-b",
});
expect(projectedIds([updateA, updateB, completedA, completedB])).toEqual([
completedA.id,
completedB.id,
]);
});
it("keeps an update whose completion lives in another turn", () => {
// A live thread.reverted can discard the completing turn while keeping
// the updating one, which would leave the call unrepresented.
const update = makeToolLifecycleActivity("upd-kept", "tool.updated", { turn: "turn-kept" });
const completed = makeToolLifecycleActivity("done-later", "tool.completed", {
turn: "turn-reverted",
});
expect(projectedIds([update, completed])).toEqual([update.id, completed.id]);
});
it("keeps an update that follows its completion", () => {
// A later update under the same identity is the next call, still in flight.
const completed = makeToolLifecycleActivity("done-first", "tool.completed");
const nextCall = makeToolLifecycleActivity("upd-next", "tool.updated");
expect(projectedIds([completed, nextCall])).toEqual([completed.id, nextCall.id]);
});
it("keeps identity-less rows the clients never collapse", () => {
const anonymous: OrchestrationThreadActivity = {
id: EventId.make("upd-anon"),
tone: "tool",
kind: "tool.updated",
summary: " ",
payload: { data: { toolName: "Edit" } },
turnId: TurnId.make("turn-a"),
createdAt: "2026-07-27T00:00:00.000Z",
};
const completed: OrchestrationThreadActivity = {
...anonymous,
id: EventId.make("done-anon"),
kind: "tool.completed",
};
expect(projectedIds([anonymous, completed])).toEqual([anonymous.id, completed.id]);
});
it("does not filter live activity-appended events", () => {
const update = makeToolLifecycleActivity("upd-live-event", "tool.updated");
const event = {
sequence: 11,
eventId: EventId.make("event-tool-updated"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-projection"),
occurredAt: "2026-07-27T00:00:03.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.activity-appended",
payload: {
threadId: ThreadId.make("thread-projection"),
activity: update,
},
} satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
const projected = projectActivityEvent(event);
expect(
projected.type === "thread.activity-appended" ? projected.payload.activity.id : undefined,
).toEqual(update.id);
});
it("leaves the collapsed work log identical to the full history", () => {
const activities = [
makeToolLifecycleActivity("upd-1", "tool.updated", { detail: "writing" }),
makeToolLifecycleActivity("upd-2", "tool.updated", { detail: "writing" }),
makeToolLifecycleActivity("done-1", "tool.completed", { detail: "writing" }),
];
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread(activities),
});
const before = deriveWorkLogEntries(activities);
const after = deriveWorkLogEntries(projected.thread.activities);
expect(after).toHaveLength(before.length);
expect(after.map((entry) => entry.label)).toEqual(before.map((entry) => entry.label));
});
});
describe("context-window snapshot dedup", () => {
function makeContextWindowActivity(
id: string,
@@ -328,12 +525,12 @@ describe("context-window snapshot dedup", () => {
);
});
it("leaves snapshots without context-window activities untouched", () => {
it("applies only payload slimming when there are no context-window activities", () => {
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread([fixtures[4]!]),
});
expect(projected.thread.activities).toEqual([fixtures[4]]);
expect(projected.thread.activities).toEqual([projectActivityPayload(fixtures[4]!)]);
});
it("does not filter live activity-appended events", () => {
+568
View File
@@ -0,0 +1,568 @@
/**
* Agents right-panel surface: the fleet view over the native subagent fold,
* and the ONLY place the roster renders (the chat carries one CTA row per
* spawn batch).
*
* Visualization rules (from live-test feedback):
* - Live work first: running workflows and direct spawns sort above settled.
* - Rows are flat status lines — no expansion, no per-agent tool feeds. The
* row answers "who / what phase / how much"; anything deeper is a future
* drill-in, not an unfold.
* - A settled workflow run collapses to a single summary line; click it to
* show its member list inline (the one allowed toggle — run granularity,
* not agent granularity).
* - Static status dots, DOM-write elapsed timers, plain token counters.
*/
import { useAtomValue } from "@effect/atom-react";
import type {
AgentPanelModel,
AgentPanelWorkflowGroup,
RuntimeSubagent,
} from "@t3tools/client-runtime/state/subagentRuntime";
import {
formatSubagentModelLabel,
formatSubagentTokenCount,
} from "@t3tools/client-runtime/state/subagentRuntime";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { Bot, Braces, Check, ChevronDown, ChevronRight, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { cn } from "~/lib/utils";
import { orchestrationEnvironment } from "~/state/orchestration";
import { ScrollArea } from "~/components/ui/scroll-area";
/**
* In-flight states all present as Working (one steady state, per the
* monitoring-pill design: detail belongs in the activity sub-line, and a
* stalled/waiting/queued subagent is still the fleet doing its job, not a
* user problem). Only settled states differentiate.
*/
const STATUS_VISUALS: Record<RuntimeSubagent["status"], { dotClass: string; label: string }> = {
pending: { dotClass: "bg-info", label: "Working" },
running: { dotClass: "bg-info", label: "Working" },
waiting: { dotClass: "bg-info", label: "Working" },
// Idle reads as settled (muted, not sky): a resting Codex child looks done
// unless resumed — live-test: sky idle dots read as stuck in-progress.
idle: { dotClass: "bg-muted-foreground/50", label: "Idle · resumable" },
completed: { dotClass: "bg-success", label: "Completed" },
failed: { dotClass: "bg-destructive", label: "Failed" },
cancelled: { dotClass: "bg-muted-foreground/60", label: "Stopped" },
interrupted: { dotClass: "bg-muted-foreground/60", label: "Stopped" },
};
function StatusDot({ status }: { status: RuntimeSubagent["status"] }) {
return (
<span
aria-hidden
className={cn("size-1.5 shrink-0 rounded-full", STATUS_VISUALS[status].dotClass)}
/>
);
}
function formatElapsedSeconds(totalSeconds: number): string {
const seconds = Math.max(0, Math.floor(totalSeconds));
const minutes = Math.floor(seconds / 60);
if (minutes === 0) {
return `${seconds}s`;
}
const hours = Math.floor(minutes / 60);
if (hours === 0) {
return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
}
return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`;
}
function elapsedBetween(startedAt: string, endIso: string | null): string {
const start = Date.parse(startedAt);
const end = endIso ? Date.parse(endIso) : Date.now();
if (Number.isNaN(start) || Number.isNaN(end)) {
return "";
}
return formatElapsedSeconds((end - start) / 1000);
}
/**
* Elapsed time for the current activation. Live agents self-tick via DOM
* writes (zero React commits per tick); settled agents freeze at completedAt.
*/
function AgentElapsed({ agent }: { agent: RuntimeSubagent }) {
const textRef = useRef<HTMLSpanElement>(null);
const live = agent.status === "running" || agent.status === "waiting";
const startedAt = agent.startedAt;
useEffect(() => {
if (!live || !startedAt) {
return;
}
const update = () => {
if (textRef.current) {
textRef.current.textContent = elapsedBetween(startedAt, null);
}
};
update();
const id = setInterval(update, 1000);
return () => clearInterval(id);
}, [live, startedAt]);
if (!startedAt) {
return null;
}
return (
<span ref={textRef} className="tabular-nums">
{elapsedBetween(startedAt, live ? null : agent.completedAt)}
</span>
);
}
/**
* Status-dependent activity line. Live rows lead with what is happening now;
* settled rows lead with the outcome. Errors are the only inline previews on
* failed rows because they explain a red row at a glance.
*/
function agentActivityText(agent: RuntimeSubagent): string | null {
const live =
agent.status === "running" || agent.status === "pending" || agent.status === "waiting";
if (live) {
return (
agent.progress ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
agent.result ??
agent.error
);
}
return (
agent.error ??
agent.result ??
agent.progress ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null)
);
}
/** Flat, non-interactive agent status line. No unfold. */
function AgentRow({ agent }: { agent: RuntimeSubagent }) {
const visuals = STATUS_VISUALS[agent.status];
const activity = agentActivityText(agent);
const modelLabel = formatSubagentModelLabel(agent.model, agent.effort);
return (
<div className="rounded-md px-1.5 py-1">
<div className="flex items-start gap-2">
<span className="flex h-5 items-center">
<StatusDot status={agent.status} />
</span>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="truncate text-sm font-medium">{agent.title}</span>
{agent.role ? (
<span className="max-w-28 truncate rounded-sm border border-border/60 px-1 font-mono text-[.65rem] text-muted-foreground">
{agent.role}
</span>
) : null}
<span className="ml-auto flex items-center gap-1 font-mono text-[.7rem] text-muted-foreground/80">
<AgentElapsed agent={agent} />
{agent.status === "completed" ? (
<Check aria-hidden className="size-3 text-success" />
) : null}
</span>
</span>
{activity ? (
<span
className={cn(
"mt-0.5 block truncate text-xs",
agent.status === "failed" ? "text-destructive-foreground" : "text-muted-foreground",
)}
>
{activity}
</span>
) : null}
<span className="mt-0.5 flex items-center gap-1 font-mono text-[.7rem] text-muted-foreground/70">
{modelLabel ? <span className="truncate">{modelLabel}</span> : null}
{agent.usage ? (
<span className="tabular-nums">
{modelLabel ? "· " : ""}
{formatSubagentTokenCount(agent.usage.totalTokens)} tok
</span>
) : null}
{agent.usage?.toolUses !== undefined ? (
<span>· {agent.usage.toolUses} tools</span>
) : null}
{agent.activationCount > 1 ? <span>· run {agent.activationCount}</span> : null}
<span className="sr-only">{visuals.label}</span>
</span>
</span>
</div>
</div>
);
}
function workflowIsLive(group: AgentPanelWorkflowGroup): boolean {
const status = group.workflow.status;
return (
status !== "completed" &&
status !== "failed" &&
status !== "cancelled" &&
status !== "interrupted"
);
}
function workflowMembers(group: AgentPanelWorkflowGroup): ReadonlyArray<RuntimeSubagent> {
return [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];
}
/**
* Phase rail: the run's shape at a glance. One segment per phase in order,
* separated by chevrons; each segment shows title + one dot per member.
* The whole arc (done → live → pending) is visible without scrolling the
* member list.
*/
function PhaseRail({ group }: { group: AgentPanelWorkflowGroup }) {
if (group.phases.length === 0) {
return null;
}
return (
<div className="flex flex-wrap items-center gap-x-1 gap-y-1 px-1.5 pb-1 pt-1.5">
{group.phases.map((phase, index) => (
<div key={phase.index} className="flex items-center gap-1">
{index > 0 ? (
<ChevronRight aria-hidden className="size-3 text-muted-foreground/40" />
) : null}
<div
className={cn(
"flex items-center gap-1 rounded-sm border px-1.5 py-0.5",
phase.state === "running"
? "border-info/40"
: phase.state === "done"
? "border-success/30"
: "border-border/50",
)}
>
<span
className={cn(
"font-mono text-[.65rem]",
phase.state === "running"
? "text-info-foreground"
: phase.state === "done"
? "text-success-foreground"
: "text-muted-foreground/70",
)}
>
{phase.state === "done" ? "✓ " : ""}
{phase.title}
</span>
<span className="flex items-center gap-0.5">
{phase.members.length === 0 ? (
<span className="font-mono text-[.6rem] text-muted-foreground/50">–</span>
) : (
phase.members.map((member) => <StatusDot key={member.id} status={member.status} />)
)}
</span>
</div>
</div>
))}
</div>
);
}
/**
* Read-only workflow script viewer, fetched through the contained
* getWorkflowScript RPC (never a raw filesystem read from the client).
*/
function WorkflowScriptView({
environmentId,
threadId,
scriptPath,
onClose,
}: {
environmentId: EnvironmentId;
threadId: ThreadId;
scriptPath: string;
onClose: () => void;
}) {
const result = useAtomValue(
orchestrationEnvironment.workflowScript({ environmentId, input: { threadId, scriptPath } }),
);
return (
<div className="mx-1.5 mb-1 rounded-md border border-border/60 bg-background/60">
<div className="flex items-center gap-2 border-b border-border/50 px-2 py-1">
<Braces aria-hidden className="size-3 text-muted-foreground" />
<span className="truncate font-mono text-[.65rem] text-muted-foreground">
{scriptPath.split("/").at(-1)}
</span>
<button
type="button"
onClick={onClose}
aria-label="Close script"
className="ml-auto text-muted-foreground hover:text-foreground"
>
<X aria-hidden className="size-3" />
</button>
</div>
<div className="max-h-72 overflow-auto p-2">
{result._tag === "Success" ? (
<pre className="whitespace-pre-wrap break-words font-mono text-[.7rem] leading-relaxed text-foreground/90">
{result.value.contents}
{result.value.truncated ? "\n… (truncated)" : ""}
</pre>
) : result._tag === "Failure" ? (
<p className="text-xs text-destructive-foreground">Could not load the script.</p>
) : (
<p className="text-xs text-muted-foreground">Loading…</p>
)}
</div>
</div>
);
}
/**
* Collapsible phase section (Claude Code Background-tasks pattern): live
* phases open by default, done phases collapsed to header + member dot row.
* User toggles override the default and stick for the phase's lifetime.
*/
function PhaseSection({ phase }: { phase: AgentPanelWorkflowGroup["phases"][number] }) {
const [userOpen, setUserOpen] = useState<boolean | null>(null);
const open = userOpen ?? phase.state === "running";
return (
<div>
<button
type="button"
onClick={() => setUserOpen(!open)}
aria-expanded={open}
className={cn(
"mt-2 flex w-full items-center gap-1.5 rounded-sm px-1.5 text-left text-[.65rem] font-medium uppercase tracking-wider hover:bg-accent/40",
phase.state === "done"
? "text-success-foreground"
: phase.state === "running"
? "text-info-foreground"
: "text-muted-foreground/70",
)}
>
{open ? (
<ChevronDown aria-hidden className="size-3 shrink-0" />
) : (
<ChevronRight aria-hidden className="size-3 shrink-0" />
)}
{phase.state === "done" ? <Check aria-hidden className="size-3" /> : null}
<span>{phase.title}</span>
<span className="font-normal normal-case text-muted-foreground/70">
{phase.state === "pending" && phase.members.length === 0
? "pending"
: phase.state === "done"
? `${phase.settledCount} done`
: `${phase.activeCount} active · ${phase.settledCount} done`}
</span>
{!open && phase.members.length > 0 ? (
<span className="ml-auto flex items-center gap-0.5">
{phase.members.map((member) => (
<StatusDot key={member.id} status={member.status} />
))}
</span>
) : null}
</button>
{open ? phase.members.map((member) => <AgentRow key={member.id} agent={member} />) : null}
</div>
);
}
/** Live workflow: phase rail + full phase tree. */
function LiveWorkflowSection({
group,
environmentId,
threadId,
}: {
group: AgentPanelWorkflowGroup;
environmentId: EnvironmentId | null;
threadId: ThreadId | null;
}) {
const [scriptOpen, setScriptOpen] = useState(false);
const members = workflowMembers(group);
const settled = members.filter(
(member) =>
member.status === "completed" ||
member.status === "failed" ||
member.status === "cancelled" ||
member.status === "interrupted",
).length;
const scriptPath = group.workflow.runHandles?.scriptPath;
const canShowScript = scriptPath !== undefined && environmentId !== null && threadId !== null;
return (
<section className="rounded-lg border border-border/50 bg-card/30 p-1.5">
<div className="flex items-center gap-2 px-1.5 pt-0.5 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">
<span aria-hidden className="size-1.5 rounded-full bg-info" />
<span>{group.workflow.workflowName ?? group.workflow.title}</span>
{canShowScript ? (
<button
type="button"
onClick={() => setScriptOpen((value) => !value)}
className={cn(
"rounded-sm border border-border/60 px-1 font-mono normal-case hover:text-foreground",
scriptOpen && "text-foreground",
)}
aria-expanded={scriptOpen}
>
{"{}"} script
</button>
) : null}
<span className="ml-auto font-mono normal-case text-muted-foreground/80">
{settled}/{members.length} settled
</span>
</div>
<PhaseRail group={group} />
{scriptOpen && canShowScript ? (
<WorkflowScriptView
environmentId={environmentId}
threadId={threadId}
scriptPath={scriptPath}
onClose={() => setScriptOpen(false)}
/>
) : null}
{group.phases.map((phase) => (
<PhaseSection key={phase.index} phase={phase} />
))}
{group.unphasedMembers.map((member) => (
<AgentRow key={member.id} agent={member} />
))}
{group.phases.length === 0 && group.unphasedMembers.length === 0 ? (
<AgentRow agent={group.workflow} />
) : null}
</section>
);
}
/**
* Settled workflow: one summary line. Click toggles the member list — the
* only expansion in the panel, at run granularity.
*/
function SettledWorkflowSection({ group }: { group: AgentPanelWorkflowGroup }) {
const [open, setOpen] = useState(false);
const members = workflowMembers(group);
const failed = members.filter((member) => member.status === "failed").length;
// Coordinator usage may already aggregate members (panel-footer rule):
// count it only when there are no member rows to sum.
const totalTokens = members.reduce(
(sum, member) => sum + (member.usage?.totalTokens ?? 0),
members.length === 0 ? (group.workflow.usage?.totalTokens ?? 0) : 0,
);
const elapsed =
group.workflow.startedAt && group.workflow.completedAt
? elapsedBetween(group.workflow.startedAt, group.workflow.completedAt)
: null;
return (
<section>
<button
type="button"
onClick={() => setOpen((value) => !value)}
className="flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left hover:bg-accent/40"
aria-expanded={open}
>
<StatusDot status={failed > 0 ? "failed" : group.workflow.status} />
<span className="truncate text-sm">
{group.workflow.workflowName ?? group.workflow.title}
</span>
<span className="ml-auto flex items-center gap-1.5 font-mono text-[.7rem] text-muted-foreground/80">
{failed > 0 ? <span className="text-destructive-foreground">{failed} failed</span> : null}
<span>{members.length} agents</span>
<span className="tabular-nums">· {formatSubagentTokenCount(totalTokens)} tok</span>
{elapsed ? <span className="tabular-nums">· {elapsed}</span> : null}
{open ? (
<ChevronDown aria-hidden className="size-3" />
) : (
<ChevronRight aria-hidden className="size-3" />
)}
</span>
</button>
{open ? (
<div className="ms-3 border-s border-border/45 ps-2">
{members.map((member) => (
<AgentRow key={member.id} agent={member} />
))}
</div>
) : null}
</section>
);
}
export function AgentsPanel({
model,
environmentId = null,
threadId = null,
}: {
model: AgentPanelModel;
environmentId?: EnvironmentId | null;
threadId?: ThreadId | null;
}) {
if (!model.hasAgents) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
<Bot aria-hidden className="size-6 text-muted-foreground/60" />
<p className="text-sm font-medium">No agents yet</p>
<p className="max-w-56 text-xs text-muted-foreground">
When this thread spawns subagents or runs a workflow, they show up here with live status,
activity, and token usage.
</p>
</div>
);
}
const liveWorkflows = model.workflows.filter(workflowIsLive);
const settledWorkflows = model.workflows.filter((group) => !workflowIsLive(group));
const liveDirect = model.directAgents.filter(
(agent) =>
agent.status === "running" || agent.status === "pending" || agent.status === "waiting",
);
const settledDirect = model.directAgents.filter(
(agent) =>
agent.status !== "running" && agent.status !== "pending" && agent.status !== "waiting",
);
return (
<div className="flex h-full min-h-0 flex-col">
<ScrollArea className="min-h-0 flex-1">
<div className="flex flex-col gap-2 p-2">
{liveWorkflows.map((group) => (
<LiveWorkflowSection
key={group.workflow.id}
group={group}
environmentId={environmentId}
threadId={threadId}
/>
))}
{liveDirect.length > 0 ? (
<section>
<div className="px-1.5 pt-1 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">
Direct spawns
</div>
{liveDirect.map((agent) => (
<AgentRow key={agent.id} agent={agent} />
))}
</section>
) : null}
{settledWorkflows.length > 0 || settledDirect.length > 0 ? (
<section>
<div className="px-1.5 pt-2 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground/70">
Earlier
</div>
{settledWorkflows.map((group) => (
<SettledWorkflowSection key={group.workflow.id} group={group} />
))}
{settledDirect.map((agent) => (
<AgentRow key={agent.id} agent={agent} />
))}
</section>
) : null}
</div>
</ScrollArea>
<footer className="flex items-center justify-between border-t border-border/60 px-3 py-1.5 font-mono text-[.7rem] text-muted-foreground">
<span className="flex items-center gap-2">
{model.runningCount + model.waitingCount > 0 ? (
<span className="text-info-foreground">
● {model.runningCount + model.waitingCount} working
</span>
) : null}
{model.idleCount > 0 ? <span>{model.idleCount} idle</span> : null}
{model.settledCount > 0 ? <span>{model.settledCount} settled</span> : null}
</span>
<span className="tabular-nums">Σ {formatSubagentTokenCount(model.totalTokens)} tok</span>
</footer>
</div>
);
}
@@ -17,6 +17,7 @@ import {
resolvePreviousWorktreeLabel,
resolvePreviousWorktreeSeed,
shouldIncludeBranchPickerItem,
shouldShowComposerContextStrip,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
@@ -421,6 +422,38 @@ describe("shouldShowEnvironmentIndicator", () => {
});
});
describe("shouldShowComposerContextStrip", () => {
it("keeps the environment indicator visible for a non-Git project", () => {
expect(
shouldShowComposerContextStrip({
hasActiveProject: true,
isGitRepo: false,
showEnvironmentIndicator: true,
}),
).toBe(true);
});
it("hides the strip when a non-Git project has no environment indicator", () => {
expect(
shouldShowComposerContextStrip({
hasActiveProject: true,
isGitRepo: false,
showEnvironmentIndicator: false,
}),
).toBe(false);
});
it("shows Git controls without requiring an environment indicator", () => {
expect(
shouldShowComposerContextStrip({
hasActiveProject: true,
isGitRepo: true,
showEnvironmentIndicator: false,
}),
).toBe(true);
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
@@ -54,6 +54,14 @@ export function shouldShowEnvironmentIndicator(input: {
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
}
export function shouldShowComposerContextStrip(input: {
hasActiveProject: boolean;
isGitRepo: boolean;
showEnvironmentIndicator: boolean;
}): boolean {
return input.hasActiveProject && (input.isGitRepo || input.showEnvironmentIndicator);
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
+32 -24
View File
@@ -44,6 +44,7 @@ import { Separator } from "./ui/separator";
interface BranchToolbarProps {
environmentId: EnvironmentId;
threadId: ThreadId;
showGitControls: boolean;
draftId?: DraftId;
onEnvModeChange: (mode: EnvMode) => void;
effectiveEnvModeOverride?: EnvMode;
@@ -309,6 +310,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
export const BranchToolbar = memo(function BranchToolbar({
environmentId,
threadId,
showGitControls,
draftId,
onEnvModeChange,
effectiveEnvModeOverride,
@@ -403,7 +405,7 @@ export const BranchToolbar = memo(function BranchToolbar({
data-compact={labelsOverflow ? "" : undefined}
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1"
>
{isMobile ? (
{isMobile && showGitControls ? (
<MobileRunContextSelector
envLocked={envLocked}
envModeLocked={envModeLocked}
@@ -428,34 +430,40 @@ export const BranchToolbar = memo(function BranchToolbar({
availableEnvironments={availableEnvironments}
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
{showGitControls ? (
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
) : null}
</>
)}
<BranchToolbarEnvModeSelector
envLocked={envModeLocked}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
previousWorktreeLabel={previousWorktreeLabel}
onUsePreviousWorktree={onUsePreviousWorktree}
/>
{showGitControls ? (
<BranchToolbarEnvModeSelector
envLocked={envModeLocked}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
previousWorktreeLabel={previousWorktreeLabel}
onUsePreviousWorktree={onUsePreviousWorktree}
/>
) : null}
</div>
)}
<BranchToolbarBranchSelector
className="min-w-0 flex-1 justify-end md:ml-auto md:flex-none"
environmentId={environmentId}
threadId={threadId}
{...(draftId ? { draftId } : {})}
envLocked={envLocked}
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
/>
{showGitControls ? (
<BranchToolbarBranchSelector
className="min-w-0 flex-1 justify-end md:ml-auto md:flex-none"
environmentId={environmentId}
threadId={threadId}
{...(draftId ? { draftId } : {})}
envLocked={envLocked}
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
/>
) : null}
</div>
);
});
+231 -69
View File
@@ -26,7 +26,11 @@ import {
connectionStatusTitle,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import {
effectiveSettled,
effectiveSnoozed,
threadWokeAt,
} from "@t3tools/client-runtime/state/thread-settled";
import {
parseScopedThreadKey,
scopedThreadKey,
@@ -117,6 +121,11 @@ import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import {
clearPlanSidebarDismissal,
dismissPlanSidebarForTurn,
isPlanSidebarDismissedForTurn,
} from "../planSidebarDismissal";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import {
selectActiveRightPanel,
@@ -140,6 +149,11 @@ import {
usePreviewMiniPlayerStore,
} from "../previewMiniPlayerStore";
import { RightPanelTabs } from "./RightPanelTabs";
import { AgentsPanel } from "./AgentsPanel";
import {
deriveAgentPanelModel,
foldSubagentActivities,
} from "@t3tools/client-runtime/state/subagentRuntime";
import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
@@ -150,7 +164,6 @@ import {
CheckCircle2Icon,
ChevronDownIcon,
GitBranchIcon,
TriangleAlertIcon,
WifiOffIcon,
} from "lucide-react";
import { cn, randomHex } from "~/lib/utils";
@@ -210,7 +223,11 @@ import {
serverEnvironment,
} from "../state/server";
import { terminalEnvironment } from "../state/terminal";
import { threadEnvironment } from "../state/threads";
import { threadEnvironment, useEnvironmentThread } from "../state/threads";
import {
requestOlderThreadTurns,
threadHasOlderTurns,
} from "@t3tools/client-runtime/state/threads";
import { vcsEnvironment } from "../state/vcs";
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import {
@@ -231,7 +248,12 @@ import { ChatHeader } from "./chat/ChatHeader";
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { NoActiveThreadState } from "./NoActiveThreadState";
import { resolveEffectiveEnvMode, resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
import {
resolveEffectiveEnvMode,
resolveLocalCheckoutBranchMismatch,
shouldShowComposerContextStrip,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import {
getProviderStatusBannerKey,
ProviderStatusBanner,
@@ -1221,10 +1243,24 @@ function ChatViewContent(props: ChatViewProps) {
[routeServerThreadShell, threadDetailLoading],
);
const activeServerThread = serverThread ?? loadingServerThread;
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
(store) => store.threadLastVisitedAtById[routeThreadKey],
// Pagination window state for the routed server thread: drives the
// "load earlier turns" header when the loaded window has older history.
const routeThreadState = useEnvironmentThread(
routeKind === "server" ? routeThreadRef.environmentId : null,
routeKind === "server" ? routeThreadRef.threadId : null,
);
const loadEarlierTurns = useMemo(() => {
if (routeKind !== "server" || !threadHasOlderTurns(routeThreadState)) {
return null;
}
return {
loading: routeThreadState.page._tag === "Some" && routeThreadState.page.value.loadingOlder,
onLoadEarlier: () => {
requestOlderThreadTurns(routeThreadRef.environmentId, routeThreadRef.threadId);
},
};
}, [routeKind, routeThreadRef, routeThreadState]);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const settings = useEnvironmentSettings(environmentId);
// New-thread defaults live in the primary environment's settings.json (the
// settings UI never writes to remote environments), so read them from the
@@ -1305,8 +1341,6 @@ function ChatViewContent(props: ChatViewProps) {
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
// When set, the thread-change reset effect will open the sidebar instead of closing it.
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
@@ -1737,6 +1771,14 @@ function ChatViewContent(props: ChatViewProps) {
return envs;
}, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]);
const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
const activeEnvironmentOption =
logicalProjectEnvironments.find(
(environment) => environment.environmentId === activeThread?.environmentId,
) ?? null;
const showComposerEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: hasMultipleEnvironments,
});
const openPullRequestDialog = useCallback(
(reference?: string) => {
@@ -1843,25 +1885,6 @@ function ChatViewContent(props: ChatViewProps) {
[openOrReuseProjectDraftThread],
);
useEffect(() => {
if (!serverThread?.id) return;
const threadUpdatedAt = Date.parse(serverThread.updatedAt);
if (Number.isNaN(threadUpdatedAt)) return;
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
markThreadVisited(
scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
serverThread.updatedAt,
);
}, [
activeThreadLastVisitedAt,
markThreadVisited,
serverThread?.environmentId,
serverThread?.id,
serverThread?.updatedAt,
]);
const selectedProviderByThreadId = composerActiveProvider ?? null;
const threadProvider =
activeThread?.modelSelection.instanceId ??
@@ -1978,31 +2001,41 @@ function ChatViewContent(props: ChatViewProps) {
const updateFailed = serverUpdateState.status === "failed";
items.push({
id: `server-version:${serverUpdateEnvironmentId}`,
variant: updateFailed ? "error" : updateInProgress ? "default" : "warning",
icon: updateInProgress ? (
<span
className="size-1.5 animate-status-pulse rounded-full bg-foreground"
aria-hidden="true"
/>
) : (
<TriangleAlertIcon />
),
variant: updateFailed ? "error" : "default",
// In-flight and failed states carry their own status dot inside
// ServerUpdateProgress; only the idle offer needs an icon.
icon:
updateInProgress || updateFailed ? null : (
<span
className="size-1.5 rounded-full border border-muted-foreground/40"
aria-hidden="true"
/>
),
title:
updateInProgress || updateFailed
? `${updateFailed ? "Could not update" : "Updating"} ${versionMismatchServerLabel}`
: "Client and server versions differ",
updateInProgress || updateFailed ? (
`${updateFailed ? "Could not update" : "Updating"} ${versionMismatchServerLabel}`
) : versionMismatch ? (
<Tooltip>
<TooltipTrigger
render={
<button type="button" className="cursor-help rounded-sm text-left">
Server update available
</button>
}
/>
<TooltipPopup side="top">
{versionMismatchServerLabel} {versionMismatch.serverVersion}{" "}
<span aria-hidden="true">→</span> {versionMismatch.clientVersion}
</TooltipPopup>
</Tooltip>
) : (
"Server update available"
),
description:
updateInProgress || updateFailed ? (
<ServerUpdateProgress
fromVersion={serverUpdateState.fromVersion}
state={serverUpdateState}
/>
) : versionMismatch ? (
<>
Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "}
{versionMismatch.serverVersion}.{" "}
{serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)}
</>
<ServerUpdateProgress state={serverUpdateState} />
) : versionMismatchSelfUpdate === "desktop-managed" ? (
serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)
) : null,
// The desktop-managed guidance is already the description; the action
// slot would only repeat it.
@@ -2015,13 +2048,13 @@ function ChatViewContent(props: ChatViewProps) {
serverLabel={versionMismatchServerLabel}
selfUpdate={versionMismatchSelfUpdate}
targetVersion={versionMismatch.clientVersion}
{...(updateFailed ? { label: "Retry update" } : {})}
label={updateFailed ? "Retry" : "Update"}
/>
),
...(updateInProgress || updateFailed || !versionMismatchDismissKey
? {}
: {
dismissLabel: "Dismiss version mismatch warning",
dismissLabel: "Dismiss update notice",
onDismiss: () => {
dismissVersionMismatch(versionMismatchDismissKey);
setDismissedVersionMismatchKey(versionMismatchDismissKey);
@@ -2052,6 +2085,18 @@ function ChatViewContent(props: ChatViewProps) {
const phase = derivePhase(activeThread?.session ?? null);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
// Native subagent fold: memoized by activity-list identity, shared by the
// Agents surface, live strip, and workflow cards. v2Projection is null
// until orchestration-v2 lands (source precedence lives in the derive).
// sessionLive derives interruption for agents orphaned by session death.
const agentSessionLive = phase !== "disconnected";
const agentPanelModel = useMemo(
() =>
deriveAgentPanelModel({
agents: foldSubagentActivities(threadActivities, { sessionLive: agentSessionLive }),
}),
[agentSessionLive, threadActivities],
);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
[threadActivities],
@@ -2503,7 +2548,11 @@ function ChatViewContent(props: ChatViewProps) {
terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const showComposerContextStrip = isGitRepo && activeProject !== null;
const showComposerContextStrip = shouldShowComposerContextStrip({
hasActiveProject: activeProject !== null,
isGitRepo,
showEnvironmentIndicator: showComposerEnvironmentIndicator,
});
const initialDiffPanelGitScope =
gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";
const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending";
@@ -3093,18 +3142,21 @@ function ChatViewContent(props: ChatViewProps) {
handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");
}, [handleInteractionModeChange, interactionMode]);
const dismissPlanSidebarForCurrentTurn = useCallback(() => {
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
if (!activeThreadKey) return;
dismissPlanSidebarForTurn(
activeThreadKey,
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__",
);
}, [activeThreadKey, activePlan?.turnId, sidebarProposedPlan?.turnId]);
const togglePlanSidebar = useCallback(() => {
if (!activeThreadRef) return;
if (planSidebarOpen) {
dismissPlanSidebarForCurrentTurn();
} else {
planSidebarDismissedForTurnRef.current = null;
} else if (activeThreadKey) {
clearPlanSidebarDismissal(activeThreadKey);
}
useRightPanelStore.getState().toggle(activeThreadRef, "plan");
}, [activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]);
}, [activeThreadKey, activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]);
const closePlanSidebar = useCallback(() => {
if (!activeThreadRef) return;
setMaximizedRightPanelThreadKey(null);
@@ -3134,6 +3186,10 @@ function ChatViewContent(props: ChatViewProps) {
if (!activeThreadRef || !activeProject) return;
useRightPanelStore.getState().open(activeThreadRef, "files");
}, [activeProject, activeThreadRef]);
const addAgentsSurface = useCallback(() => {
if (!activeThreadRef) return;
useRightPanelStore.getState().open(activeThreadRef, "agents");
}, [activeThreadRef]);
const openFileSurface = useCallback(
(relativePath: string) => {
if (!activeThreadRef || !activeProject) return;
@@ -3262,7 +3318,7 @@ function ChatViewContent(props: ChatViewProps) {
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
if (surface.kind === "plan") {
planSidebarDismissedForTurnRef.current = null;
clearPlanSidebarDismissal(scopedThreadKey(activeThreadRef));
} else if (planSidebarOpen) {
dismissPlanSidebarForCurrentTurn();
}
@@ -3831,10 +3887,10 @@ function ChatViewContent(props: ChatViewProps) {
if (planSidebarOpenOnNextThreadRef.current) {
planSidebarOpenOnNextThreadRef.current = false;
if (activeThreadRef) {
clearPlanSidebarDismissal(scopedThreadKey(activeThreadRef));
useRightPanelStore.getState().open(activeThreadRef, "plan");
}
}
planSidebarDismissedForTurnRef.current = null;
// activeThreadRef resets transitively with the active thread.
}, [activeThread?.id]);
@@ -3847,10 +3903,9 @@ function ChatViewContent(props: ChatViewProps) {
const latestTurnId = activeLatestTurn?.turnId ?? null;
if (latestTurnId && activePlan.turnId !== latestTurnId) return;
const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
if (planSidebarDismissedForTurnRef.current === turnKey) return;
if (activeThreadRef) {
useRightPanelStore.getState().open(activeThreadRef, "plan");
}
if (!activeThreadRef) return;
if (isPlanSidebarDismissedForTurn(scopedThreadKey(activeThreadRef), turnKey)) return;
useRightPanelStore.getState().open(activeThreadRef, "plan");
}, [
activePlan,
activeLatestTurn?.turnId,
@@ -3971,13 +4026,18 @@ function ChatViewContent(props: ChatViewProps) {
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
const snoozeNow = new Date().toISOString();
const activeThreadSnoozed =
activeThreadShell !== null &&
supportsSnooze &&
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
effectiveSnoozed(activeThreadShell, { now: snoozeNow });
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
void snoozeWakeTick;
const activeThreadWokeAt =
activeThreadShell !== null && supportsSnooze
? threadWokeAt(activeThreadShell, { now: snoozeNow })
: null;
useEffect(() => {
void snoozeWakeTick;
if (!activeThreadSnoozed) return;
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
if (!Number.isFinite(wakeAtMs)) return;
@@ -3987,6 +4047,10 @@ function ChatViewContent(props: ChatViewProps) {
);
return () => window.clearTimeout(id);
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
const acknowledgeActiveThreadWoke = useCallback(() => {
if (activeThreadRef === null || activeThreadWokeAt === null) return;
markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt);
}, [activeThreadRef, activeThreadWokeAt, markThreadVisited]);
const activeThreadSettled = useMemo(() => {
if (activeThreadShell === null || !supportsSettlement) return false;
return effectiveSettled(activeThreadShell, {
@@ -4167,6 +4231,85 @@ function ChatViewContent(props: ChatViewProps) {
switchGitRef,
updateThreadMetadata,
]);
// Background work (subagent fleets, workflow runs, watch loops) can outlive
// the turn; once it settles, the composer stop button is gone, so this
// banner is the only visible stop affordance. Stop routes through the
// stop-everything interrupt: it kills every live background task before
// interrupting, and works by session, so no active turn is needed.
const activeBackgroundLiveness =
!isWorking && activeThread ? (activeThreadShell?.backgroundLiveness ?? null) : null;
const [isStoppingBackgroundWork, setIsStoppingBackgroundWork] = useState(false);
useEffect(() => {
// "Stopping..." holds until the liveness clears; the interrupt command
// returning only means the request was accepted.
if (activeBackgroundLiveness === null) {
setIsStoppingBackgroundWork(false);
}
}, [activeBackgroundLiveness]);
useEffect(() => {
// Per-thread state: switching threads while A's stop is pending must not
// disable B's Stop button (review finding).
setIsStoppingBackgroundWork(false);
}, [activeThreadId]);
const handleStopBackgroundWork = useCallback(async () => {
if (!activeThread) return;
setIsStoppingBackgroundWork(true);
const result = await interruptThreadTurn({
environmentId,
input: buildThreadTurnInterruptInput(activeThread),
});
if (result._tag === "Failure") {
// Every failure clears the pending state — an interrupted command
// never reached the server, so liveness would hold "Stopping..."
// forever. Only real failures toast.
setIsStoppingBackgroundWork(false);
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
setThreadError(
activeThread.id,
error instanceof Error ? error.message : "Failed to stop background work.",
);
}
}
}, [activeThread, environmentId, interruptThreadTurn, setThreadError]);
const backgroundLivenessBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
if (activeBackgroundLiveness === null || !activeThread) {
return null;
}
const working = activeBackgroundLiveness === "working";
const liveCount = agentPanelModel.liveCount;
return {
id: `background-liveness:${activeThread.id}`,
variant: "default",
icon: (
<span
className={cn("size-1.5 rounded-full bg-foreground", working && "animate-status-pulse")}
aria-hidden="true"
/>
),
title: working
? liveCount > 0
? `${liveCount} ${liveCount === 1 ? "agent" : "agents"} working in the background`
: "Background work running"
: "Monitoring in the background",
actions: (
<Button
size="xs"
variant="outline"
disabled={isStoppingBackgroundWork}
onClick={() => void handleStopBackgroundWork()}
>
{isStoppingBackgroundWork ? "Stopping..." : "Stop"}
</Button>
),
};
}, [
activeBackgroundLiveness,
activeThread,
agentPanelModel.liveCount,
handleStopBackgroundWork,
isStoppingBackgroundWork,
]);
// The stack renders items[0] front-most and tucks the rest behind hover, so
// ordering is priority: system banners, then the branch-mismatch notice,
// and the informational parked-thread banner last — it must never cover another.
@@ -4219,12 +4362,15 @@ function ChatViewContent(props: ChatViewProps) {
void handleSwitchCheckoutToThread();
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const backgroundLivenessItems =
backgroundLivenessBannerItem === null ? [] : [backgroundLivenessBannerItem];
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
return [...systemComposerBannerItems, ...parkedThreadItems];
return [...systemComposerBannerItems, ...backgroundLivenessItems, ...parkedThreadItems];
}
return [
...systemComposerBannerItems,
...backgroundLivenessItems,
{
id: `branch-mismatch:${activeBranchMismatchKey}`,
variant: "info",
@@ -4268,6 +4414,7 @@ function ChatViewContent(props: ChatViewProps) {
];
}, [
activeBranchMismatchKey,
backgroundLivenessBannerItem,
handleRestoreThreadBranch,
isRestoringThreadBranch,
localCheckoutBranchMismatch,
@@ -4945,6 +5092,7 @@ function ChatViewContent(props: ChatViewProps) {
failure = startResult;
} else {
turnStartSucceeded = true;
acknowledgeActiveThreadWoke();
}
}
@@ -5304,12 +5452,13 @@ function ChatViewContent(props: ChatViewProps) {
}
if (failure === null) {
acknowledgeActiveThreadWoke();
// Optimistically open the plan sidebar when implementing (not refining).
// "default" mode here means the agent is executing the plan, which produces
// step-tracking activities that the sidebar will display.
if (nextInteractionMode === "default" && autoOpenPlanSidebar) {
planSidebarDismissedForTurnRef.current = null;
if (activeThreadRef) {
clearPlanSidebarDismissal(scopedThreadKey(activeThreadRef));
useRightPanelStore.getState().open(activeThreadRef, "plan");
}
}
@@ -5333,6 +5482,7 @@ function ChatViewContent(props: ChatViewProps) {
[
activeThread,
activeProposedPlan,
acknowledgeActiveThreadWoke,
beginLocalDispatch,
isConnecting,
isSendBusy,
@@ -5764,6 +5914,12 @@ function ChatViewContent(props: ChatViewProps) {
timestampFormat={timestampFormat}
mode="embedded"
/>
) : activeRightPanelSurface?.kind === "agents" ? (
<AgentsPanel
model={agentPanelModel}
environmentId={activeThreadRef?.environmentId ?? null}
threadId={activeThreadRef?.threadId ?? null}
/>
) : (activeRightPanelSurface?.kind === "files" || activeRightPanelSurface?.kind === "file") &&
activeProject &&
activeWorkspaceRoot ? (
@@ -5859,6 +6015,8 @@ function ChatViewContent(props: ChatViewProps) {
<div className="relative flex min-h-0 flex-1 flex-col">
{/* Messages — LegendList handles virtualization and scrolling internally */}
<MessagesTimeline
agentPanelModel={agentPanelModel}
onOpenAgents={addAgentsSurface}
key={activeThread.id}
isWorking={isWorking}
activeTurnInProgress={isWorking || !latestTurnSettled}
@@ -5892,6 +6050,7 @@ function ChatViewContent(props: ChatViewProps) {
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
topFadeEnabled={!hasTimelineTopBanner}
loadEarlier={loadEarlierTurns}
/>
{/* scroll to end pill — shown when user has scrolled away from the live edge */}
@@ -6060,6 +6219,7 @@ function ChatViewContent(props: ChatViewProps) {
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
showGitControls={isGitRepo}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
@@ -6195,6 +6355,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
@@ -6222,6 +6383,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
@@ -72,8 +72,8 @@ import { cn, isMacPlatform } from "~/lib/utils";
import { basenameOfPath } from "~/pierre-icons";
import {
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
COMPOSER_INLINE_SKILL_CHIP_LABEL_CLASS_NAME,
SKILL_CHIP_ICON_SVG,
} from "./composerInlineChip";
import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
@@ -188,7 +188,7 @@ class ComposerMentionNode extends DecoratorNode<React.ReactElement> {
override createDOM(): HTMLElement {
const dom = document.createElement("span");
dom.className = "composer-inline-chip relative inline-flex align-middle leading-none";
dom.className = "composer-inline-chip relative inline-flex align-[-0.125em] leading-none";
return dom;
}
@@ -256,7 +256,7 @@ function ComposerSkillDecorator(props: { skillLabel: string; skillDescription: s
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
/>
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{props.skillLabel}</span>
<span className={COMPOSER_INLINE_SKILL_CHIP_LABEL_CLASS_NAME}>{props.skillLabel}</span>
</span>
);
@@ -326,7 +326,7 @@ class ComposerSkillNode extends DecoratorNode<React.ReactElement> {
override createDOM(): HTMLElement {
const dom = document.createElement("span");
dom.className = "composer-inline-chip relative inline-flex align-middle leading-none";
dom.className = "composer-inline-chip relative inline-flex align-[-0.125em] leading-none";
return dom;
}
@@ -397,7 +397,7 @@ class ComposerTerminalContextNode extends DecoratorNode<React.ReactElement> {
override createDOM(): HTMLElement {
const dom = document.createElement("span");
dom.className = "composer-inline-chip relative inline-flex align-middle leading-none";
dom.className = "composer-inline-chip relative inline-flex align-[-0.125em] leading-none";
return dom;
}
+20 -1
View File
@@ -1,6 +1,6 @@
import type { ContextMenuItem, PreviewSessionSnapshot } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import { ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import { Bot, ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import {
type MouseEvent as ReactMouseEvent,
type ReactElement,
@@ -44,6 +44,7 @@ interface RightPanelTabsProps {
onAddTerminal: () => void;
onAddDiff: () => void;
onAddFiles: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
@@ -91,6 +92,7 @@ function RightPanelEmptyState(props: {
onAddTerminal: () => void;
onAddDiff: () => void;
onAddFiles: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
@@ -128,6 +130,14 @@ function RightPanelEmptyState(props: {
disabledReason: SURFACE_DISABLED_REASONS.diff,
onClick: props.onAddDiff,
},
{
label: "Agents",
description: "Watch subagents and workflows run.",
icon: Bot,
available: true,
disabledReason: null,
onClick: props.onAddAgents,
},
] as const;
return (
@@ -205,6 +215,8 @@ function surfaceTitle(
);
case "plan":
return "Plan";
case "agents":
return "Agents";
case "preview": {
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
@@ -266,6 +278,8 @@ function SurfaceIcon({
return <TerminalSquare className="size-3 shrink-0" />;
case "plan":
return <ClipboardList className="size-3 shrink-0" />;
case "agents":
return <Bot className="size-3 shrink-0" />;
}
}
@@ -466,6 +480,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<FileDiff />
Diff
</SurfaceMenuItem>
<SurfaceMenuItem available onClick={props.onAddAgents}>
<Bot />
Agents
</SurfaceMenuItem>
</MenuPopup>
</Menu>
) : null}
@@ -480,6 +498,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
onAddTerminal={props.onAddTerminal}
onAddDiff={props.onAddDiff}
onAddFiles={props.onAddFiles}
onAddAgents={props.onAddAgents}
browserAvailable={props.browserAvailable}
diffAvailable={props.diffAvailable}
filesAvailable={props.filesAvailable}
@@ -101,10 +101,9 @@ describe("ServerUpdateAction", () => {
});
describe("ServerUpdateProgress", () => {
it("renders the monochrome step rail with only the active step highlighted", () => {
it("shows one calm status row for the restart wait", () => {
const markup = renderToStaticMarkup(
<ServerUpdateProgress
fromVersion="0.0.30"
state={{
status: "running",
stage: "resuming",
@@ -114,23 +113,36 @@ describe("ServerUpdateProgress", () => {
/>,
);
expect(markup).toContain("0.0.30");
expect(markup).toContain("0.0.31");
expect(markup).toContain("Download");
expect(markup).toContain("Install");
expect(markup).toContain("Resuming");
// The wait state is monochrome and calm: no success/warning colors, no
// status sentence, one duty-cycled pulse on the active step.
expect(markup).toContain("Restarting…");
// The wait state is monochrome and calm: no versions, no step rail, no
// success/warning colors, one duty-cycled pulse on the dot.
expect(markup).not.toContain("0.0.30");
expect(markup).not.toContain("Resum");
expect(markup).not.toContain("text-success");
expect(markup).not.toContain("text-primary");
expect(markup).toContain("animate-status-pulse");
expect(markup).not.toContain("animate-spin");
});
it("keeps the failed stage visible with its retryable error", () => {
it("folds the sub-second installing handoff into the download phase", () => {
const markup = renderToStaticMarkup(
<ServerUpdateProgress
state={{
status: "running",
stage: "installing",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
}}
/>,
);
expect(markup).toContain("Downloading…");
expect(markup).not.toContain("Install");
});
it("keeps the failure visible with its retryable error", () => {
const markup = renderToStaticMarkup(
<ServerUpdateProgress
fromVersion="0.0.30"
state={{
status: "failed",
stage: "installing",
+34 -81
View File
@@ -1,110 +1,63 @@
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
import type { ServerUpdateStage, ServerUpdateState } from "@t3tools/client-runtime/state/server";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { CheckIcon } from "lucide-react";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { cn } from "~/lib/utils";
import { serverEnvironment } from "~/state/server";
import { useAtomCommand } from "~/state/use-atom-command";
import { manualServerUpdateCommand } from "~/versionSkew";
import { Button } from "./ui/button";
import { toastManager } from "./ui/toast";
const UPDATE_STEPS = [
{ stage: "downloading", label: "Download", activeLabel: "Downloading" },
{ stage: "installing", label: "Install", activeLabel: "Installing" },
{ stage: "resuming", label: "Resume", activeLabel: "Resuming" },
] as const;
// The wire "installing" stage is a sub-second launcher handoff, so the UI
// folds it into the download phase; everything after the handoff is the
// restart the user is actually waiting through.
const UPDATE_STAGE_LABELS: Record<ServerUpdateStage, string> = {
downloading: "Downloading…",
installing: "Downloading…",
resuming: "Restarting…",
};
const pendingUpdateEnvironmentIds = new Set<EnvironmentId>();
export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
return UPDATE_STAGE_LABELS[stage];
}
function updateFailureMessage(error: unknown): string {
return error instanceof Error ? error.message : "Server update failed.";
}
/**
* Monochrome step rail for an in-flight server update. The update is a
* wait, not a warning: done steps recede to gray, the active step is the
* only bright element and pulses. Failure keeps the rail but surfaces the
* error below it.
* One-row status for an in-flight server update: "Downloading…" then
* "Restarting…". The update is a wait, not a warning: a single pulsing dot
* and label, no step rail, no versions. Failure turns the row red with the
* rollback reason.
*/
export function ServerUpdateProgress({
fromVersion,
state,
}: {
readonly fromVersion: string;
readonly state: Exclude<ServerUpdateState, { status: "idle" }>;
}) {
const currentIndex = UPDATE_STEPS.findIndex(({ stage }) => stage === state.stage);
return (
<div className="mt-1 min-w-0 space-y-2.5">
<p className="text-xs text-muted-foreground/70">
{fromVersion} <span aria-hidden="true">→</span> {state.targetVersion}
</p>
<ol className="flex min-w-0 items-center" aria-label="Server update progress">
{UPDATE_STEPS.map((step, index) => {
const complete = index < currentIndex;
const current = index === currentIndex;
const failed = current && state.status === "failed";
const running = current && state.status === "running";
return (
<li
key={step.stage}
className={cn(
"flex min-w-0 items-center text-xs font-medium",
index < UPDATE_STEPS.length - 1 ? "flex-1" : null,
complete
? "text-muted-foreground"
: failed
? "text-destructive"
: running
? "animate-status-pulse text-foreground"
: "text-muted-foreground/50",
)}
aria-current={running ? "step" : undefined}
>
{complete ? (
<CheckIcon
className="size-3.5 shrink-0 opacity-70"
strokeWidth={2.5}
aria-hidden="true"
/>
) : (
<span
className={cn(
"size-1.5 shrink-0 rounded-full",
failed
? "bg-destructive"
: running
? "bg-foreground"
: "border border-muted-foreground/40",
)}
aria-hidden="true"
/>
)}
<span className="ml-1.5 truncate">{running ? step.activeLabel : step.label}</span>
{index < UPDATE_STEPS.length - 1 ? (
<span
className={cn(
"mx-2 h-px min-w-3 flex-1",
complete ? "bg-muted-foreground/40" : "bg-border",
)}
aria-hidden="true"
/>
) : null}
</li>
);
})}
</ol>
{state.status === "failed" ? (
<p className="text-xs text-destructive" role="alert">
if (state.status === "failed") {
return (
<div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-destructive" role="alert">
<span className="size-1.5 shrink-0 rounded-full bg-destructive" aria-hidden="true" />
<span className="min-w-0 truncate" title={state.message}>
{state.message}
</p>
) : null}
</span>
</div>
);
}
return (
<div className="mt-1 flex items-center gap-2 text-xs font-medium text-foreground">
<span
className="size-1.5 shrink-0 animate-status-pulse rounded-full bg-foreground"
aria-hidden="true"
/>
<span>{serverUpdateStageLabel(state.stage)}</span>
</div>
);
}
@@ -119,7 +72,7 @@ export function ServerUpdateAction({
serverLabel,
selfUpdate,
targetVersion,
label = "Update server",
label = "Update",
}: {
readonly environmentId: EnvironmentId;
readonly serverLabel: string;
+47 -7
View File
@@ -120,6 +120,7 @@ export function buildBulkTitleRegenerationContextMenuItem(input: {
export interface ThreadStatusPill {
label:
| "Working"
| "Monitoring"
| "Connecting"
| "Completed"
| "Pending Approval"
@@ -130,12 +131,16 @@ export interface ThreadStatusPill {
pulse: boolean;
}
// Rollup order mirrors the per-thread resolver exactly: attention states,
// then active work, then the actionable plan prompt, then passive
// monitoring. A Monitoring sibling must never hide a Plan Ready thread.
const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
"Pending Approval": 5,
"Awaiting Input": 4,
Working: 3,
Connecting: 3,
"Plan Ready": 2,
"Pending Approval": 6,
"Awaiting Input": 5,
Working: 4,
Connecting: 4,
"Plan Ready": 3,
Monitoring: 2,
Completed: 1,
};
@@ -147,6 +152,7 @@ type ThreadStatusInput = Pick<
| "interactionMode"
| "latestTurn"
| "session"
| "backgroundLiveness"
> & {
lastVisitedAt?: string | undefined;
};
@@ -424,11 +430,11 @@ export function resolveThreadRowClassName(input: {
// whether it finished, asked a question, or proposed a plan.
// Unread completion is tracked separately: it describes whether a ready
// thread needs attention, not what the thread is currently doing.
export type SidebarV2Status = "approval" | "input" | "working" | "failed" | "ready";
export type SidebarV2Status = "approval" | "input" | "working" | "monitoring" | "failed" | "ready";
type SidebarV2StatusInput = Pick<
SidebarThreadSummary,
"hasPendingApprovals" | "hasPendingUserInput" | "session"
"hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
>;
export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {
@@ -441,9 +447,19 @@ export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2S
if (thread.session?.status === "running" || thread.session?.status === "starting") {
return "working";
}
// A failed session outranks lingering background liveness: the user must
// see the failure, not a stale Working (review finding).
if (thread.session?.status === "error") {
return "failed";
}
// Background work outlives the turn: fleets read as working; monitoring
// only when watch loops are the sole live work.
if (thread.backgroundLiveness === "working") {
return "working";
}
if (thread.backgroundLiveness === "monitoring") {
return "monitoring";
}
return "ready";
}
@@ -616,6 +632,8 @@ export function resolveThreadStatusPill(input: {
};
}
// An actionable plan prompt outranks lingering background work: it needs
// the user's decision, while liveness merely reports (review finding).
const hasPlanReadyPrompt =
!thread.hasPendingUserInput &&
thread.interactionMode === "plan" &&
@@ -630,6 +648,28 @@ export function resolveThreadStatusPill(input: {
};
}
// The turn can settle while native background work runs on. Subagent and
// workflow fleets read as plain Working; Monitoring is reserved for watch
// loops (a parent agent babysitting a PR, tailing checks) with no other
// live work. Same recede treatment as Working per inbox-zero.
if (thread.backgroundLiveness === "working") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.backgroundLiveness === "monitoring") {
return {
label: "Monitoring",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: false,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
+31 -17
View File
@@ -10,7 +10,7 @@ function localDate(year: number, month: number, day: number, hour: number, minut
describe("resolveSnoozePresets", () => {
it("offers hour, evening, tomorrow, next week in the morning", () => {
// Wednesday 2026-04-08 10:00 local.
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10), "locale");
expect(presets.map((preset) => preset.id)).toEqual([
"hour",
"evening",
@@ -30,7 +30,7 @@ describe("resolveSnoozePresets", () => {
});
it("whenLabel complements the label instead of repeating it", () => {
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10), "locale");
for (const preset of presets) {
// Day words live in the label column; the time column is time-only
// (plus a weekday for next week, which names a different day).
@@ -43,37 +43,51 @@ describe("resolveSnoozePresets", () => {
});
it("drops the evening preset once evening is near or past", () => {
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
"hour",
"tomorrow",
"next-week",
]);
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
"hour",
"tomorrow",
"next-week",
]);
expect(
resolveSnoozePresets(localDate(2026, 4, 8, 17, 30), "locale").map((preset) => preset.id),
).toEqual(["hour", "tomorrow", "next-week"]);
expect(
resolveSnoozePresets(localDate(2026, 4, 8, 21), "locale").map((preset) => preset.id),
).toEqual(["hour", "tomorrow", "next-week"]);
});
it("puts next week a full week out when today is Monday", () => {
// Monday 2026-04-06.
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10), "locale");
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
expect(nextWeek.getDay()).toBe(1);
expect(nextWeek.getDate()).toBe(13);
});
it("formats preset times with the selected clock preference", () => {
const twelveHour = resolveSnoozePresets(localDate(2026, 4, 8, 10), "12-hour");
const twentyFourHour = resolveSnoozePresets(localDate(2026, 4, 8, 10), "24-hour");
expect(twelveHour.find((preset) => preset.id === "evening")!.whenLabel).toMatch(/PM/i);
expect(twentyFourHour.find((preset) => preset.id === "evening")!.whenLabel).toBe("18:00");
});
});
describe("snoozeWakeDescription", () => {
const now = localDate(2026, 4, 8, 10);
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
expect(
snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now, "locale"),
).not.toContain("tomorrow");
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now, "locale")).toContain(
"tomorrow",
);
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
"tomorrow",
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now, "locale")).toMatch(
/Mon/,
);
});
it("formats wake descriptions with the selected clock preference", () => {
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now, "12-hour")).toMatch(
/PM/i,
);
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now, "24-hour")).toBe(
"18:00",
);
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
});
});
+36 -8
View File
@@ -1,22 +1,50 @@
import { snoozeWakeLabel } from "@t3tools/client-runtime/state/thread-settled";
import { parseTimestampDate } from "../timestampFormat";
export {
resolveSnoozePresets,
import type { TimestampFormat } from "@t3tools/contracts/settings";
import {
resolveSnoozePresets as resolveSharedSnoozePresets,
snoozeWakeLabel,
type SnoozePreset,
} from "@t3tools/client-runtime/state/thread-settled";
export { snoozeWakeLabel };
import { formatShortTimestamp, parseTimestampDate } from "../timestampFormat";
export { snoozeWakeLabel, type SnoozePreset };
const DAY_MS = 24 * 60 * 60 * 1_000;
function timeOfDayLabel(date: Date, timestampFormat: TimestampFormat): string {
return formatShortTimestamp(date.toISOString(), timestampFormat);
}
export function resolveSnoozePresets(
now: Date,
timestampFormat: TimestampFormat,
): ReadonlyArray<SnoozePreset> {
return resolveSharedSnoozePresets(now).map((preset) => {
const wake = parseTimestampDate(preset.snoozedUntil);
if (wake === null) return preset;
const time = timeOfDayLabel(wake, timestampFormat);
return {
...preset,
whenLabel:
preset.id === "next-week"
? `${wake.toLocaleDateString(undefined, { weekday: "short" })} ${time}`
: time,
};
});
}
/**
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
* "17:30" (today).
*/
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
export function snoozeWakeDescription(
snoozedUntil: string,
now: Date,
timestampFormat: TimestampFormat,
): string {
const wake = parseTimestampDate(snoozedUntil);
if (wake === null) return "";
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
const time = timeOfDayLabel(wake, timestampFormat);
const startOfToday = new Date(now);
startOfToday.setHours(0, 0, 0, 0);
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
+241 -106
View File
@@ -13,6 +13,7 @@ import {
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import type { ScopedThreadRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { TimestampFormat } from "@t3tools/contracts/settings";
import {
AlarmClockIcon,
AlarmClockOffIcon,
@@ -341,11 +342,15 @@ function SnoozePopoverButton(props: {
open: boolean;
onOpenChange: (open: boolean) => void;
onSnooze: (preset: SnoozePreset) => void;
timestampFormat: TimestampFormat;
}) {
const { open, onOpenChange, onSnooze } = props;
const { open, onOpenChange, onSnooze, timestampFormat } = props;
// Presets resolve at open time so "In 1 hour" is relative to the click,
// not to when the row mounted.
const presets = useMemo(() => (open ? resolveSnoozePresets(new Date()) : []), [open]);
const presets = useMemo(
() => (open ? resolveSnoozePresets(new Date(), timestampFormat) : []),
[open, timestampFormat],
);
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger
@@ -412,6 +417,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
projectCwd: string | null;
projectTitle: string | null;
providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
timestampFormat: TimestampFormat;
onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void;
onThreadActivate: (threadRef: ScopedThreadRef) => void;
onStartRename: (threadRef: ScopedThreadRef, title: string) => void;
@@ -425,6 +431,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
onUnsettle: (threadRef: ScopedThreadRef) => void;
onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void;
onUnsnooze: (threadRef: ScopedThreadRef) => void;
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void;
}) {
const {
@@ -433,6 +440,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
onCancelRename,
onCommitRename,
onContextMenu,
onAcknowledgeWoke,
onRenameTitleChange,
onSettle,
onSnooze,
@@ -482,7 +490,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// findable. In-flight rows recede the same as read-ready ones (inbox-zero:
// working threads aren't your problem yet) — only the colored status label
// stands out.
const isInFlight = status === "working" || status === "approval" || status === "input";
const isInFlight =
status === "working" || status === "monitoring" || status === "approval" || status === "input";
const shouldRecede =
(status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected;
// Status hues follow the system-wide convention set by sidebar v1 and the
@@ -496,37 +505,46 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
className:
"animate-sidebar-working-text text-sky-600 motion-reduce:animate-none dark:text-sky-400",
}
: status === "approval"
: status === "monitoring"
? {
label: "Approval",
// Steady label, no duty-cycled shimmer: monitoring is calm
// background presence, not active progress (monitoring-pill D6).
label: "Monitoring",
icon: null,
className: "text-amber-700 dark:text-amber-300",
className: "text-sky-600 dark:text-sky-400",
}
: status === "input"
: status === "approval"
? {
label: "Input",
label: "Approval",
icon: null,
className: "text-indigo-600 dark:text-indigo-300",
className: "text-amber-700 dark:text-amber-300",
}
: status === "failed"
: status === "input"
? {
label: "Failed",
label: "Input",
icon: null,
className: "text-red-700 dark:text-red-300",
className: "text-indigo-600 dark:text-indigo-300",
}
: isWoke
: status === "failed"
? {
label: "Woke",
icon: "woke" as const,
className: "text-amber-700 dark:text-amber-300",
label: "Failed",
icon: null,
className: "text-red-700 dark:text-red-300",
}
: isUnread
: isWoke
? {
label: "Done",
icon: "done" as const,
className: "text-emerald-700 dark:text-emerald-300",
label: "Woke",
icon: "woke" as const,
className: "text-amber-700 dark:text-amber-300",
}
: null;
: isUnread
? {
label: "Done",
icon: "done" as const,
className: "text-emerald-700 dark:text-emerald-300",
}
: null;
const isWokeStatus = topStatus?.icon === "woke";
const gitCwd = thread.worktreePath ?? props.projectCwd;
const gitStatus = useEnvironmentQuery(
@@ -590,6 +608,15 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
},
[onThreadClick, threadRef],
);
const handleAcknowledgeWokeClick = useCallback(
(event: ReactMouseEvent) => {
event.preventDefault();
event.stopPropagation();
if (props.wokeAt === null) return;
onAcknowledgeWoke(threadRef, props.wokeAt);
},
[onAcknowledgeWoke, props.wokeAt, threadRef],
);
const handleContextMenu = useCallback(
(event: ReactMouseEvent) => {
event.preventDefault();
@@ -838,7 +865,12 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
the time/jump label yields to the settle affordance. */}
{prBadge}
<span className="relative ml-auto flex h-6 min-w-8 shrink-0 items-center justify-end">
<span className="inline-flex justify-end tabular-nums text-muted-foreground/55 transition-opacity group-hover/v2-row:opacity-0">
<span
className={cn(
"inline-flex justify-end tabular-nums text-muted-foreground/55 transition-opacity",
!isWoke && "group-hover/v2-row:opacity-0",
)}
>
{variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? (
// Snoozed rows show when they come BACK, not when they were
// last touched — the return ticket is the row's whole story.
@@ -848,14 +880,16 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
) : isWoke ? (
// A wake can land straight in the settled tail (e.g. PR
// merged while snoozed); the signal must survive the trip.
<span
role="status"
aria-label="Woke from snooze"
className="inline-flex items-center gap-1 text-xs font-medium text-amber-700 dark:text-amber-300"
<button
type="button"
aria-label="Dismiss Woke notification"
title="Dismiss Woke notification"
onClick={handleAcknowledgeWokeClick}
className="inline-flex cursor-pointer items-center gap-1 rounded-sm text-xs font-medium text-amber-700 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring dark:text-amber-300"
>
<AlarmClockIcon aria-hidden className="size-3" />
Woke
</span>
<span role="status">Woke</span>
</button>
) : (
<span className="text-xs">
{variantAction === "unsettle"
@@ -870,7 +904,10 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
type="button"
aria-label="Wake thread now"
onClick={handleUnsnoozeClick}
className="absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
className={cn(
"pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100",
isWoke && "group-hover/v2-row:static",
)}
>
<AlarmClockOffIcon className="size-3" />
</button>
@@ -880,7 +917,10 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
type="button"
aria-label="Un-settle thread"
onClick={handleUnsettleClick}
className="absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
className={cn(
"pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100",
isWoke && "group-hover/v2-row:static",
)}
>
<Undo2Icon className="mb-px size-3.5" />
</button>
@@ -889,7 +929,10 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
type="button"
aria-label="Settle thread"
onClick={handleSettleClick}
className="absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
className={cn(
"pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100",
isWoke && "group-hover/v2-row:static",
)}
>
<CheckIcon className="size-3" />
</button>
@@ -957,39 +1000,56 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
the hidden state out of flow lets the project label reclaim
space without either state overlapping it. */}
<span className="group/v2-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs">
{/* pointer-events-none: while hovered this label is absolute
+ opacity-0, which paints it ABOVE the in-flow settle/snooze
buttons; without it the invisible label eats their clicks. */}
{/* Read-only status labels yield to the hover actions. Woke is
itself an action, so it stays pointer-enabled and visible
while the other controls appear beside it. */}
<span
className={cn(
"pointer-events-none self-center justify-self-end tabular-nums text-muted-foreground/65 transition-opacity group-has-[:focus-visible]/v2-status-slot:absolute group-has-[:focus-visible]/v2-status-slot:right-0 group-has-[:focus-visible]/v2-status-slot:opacity-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
snoozeMenuOpen && "absolute right-0 opacity-0",
isWokeStatus
? "pointer-events-auto"
: "pointer-events-none group-has-[:focus-visible]/v2-status-slot:absolute group-has-[:focus-visible]/v2-status-slot:right-0 group-has-[:focus-visible]/v2-status-slot:opacity-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
"self-center justify-self-end tabular-nums text-muted-foreground/65 transition-opacity",
snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0",
)}
>
{topStatus ? (
<span
className={cn(
"inline-flex items-center gap-1 font-medium",
topStatus.className,
)}
>
{topStatus.icon === "working" ? (
<CircleDashedIcon aria-hidden className="size-4 shrink-0" />
) : topStatus.icon === "done" ? (
<CircleCheckIcon aria-hidden className="size-4 shrink-0" />
) : topStatus.icon === "woke" ? (
isWokeStatus ? (
<button
type="button"
aria-label="Dismiss Woke notification"
title="Dismiss Woke notification"
onClick={handleAcknowledgeWokeClick}
className={cn(
"inline-flex cursor-pointer items-center gap-1 rounded-sm font-medium outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring",
topStatus.className,
)}
>
<AlarmClockIcon aria-hidden className="size-4 shrink-0" />
) : null}
{/* The label alone is the live region: a role="status"
wrapper around the ticking duration would make
screen readers announce every second. */}
<span role="status">{topStatus.label}</span>
{status === "working" ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
</span>
) : null}
</span>
<span role="status">{topStatus.label}</span>
</button>
) : (
<span
className={cn(
"inline-flex items-center gap-1 font-medium",
topStatus.className,
)}
>
{topStatus.icon === "working" ? (
<CircleDashedIcon aria-hidden className="size-4 shrink-0" />
) : topStatus.icon === "done" ? (
<CircleCheckIcon aria-hidden className="size-4 shrink-0" />
) : null}
{/* The label alone is the live region: a role="status"
wrapper around the ticking duration would make
screen readers announce every second. */}
<span role="status">{topStatus.label}</span>
{status === "working" ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
</span>
) : null}
</span>
)
) : (
threadTimeLabel(thread)
)}
@@ -1002,8 +1062,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// would keep the controls pinned over the status label
// once the pointer moves away (e.g. after a failed
// settle) instead of cross-fading back.
"absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/v2-row:static group-hover/v2-row:opacity-100",
snoozeMenuOpen && "static opacity-100",
"pointer-events-none absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:static group-hover/v2-row:opacity-100",
snoozeMenuOpen && "pointer-events-auto static opacity-100",
)}
>
{showSnoozeButton ? (
@@ -1011,6 +1071,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
open={snoozeMenuOpen}
onOpenChange={setSnoozeMenuOpen}
onSnooze={handleSnoozePreset}
timestampFormat={props.timestampFormat}
/>
) : null}
{props.settlementSupported ? (
@@ -1198,6 +1259,7 @@ export default function SidebarV2() {
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const {
settleThread,
@@ -1271,6 +1333,13 @@ export default function SidebarV2() {
const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread);
const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo);
const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
const markThreadVisited = useUiStateStore((s) => s.markThreadVisited);
const acknowledgeWoke = useCallback(
(threadRef: ScopedThreadRef, visitedAt: string) => {
markThreadVisited(scopedThreadKey(threadRef), visitedAt);
},
[markThreadVisited],
);
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
@@ -2113,6 +2182,40 @@ export default function SidebarV2() {
);
// One snooze per thread at a time — same double-dispatch guard as settle.
const snoozingThreadKeysRef = useRef(new Set<string>());
const performSnooze = useCallback(
async (
threadRef: ScopedThreadRef,
preset: SnoozePreset,
opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
) => {
const threadKey = scopedThreadKey(threadRef);
if (snoozingThreadKeysRef.current.has(threadKey)) {
return { status: "skipped" } as const;
}
snoozingThreadKeysRef.current.add(threadKey);
try {
// Snoozing the open thread moves you forward, same as settle —
// both park the thread you're done with for now.
const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);
const result = await snoozeThread(threadRef, preset.snoozedUntil);
if (result._tag === "Failure") {
// Never navigate away from a thread that did not snooze.
return isAtomCommandInterrupted(result)
? ({ status: "interrupted" } as const)
: ({ status: "failure", error: squashAtomCommandFailure(result) } as const);
}
// Only move forward if the user is still on the snoozed thread —
// a navigation made during the await wins over ours.
if (routeThreadKeyRef.current === threadKey) {
navigateAfterSnooze?.();
}
return { status: "success" } as const;
} finally {
snoozingThreadKeysRef.current.delete(threadKey);
}
},
[planForwardNavigation, snoozeThread],
);
const attemptSnooze = useCallback(
(
threadRef: ScopedThreadRef,
@@ -2120,52 +2223,35 @@ export default function SidebarV2() {
opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
) => {
void (async () => {
const threadKey = scopedThreadKey(threadRef);
if (snoozingThreadKeysRef.current.has(threadKey)) return;
snoozingThreadKeysRef.current.add(threadKey);
try {
// Snoozing the open thread moves you forward, same as settle —
// both park the thread you're done with for now.
const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);
const result = await snoozeThread(threadRef, preset.snoozedUntil);
if (result._tag === "Failure") {
// Never navigate away from a thread that did not snooze.
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to snooze thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
// Snooze hides the row, so the toast is the only confirmation —
// and the Undo is the escape hatch for a mis-click.
const outcome = await performSnooze(threadRef, preset, opts);
if (outcome.status === "failure") {
toastManager.add(
stackedThreadToast({
type: "success",
title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date())}`,
timeout: 5_000,
actionProps: {
children: "Undo",
onClick: () => attemptUnsnooze(threadRef),
},
type: "error",
title: "Failed to snooze thread",
description:
outcome.error instanceof Error ? outcome.error.message : "An error occurred.",
}),
);
// Only move forward if the user is still on the snoozed thread —
// a navigation made during the await wins over ours.
if (routeThreadKeyRef.current === threadKey) {
navigateAfterSnooze?.();
}
} finally {
snoozingThreadKeysRef.current.delete(threadKey);
return;
}
if (outcome.status !== "success") return;
// Snooze hides the row, so the toast is the only confirmation —
// and the Undo is the escape hatch for a mis-click.
toastManager.add(
stackedThreadToast({
type: "success",
title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,
timeout: 5_000,
actionProps: {
children: "Undo",
onClick: () => attemptUnsnooze(threadRef),
},
}),
);
})();
},
[attemptUnsnooze, planForwardNavigation, snoozeThread],
[attemptUnsnooze, performSnooze, timestampFormat],
);
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
@@ -2206,7 +2292,7 @@ export default function SidebarV2() {
supportedCount: titleRegenerationThreads.length,
actionableCount: regeneratableTitleThreads.length,
});
const snoozePresets = resolveSnoozePresets(new Date());
const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat);
const clicked = await settlePromise(() =>
api.contextMenu.show(
[
@@ -2239,12 +2325,55 @@ export default function SidebarV2() {
// Post-snooze navigation must skip threads snoozing in this same
// batch — they are all leaving the card block together.
const coSnoozingKeys = new Set(threadKeys);
for (const thread of selectedThreads) {
attemptSnooze(scopeThreadRef(thread.environmentId, thread.id), preset, {
coSnoozingKeys,
});
}
clearSelection();
const outcomes = await Promise.all(
selectedThreads.map(async (thread) => {
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const outcome = await performSnooze(threadRef, preset, { coSnoozingKeys });
return { outcome, threadRef };
}),
);
const snoozedThreadRefs = outcomes.flatMap(({ outcome, threadRef }) =>
outcome.status === "success" ? [threadRef] : [],
);
const failures = outcomes.flatMap(({ outcome }) =>
outcome.status === "failure" ? [outcome.error] : [],
);
if (snoozedThreadRefs.length > 0) {
const snoozedCount = snoozedThreadRefs.length;
const failedCount = failures.length;
toastManager.add(
stackedThreadToast({
type: failedCount > 0 ? "warning" : "success",
title:
failedCount > 0
? `Snoozed ${snoozedCount} of ${selectedThreads.length} threads`
: `Snoozed ${snoozedCount} thread${snoozedCount === 1 ? "" : "s"}`,
description:
failedCount > 0
? `${failedCount} thread${failedCount === 1 ? "" : "s"} couldn't be snoozed.`
: undefined,
timeout: 5_000,
actionProps: {
children: "Undo",
onClick: () => {
for (const threadRef of snoozedThreadRefs) attemptUnsnooze(threadRef);
},
},
}),
);
} else if (failures.length > 0) {
const firstError = failures[0];
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to snooze threads",
description:
firstError instanceof Error ? firstError.message : "An error occurred.",
}),
);
}
}
return;
}
@@ -2340,9 +2469,12 @@ export default function SidebarV2() {
confirmThreadDelete,
deleteThread,
markThreadUnread,
performSnooze,
removeFromSelection,
serverConfigs,
attemptUnsnooze,
updateThreadMetadata,
timestampFormat,
],
);
@@ -2382,7 +2514,7 @@ export default function SidebarV2() {
const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);
const isPinned = thread.pinnedAt != null;
// Presets resolve at menu-open time (same as the popover).
const snoozePresets = resolveSnoozePresets(new Date());
const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat);
const clicked = await settlePromise(() =>
api.contextMenu.show(
[
@@ -2581,6 +2713,7 @@ export default function SidebarV2() {
serverConfigs,
startThreadRename,
updateThreadMetadata,
timestampFormat,
],
);
@@ -2989,6 +3122,7 @@ export default function SidebarV2() {
) ?? null
}
providerEntryByInstanceId={providerEntryByInstanceId}
timestampFormat={timestampFormat}
onThreadClick={handleThreadClick}
onThreadActivate={navigateToThread}
onStartRename={startThreadRename}
@@ -3002,6 +3136,7 @@ export default function SidebarV2() {
onUnsettle={attemptUnsettle}
onSnooze={attemptSnooze}
onUnsnooze={attemptUnsnooze}
onAcknowledgeWoke={acknowledgeWoke}
onChangeRequestState={handleChangeRequestState}
/>
);
@@ -245,7 +245,7 @@ const runtimeModeConfig: Record<
},
auto: {
label: "Auto",
description: "An AI reviewer approves routine actions; risky ones still ask.",
description: "Supported providers approve routine actions; others still ask.",
icon: SparklesIcon,
},
"full-access": {
@@ -352,9 +352,16 @@ function deriveTurnFolds(input: {
}
const hiddenEntryIds = new Set<string>();
for (const entry of group.entries) {
if (entry.id !== group.terminalEntry?.id) {
hiddenEntryIds.add(entry.id);
if (entry.id === group.terminalEntry?.id) {
continue;
}
// Agent-spawn CTA rows never fold: workflows outlive their launching
// turn (dynamic spawns, background execution), and folding the CTA
// when the turn settles makes a still-running fleet invisible.
if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {
continue;
}
hiddenEntryIds.add(entry.id);
}
if (hiddenEntryIds.size === 0) {
continue;
@@ -489,9 +496,21 @@ export function deriveMessagesTimelineRows(input: {
} else {
const groupId = `work-group:${timelineEntry.id}`;
const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
const hiddenEntries = visibleGroupedEntries.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
const visibleEntries = visibleGroupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
const renderedEntries = expanded ? [...hiddenEntries, ...visibleEntries] : visibleEntries;
// Agent-spawn CTA rows are always visible: a running fleet must
// never hide behind a "+N tool calls" toggle. Selection is by
// membership (spawn OR recent-tail), preserving the group's
// chronological order in both collapsed and expanded states
// (review finding: concatenating two filtered lists moved a
// mid-group spawn row above earlier tool rows).
const overflowCandidates = visibleGroupedEntries.filter(
(entry) => entry.agentSpawn === undefined,
);
const hiddenEntries = overflowCandidates.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
const hiddenIds = new Set(hiddenEntries.map((entry) => entry.id));
const visibleEntries = visibleGroupedEntries.filter(
(entry) => entry.agentSpawn !== undefined || !hiddenIds.has(entry.id),
);
const renderedEntries = expanded ? visibleGroupedEntries : visibleEntries;
for (const workEntry of renderedEntries) {
nextRows.push({
@@ -502,15 +521,19 @@ export function deriveMessagesTimelineRows(input: {
});
}
nextRows.push({
kind: "work-toggle",
id: `work-toggle:${timelineEntry.id}`,
createdAt: timelineEntry.createdAt,
groupId,
hiddenCount: hiddenEntries.length,
expanded,
onlyToolEntries: visibleGroupedEntries.every((entry) => workLogEntryIsToolLike(entry)),
});
if (hiddenEntries.length > 0) {
nextRows.push({
kind: "work-toggle",
id: `work-toggle:${timelineEntry.id}`,
createdAt: timelineEntry.createdAt,
groupId,
hiddenCount: hiddenEntries.length,
expanded,
onlyToolEntries: visibleGroupedEntries.every((entry) =>
workLogEntryIsToolLike(entry),
),
});
}
}
}
index = cursor - 1;
@@ -6,6 +6,14 @@ import {
type TurnId,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import type { AgentPanelModel } from "@t3tools/client-runtime/state/subagentRuntime";
import {
emptyAgentPanelModel,
formatSubagentTokenCount,
} from "@t3tools/client-runtime/state/subagentRuntime";
const EMPTY_AGENT_PANEL_MODEL = emptyAgentPanelModel();
const NOOP_OPEN_AGENTS = () => {};
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import {
createContext,
@@ -135,6 +143,8 @@ interface TimelineRowSharedState {
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
onToggleTurnFold: (turnId: TurnId) => void;
onToggleWorkGroup: (groupId: string, anchorElement?: HTMLElement) => void;
agentPanelModel: AgentPanelModel;
onOpenAgents: () => void;
}
interface TimelineRowActivityState {
@@ -148,6 +158,33 @@ const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FADE_HEADER = <div className="h-10 sm:h-12" />;
// Header row shown when older turns exist beyond the loaded window. Plain
// button, no spinner animation; the label change is the loading indicator.
function TimelineLoadEarlierHeader({
loading,
onLoadEarlier,
fade,
}: {
loading: boolean;
onLoadEarlier: () => void;
fade: boolean;
}) {
return (
<div className={fade ? "pt-10 sm:pt-12" : "pt-3 sm:pt-4"}>
<div className="mx-auto w-full max-w-3xl pb-2">
<button
type="button"
onClick={onLoadEarlier}
disabled={loading}
className="w-full py-1.5 text-xs text-muted-foreground/60 hover:text-foreground disabled:cursor-default"
>
{loading ? "Loading earlier turns…" : "Load earlier turns"}
</button>
</div>
</div>
);
}
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
@@ -156,6 +193,8 @@ const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "d
// ---------------------------------------------------------------------------
interface MessagesTimelineProps {
agentPanelModel?: AgentPanelModel;
onOpenAgents?: () => void;
isWorking: boolean;
activeTurnInProgress: boolean;
activeTurnStartedAt: string | null;
@@ -184,6 +223,8 @@ interface MessagesTimelineProps {
onManualNavigation: () => void;
hideEmptyPlaceholder?: boolean;
topFadeEnabled?: boolean;
/** Non-null when older turns exist beyond the loaded window. */
loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
}
// ---------------------------------------------------------------------------
@@ -194,6 +235,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
activeTurnInProgress,
activeTurnStartedAt,
agentPanelModel = EMPTY_AGENT_PANEL_MODEL,
onOpenAgents = NOOP_OPEN_AGENTS,
listRef,
timelineEntries,
latestTurn,
@@ -219,6 +262,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onManualNavigation,
hideEmptyPlaceholder = false,
topFadeEnabled = false,
loadEarlier = null,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
@@ -430,6 +474,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
agentPanelModel,
onOpenAgents,
}),
[
timestampFormat,
@@ -444,6 +490,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
agentPanelModel,
onOpenAgents,
],
);
const activityState = useMemo<TimelineRowActivityState>(
@@ -515,7 +563,19 @@ export const MessagesTimeline = memo(function MessagesTimeline({
"scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5",
topFadeEnabled && "chat-timeline-scroll-fade",
)}
ListHeaderComponent={topFadeEnabled ? TIMELINE_LIST_FADE_HEADER : TIMELINE_LIST_HEADER}
ListHeaderComponent={
loadEarlier !== null ? (
<TimelineLoadEarlierHeader
loading={loadEarlier.loading}
onLoadEarlier={loadEarlier.onLoadEarlier}
fade={topFadeEnabled}
/>
) : topFadeEnabled ? (
TIMELINE_LIST_FADE_HEADER
) : (
TIMELINE_LIST_HEADER
)
}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
<TimelineMinimap
@@ -1897,8 +1957,14 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
case "mcp_tool_call":
return "wrench";
case "dynamic_tool_call":
case "collab_agent_tool_call":
return "hammer";
case "collab_agent_tool_call":
return "bot";
}
// Subagent lifecycle rows (grouped by taskId) get agent identity chrome.
if (workEntry.taskId) {
return "bot";
}
return workToneIcon(workEntry.tone).iconName;
@@ -1921,9 +1987,115 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
/**
* A1 spawn CTA: one anchored row per workflow run (or per-turn direct-spawn
* batch). Live status is derived from the shared agent panel model at render
* time — the row itself never re-renders a roster; the Agents panel is the
* only roster. Freezes to past tense when every member settles. Static dot,
* no animation.
*/
const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { workEntry: TimelineWorkEntry }) {
const { workEntry } = props;
const { agentPanelModel, onOpenAgents } = use(TimelineRowCtx);
const spawn = workEntry.agentSpawn;
if (!spawn) {
return null;
}
const memberIds = new Set(spawn.agentTaskIds);
const workflowGroup = spawn.workflowId
? agentPanelModel.workflows.find((group) => group.workflow.id === spawn.workflowId)
: undefined;
const agents = workflowGroup
? [...workflowGroup.phases.flatMap((phase) => phase.members), ...workflowGroup.unphasedMembers]
: agentPanelModel.directAgents.filter((agent) => memberIds.has(agent.id));
const agentCount = Math.max(
agents.length,
Math.max(memberIds.size - (spawn.workflowId ? 1 : 0), 0),
);
const running = agents.filter(
(agent) => agent.status === "running" || agent.status === "pending",
).length;
const waiting = agents.filter((agent) => agent.status === "waiting").length;
const failed = agents.filter((agent) => agent.status === "failed").length;
// The coordinator's own status is authoritative for workflows: dynamic
// spawns mean the member list can be momentarily all-settled while the
// run is still mid-flight (the "completed" lie from live testing). A
// workflow is live until the coordinator itself reaches a terminal state.
const coordinatorStatus = workflowGroup?.workflow.status;
const coordinatorSettled =
coordinatorStatus === "completed" ||
coordinatorStatus === "failed" ||
coordinatorStatus === "cancelled" ||
coordinatorStatus === "interrupted";
const live = workflowGroup !== undefined ? !coordinatorSettled : running + waiting > 0;
// Same rule as the panel footer: providers may aggregate member usage into
// the coordinator, so count the coordinator only when no members exist.
const totalTokens = agents.reduce(
(sum, agent) => sum + (agent.usage?.totalTokens ?? 0),
spawn.workflowId && agents.length === 0 ? (workflowGroup?.workflow.usage?.totalTokens ?? 0) : 0,
);
const livePhase = workflowGroup?.phases.find((phase) => phase.state === "running");
const workflowName =
workflowGroup?.workflow.workflowName ?? workflowGroup?.workflow.title ?? null;
// One steady in-flight presentation (monitoring-pill rule): waiting and
// stalled agents read as working; only settled states differentiate.
const working = running + waiting;
const dotClass = live ? "bg-info" : failed > 0 ? "bg-destructive" : "bg-success";
const lead = live
? `Kicked off ${agentCount} subagent${agentCount === 1 ? "" : "s"}`
: `Ran ${agentCount} subagent${agentCount === 1 ? "" : "s"}`;
const status = live
? livePhase
? `${livePhase.title} · ${livePhase.activeCount} working`
: working > 0
? `${working} working`
: "working"
: failed > 0
? `${failed} failed`
: "✓ completed";
return (
<button
type="button"
onClick={onOpenAgents}
className="-mx-1 flex w-full items-center gap-2 rounded-md border border-border/60 bg-card/50 px-2.5 py-1.5 text-left text-[13px] transition hover:bg-accent/50"
>
<span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", dotClass)} />
<WorkEntryIconSvg name="bot" className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 truncate">
<span className="font-medium">{lead}</span>
{workflowName ? <span className="text-muted-foreground"> · {workflowName}</span> : null}
</span>
<span className="ml-auto flex shrink-0 items-center gap-2 font-mono text-[.7rem] text-muted-foreground">
<span>{status}</span>
{totalTokens > 0 ? (
<span className="tabular-nums">Σ {formatSubagentTokenCount(totalTokens)}</span>
) : null}
<span className="text-info-foreground">{live ? "Open Agents ▸" : "View ▸"}</span>
</span>
</button>
);
});
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry, workspaceRoot } = props;
// Before any hooks: spawn CTA rows render their own component.
if (workEntry.agentSpawn) {
return <AgentSpawnCtaRow workEntry={workEntry} />;
}
return <PlainWorkEntryRow workEntry={workEntry} workspaceRoot={workspaceRoot} />;
});
const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry, workspaceRoot } = props;
const activity = use(TimelineRowActivityCtx);
@@ -14,6 +14,10 @@ export const CHAT_INLINE_CHIP_LABEL_CLASS_NAME = "truncate leading-tight";
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = `${CHAT_INLINE_CHIP_LABEL_CLASS_NAME} select-none`;
// The skill label is smaller than the surrounding prompt text; offset its
// glyphs without moving the pill box or changing the editor's line height.
export const COMPOSER_INLINE_SKILL_CHIP_LABEL_CLASS_NAME = `${COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME} relative top-[0.15em]`;
export const COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME =
"inline-flex max-w-full select-none items-center gap-[0.33em] rounded-[0.5em] border border-fuchsia-500/25 bg-fuchsia-500/12 px-[0.5em] py-[0.08em] font-medium text-[0.86em] leading-[1.1] text-fuchsia-700 align-middle dark:text-fuchsia-300";
@@ -4,7 +4,6 @@ import {
QrCodeIcon,
RefreshCwIcon,
TerminalIcon,
TriangleAlertIcon,
} from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
import { type ReactNode, memo, useCallback, useId, useMemo, useState } from "react";
@@ -1426,17 +1425,25 @@ function SavedBackendListRow({
) : null}
{serverUpdateState.status !== "idle" ? (
<div className="max-w-md">
<ServerUpdateProgress
fromVersion={serverUpdateState.fromVersion}
state={serverUpdateState}
/>
<ServerUpdateProgress state={serverUpdateState} />
</div>
) : versionMismatch ? (
<p className="flex items-center gap-1 text-warning text-xs">
<TriangleAlertIcon className="size-3.5 shrink-0" />
Version drift: client {versionMismatch.clientVersion}, server{" "}
{versionMismatch.serverVersion}.
</p>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="w-fit cursor-help rounded-sm text-left text-muted-foreground text-xs"
>
Server update available
</button>
}
/>
<TooltipPopup side="top">
{versionMismatch.serverVersion} <span aria-hidden="true">→</span>{" "}
{versionMismatch.clientVersion}
</TooltipPopup>
</Tooltip>
) : null}
{environment.connection.error && !resumingServerUpdate ? (
<p className="flex min-w-0 items-center gap-2 text-destructive text-xs">
@@ -1461,7 +1468,7 @@ function SavedBackendListRow({
serverLabel={`${environment.label} server`}
selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)}
targetVersion={versionMismatch.clientVersion}
label={serverUpdateState.status === "failed" ? "Retry update" : "Update server"}
label={serverUpdateState.status === "failed" ? "Retry" : "Update"}
/>
) : null}
{isWslEnvironment ? (
@@ -2998,21 +3005,25 @@ export function ConnectionsSettings() {
? "Update failed"
: primaryServerUpdateState.status === "running"
? "Updating server"
: "Version drift"
: "Server update available"
}
description={
primaryServerUpdateState.status !== "idle" ? (
<ServerUpdateProgress
fromVersion={primaryServerUpdateState.fromVersion}
state={primaryServerUpdateState}
/>
<ServerUpdateProgress state={primaryServerUpdateState} />
) : primaryVersionMismatch ? (
<span className="flex items-center gap-1 text-warning">
<TriangleAlertIcon className="size-3.5 shrink-0" />
Client {primaryVersionMismatch.clientVersion}, server{" "}
{primaryVersionMismatch.serverVersion}. Sync them if RPC calls or reconnects
fail.
</span>
<Tooltip>
<TooltipTrigger
render={
<button type="button" className="w-fit cursor-help rounded-sm text-left">
Update to match this client.
</button>
}
/>
<TooltipPopup side="top">
{primaryVersionMismatch.serverVersion} <span aria-hidden="true">→</span>{" "}
{primaryVersionMismatch.clientVersion}
</TooltipPopup>
</Tooltip>
) : null
}
control={
@@ -3024,9 +3035,7 @@ export function ConnectionsSettings() {
serverLabel={primaryEnvironment?.label ?? "this server"}
selfUpdate={resolveServerSelfUpdateCapability(primaryServerConfig)}
targetVersion={primaryVersionMismatch.clientVersion}
{...(primaryServerUpdateState.status === "failed"
? { label: "Retry update" }
: {})}
label={primaryServerUpdateState.status === "failed" ? "Retry" : "Update"}
/>
) : undefined
}
@@ -44,7 +44,7 @@ function SidebarUpdateReleaseNotesTooltip({
<div className="px-1">
<div className="text-sm leading-5 font-medium">{tooltip}</div>
</div>
<div className="pointer-events-auto max-h-[min(28rem,calc(100vh-6rem))] overflow-y-auto px-1 pt-4 pb-1">
<div className="max-h-[min(28rem,calc(100vh-6rem))] overflow-y-auto px-1 pt-4 pb-1">
{state.releaseNotes.map((releaseNote, index) => (
<div key={releaseNote.version}>
{index > 0 && <Separator className="my-3 bg-border/60" />}
@@ -203,7 +203,9 @@ export function SidebarUpdatePill() {
align="start"
className={
state?.channel === "nightly" && state.releaseNotes.length > 0
? "max-w-none text-balance"
? // pointer-events-auto overrides the positioner's pointer-events-none so the
// release notes stay open (and scrollable) when the cursor moves into them.
"pointer-events-auto max-w-none text-balance"
: undefined
}
side="top"
+6 -3
View File
@@ -51,9 +51,12 @@ const StoredShellSnapshot = Schema.Struct({
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
// v2 stores the snapshot sequence alongside the thread so a warm cache can
// resume via `afterSequence` instead of re-downloading the full thread body.
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
// v3 adds windowed (paginated) snapshots carrying `page` metadata. The bump
// exists for rollback safety: a pre-pagination client would decode a windowed
// v2 record, silently drop the unknown `page` field, and treat the partial
// thread as complete forever. Older entries fail to decode → cold cache.
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(2),
schemaVersion: Schema.Literal(3),
environmentId: EnvironmentId,
threadId: ThreadId,
snapshot: OrchestrationThreadDetailSnapshot,
@@ -561,7 +564,7 @@ export const connectionStorageLayer = Layer.effectContext(
saveThread: (environmentId, snapshot) =>
Effect.gen(function* () {
const encoded = yield* encodeStoredThreadSnapshot({
schemaVersion: 2,
schemaVersion: 3,
environmentId,
threadId: snapshot.thread.id,
snapshot,
+18 -4
View File
@@ -2,9 +2,10 @@ import {
parseScopedThreadKey,
scopeProjectRef,
scopeThreadRef,
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
import { canSettle, canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
@@ -29,6 +30,7 @@ import {
readThreadShell,
} from "../state/entities";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
import { useUiStateStore } from "../uiStateStore";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
@@ -150,6 +152,7 @@ export function useThreadActions() {
(store) => store.clearProjectDraftThreadById,
);
const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
const router = useRouter();
const handleNewThread = useNewThreadHandler();
// Keep a ref so archiveThread can call handleNewThread without appearing in
@@ -201,6 +204,10 @@ export function useThreadActions() {
if (archiveResult._tag === "Failure") {
return archiveResult;
}
const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
if (wokeAt !== null) {
markThreadVisited(scopedThreadKey(threadRef), wokeAt);
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
opts.onArchived?.();
@@ -216,7 +223,7 @@ export function useThreadActions() {
return archiveResult;
},
[archiveThreadMutation, getCurrentRouteThreadRef, resolveThreadTarget],
[archiveThreadMutation, getCurrentRouteThreadRef, markThreadVisited, resolveThreadTarget],
);
const unarchiveThread = useCallback(
@@ -459,14 +466,21 @@ export function useThreadActions() {
),
);
}
const wokeAt = resolved
? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
: null;
// Settle is a high-frequency lifecycle action and stays silent — no
// toast.
return settleThreadMutation({
const result = await settleThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
if (result._tag === "Success" && wokeAt !== null) {
markThreadVisited(scopedThreadKey(target), wokeAt);
}
return result;
},
[resolveThreadTarget, settleThreadMutation],
[markThreadVisited, resolveThreadTarget, settleThreadMutation],
);
const unsettleThread = useCallback(
+21
View File
@@ -0,0 +1,21 @@
/**
* Tracks which turn's plan sidebar the user explicitly dismissed, per thread.
*
* Kept outside React state so a dismissal survives leaving and re-entering a
* thread (ChatView resets its per-thread refs on navigation). Dismissals are
* keyed by turn, so when a new turn produces fresh plan steps the sidebar
* still auto-opens.
*/
const dismissedTurnByThreadKey = new Map<string, string>();
export function dismissPlanSidebarForTurn(threadKey: string, turnKey: string): void {
dismissedTurnByThreadKey.set(threadKey, turnKey);
}
export function clearPlanSidebarDismissal(threadKey: string): void {
dismissedTurnByThreadKey.delete(threadKey);
}
export function isPlanSidebarDismissedForTurn(threadKey: string, turnKey: string): boolean {
return dismissedTurnByThreadKey.get(threadKey) === turnKey;
}
+14 -3
View File
@@ -14,7 +14,15 @@ import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "./lib/storage";
export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
export const RIGHT_PANEL_KINDS = [
"plan",
"diff",
"files",
"file",
"preview",
"terminal",
"agents",
] as const;
export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
export type RightPanelSurface =
@@ -37,10 +45,11 @@ export type RightPanelSurface =
revealLine: number | null;
revealRequestId: number;
}
| { id: "plan"; kind: "plan" };
| { id: "plan"; kind: "plan" }
| { id: "agents"; kind: "agents" };
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
const RIGHT_PANEL_STORAGE_VERSION = 7;
const RIGHT_PANEL_STORAGE_VERSION = 8;
export interface ThreadRightPanelState {
isOpen: boolean;
@@ -92,6 +101,8 @@ const singletonSurface = (
return { id: "files", kind };
case "plan":
return { id: "plan", kind };
case "agents":
return { id: "agents", kind };
}
};
+252 -1
View File
@@ -1,4 +1,5 @@
import {
classifyTaskAgentKind,
EventId,
MessageId,
ThreadId,
@@ -35,7 +36,19 @@ function makeActivity(overrides: {
turnId?: string;
sequence?: number;
}): OrchestrationThreadActivity {
const payload = overrides.payload ?? {};
// Fixtures model post-ingestion rows: ingestion stamps agentKind on every
// task.* payload. Pass an explicit agentKind to model legacy rows.
const rawPayload = overrides.payload ?? {};
const payload =
overrides.kind?.startsWith("task.") && !("agentKind" in rawPayload)
? {
...rawPayload,
agentKind: classifyTaskAgentKind({
taskType: typeof rawPayload.taskType === "string" ? rawPayload.taskType : undefined,
agentId: typeof rawPayload.agentId === "string" ? rawPayload.agentId : undefined,
}),
}
: rawPayload;
return {
id: EventId.make(overrides.id ?? `activity-${nextActivityId++}`),
createdAt: overrides.createdAt ?? "2026-02-23T00:00:00.000Z",
@@ -117,6 +130,32 @@ describe("derivePendingApprovals", () => {
]);
});
it("derives dynamic tool requests as actionable generic approvals", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "approval-open-dynamic-tool",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "approval.requested",
summary: "Approval requested",
tone: "approval",
payload: {
requestId: "req-dynamic-tool",
requestType: "dynamic_tool_call",
detail: "Search the web",
},
}),
];
expect(derivePendingApprovals(activities)).toEqual([
{
requestId: "req-dynamic-tool",
requestKind: "command",
createdAt: "2026-02-23T00:00:01.000Z",
detail: "Search the web",
},
]);
});
it("clears stale pending approvals when provider reports unknown pending request", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
@@ -1686,3 +1725,215 @@ describe("deriveActiveWorkStartedAt", () => {
).toBe("2026-02-27T21:11:00.000Z");
});
});
describe("deriveWorkLogEntries quiet-timeline guarantee", () => {
it("N concurrent subagents produce exactly N lifecycle rows, zero attributed tool rows", () => {
const activities: OrchestrationThreadActivity[] = [];
for (let agent = 0; agent < 5; agent += 1) {
const taskId = `task-${agent}`;
// Progress ticks (several per agent) + attributed tool rows.
for (let tick = 0; tick < 4; tick += 1) {
activities.push(
makeActivity({
kind: "task.progress",
summary: `agent ${agent} tick ${tick}`,
tone: "info",
payload: { taskId, summary: `working ${tick}`, role: "explorer" },
turnId: "turn-batch",
sequence: agent * 20 + tick,
}),
);
activities.push(
makeActivity({
kind: "tool.completed",
summary: "Read",
payload: { itemType: "dynamic_tool_call", agentId: taskId },
sequence: agent * 20 + 10 + tick,
}),
);
}
activities.push(
makeActivity({
kind: "task.completed",
summary: "Task completed",
tone: "info",
payload: {
taskId,
status: "completed",
summary: `agent ${agent} done`,
role: "explorer",
},
turnId: "turn-batch",
sequence: agent * 20 + 19,
}),
);
}
const entries = deriveWorkLogEntries(activities);
// A1 CTA design: all direct spawns in one turn collapse into ONE
// call-to-action row carrying the batch's agent ids.
const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);
expect(spawnRows).toHaveLength(1);
expect(spawnRows[0]!.agentSpawn!.agentTaskIds).toHaveLength(5);
expect(spawnRows[0]!.agentSpawn!.workflowId).toBeNull();
// No agent-attributed tool rows leak into the main log.
expect(entries.some((entry) => entry.sourceActivityKind?.startsWith("tool."))).toBe(false);
});
it("a workflow run and its members collapse into one CTA row keyed to the coordinator", () => {
const entries = deriveWorkLogEntries([
makeActivity({
kind: "task.progress",
summary: "coordinator",
tone: "info",
payload: { taskId: "wf-1", taskType: "local_workflow", workflowName: "math-check" },
sequence: 1,
}),
makeActivity({
kind: "task.progress",
summary: "member",
tone: "info",
payload: { taskId: "wf-1:wf:0", status: "running", parentAgentId: "wf-1" },
sequence: 2,
}),
makeActivity({
kind: "task.completed",
summary: "member done",
tone: "info",
payload: { taskId: "wf-1:wf:1", status: "completed", parentAgentId: "wf-1" },
sequence: 3,
}),
]);
const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);
expect(spawnRows).toHaveLength(1);
expect(spawnRows[0]!.agentSpawn!.workflowId).toBe("wf-1");
expect(spawnRows[0]!.agentSpawn!.agentTaskIds).toEqual(
expect.arrayContaining(["wf-1", "wf-1:wf:0", "wf-1:wf:1"]),
);
});
it("keeps unattributed tool rows (over-hiding loses the only signal)", () => {
const entries = deriveWorkLogEntries([
makeActivity({
kind: "tool.completed",
summary: "Bash",
payload: { itemType: "command_execution", command: "ls" },
}),
]);
expect(entries).toHaveLength(1);
});
it("folds timelineBypass agent rows into one CTA (Codex children, workflow members)", () => {
// Codex children carry their parent's spawn turn (spawnTurnId stamping),
// which is what batches a fleet into one CTA.
const entries = deriveWorkLogEntries([
makeActivity({
kind: "task.progress",
summary: "child work",
tone: "info",
payload: { taskId: "child-1", timelineBypass: true },
turnId: "turn-spawn",
}),
makeActivity({
kind: "task.progress",
summary: "child work again",
tone: "info",
payload: { taskId: "child-2", timelineBypass: true },
turnId: "turn-spawn",
}),
]);
// Not suppressed outright (a Codex fleet's rows are ALL bypassed and
// still need a CTA anchor) — but never more than the batch's single row.
expect(entries).toHaveLength(1);
expect(entries[0]!.agentSpawn?.agentTaskIds).toEqual(["child-1", "child-2"]);
});
it("timelineBypass non-agent rows (background shells) stay suppressed", () => {
const entries = deriveWorkLogEntries([
makeActivity({
kind: "task.progress",
summary: "stall",
tone: "info",
payload: { taskId: "sh-1", taskType: "local_bash", timelineBypass: true },
}),
]);
expect(entries).toHaveLength(0);
});
it("drops task.updated and tool.progress from the work log (fold input only)", () => {
const entries = deriveWorkLogEntries([
makeActivity({
kind: "task.updated",
summary: "Task running",
tone: "info",
payload: { taskId: "task-1", status: "running" },
}),
makeActivity({
kind: "tool.progress",
summary: "Read",
tone: "info",
payload: { taskId: "task-1", toolName: "Read" },
}),
]);
expect(entries).toHaveLength(0);
});
});
describe("rerun workflows", () => {
it("turn-less direct spawns do not collapse into one global batch", () => {
// Rows that lost their turn id (defensive path) group per task, so two
// unrelated turn-less spawns never merge into one immortal CTA.
const entries = deriveWorkLogEntries([
makeActivity({
kind: "task.started",
summary: "Task started",
payload: { taskId: "loose-1", taskType: "local_agent", role: "a" },
sequence: 1,
}),
makeActivity({
kind: "task.started",
summary: "Task started",
payload: { taskId: "loose-2", taskType: "local_agent", role: "b" },
sequence: 2,
}),
]);
const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);
expect(spawnRows).toHaveLength(2);
expect(spawnRows.map((row) => row.agentSpawn!.agentTaskIds)).toEqual([
["loose-1"],
["loose-2"],
]);
});
it("each workflow run gets its own CTA row (distinct coordinator ids)", () => {
const entries = deriveWorkLogEntries([
makeActivity({
kind: "task.progress",
summary: "run 1",
tone: "info",
payload: { taskId: "wf-run1", taskType: "local_workflow", workflowName: "math-check" },
turnId: "turn-1",
sequence: 1,
}),
makeActivity({
kind: "task.completed",
summary: "run 1 done",
tone: "info",
payload: { taskId: "wf-run1", status: "completed", taskType: "local_workflow" },
turnId: "turn-1",
sequence: 2,
}),
makeActivity({
kind: "task.progress",
summary: "run 2",
tone: "info",
payload: { taskId: "wf-run2", taskType: "local_workflow", workflowName: "math-check" },
turnId: "turn-2",
sequence: 3,
}),
]);
const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);
expect(spawnRows.map((row) => row.agentSpawn!.workflowId)).toEqual(["wf-run1", "wf-run2"]);
expect(spawnRows.map((row) => row.turnId)).toEqual(["turn-1", "turn-2"]);
});
});
+203 -2
View File
@@ -1,5 +1,6 @@
import * as Option from "effect/Option";
import * as Arr from "effect/Array";
import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentRuntime";
import {
ApprovalRequestId,
isToolLifecycleItemType,
@@ -78,12 +79,30 @@ export interface WorkLogEntry {
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
/** Originating orchestration activity kind (e.g. `user-input.requested`) for row chrome. */
sourceActivityKind?: OrchestrationThreadActivity["kind"];
/** Grouping key for subagent lifecycle rows (one row per agent). */
taskId?: string;
/** Agent role (subagent_type) for labeled timeline rows. */
agentRole?: string;
/**
* Present on agent-spawn CTA rows: one per workflow run or per-turn batch
* of direct spawns. The row renders as a call-to-action ("Kicked off N
* subagents") whose live status is derived from the agent panel model at
* render time; clicking opens the Agents panel.
*/
agentSpawn?: {
/** Workflow coordinator taskId, or null for a direct-spawn batch. */
workflowId: string | null;
agentTaskIds: ReadonlyArray<string>;
};
}
interface DerivedWorkLogEntry extends WorkLogEntry {
activityKind: OrchestrationThreadActivity["kind"];
collapseKey?: string;
toolCallId?: string;
isWorkflowCoordinator?: boolean;
/** Shell/monitor/plan tasks: ordinary work-log rows, never spawn CTAs. */
isBackgroundTask?: boolean;
}
export interface PendingApproval {
@@ -250,6 +269,12 @@ export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
/** Tool-like row with neither clear success nor failure (empty, incomplete, in progress, etc.). */
export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
// Spawn CTA rows are never neutral-hidden: mid-run they derive from
// task.progress (tone "thinking") and the neutral filter was swallowing
// them exactly while the fleet ran — the one moment they matter most.
if (entry.agentSpawn !== undefined) {
return false;
}
if (!workLogEntryIsToolLike(entry)) {
return false;
}
@@ -624,6 +649,67 @@ export function hasActionableProposedPlan(
return proposedPlan !== null && proposedPlan.implementedAt === null;
}
/**
* Quiet-timeline guarantee: the work log carries the parent's narrative plus
* at most one row per agent. Everything an agent does internally lives in the
* Agents surface:
* - timelineBypass rows (Codex children, workflow members) never render here;
* - tool rows attributed to an owning agent (payload.agentId) are re-homed;
* - task.progress ticks collapse into one row per taskId;
* - task.updated is fold input only (status patches are not narrative).
* Unattributed rows always stay: over-hiding loses the only terminal signal.
*/
/** Agent (non-background) task.started rows seed spawn CTA batches. */
function isAgentTaskStartedActivity(activity: OrchestrationThreadActivity): boolean {
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
if (!payload || typeof payload.taskId !== "string") {
return false;
}
return !isBackgroundTaskActivity(payload);
}
function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
if (!payload) {
return false;
}
const isTaskRow =
activity.kind === "task.started" ||
activity.kind === "task.progress" ||
activity.kind === "task.updated" ||
activity.kind === "task.completed";
// Task rows classify by the server stamp: a subagent's own background
// shell (agentId + "background") is agent-internal, but a nested AGENT
// (agentId + "agent") stays visible so its rows can anchor a spawn CTA
// (review finding: hiding on agentId alone removed nested agents and
// their anchors). Bypassed agent lifecycle rows also pass — collapse
// folds every such row into its batch's single CTA row, which is how
// Codex children (whose rows are ALL bypassed) get an anchor at the
// spawn point.
if (isTaskRow) {
const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
if (ownedByAgent || payload.timelineBypass === true) {
const isAgentTaskRow =
activity.kind !== "task.updated" &&
typeof payload.taskId === "string" &&
!isBackgroundTaskActivity(payload);
return !isAgentTaskRow;
}
return false;
}
if (payload.timelineBypass === true) {
return true;
}
// Non-task rows (attributed tool activity) owned by an agent are internal.
return typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
}
export function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): WorkLogEntry[] {
@@ -631,10 +717,17 @@ export function deriveWorkLogEntries(
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
// Agent task.started rows are CTA seeds: they carry the true spawn turn,
// which is the batch key (completions of background subagents arrive
// under later synthetic turns and must not start new batches). They
// collapse into the batch's single CTA row, never render standalone.
if (activity.kind === "task.started" && !isAgentTaskStartedActivity(activity)) continue;
if (activity.kind === "task.updated") continue;
if (activity.kind === "tool.progress") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
if (isAgentInternalActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries).map((entry) => {
@@ -682,7 +775,10 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
const commandPreview = extractToolCommand(payload);
const changedFiles = extractChangedFiles(payload);
const title = extractToolTitle(payload);
const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
const isTaskActivity =
activity.kind === "task.started" ||
activity.kind === "task.progress" ||
activity.kind === "task.completed";
const taskSummary =
isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
? payload.summary
@@ -756,6 +852,22 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (toolLifecycleStatus) {
entry.toolLifecycleStatus = toolLifecycleStatus;
}
if (isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0) {
entry.taskId = payload.taskId;
}
if (isTaskActivity && typeof payload?.role === "string" && payload.role.length > 0) {
entry.agentRole = payload.role;
}
if (
isTaskActivity &&
(payload?.taskType === "local_workflow" ||
(typeof payload?.workflowName === "string" && payload.workflowName.length > 0))
) {
entry.isWorkflowCoordinator = true;
}
if (isTaskActivity && payload && isBackgroundTaskActivity(payload)) {
entry.isBackgroundTask = true;
}
const collapseKey = deriveToolLifecycleCollapseKey(entry);
if (collapseKey) {
entry.collapseKey = collapseKey;
@@ -763,11 +875,92 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
return entry;
}
/**
* Spawn-group key for a subagent lifecycle row. Workflow members and their
* coordinator share the coordinator's group; direct spawns batch per turn.
* One CTA row per group (A1 design): "Kicked off N subagents".
*/
function agentSpawnGroupKey(entry: DerivedWorkLogEntry): string {
const taskId = entry.taskId ?? "";
const workflowSlot = taskId.indexOf(":wf:");
if (workflowSlot !== -1) {
return `wf:${taskId.slice(0, workflowSlot)}`;
}
if (entry.agentSpawn?.workflowId) {
return `wf:${entry.agentSpawn.workflowId}`;
}
if (entry.isWorkflowCoordinator) {
return `wf:${taskId}`;
}
// No turn id means no batch signal at all: fall back to one group per
// task. Unrelated turn-less spawns (separate fleets whose rows lost their
// turn) must not collapse into one immortal "direct:no-turn" CTA
// accumulating every agent the thread ever ran (review finding). Adapters
// stamp spawn turns (Codex spawnTurnId; Claude rows ride real turns), so
// this path is defensive.
return entry.turnId ? `direct:${entry.turnId}` : `direct:task:${taskId}`;
}
function collapseDerivedWorkLogEntries(
entries: ReadonlyArray<DerivedWorkLogEntry>,
): DerivedWorkLogEntry[] {
const collapsed: DerivedWorkLogEntry[] = [];
// Subagent rows collapse by spawn group, not adjacency: a workflow run (or
// a turn's batch of direct spawns) is ONE narrative event in the chat — a
// CTA row that opens the Agents panel — no matter how many agents it
// contains or how their progress rows interleave (quiet-timeline
// guarantee).
const spawnRowIndex = new Map<string, number>();
// Batch membership is decided once, at the FIRST row seen for a taskId.
// Claude background subagents settle between turns, so their completion
// rows carry fresh synthetic turn ids (or none) — keying each row by its
// own turn splintered one batch into a stream of "Kicked off N subagents"
// rows (live-test finding, thread 7ac7ef05).
const groupKeyByTaskId = new Map<string, string>();
for (const entry of entries) {
const isTaskRow =
entry.taskId !== undefined &&
!entry.isBackgroundTask &&
(entry.activityKind === "task.started" ||
entry.activityKind === "task.progress" ||
entry.activityKind === "task.completed");
if (isTaskRow && entry.taskId !== undefined) {
const rememberedKey = groupKeyByTaskId.get(entry.taskId);
const groupKey = rememberedKey ?? agentSpawnGroupKey(entry);
if (rememberedKey === undefined) {
groupKeyByTaskId.set(entry.taskId, groupKey);
}
const workflowId = groupKey.startsWith("wf:") ? groupKey.slice(3) : null;
const existingIndex = spawnRowIndex.get(groupKey);
if (existingIndex !== undefined) {
const existing = collapsed[existingIndex]!;
const agentTaskIds = existing.agentSpawn?.agentTaskIds.includes(entry.taskId)
? existing.agentSpawn.agentTaskIds
: [...(existing.agentSpawn?.agentTaskIds ?? []), entry.taskId];
collapsed[existingIndex] = {
...mergeDerivedWorkLogEntries(existing, entry),
// The CTA row keeps the group's ANCHOR identity, not the last
// agent's: id/createdAt/turnId stay pinned to the spawn point so
// the row renders where the run launched instead of drifting to
// the newest progress tick (mid-run it drifted below the whole
// conversation, reading as "no visualization"), and the stable id
// keeps React state/virtualization sane.
id: existing.id,
createdAt: existing.createdAt,
turnId: existing.turnId ?? null,
...(existing.taskId !== undefined ? { taskId: existing.taskId } : {}),
label: existing.label,
agentSpawn: { workflowId, agentTaskIds },
};
continue;
}
spawnRowIndex.set(groupKey, collapsed.length);
collapsed.push({
...entry,
agentSpawn: { workflowId, agentTaskIds: [entry.taskId] },
});
continue;
}
const previous = collapsed.at(-1);
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
@@ -847,6 +1040,14 @@ function mergeChangedFiles(
}
function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
// Subagent lifecycle rows collapse by agent identity: one row per agent,
// progress ticks fold into it, the terminal row wins the label.
if (
entry.taskId &&
(entry.activityKind === "task.progress" || entry.activityKind === "task.completed")
) {
return `task${entry.taskId}`;
}
if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
return undefined;
}
+4 -4
View File
@@ -35,10 +35,10 @@ An older background-service launcher may ask you to run the exact
`npx t3@<version> service update` command on the server machine. That one local update installs the
rollback support needed for later remote updates, including versions that change the database.
After selecting **Update server**, the warning becomes a three-step progress rail:
**Download**, **Install**, and **Resume**. The same progress appears in the conversation and in
Connections, so navigating between them does not lose the update. A failed step remains visible
with its error and an option to retry.
After selecting **Update**, the notice becomes a live status line: **Downloading…** while the new
version is fetched and verified, then **Restarting…** while the server restarts into it. The same
status appears in the conversation and in Connections, so navigating between them does not lose the
update. A failure remains visible with its error and an option to retry.
**Copy update command** gives you `npx t3@<client-version>`, which relaunches the server directly
at the matching version. Add whatever startup options you normally use.
+4
View File
@@ -123,6 +123,10 @@
"types": "./src/state/threads.ts",
"default": "./src/state/threads.ts"
},
"./state/subagentRuntime": {
"types": "./src/state/subagentRuntime.ts",
"default": "./src/state/subagentRuntime.ts"
},
"./state/thread-sort": {
"types": "./src/state/threadSort.ts",
"default": "./src/state/threadSort.ts"
@@ -333,6 +333,7 @@ describe("environment entity projections", () => {
data: Option.some(detail),
status: "live",
error: Option.none(),
page: Option.none(),
}),
);
@@ -361,6 +362,7 @@ describe("environment entity projections", () => {
}),
status: "live",
error: Option.none(),
page: Option.none(),
}),
);
@@ -12,6 +12,13 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
label: "environment-data:orchestration:turn-diff",
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
}),
workflowScript: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:workflow-script",
tag: ORCHESTRATION_WS_METHODS.getWorkflowScript,
// Scripts are immutable per run: cache generously.
staleTimeMs: 300_000,
idleTtlMs: 300_000,
}),
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:full-thread-diff",
tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,
@@ -7,12 +7,16 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import { RpcClientError } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
@@ -30,6 +34,7 @@ import {
makeEnvironmentServerConfigState,
isLegacyUpdateHandoffLoss,
matchesServerUpdateReadyEvent,
nudgeReconnectDuringUpdateRestart,
projectServerWelcome,
resolveServerConfigValue,
resolveServerUpdateProgressResult,
@@ -71,6 +76,56 @@ function session(client: WsRpcProtocolClient): RpcSession {
};
}
describe("update restart reconnect nudges", () => {
it.effect("retries once per backoff entry instead of only the first", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const states = [
{ phase: "backoff" },
{ phase: "connecting" },
{ phase: "backoff" },
{ phase: "backoff" },
];
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable(states),
retryNow: Ref.update(retries, (count) => count + 1),
interval: Duration.zero,
});
// Three backoff entries, three nudges. The old one-shot behavior fired
// once and then let the supervisor's ladder stretch to 16-second gaps.
expect(yield* Ref.get(retries)).toBe(3);
}),
);
it.effect("paces nudges so a fast-failing connection cannot spin", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const fiber = yield* Effect.forkChild(
nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable([{ phase: "backoff" }, { phase: "backoff" }]),
retryNow: Ref.update(retries, (count) => count + 1),
}),
{ startImmediately: true },
);
// Each nudge waits out the interval first, so nothing fires immediately.
yield* TestClock.adjust(Duration.millis(999));
expect(yield* Ref.get(retries)).toBe(0);
yield* TestClock.adjust(Duration.millis(1));
expect(yield* Ref.get(retries)).toBe(1);
yield* TestClock.adjust(Duration.seconds(1));
expect(yield* Ref.get(retries)).toBe(2);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer())),
);
});
describe("server state projection", () => {
it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
+36 -12
View File
@@ -149,6 +149,35 @@ export function validateServerUpdateReadyEvent(
);
}
/**
* Keeps reconnect attempts ~1s apart for the whole update restart.
*
* A restart takes the server down for ~15 seconds, but the supervisor's normal
* backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
* at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
* 33-second "Resuming". Nudging on every backoff entry (not just the first)
* holds the retry cadence flat until the server answers again. The sleep before
* each nudge is the pacer: a connection that fails instantly re-enters backoff
* immediately and would otherwise spin a tight retry loop.
*
* Callers fork this as a child of the update command so it is interrupted as
* soon as the update settles, whether it succeeds, fails, or times out.
*/
export function nudgeReconnectDuringUpdateRestart(input: {
readonly stateChanges: Stream.Stream<{ readonly phase: string }, unknown>;
readonly retryNow: Effect.Effect<void>;
readonly interval?: Duration.Duration;
}): Effect.Effect<void> {
return input.stateChanges.pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.runForEach(() =>
Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
),
Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
Effect.ignore,
);
}
export function serverUpdateStateForProgressEvent(
fromVersion: string,
targetVersion: string,
@@ -589,18 +618,13 @@ export function createServerEnvironmentAtoms<R, E>(
}),
);
// The update restart is intentional. As soon as the supervisor sees
// that first failed connection, discard any prior backoff debt and
// retry immediately instead of carrying an old 16-second delay.
yield* environmentRegistry.stateChanges(target.environmentId).pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.take(1),
Stream.runDrain,
Effect.andThen(environmentRegistry.retryNow(target.environmentId)),
Effect.timeoutOption(Duration.seconds(30)),
Effect.ignore,
Effect.forkChild,
);
// The update restart is intentional and the server stays unreachable
// for the whole restart, so hold the retry cadence flat instead of
// letting the supervisor climb its backoff ladder.
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: environmentRegistry.stateChanges(target.environmentId),
retryNow: environmentRegistry.retryNow(target.environmentId),
}).pipe(Effect.forkChild);
const resumed = yield* environmentRegistry
.followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
@@ -0,0 +1,772 @@
import { describe, expect, it } from "vite-plus/test";
import { classifyTaskAgentKind, type OrchestrationThreadActivity } from "@t3tools/contracts";
import {
deriveAgentPanelModel,
foldSubagentActivities,
formatSubagentModelLabel,
formatSubagentTokenCount,
isAgentAttributedToolActivity,
isSubagentActivityKind,
isTimelineBypassActivity,
workflowCardMembers,
} from "./subagentRuntime.ts";
let sequence = 0;
/**
* Fixtures model POST-INGESTION rows: ingestion stamps agentKind on every
* task.* payload, so the helper stamps too (same classifier). Pass an
* explicit agentKind (or agentKind: undefined via legacy()) to override.
*/
function activity(
kind: string,
payload: Record<string, unknown>,
at = `2026-08-01T10:00:${String(sequence).padStart(2, "0")}.000Z`,
): OrchestrationThreadActivity {
sequence += 1;
const stamped =
kind.startsWith("task.") && !("agentKind" in payload)
? {
...payload,
agentKind: classifyTaskAgentKind({
taskType: typeof payload.taskType === "string" ? payload.taskType : undefined,
agentId: typeof payload.agentId === "string" ? payload.agentId : undefined,
}),
}
: payload;
return {
id: `activity-${sequence}`,
tone: "info",
kind,
summary: kind,
payload: stamped,
turnId: null,
createdAt: at,
} as unknown as OrchestrationThreadActivity;
}
/** A pre-stamp row (legacy thread / old server): no agentKind at all. */
function legacyActivity(
kind: string,
payload: Record<string, unknown>,
): OrchestrationThreadActivity {
sequence += 1;
return {
id: `activity-${sequence}`,
tone: "info",
kind,
summary: kind,
payload,
turnId: null,
createdAt: `2026-08-01T10:00:${String(sequence).padStart(2, "0")}.000Z`,
} as unknown as OrchestrationThreadActivity;
}
function fold(rows: ReadonlyArray<OrchestrationThreadActivity>) {
return foldSubagentActivities(rows);
}
describe("foldSubagentActivities", () => {
it("builds an agent from start → progress → completion", () => {
const agents = fold([
activity("task.started", {
taskId: "task-1",
title: "Audit auth flow",
role: "explorer",
}),
activity("task.progress", {
taskId: "task-1",
lastToolName: "Read",
typedUsage: { totalTokens: 1200, toolUses: 3 },
}),
activity("task.completed", {
taskId: "task-1",
status: "completed",
summary: "Found 2 issues",
typedUsage: { totalTokens: 5000, toolUses: 9 },
}),
]);
expect(agents).toHaveLength(1);
const agent = agents[0]!;
expect(agent.title).toBe("Audit auth flow");
expect(agent.role).toBe("explorer");
expect(agent.status).toBe("completed");
expect(agent.result).toBe("Found 2 issues");
expect(agent.usage?.totalTokens).toBe(5000);
expect(agent.activationCount).toBe(1);
expect(agent.completedAt).not.toBeNull();
});
it("progress can create an agent when its start row aged out of retention", () => {
const agents = fold([
activity("task.progress", {
taskId: "task-orphan",
title: "Recovered agent",
role: "verifier",
typedUsage: { totalTokens: 100 },
}),
]);
expect(agents).toHaveLength(1);
expect(agents[0]!.title).toBe("Recovered agent");
expect(agents[0]!.status).toBe("running");
});
it("completion before start stays terminal; a late start only fills metadata", () => {
const agents = fold([
activity("task.completed", {
taskId: "task-2",
status: "failed",
summary: "boom",
role: "fixer",
}),
activity("task.started", { taskId: "task-2", title: "Late metadata", role: "fixer" }),
]);
expect(agents).toHaveLength(1);
const agent = agents[0]!;
expect(agent.title).toBe("Late metadata");
expect(agent.role).toBe("fixer");
// The late start must NOT reopen the terminal activation as a new run.
expect(agent.status).toBe("failed");
expect(agent.error).toBe("boom");
});
it("duplicate terminal events are idempotent (timestamps do not slide)", () => {
const agents = fold([
activity("task.started", { taskId: "task-3", taskType: "local_agent" }),
activity(
"task.completed",
{ taskId: "task-3", status: "completed" },
"2026-08-01T11:00:00.000Z",
),
activity(
"task.completed",
{ taskId: "task-3", status: "completed" },
"2026-08-01T12:00:00.000Z",
),
]);
expect(agents[0]!.completedAt).toBe("2026-08-01T11:00:00.000Z");
});
it("reactivation increments the run count and clears result/error", () => {
const agents = fold([
activity("task.started", { taskId: "task-4", taskType: "local_agent" }),
activity("task.completed", { taskId: "task-4", status: "completed", summary: "run 1 done" }),
activity("task.updated", { taskId: "task-4", status: "running" }),
]);
const agent = agents[0]!;
expect(agent.activationCount).toBe(2);
expect(agent.result).toBeNull();
expect(agent.completedAt).toBeNull();
expect(agent.status).toBe("running");
});
it("idle is nonterminal: an idle agent resumes without losing identity", () => {
const agents = fold([
activity("task.started", { taskId: "codex-child-1", title: "Marlow", role: "explorer" }),
activity("task.updated", { taskId: "codex-child-1", status: "idle" }),
activity("task.updated", { taskId: "codex-child-1", status: "running" }),
]);
expect(agents).toHaveLength(1);
expect(agents[0]!.activationCount).toBe(2);
expect(agents[0]!.status).toBe("running");
});
it("cumulative usage max-merges: duplicate and late frames never shrink or double-count", () => {
const agents = fold([
activity("task.started", { taskId: "task-5", taskType: "local_agent" }),
activity("task.progress", {
taskId: "task-5",
typedUsage: { totalTokens: 900, inputTokens: 700 },
}),
activity("task.progress", {
taskId: "task-5",
typedUsage: { totalTokens: 900, inputTokens: 700 },
}),
activity("task.progress", { taskId: "task-5", typedUsage: { totalTokens: 500 } }),
]);
expect(agents[0]!.usage).toEqual({ totalTokens: 900, inputTokens: 700 });
});
it("partial terminal usage preserves known breakdown fields", () => {
const agents = fold([
activity("task.started", { taskId: "task-6", taskType: "local_agent" }),
activity("task.progress", {
taskId: "task-6",
typedUsage: { totalTokens: 800, inputTokens: 600, outputTokens: 150 },
}),
activity("task.completed", {
taskId: "task-6",
status: "completed",
typedUsage: { totalTokens: 1000 },
}),
]);
expect(agents[0]!.usage).toEqual({ totalTokens: 1000, inputTokens: 600, outputTokens: 150 });
});
it("skips malformed rows individually without failing the fold", () => {
const agents = fold([
activity("task.started", { taskId: "task-7", title: "Good", taskType: "local_agent" }),
activity("task.progress", { bogus: true }),
activity("task.progress", { taskId: 42 }),
]);
expect(agents).toHaveLength(1);
expect(agents[0]!.title).toBe("Good");
});
it("bounds repeated strings at 180 chars and the activity ring at 6 deduped entries", () => {
const long = "x".repeat(500);
const rows = [activity("task.started", { taskId: "task-8", taskType: "local_agent" })];
for (let i = 0; i < 10; i += 1) {
rows.push(activity("task.progress", { taskId: "task-8", summary: `${long}-${i}` }));
}
rows.push(activity("task.progress", { taskId: "task-8", summary: `${long}-9` }));
const agents = fold(rows);
const agent = agents[0]!;
expect(agent.recentActivity.length).toBeLessThanOrEqual(6);
for (const entry of agent.recentActivity) {
expect(entry.summary.length).toBeLessThanOrEqual(180);
}
// Consecutive identical summaries dedupe (truncation makes them equal).
const summaries = agent.recentActivity.map((entry) => entry.summary);
expect(new Set(summaries).size).toBe(summaries.length);
});
it("plan tasks are not agents", () => {
const agents = fold([activity("task.started", { taskId: "plan-1", taskType: "plan" })]);
expect(agents).toHaveLength(0);
});
it("workflow members key by stable slot and attach to their coordinator", () => {
const agents = fold([
activity("task.started", {
taskId: "wf-1",
taskType: "local_workflow",
title: "audit-auth-flow",
workflowName: "audit-auth-flow",
}),
activity("task.progress", {
taskId: "wf-1",
phases: [
{ index: 0, title: "Audit" },
{ index: 1, title: "Verify" },
],
}),
activity("task.progress", {
taskId: "wf-1:wf:0",
title: "audit:entrypoints",
status: "running",
parentAgentId: "wf-1",
agentIndex: 0,
phaseIndex: 0,
phaseTitle: "Audit",
timelineBypass: true,
}),
]);
const workflow = agents.find((agent) => agent.id === "wf-1");
const member = agents.find((agent) => agent.id === "wf-1:wf:0");
expect(workflow?.kind).toBe("workflow");
expect(workflow?.phases).toEqual([
{ index: 0, title: "Audit" },
{ index: 1, title: "Verify" },
]);
expect(member?.kind).toBe("workflow_agent");
expect(member?.parentAgentId).toBe("wf-1");
});
it("a workflow member retry (attempt bump) is a reactivation of the same slot", () => {
const agents = fold([
activity("task.progress", {
taskId: "wf-2:wf:1",
title: "verify:refresh",
status: "failed",
error: "attempt 1 died",
parentAgentId: "wf-2",
attempt: 1,
}),
activity("task.progress", {
taskId: "wf-2:wf:1",
title: "verify:refresh",
status: "running",
parentAgentId: "wf-2",
attempt: 2,
}),
]);
expect(agents).toHaveLength(1);
const member = agents[0]!;
expect(member.activationCount).toBeGreaterThanOrEqual(2);
expect(member.error).toBeNull();
expect(member.status).toBe("running");
});
it("drops non-http(s) session urls at the fold boundary", () => {
const agents = fold([
activity("task.started", {
taskId: "wf-3",
taskType: "local_workflow",
runHandles: { sessionUrl: "javascript:alert(1)", runId: "run-1" },
}),
]);
expect(agents[0]!.runHandles?.sessionUrl).toBeUndefined();
expect(agents[0]!.runHandles?.runId).toBe("run-1");
});
});
describe("deriveAgentPanelModel", () => {
const roster = fold([
activity("task.started", { taskId: "wf-1", taskType: "local_workflow", title: "audit" }),
activity("task.progress", {
taskId: "wf-1",
phases: [
{ index: 0, title: "Audit" },
{ index: 1, title: "Verify" },
],
}),
activity("task.progress", {
taskId: "wf-1:wf:0",
title: "audit:a",
status: "completed",
parentAgentId: "wf-1",
agentIndex: 0,
phaseIndex: 0,
}),
activity("task.completed", { taskId: "wf-1:wf:0", status: "completed", parentAgentId: "wf-1" }),
activity("task.progress", {
taskId: "wf-1:wf:1",
title: "verify:b",
status: "running",
parentAgentId: "wf-1",
agentIndex: 1,
phaseIndex: 1,
typedUsage: { totalTokens: 4000 },
}),
activity("task.started", { taskId: "direct-1", title: "Marlow", role: "explorer" }),
activity("task.updated", { taskId: "direct-1", status: "idle" }),
]);
it("groups workflow members by phase and separates direct spawns", () => {
const model = deriveAgentPanelModel({ agents: roster });
expect(model.workflows).toHaveLength(1);
const group = model.workflows[0]!;
expect(group.phases).toHaveLength(2);
expect(group.phases[0]!.state).toBe("done");
expect(group.phases[1]!.state).toBe("running");
expect(model.directAgents.map((agent) => agent.id)).toEqual(["direct-1"]);
});
it("counts idle deliberately and waiting as active", () => {
const model = deriveAgentPanelModel({ agents: roster });
expect(model.idleCount).toBe(1);
// wf-1 coordinator + member 1 running.
expect(model.runningCount).toBeGreaterThanOrEqual(1);
expect(model.idleCount + model.runningCount + model.waitingCount + model.settledCount).toBe(
roster.length,
);
});
it("a phase with only pending members never reads as running", () => {
const pendingRoster = fold([
activity("task.started", { taskId: "wf-9", taskType: "local_workflow" }),
activity("task.progress", {
taskId: "wf-9",
phases: [{ index: 0, title: "Fix" }],
}),
activity("task.progress", {
taskId: "wf-9:wf:0",
title: "fixer",
status: "pending",
parentAgentId: "wf-9",
agentIndex: 0,
phaseIndex: 0,
}),
]);
const model = deriveAgentPanelModel({ agents: pendingRoster });
// "pending" counts as active liveness (queued work), so the phase reads
// running only if a member is genuinely pending/running — this asserts
// the settled-count rule: no member settled, phase not done.
expect(model.workflows[0]!.phases[0]!.state).not.toBe("done");
});
it("v2 projection wins outright and sources are never merged", () => {
const v2Agent = { ...roster[0]!, id: "v2-only", title: "From v2" };
const model = deriveAgentPanelModel({ agents: roster, v2Projection: [v2Agent] });
const allIds = [
...model.workflows.map((group) => group.workflow.id),
...model.directAgents.map((agent) => agent.id),
];
expect(allIds).toContain("v2-only");
expect(allIds).not.toContain("direct-1");
});
it("orphaned members fall back to the direct list", () => {
const orphans = fold([
activity("task.progress", {
taskId: "gone:wf:0",
title: "orphan",
status: "running",
parentAgentId: "gone",
}),
]);
const model = deriveAgentPanelModel({ agents: orphans });
expect(model.workflows).toHaveLength(0);
expect(model.directAgents.map((agent) => agent.id)).toEqual(["gone:wf:0"]);
});
});
describe("workflowCardMembers", () => {
it("orders by urgency (failed, running, waiting) and reports overflow", () => {
const roster = fold([
activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),
...[..."abcdefghij"].map((letter, index) =>
activity("task.progress", {
taskId: `wf-1:wf:${index}`,
title: `agent-${letter}`,
status: index === 3 ? "failed" : index < 3 ? "completed" : "running",
...(index === 3 ? { error: "died" } : {}),
parentAgentId: "wf-1",
agentIndex: index,
phaseIndex: 0,
phaseTitle: "Work",
}),
),
]);
const model = deriveAgentPanelModel({ agents: roster });
const { visible, overflow } = workflowCardMembers(model.workflows[0]!, 8);
expect(visible).toHaveLength(8);
expect(overflow).toBe(2);
expect(visible[0]!.status).toBe("failed");
expect(visible.filter((agent) => agent.status === "completed").length).toBeLessThanOrEqual(2);
});
});
describe("timeline predicates", () => {
it("recognizes subagent activity kinds as fold input", () => {
for (const kind of [
"task.started",
"task.progress",
"task.updated",
"task.completed",
"tool.progress",
]) {
expect(isSubagentActivityKind(kind)).toBe(true);
}
expect(isSubagentActivityKind("tool.completed")).toBe(false);
});
it("attributed tool rows are re-homed; unattributed rows stay in the timeline", () => {
expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: "task-1" }))).toBe(
true,
);
expect(isAgentAttributedToolActivity(activity("tool.completed", {}))).toBe(false);
expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: " " }))).toBe(
false,
);
});
it("timelineBypass rows never render in the parent chat", () => {
expect(isTimelineBypassActivity(activity("task.progress", { timelineBypass: true }))).toBe(
true,
);
expect(isTimelineBypassActivity(activity("task.progress", {}))).toBe(false);
});
});
describe("formatSubagentTokenCount", () => {
it("formats plain counters", () => {
expect(formatSubagentTokenCount(950)).toBe("950");
expect(formatSubagentTokenCount(41200)).toBe("41.2k");
expect(formatSubagentTokenCount(247000)).toBe("247k");
expect(formatSubagentTokenCount(1_400_000)).toBe("1.4M");
});
});
describe("model and effort attribution", () => {
it("carries model/effort from start rows and refines model from later rows", () => {
const agents = fold([
activity("task.started", {
taskId: "task-m",
title: "Verify math",
model: "sonnet",
effort: "high",
}),
// Later row refines with the authoritative API model id; effort absent
// must not clear the known value.
activity("task.progress", { taskId: "task-m", model: "claude-sonnet-5[1m]" }),
]);
expect(agents).toHaveLength(1);
expect(agents[0]!.model).toBe("claude-sonnet-5[1m]");
expect(agents[0]!.effort).toBe("high");
});
it("formatSubagentModelLabel compacts ids and appends effort", () => {
expect(formatSubagentModelLabel("claude-sonnet-5[1m]", "high")).toBe("sonnet-5[1m] · high");
expect(formatSubagentModelLabel("claude-opus-4-20250514", null)).toBe("opus-4");
expect(formatSubagentModelLabel("gpt-5.6-sol", "low")).toBe("gpt-5.6-sol · low");
expect(formatSubagentModelLabel(null, "high")).toBeNull();
});
});
describe("background task exclusion", () => {
it("shells and monitors never join the roster (from any lifecycle row)", () => {
const agents = fold([
activity("task.started", { taskId: "shell-1", taskType: "shell", title: "Run 12s stall" }),
activity("task.progress", { taskId: "shell-2", taskType: "shell", title: "Run stall" }),
activity("task.completed", { taskId: "mon-1", taskType: "monitor", status: "completed" }),
activity("task.started", { taskId: "agent-1", taskType: "subagent", title: "Real agent" }),
]);
expect(agents.map((agent) => agent.id)).toEqual(["agent-1"]);
});
it("rows without a taskType stay in the roster (workflow members, Codex children)", () => {
const agents = fold([
activity("task.progress", { taskId: "wf-1:wf:0", status: "running", parentAgentId: "wf-1" }),
]);
expect(agents).toHaveLength(1);
});
it("the server stamp is the only classifier: no stamp means no roster row", () => {
const agents = fold([
// Stamped background: agent-looking fields don't matter.
activity("task.started", {
taskId: "bg-1",
agentKind: "background",
role: "watcher",
model: "sonnet",
}),
// Stamped agent: plain row still joins the roster.
activity("task.started", { taskId: "ag-1", agentKind: "agent", detail: "plain row" }),
// Legacy pre-stamp rows (old threads/servers) stay in the work log —
// exactly their pre-upgrade behavior.
legacyActivity("task.started", { taskId: "old-task", detail: "tailing logs" }),
legacyActivity("task.progress", { taskId: "old-task", summary: "still tailing" }),
]);
expect(agents.map((agent) => agent.id)).toEqual(["ag-1"]);
});
it("membership is sticky: a stampless later row still reaches a known agent", () => {
const agents = fold([
activity("task.started", { taskId: "a1", taskType: "local_agent", title: "Agent" }),
// Terminal row missing the stamp (defensive: adapters synthesize some
// rows) — sticky membership still routes it to the agent.
legacyActivity("task.completed", { taskId: "a1", status: "completed", summary: "done" }),
]);
expect(agents).toHaveLength(1);
expect(agents[0]!.status).toBe("completed");
expect(agents[0]!.result).toBe("done");
});
});
describe("session-derived interruption", () => {
it("dead session interrupts live agents but preserves idle and settled", () => {
const rows = [
activity("task.started", { taskId: "live-1", taskType: "local_agent" }),
activity("task.started", { taskId: "idle-1", taskType: "local_agent" }),
activity("task.updated", { taskId: "idle-1", status: "idle" }),
activity("task.started", { taskId: "done-1", taskType: "local_agent" }),
activity("task.completed", { taskId: "done-1", status: "completed" }),
];
const dead = foldSubagentActivities(rows, { sessionLive: false });
expect(dead.find((agent) => agent.id === "live-1")?.status).toBe("interrupted");
expect(dead.find((agent) => agent.id === "idle-1")?.status).toBe("idle");
expect(dead.find((agent) => agent.id === "done-1")?.status).toBe("completed");
const alive = foldSubagentActivities(rows, { sessionLive: true });
expect(alive.find((agent) => agent.id === "live-1")?.status).toBe("running");
});
});
describe("terminal robustness", () => {
it("task.updated creating an agent (start row aged out) counts one activation", () => {
const agents = fold([
activity("task.updated", { taskId: "orphan-u", status: "running", role: "worker" }),
]);
expect(agents).toHaveLength(1);
expect(agents[0]!.activationCount).toBe(1);
expect(agents[0]!.status).toBe("running");
});
it("a late start after a terminal task.updated does not reopen the run", () => {
const agents = fold([
activity("task.updated", { taskId: "t1", status: "failed", role: "worker" }),
activity("task.started", { taskId: "t1", taskType: "local_agent", title: "Late" }),
]);
expect(agents).toHaveLength(1);
expect(agents[0]!.status).toBe("failed");
expect(agents[0]!.title).toBe("Late");
});
it("a completion after a terminal task.updated still enriches result and usage", () => {
// Claude commonly emits terminal task.updated before task.completed;
// the completion carries the summary and final usage the update lacked.
const agents = fold([
activity("task.started", { taskId: "te-1", taskType: "local_agent" }),
activity(
"task.updated",
{ taskId: "te-1", status: "completed", endedAt: "2026-08-01T10:59:00.000Z" },
"2026-08-01T11:00:00.000Z",
),
activity(
"task.completed",
{
taskId: "te-1",
status: "completed",
summary: "final answer",
typedUsage: { totalTokens: 4200, toolUses: 7 },
},
"2026-08-01T11:00:01.000Z",
),
]);
const agent = agents[0]!;
expect(agent.status).toBe("completed");
expect(agent.result).toBe("final answer");
expect(agent.usage?.totalTokens).toBe(4200);
// Timestamps stay pinned to the transition that settled the run.
expect(agent.completedAt).toBe("2026-08-01T10:59:00.000Z");
});
it("duplicate completions keep the FIRST result, not the last", () => {
const agents = fold([
activity("task.started", { taskId: "t2", taskType: "local_agent" }),
activity("task.completed", { taskId: "t2", status: "completed", summary: "first result" }),
activity("task.completed", { taskId: "t2", status: "completed", summary: "second result" }),
]);
expect(agents[0]!.result).toBe("first result");
});
it("provider endedAt wins over ingestion time on the settling transition", () => {
const agents = fold([
activity("task.started", { taskId: "t3", taskType: "local_agent" }),
activity(
"task.updated",
{ taskId: "t3", status: "failed", endedAt: "2026-08-01T09:59:59.000Z" },
"2026-08-01T10:00:30.000Z",
),
]);
expect(agents[0]!.completedAt).toBe("2026-08-01T09:59:59.000Z");
});
it("workflow retries count each attempt once", () => {
const agents = fold([
activity("task.progress", {
taskId: "wf-r:wf:0",
parentAgentId: "wf-r",
status: "running",
attempt: 1,
}),
activity("task.progress", {
taskId: "wf-r:wf:0",
parentAgentId: "wf-r",
status: "failed",
attempt: 1,
}),
activity("task.progress", {
taskId: "wf-r:wf:0",
parentAgentId: "wf-r",
status: "running",
attempt: 2,
}),
]);
expect(agents[0]!.activationCount).toBe(2);
});
});
describe("phase membership", () => {
it("members with unknown phase indices land in unphasedMembers, never vanish", () => {
const model = deriveAgentPanelModel({
agents: fold([
activity("task.started", {
taskId: "wf-p",
taskType: "local_workflow",
phases: [{ index: 0, title: "Only phase" }],
}),
activity("task.progress", {
taskId: "wf-p:wf:0",
parentAgentId: "wf-p",
status: "running",
phaseIndex: 0,
}),
activity("task.progress", {
taskId: "wf-p:wf:9",
parentAgentId: "wf-p",
status: "running",
phaseIndex: 9,
}),
]),
});
const group = model.workflows[0]!;
const visible = [
...group.phases.flatMap((phase) => phase.members),
...group.unphasedMembers,
].map((member) => member.id);
expect(visible).toContain("wf-p:wf:0");
expect(visible).toContain("wf-p:wf:9");
});
});
describe("coordinator settle cascade", () => {
it("members without their own terminal row settle when the coordinator does", () => {
const agents = fold([
activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),
activity("task.progress", {
taskId: "wf-1:wf:0",
title: "stalled member",
status: "running",
parentAgentId: "wf-1",
}),
activity("task.completed", {
taskId: "wf-1",
status: "completed",
taskType: "local_workflow",
}),
]);
const member = agents.find((agent) => agent.id === "wf-1:wf:0");
expect(member?.status).toBe("completed");
expect(member?.completedAt).not.toBeNull();
});
it("a failed coordinator marks unfinished members interrupted, not completed", () => {
const agents = fold([
activity("task.started", { taskId: "wf-2", taskType: "local_workflow" }),
activity("task.progress", {
taskId: "wf-2:wf:0",
status: "running",
parentAgentId: "wf-2",
}),
activity("task.completed", { taskId: "wf-2", status: "failed", taskType: "local_workflow" }),
]);
const member = agents.find((agent) => agent.id === "wf-2:wf:0");
expect(member?.status).toBe("interrupted");
});
});
describe("task type classification is a denylist", () => {
it("unknown agent-flavored types (local_agent, future names) join the roster", () => {
const agents = fold([
activity("task.started", {
taskId: "a1",
taskType: "local_agent",
title: "Math test 1",
role: "claude",
}),
activity("task.started", { taskId: "a2", taskType: "some_future_agent_kind", title: "X" }),
]);
expect(agents.map((agent) => agent.id).toSorted()).toEqual(["a1", "a2"]);
});
});
describe("nested agents vs subagent shells", () => {
it("a nested agent (agentId + agent taskType) stays in the roster; its shells do not", () => {
const agents = fold([
activity("task.started", {
taskId: "nested-1",
taskType: "local_agent",
agentId: "parent-agent",
title: "Nested researcher",
}),
activity("task.started", {
taskId: "shell-1",
taskType: "local_bash",
agentId: "parent-agent",
title: "Nested sleep",
}),
]);
expect(agents.map((agent) => agent.id)).toEqual(["nested-1"]);
});
});
@@ -0,0 +1,924 @@
/**
* Native-provider subagent observability: a tolerant fold over persisted
* task.* / tool.* thread activities into orchestration-v2-shaped subagent
* state, plus the source-neutral panel model every client renders.
*
* This module is deliberately legacy-bridge code. When orchestration-v2's
* subagent projection is available for a thread, deriveAgentPanelModel
* prefers it (see the v2Projection parameter) and the fold is skipped; when
* the v1 orchestrator is retired this file is deleted. Field names and
* transition semantics copy the v2 stack (#4779) exactly so that swap is
* mechanical.
*
* Invariants encoded here trace to shipped bugs in the prior PRs (#4220,
* #3650, #4662): reusable identity vs one-shot activations, idle as a real
* nonterminal state, provider-specific usage merges, first-write terminal
* timestamps, reactivation clearing terminal detail, and order-robust
* folding (completion can create an agent; a late start only fills
* metadata).
*/
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
export type RuntimeSubagentStatus =
| "pending"
| "running"
| "waiting"
| "idle"
| "completed"
| "failed"
| "cancelled"
| "interrupted";
export interface SubagentUsage {
readonly totalTokens: number;
readonly inputTokens?: number;
readonly cachedInputTokens?: number;
readonly outputTokens?: number;
readonly reasoningOutputTokens?: number;
readonly toolUses?: number;
readonly durationMs?: number;
}
export interface SubagentActivityEntry {
readonly at: string;
readonly summary: string;
}
export interface SubagentWorkflowPhase {
readonly index: number;
readonly title: string;
}
export interface SubagentRunHandles {
readonly runId?: string;
readonly scriptPath?: string;
readonly transcriptDir?: string;
readonly sessionUrl?: string;
}
export interface RuntimeSubagent {
readonly id: string;
readonly kind: "subagent" | "workflow" | "workflow_agent";
readonly title: string;
readonly role: string | null;
readonly model: string | null;
readonly effort: string | null;
readonly status: RuntimeSubagentStatus;
readonly activationCount: number;
readonly usage: SubagentUsage | null;
readonly progress: string | null;
readonly lastToolName: string | null;
readonly result: string | null;
readonly error: string | null;
readonly outputFile: string | null;
readonly parentAgentId: string | null;
readonly agentIndex: number | null;
readonly phaseIndex: number | null;
readonly phaseTitle: string | null;
readonly attempt: number | null;
readonly workflowName: string | null;
readonly phases: ReadonlyArray<SubagentWorkflowPhase>;
readonly runHandles: SubagentRunHandles | null;
readonly recentActivity: ReadonlyArray<SubagentActivityEntry>;
readonly startedAt: string | null;
readonly completedAt: string | null;
readonly updatedAt: string;
}
const TERMINAL_STATUSES: ReadonlySet<RuntimeSubagentStatus> = new Set([
"completed",
"failed",
"cancelled",
"interrupted",
]);
export function isTerminalSubagentStatus(status: RuntimeSubagentStatus): boolean {
return TERMINAL_STATUSES.has(status);
}
/** Active = the user may still need to care while it runs. Idle is settled-ish
* but resumable; waiting counts as active because it needs the user. */
export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean {
return status === "pending" || status === "running" || status === "waiting";
}
const RECENT_ACTIVITY_LIMIT = 6;
const SUMMARY_CHAR_LIMIT = 180;
const ROSTER_LIMIT = 100;
/**
* True when this activity's payload does NOT belong on the Agents surface.
* Classification happens exactly once, server-side at ingestion
* (classifyTaskAgentKind → the persisted agentKind stamp); the client only
* reads it. Rows without a stamp — legacy threads, pre-stamp servers — are
* background by definition: they render in the ordinary work log, exactly
* as they did before this feature existed.
*/
export function isBackgroundTaskActivity(payload: Record<string, unknown>): boolean {
return payload.agentKind !== "agent";
}
function bounded(value: string): string {
return value.length <= SUMMARY_CHAR_LIMIT ? value : `${value.slice(0, SUMMARY_CHAR_LIMIT - 1)}…`;
}
/** Appends to the ring buffer, deduping consecutive identical summaries. */
function appendActivity(
entries: ReadonlyArray<SubagentActivityEntry>,
at: string,
summary: string,
): ReadonlyArray<SubagentActivityEntry> {
const boundedSummary = bounded(summary);
if (entries.length > 0 && entries[entries.length - 1]?.summary === boundedSummary) {
return entries;
}
const next = [...entries, { at, summary: boundedSummary }];
return next.length > RECENT_ACTIVITY_LIMIT ? next.slice(-RECENT_ACTIVITY_LIMIT) : next;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function asCount(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
}
function asUsage(value: unknown): SubagentUsage | undefined {
if (typeof value !== "object" || value === null) {
return undefined;
}
const record = value as Record<string, unknown>;
const totalTokens = asCount(record.totalTokens);
if (totalTokens === undefined) {
return undefined;
}
const usage: {
totalTokens: number;
inputTokens?: number;
cachedInputTokens?: number;
outputTokens?: number;
reasoningOutputTokens?: number;
toolUses?: number;
durationMs?: number;
} = { totalTokens };
const inputTokens = asCount(record.inputTokens);
if (inputTokens !== undefined) usage.inputTokens = inputTokens;
const cachedInputTokens = asCount(record.cachedInputTokens);
if (cachedInputTokens !== undefined) usage.cachedInputTokens = cachedInputTokens;
const outputTokens = asCount(record.outputTokens);
if (outputTokens !== undefined) usage.outputTokens = outputTokens;
const reasoningOutputTokens = asCount(record.reasoningOutputTokens);
if (reasoningOutputTokens !== undefined) usage.reasoningOutputTokens = reasoningOutputTokens;
const toolUses = asCount(record.toolUses);
if (toolUses !== undefined) usage.toolUses = toolUses;
const durationMs = asCount(record.durationMs);
if (durationMs !== undefined) usage.durationMs = durationMs;
return usage;
}
/**
* Provider-specific usage merge (#4779 semantics, verbatim):
* - max-merge (Codex-style cumulative frames): field-wise maximum, idempotent
* under duplicate or late frames. Cumulative totals never shrink.
* - accumulate (Claude-style activation deltas): not needed at this layer —
* Claude's task_progress usage is itself cumulative per task, so the fold
* also max-merges. The distinction matters when v2 sums activations.
* Field-wise: a terminal payload carrying only totalTokens must not wipe a
* known breakdown.
*/
function mergeUsageMax(
current: SubagentUsage | null,
incoming: SubagentUsage | undefined,
): SubagentUsage | null {
if (!incoming) {
return current;
}
if (!current) {
return incoming;
}
const pick = (a: number | undefined, b: number | undefined): number | undefined =>
a === undefined ? b : b === undefined ? a : Math.max(a, b);
const merged: {
totalTokens: number;
inputTokens?: number;
cachedInputTokens?: number;
outputTokens?: number;
reasoningOutputTokens?: number;
toolUses?: number;
durationMs?: number;
} = { totalTokens: Math.max(current.totalTokens, incoming.totalTokens) };
const inputTokens = pick(current.inputTokens, incoming.inputTokens);
if (inputTokens !== undefined) merged.inputTokens = inputTokens;
const cachedInputTokens = pick(current.cachedInputTokens, incoming.cachedInputTokens);
if (cachedInputTokens !== undefined) merged.cachedInputTokens = cachedInputTokens;
const outputTokens = pick(current.outputTokens, incoming.outputTokens);
if (outputTokens !== undefined) merged.outputTokens = outputTokens;
const reasoningOutputTokens = pick(current.reasoningOutputTokens, incoming.reasoningOutputTokens);
if (reasoningOutputTokens !== undefined) merged.reasoningOutputTokens = reasoningOutputTokens;
const toolUses = pick(current.toolUses, incoming.toolUses);
if (toolUses !== undefined) merged.toolUses = toolUses;
const durationMs = pick(current.durationMs, incoming.durationMs);
if (durationMs !== undefined) merged.durationMs = durationMs;
return merged;
}
interface MutableAgent {
id: string;
kind: RuntimeSubagent["kind"];
title: string;
role: string | null;
model: string | null;
effort: string | null;
status: RuntimeSubagentStatus;
activationCount: number;
usage: SubagentUsage | null;
progress: string | null;
lastToolName: string | null;
result: string | null;
error: string | null;
outputFile: string | null;
parentAgentId: string | null;
agentIndex: number | null;
phaseIndex: number | null;
phaseTitle: string | null;
attempt: number | null;
workflowName: string | null;
phases: ReadonlyArray<SubagentWorkflowPhase>;
runHandles: SubagentRunHandles | null;
recentActivity: ReadonlyArray<SubagentActivityEntry>;
startedAt: string | null;
completedAt: string | null;
updatedAt: string;
}
function kindFromPayload(
payload: Record<string, unknown>,
agentId: string,
): RuntimeSubagent["kind"] {
if (asString(payload.taskType) === "local_workflow") {
return "workflow";
}
if (payload.parentAgentId !== undefined || agentId.includes(":wf:")) {
return "workflow_agent";
}
return "subagent";
}
/** Completion can create an agent (its start may have aged out of retention). */
function getOrCreate(
agents: Map<string, MutableAgent>,
id: string,
payload: Record<string, unknown>,
at: string,
): MutableAgent {
const existing = agents.get(id);
if (existing) {
return existing;
}
const created: MutableAgent = {
id,
kind: kindFromPayload(payload, id),
title: asString(payload.title) ?? asString(payload.detail) ?? id,
role: asString(payload.role) ?? null,
model: asString(payload.model) ?? null,
effort: asString(payload.effort) ?? null,
status: "pending",
activationCount: 0,
usage: null,
progress: null,
lastToolName: null,
result: null,
error: null,
outputFile: null,
parentAgentId: asString(payload.parentAgentId) ?? null,
agentIndex: asCount(payload.agentIndex) ?? null,
phaseIndex: asCount(payload.phaseIndex) ?? null,
phaseTitle: asString(payload.phaseTitle) ?? null,
attempt: asCount(payload.attempt) ?? null,
workflowName: asString(payload.workflowName) ?? null,
phases: [],
runHandles: null,
recentActivity: [],
startedAt: null,
completedAt: null,
updatedAt: at,
};
agents.set(id, created);
return created;
}
/** Metadata fill from any payload: never downgrades known values to null. */
function fillMetadata(agent: MutableAgent, payload: Record<string, unknown>): void {
const title = asString(payload.title);
if (title) agent.title = title;
const role = asString(payload.role);
if (role) agent.role = role;
const model = asString(payload.model);
if (model) agent.model = model;
const effort = asString(payload.effort);
if (effort) agent.effort = effort;
const parentAgentId = asString(payload.parentAgentId);
if (parentAgentId) {
agent.parentAgentId = parentAgentId;
if (agent.kind === "subagent") agent.kind = "workflow_agent";
}
const workflowName = asString(payload.workflowName);
if (workflowName) agent.workflowName = workflowName;
if (asString(payload.taskType) === "local_workflow") agent.kind = "workflow";
const agentIndex = asCount(payload.agentIndex);
if (agentIndex !== undefined) agent.agentIndex = agentIndex;
const phaseIndex = asCount(payload.phaseIndex);
if (phaseIndex !== undefined) agent.phaseIndex = phaseIndex;
const phaseTitle = asString(payload.phaseTitle);
if (phaseTitle) agent.phaseTitle = phaseTitle;
const attempt = asCount(payload.attempt);
if (attempt !== undefined) {
// A new attempt on a workflow slot is a reactivation of the same
// identity: clear the previous attempt's terminal detail so the status
// transition (terminal → running, in applyStatus) reads as a fresh run.
// The activation bump lives ONLY in applyStatus — bumping here too
// counted every retry twice (review finding: two attempts read "run 3").
if (agent.attempt !== null && attempt > agent.attempt) {
agent.result = null;
agent.error = null;
agent.completedAt = null;
}
agent.attempt = attempt;
}
const outputFile = asString(payload.outputFile);
if (outputFile) agent.outputFile = outputFile;
if (Array.isArray(payload.phases)) {
const phases: SubagentWorkflowPhase[] = [];
for (const entry of payload.phases) {
if (typeof entry !== "object" || entry === null) continue;
const record = entry as Record<string, unknown>;
const index = asCount(record.index);
const phaseName = asString(record.title);
if (index !== undefined && phaseName) {
phases.push({ index, title: phaseName });
}
}
if (phases.length > 0) {
agent.phases = phases.slice().sort((a, b) => a.index - b.index);
}
}
if (typeof payload.runHandles === "object" && payload.runHandles !== null) {
const record = payload.runHandles as Record<string, unknown>;
const runHandles: {
runId?: string;
scriptPath?: string;
transcriptDir?: string;
sessionUrl?: string;
} = {};
const runId = asString(record.runId);
if (runId) runHandles.runId = runId;
const scriptPath = asString(record.scriptPath);
if (scriptPath) runHandles.scriptPath = scriptPath;
const transcriptDir = asString(record.transcriptDir);
if (transcriptDir) runHandles.transcriptDir = transcriptDir;
// Defense-in-depth: the adapter already sanitizes, but payloads are not
// schema-validated on the read path (shipped XSS lesson).
const sessionUrl = asString(record.sessionUrl);
if (sessionUrl && /^https?:\/\//i.test(sessionUrl)) runHandles.sessionUrl = sessionUrl;
if (Object.keys(runHandles).length > 0) {
agent.runHandles = { ...agent.runHandles, ...runHandles };
}
}
}
function applyStatus(agent: MutableAgent, status: RuntimeSubagentStatus, at: string): void {
const wasTerminal = isTerminalSubagentStatus(agent.status);
const isTerminal = isTerminalSubagentStatus(status);
if (wasTerminal && isTerminal) {
// Duplicate terminal events are idempotent: first write wins, timestamps
// don't slide.
return;
}
if ((wasTerminal || agent.status === "idle") && (status === "running" || status === "pending")) {
// Reactivation: same identity, new run. Clear the previous run's terminal
// detail so a live card never shows the prior run's output.
agent.activationCount += 1;
agent.result = null;
agent.error = null;
agent.completedAt = null;
if (status === "running") {
agent.startedAt = at;
}
}
if (status === "running" && agent.startedAt === null) {
agent.startedAt = at;
}
if (isTerminal && agent.completedAt === null) {
agent.completedAt = at;
}
agent.status = status;
}
// Map, not object literal: payloads aren't schema-validated on the read
// path, so a status like "toString" must miss instead of resolving an
// inherited Function through the prototype chain.
const TASK_COMPLETED_STATUS: ReadonlyMap<string, RuntimeSubagentStatus> = new Map([
["completed", "completed"],
["failed", "failed"],
["stopped", "interrupted"],
]);
const KNOWN_STATUSES: ReadonlySet<string> = new Set([
"pending",
"running",
"waiting",
"idle",
"completed",
"failed",
"cancelled",
"interrupted",
]);
function asRuntimeStatus(value: unknown): RuntimeSubagentStatus | undefined {
return typeof value === "string" && KNOWN_STATUSES.has(value)
? (value as RuntimeSubagentStatus)
: undefined;
}
/**
* Folds a thread's persisted activities into subagent state. Tolerant by
* construction: malformed rows are skipped individually; unknown kinds are
* ignored. Pure — memoize by activity-list identity at the atom layer.
*
* sessionLive=false derives interruption: background tasks die with their
* provider session, so agents whose terminal rows were lost (server
* restart, crash) must not read as running forever (review finding: a dead
* session left a panel full of "Working" agents while the sidebar showed
* nothing). Idle is preserved — a resumable Codex child stays resumable.
*/
export function foldSubagentActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
options?: { readonly sessionLive?: boolean },
): ReadonlyArray<RuntimeSubagent> {
const agents = new Map<string, MutableAgent>();
for (const activity of activities) {
if (typeof activity.payload !== "object" || activity.payload === null) {
continue;
}
const payload = activity.payload as Record<string, unknown>;
const at = activity.createdAt;
switch (activity.kind) {
case "task.started": {
const taskId = asString(payload.taskId);
if (!taskId) break;
// Only real agents join the roster. Shells, monitors, and plan-mode
// tasks are background work — they render in the ordinary work log,
// not the Agents surface (a "Run 12s stall" shell is not a subagent).
if (isBackgroundTaskActivity(payload)) break;
const agent = getOrCreate(agents, taskId, payload, at);
fillMetadata(agent, payload);
// Order-robustness: a start row arriving after a terminal state is a
// late/out-of-order delivery and only fills metadata — it must not
// reopen the run. Reactivation comes exclusively from explicit
// status transitions (task.updated / progress status). Guard on the
// status itself, not activationCount: a task first seen via a
// terminal task.updated has zero activations but is still settled
// (review finding: a late start reopened a failed child).
if (agent.activationCount === 0 && !isTerminalSubagentStatus(agent.status)) {
agent.activationCount = 1;
agent.startedAt = agent.startedAt ?? at;
agent.status = "running";
} else if (agent.status === "idle") {
applyStatus(agent, "running", at);
}
const detail = asString(payload.detail);
if (detail && agent.title === agent.id) agent.title = detail;
agent.updatedAt = at;
break;
}
case "task.progress": {
const taskId = asString(payload.taskId);
if (!taskId) break;
// Membership is sticky per taskId: rows after the first (terminal
// rows often carry only taskId+status, no marker fields) inherit the
// first row's classification instead of being re-judged.
if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;
const agent = getOrCreate(agents, taskId, payload, at);
fillMetadata(agent, payload);
if (agent.activationCount === 0) agent.activationCount = 1;
const explicitStatus = asRuntimeStatus(payload.status);
if (explicitStatus) {
applyStatus(agent, explicitStatus, at);
} else if (!isTerminalSubagentStatus(agent.status) && agent.status !== "idle") {
applyStatus(agent, "running", at);
}
const summary = asString(payload.summary);
if (summary) {
agent.progress = bounded(summary);
agent.recentActivity = appendActivity(agent.recentActivity, at, summary);
}
const lastToolName = asString(payload.lastToolName);
if (lastToolName) {
agent.lastToolName = lastToolName;
if (!summary) {
agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${lastToolName}`);
}
}
const error = asString(payload.error);
if (error) agent.error = bounded(error);
agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
agent.updatedAt = at;
break;
}
case "task.updated": {
const taskId = asString(payload.taskId);
if (!taskId) break;
// Membership is sticky per taskId: rows after the first (terminal
// rows often carry only taskId+status, no marker fields) inherit the
// first row's classification instead of being re-judged.
if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;
const agent = getOrCreate(agents, taskId, payload, at);
fillMetadata(agent, payload);
// A task first seen via task.updated (start row aged out) has run at
// least once — zero activations would misreport "run 0" and let a
// later start row treat it as never-started (review finding).
if (agent.activationCount === 0) agent.activationCount = 1;
const wasTerminal = isTerminalSubagentStatus(agent.status);
const status = asRuntimeStatus(payload.status);
if (status) applyStatus(agent, status, at);
const error = asString(payload.error);
if (error) agent.error = bounded(error);
// Provider end time beats ingestion time for the transition that
// actually settled the run (applyStatus fills completedAt with the
// activity timestamp first, so check the transition, not null).
const endedAt = asString(payload.endedAt);
if (endedAt && !wasTerminal && isTerminalSubagentStatus(agent.status)) {
agent.completedAt = endedAt;
}
agent.updatedAt = at;
break;
}
case "task.completed": {
const taskId = asString(payload.taskId);
if (!taskId) break;
// Membership is sticky per taskId: rows after the first (terminal
// rows often carry only taskId+status, no marker fields) inherit the
// first row's classification instead of being re-judged.
if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;
const agent = getOrCreate(agents, taskId, payload, at);
fillMetadata(agent, payload);
if (agent.activationCount === 0) agent.activationCount = 1;
// Already-terminal: status and timestamps are frozen (first write
// wins, duplicates must not slide them) but the completion still
// ENRICHES — Claude commonly emits terminal task.updated before
// task.completed, and the completion carries the result summary and
// final usage the update lacked (review finding: the early return
// dropped both). Fill-if-missing keeps duplicate completions from
// replacing the first result.
const summary = asString(payload.summary) ?? asString(payload.detail);
if (isTerminalSubagentStatus(agent.status)) {
if (summary) {
if (agent.status === "failed") {
agent.error = agent.error ?? bounded(summary);
} else {
agent.result = agent.result ?? bounded(summary);
}
}
agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
break;
}
const status = TASK_COMPLETED_STATUS.get(asString(payload.status) ?? "") ?? "completed";
applyStatus(agent, status, at);
if (summary) {
if (status === "failed") {
agent.error = agent.error ?? bounded(summary);
} else {
agent.result = bounded(summary);
}
}
agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
agent.updatedAt = at;
break;
}
case "tool.progress": {
// Agent-owned heartbeat: "what it's doing right now".
const taskId = asString(payload.taskId);
if (!taskId) break;
const agent = agents.get(taskId);
if (!agent) break;
const toolName = asString(payload.toolName);
if (toolName) {
agent.lastToolName = toolName;
agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${toolName}`);
}
agent.updatedAt = at;
break;
}
default:
break;
}
}
// Consistency pass: when a workflow coordinator has settled, members that
// never received their own terminal row cannot still be in-flight — the
// run is over. Cascade the coordinator's outcome so stalled member rows
// don't read as working forever (live-test finding: statuses drifted
// whenever member terminal rows were lost or never emitted).
for (const agent of agents.values()) {
if (agent.kind !== "workflow" || !isTerminalSubagentStatus(agent.status)) {
continue;
}
for (const member of agents.values()) {
if (member.parentAgentId !== agent.id) {
continue;
}
if (isTerminalSubagentStatus(member.status) || member.status === "idle") {
continue;
}
member.status = agent.status === "completed" ? "completed" : "interrupted";
member.completedAt = member.completedAt ?? agent.completedAt ?? agent.updatedAt;
member.updatedAt = agent.updatedAt;
}
}
// Session death orphans every live agent: no process remains to finish
// them. Mirrors the server-side liveness registry clearing on
// session.exited, so panel and sidebar can never disagree.
if (options?.sessionLive === false) {
for (const agent of agents.values()) {
if (isActiveSubagentStatus(agent.status)) {
agent.status = "interrupted";
agent.completedAt = agent.completedAt ?? agent.updatedAt;
}
}
}
let roster = Array.from(agents.values());
if (roster.length > ROSTER_LIMIT) {
// Prefer live, then waiting/idle, then newest settled.
const rank = (agent: MutableAgent): number =>
isActiveSubagentStatus(agent.status) ? 0 : agent.status === "idle" ? 1 : 2;
roster = roster
.slice()
.sort((a, b) => rank(a) - rank(b) || b.updatedAt.localeCompare(a.updatedAt))
.slice(0, ROSTER_LIMIT);
}
return roster.map((agent) => ({ ...agent }));
}
export interface AgentPanelWorkflowGroup {
readonly workflow: RuntimeSubagent;
readonly phases: ReadonlyArray<{
readonly index: number;
readonly title: string;
readonly members: ReadonlyArray<RuntimeSubagent>;
/** done = every member settled (success or error); running = any active. */
readonly state: "pending" | "running" | "done";
readonly activeCount: number;
readonly settledCount: number;
}>;
/** Members with no resolvable phase (orphans render under the workflow). */
readonly unphasedMembers: ReadonlyArray<RuntimeSubagent>;
}
export interface AgentPanelModel {
readonly workflows: ReadonlyArray<AgentPanelWorkflowGroup>;
readonly directAgents: ReadonlyArray<RuntimeSubagent>;
readonly runningCount: number;
readonly waitingCount: number;
readonly idleCount: number;
readonly settledCount: number;
readonly totalTokens: number;
readonly hasAgents: boolean;
readonly liveCount: number;
}
const EMPTY_PANEL_MODEL: AgentPanelModel = {
workflows: [],
directAgents: [],
runningCount: 0,
waitingCount: 0,
idleCount: 0,
settledCount: 0,
totalTokens: 0,
hasAgents: false,
liveCount: 0,
};
export function emptyAgentPanelModel(): AgentPanelModel {
return EMPTY_PANEL_MODEL;
}
/**
* Source-neutral view model. When the orchestration-v2 subagent projection
* exists for the thread, pass it as v2Projection and it wins outright — the
* two sources are never merged (duplicate-agents failure mode). Until v2
* lands, callers pass null and the native fold output is used.
*/
export function deriveAgentPanelModel({
agents,
v2Projection,
}: {
readonly agents: ReadonlyArray<RuntimeSubagent>;
readonly v2Projection?: ReadonlyArray<RuntimeSubagent> | null;
}): AgentPanelModel {
const source = v2Projection ?? agents;
if (source.length === 0) {
return EMPTY_PANEL_MODEL;
}
const workflows = source.filter((agent) => agent.kind === "workflow");
const workflowIds = new Set(workflows.map((workflow) => workflow.id));
const members = new Map<string, RuntimeSubagent[]>();
const direct: RuntimeSubagent[] = [];
for (const agent of source) {
if (agent.kind === "workflow") {
continue;
}
if (agent.parentAgentId !== null && workflowIds.has(agent.parentAgentId)) {
const list = members.get(agent.parentAgentId) ?? [];
list.push(agent);
members.set(agent.parentAgentId, list);
} else {
// Orphaned members (coordinator aged out) fall back to the direct list.
direct.push(agent);
}
}
const workflowGroups: AgentPanelWorkflowGroup[] = workflows.map((workflow) => {
const workflowMembers = members.get(workflow.id) ?? [];
const knownPhases =
workflow.phases.length > 0
? workflow.phases
: (() => {
const derived = new Map<number, string>();
for (const member of workflowMembers) {
if (member.phaseIndex !== null && !derived.has(member.phaseIndex)) {
derived.set(
member.phaseIndex,
member.phaseTitle ?? `Phase ${member.phaseIndex + 1}`,
);
}
}
return Array.from(derived.entries())
.map(([index, title]) => ({ index, title }))
.slice()
.sort((a, b) => a.index - b.index);
})();
const knownPhaseIndices = new Set(knownPhases.map((phase) => phase.index));
const phases = knownPhases.map((phase) => {
const phaseMembers = workflowMembers
.filter((member) => member.phaseIndex === phase.index)
.slice()
.sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
const activeCount = phaseMembers.filter(
// Idle members count as active for phase-liveness: a resumable Codex
// member has not finished the phase.
(member) => isActiveSubagentStatus(member.status) || member.status === "idle",
).length;
const settledCount = phaseMembers.filter((member) =>
isTerminalSubagentStatus(member.status),
).length;
const state: "pending" | "running" | "done" =
phaseMembers.length === 0
? "pending"
: activeCount > 0
? "running"
: settledCount === phaseMembers.length
? "done"
: "pending";
return {
index: phase.index,
title: phase.title,
members: phaseMembers,
state,
activeCount,
settledCount,
};
});
// Unknown phase indices land here too — a member must never vanish just
// because its phase row was lost (review finding).
const unphasedMembers = workflowMembers
.filter((member) => member.phaseIndex === null || !knownPhaseIndices.has(member.phaseIndex))
.slice()
.sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
return { workflow, phases, unphasedMembers };
});
let runningCount = 0;
let waitingCount = 0;
let idleCount = 0;
let settledCount = 0;
let totalTokens = 0;
for (const agent of source) {
if (agent.status === "running" || agent.status === "pending") runningCount += 1;
else if (agent.status === "waiting") waitingCount += 1;
else if (agent.status === "idle") idleCount += 1;
else settledCount += 1;
// Workflow coordinators aggregate member usage upstream in some providers;
// avoid double counting by only summing leaf agents when members exist.
if (agent.kind !== "workflow" || (members.get(agent.id) ?? []).length === 0) {
totalTokens += agent.usage?.totalTokens ?? 0;
}
}
return {
workflows: workflowGroups,
directAgents: direct.slice().sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)),
runningCount,
waitingCount,
idleCount,
settledCount,
totalTokens,
hasAgents: true,
liveCount: runningCount + waitingCount,
};
}
/**
* Members ordered by urgency for the capped inline workflow card: running and
* failed first, then waiting, then most recently updated.
*/
export function workflowCardMembers(
group: AgentPanelWorkflowGroup,
limit: number,
): { readonly visible: ReadonlyArray<RuntimeSubagent>; readonly overflow: number } {
const all = [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];
const urgency = (agent: RuntimeSubagent): number => {
if (agent.status === "failed") return 0;
if (agent.status === "running") return 1;
if (agent.status === "waiting") return 2;
return 3;
};
const ordered = all
.slice()
.sort((a, b) => urgency(a) - urgency(b) || b.updatedAt.localeCompare(a.updatedAt));
return {
visible: ordered.slice(0, limit),
overflow: Math.max(0, ordered.length - limit),
};
}
/** Kinds the timeline should not render as generic rows (fold input only). */
export function isSubagentActivityKind(kind: string): boolean {
return (
kind === "task.started" ||
kind === "task.progress" ||
kind === "task.updated" ||
kind === "task.completed" ||
kind === "tool.progress"
);
}
/**
* Quiet-timeline guarantee: tool rows attributed to an owning agent belong in
* the Agents surface, not the parent chat. Unattributed rows must stay.
*/
export function isAgentAttributedToolActivity(activity: OrchestrationThreadActivity): boolean {
if (typeof activity.payload !== "object" || activity.payload === null) {
return false;
}
const payload = activity.payload as Record<string, unknown>;
return typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
}
/** Timeline-bypassing synthesized rows (Codex children, workflow members). */
export function isTimelineBypassActivity(activity: OrchestrationThreadActivity): boolean {
if (typeof activity.payload !== "object" || activity.payload === null) {
return false;
}
return (activity.payload as Record<string, unknown>).timelineBypass === true;
}
/**
* Compact model chip text: strips vendor prefixes/date-or-context suffixes
* ("claude-sonnet-5[1m]" → "sonnet-5[1m]", "claude-opus-4-20250514" →
* "opus-4"). Unknown ids pass through untouched; effort appends as "· high".
*/
export function formatSubagentModelLabel(
model: string | null,
effort: string | null,
): string | null {
if (!model) {
return null;
}
const compact = model
.replace(/^claude-/, "")
.replace(/-\d{8}$/, "")
.replace(/-latest$/, "");
return effort ? `${compact} · ${effort}` : compact;
}
export function formatSubagentTokenCount(totalTokens: number): string {
if (totalTokens < 1000) {
return `${totalTokens}`;
}
if (totalTokens < 1_000_000) {
const value = totalTokens / 1000;
return `${value >= 100 ? Math.round(value) : value.toFixed(1)}k`;
}
return `${(totalTokens / 1_000_000).toFixed(1)}M`;
}
@@ -26,6 +26,16 @@ const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
* WebSocket subscription's first frame. The response is gzip-compressible by
* the transport and keeps the (potentially multi-KB) snapshot off the socket.
*/
/**
* Optional turn window for a snapshot fetch. Only send a window to servers
* that advertise `threadSnapshotPagination`; older servers reject unknown
* query parameters.
*/
export interface ThreadSnapshotWindow {
readonly turnLimit: number;
readonly beforeCursor?: string;
}
export const fetchEnvironmentThreadSnapshot = Effect.fn(
"clientRuntime.state.fetchEnvironmentThreadSnapshot",
)(function* (input: {
@@ -33,6 +43,7 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
readonly threadId: ThreadId;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
readonly timeoutMs?: number;
readonly window?: ThreadSnapshotWindow;
}) {
const requestUrl = environmentEndpointUrl(
input.prepared.httpBaseUrl,
@@ -52,6 +63,12 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
input.prepared.httpAuthorization,
client.orchestration.threadSnapshot({
params: { threadId: input.threadId },
payload: {
...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),
...(input.window?.beforeCursor !== undefined
? { beforeCursor: input.window.beforeCursor }
: {}),
},
headers,
}),
),
@@ -72,6 +89,7 @@ export class ThreadSnapshotLoader extends Context.Service<
readonly load: (
prepared: PreparedConnection,
threadId: ThreadId,
window?: ThreadSnapshotWindow,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
}
>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
@@ -89,8 +107,13 @@ export const threadSnapshotLoaderLayer: Layer.Layer<
// connections work without one).
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
return ThreadSnapshotLoader.of({
load: (prepared: PreparedConnection, threadId: ThreadId) =>
fetchEnvironmentThreadSnapshot({ prepared, threadId, signer }).pipe(
load: (prepared: PreparedConnection, threadId: ThreadId, window?: ThreadSnapshotWindow) =>
fetchEnvironmentThreadSnapshot({
prepared,
threadId,
signer,
...(window !== undefined ? { window } : {}),
}).pipe(
Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
Effect.provideService(HttpClient.HttpClient, httpClient),
// A genuinely missing thread (404) is expected — the socket
@@ -3,14 +3,38 @@ import * as Option from "effect/Option";
export type EnvironmentThreadStatus = "empty" | "cached" | "synchronizing" | "live" | "deleted";
/**
* Pagination state for a windowed thread. Present only when the loaded thread
* is a window (the server returned `page` metadata); absent means the thread is
* fully loaded — either the server predates pagination or the window reached
* the top.
*/
export interface EnvironmentThreadPageState {
/** Opaque exclusive cursor for the next older slice; null when fully loaded. */
readonly beforeCursor: string | null;
readonly hasMore: boolean;
/** True while an older page fetch is in flight. */
readonly loadingOlder: boolean;
}
export interface EnvironmentThreadState {
readonly data: Option.Option<OrchestrationThread>;
readonly status: EnvironmentThreadStatus;
readonly error: Option.Option<string>;
readonly page: Option.Option<EnvironmentThreadPageState>;
}
export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {
data: Option.none(),
status: "empty",
error: Option.none(),
page: Option.none(),
};
/** Whether the thread has older turns that can be loaded with more pages. */
export function threadHasOlderTurns(state: EnvironmentThreadState): boolean {
return Option.match(state.page, {
onNone: () => false,
onSome: (page) => page.hasMore,
});
}
@@ -0,0 +1,543 @@
import {
EnvironmentId,
EventId,
ORCHESTRATION_WS_METHODS,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationMessage,
type OrchestrationThread,
type OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import {
AVAILABLE_CONNECTION_STATE,
PrimaryConnectionTarget,
type PreparedConnection,
type SupervisorConnectionState,
} from "../connection/model.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import * as Persistence from "../platform/persistence.ts";
import * as RpcSession from "../rpc/session.ts";
import type { ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";
import {
INITIAL_THREAD_USER_TURN_LIMIT,
makeEnvironmentThreadState,
requestOlderThreadTurns,
ThreadSnapshotLoader,
type EnvironmentThreadState,
} from "./threads.ts";
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
label: "Test environment",
httpBaseUrl: "https://environment.example.test",
wsBaseUrl: "wss://environment.example.test",
});
const THREAD_ID = ThreadId.make("thread-1");
const PREPARED: PreparedConnection = {
environmentId: TARGET.environmentId,
label: TARGET.label,
httpBaseUrl: TARGET.httpBaseUrl,
socketUrl: TARGET.wsBaseUrl,
httpAuthorization: null,
target: TARGET,
};
function message(id: string, turnId: string, createdAt: string): OrchestrationMessage {
return {
id: id as OrchestrationMessage["id"],
role: "assistant",
text: `text of ${id}`,
turnId: TurnId.make(turnId),
streaming: false,
createdAt,
updatedAt: createdAt,
};
}
const OLDER_MESSAGE = message("message-old", "turn-1", "2026-04-01T00:00:00.000Z");
const RECENT_MESSAGE = message("message-recent", "turn-2", "2026-04-01T01:00:00.000Z");
// Reverts retain turns via checkpoints with checkpointTurnCount <= the revert's
// turnCount, so both fixture turns carry one: reverting to turnCount 1 keeps
// turn-1 (the older page's turn) and discards turn-2 (the loaded window's).
function checkpoint(turnId: string, turnCount: number): OrchestrationThread["checkpoints"][number] {
return {
turnId: TurnId.make(turnId),
checkpointTurnCount: turnCount,
checkpointRef:
`checkpoint-${turnCount}` as OrchestrationThread["checkpoints"][number]["checkpointRef"],
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-04-01T01:00:00.000Z",
};
}
const BASE_THREAD: OrchestrationThread = {
id: THREAD_ID,
projectId: ProjectId.make("project-1"),
title: "Windowed thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [RECENT_MESSAGE],
proposedPlans: [],
activities: [],
checkpoints: [checkpoint("turn-2", 2)],
session: null,
};
const WINDOWED_SNAPSHOT: OrchestrationThreadDetailSnapshot = {
snapshotSequence: 10,
thread: BASE_THREAD,
page: { beforeCursor: "cursor-1", hasMore: true, snapshotSequence: 10 },
};
const OLDER_PAGE: OrchestrationThreadDetailSnapshot = {
snapshotSequence: 10,
thread: {
...BASE_THREAD,
messages: [OLDER_MESSAGE],
checkpoints: [checkpoint("turn-1", 1)],
},
page: { beforeCursor: null, hasMore: false, snapshotSequence: 10 },
};
type LoaderResponse = Option.Option<OrchestrationThreadDetailSnapshot>;
const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (options?: {
readonly paginationCapability?: boolean;
readonly initialResponse?: LoaderResponse;
/** Cached snapshot returned by the cache store (simulates a warm cache). */
readonly cached?: OrchestrationThreadDetailSnapshot;
}) {
const inputs = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
const observed = yield* Queue.unbounded<EnvironmentThreadState>();
const loaderWindows = yield* Ref.make<ReadonlyArray<ThreadSnapshotWindow | undefined>>([]);
const lastSubscribeInput = yield* Ref.make<Record<string, unknown> | undefined>(undefined);
const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThreadDetailSnapshot>>([]);
// Older-page responses resolve through deferreds so tests can interleave
// live events with an in-flight page fetch.
const pendingPageResponses = yield* Queue.unbounded<Deferred.Deferred<LoaderResponse>>();
const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
AVAILABLE_CONNECTION_STATE,
);
const client = {
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input: Record<string, unknown>) =>
Stream.unwrap(Ref.set(lastSubscribeInput, input).pipe(Effect.as(Stream.fromQueue(inputs)))),
} as unknown as WsRpcProtocolClient;
const session: RpcSession.RpcSession = {
client,
initialConfig: Effect.succeed({
threadSnapshotPagination: options?.paginationCapability !== false,
} as never),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
};
const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
Option.some(session),
);
const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
Option.some(PREPARED),
);
const snapshotLoader = ThreadSnapshotLoader.of({
load: (_prepared, _threadId, window) =>
Ref.update(loaderWindows, (current) => [...current, window]).pipe(
Effect.andThen(
window?.beforeCursor === undefined
? Effect.succeed(
options?.initialResponse ?? Option.none<OrchestrationThreadDetailSnapshot>(),
)
: Deferred.make<LoaderResponse>().pipe(
Effect.tap((deferred) => Queue.offer(pendingPageResponses, deferred)),
Effect.flatMap(Deferred.await),
),
),
),
});
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
session: supervisorSession,
prepared,
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: () => Effect.void,
loadThread: () =>
Effect.succeed(options?.cached !== undefined ? Option.some(options.cached) : Option.none()),
saveThread: (_environmentId, thread) =>
Ref.update(savedThreads, (current) => [...current, thread]),
removeThread: () => Effect.void,
loadServerConfig: () => Effect.succeed(Option.none()),
saveServerConfig: () => Effect.void,
loadVcsRefs: () => Effect.succeed(Option.none()),
saveVcsRefs: () => Effect.void,
removeVcsRefs: () => Effect.void,
clearVcsRefs: () => Effect.void,
clear: () => Effect.void,
});
const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
);
yield* SubscriptionRef.changes(threadState).pipe(
Stream.runForEach((state) => Queue.offer(observed, state)),
Effect.forkScoped,
);
const awaitState = (predicate: (state: EnvironmentThreadState) => boolean) =>
Queue.take(observed).pipe(Effect.repeat({ until: predicate }));
const resolveNextPage = (response: LoaderResponse) =>
Queue.take(pendingPageResponses).pipe(
Effect.flatMap((deferred) => Deferred.succeed(deferred, response)),
);
return {
inputs,
observed,
awaitState,
resolveNextPage,
loaderWindows,
lastSubscribeInput,
savedThreads,
threadState,
};
});
const hasMessage = (state: EnvironmentThreadState, id: string): boolean =>
Option.match(state.data, {
onNone: () => false,
onSome: (thread) => thread.messages.some((entry) => entry.id === id),
});
const titleEvent = (title: string, sequence: number): OrchestrationThreadStreamItem => ({
kind: "event",
event: {
eventId: EventId.make(`event-title-${sequence}`),
sequence,
occurredAt: "2026-04-01T01:30:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
aggregateKind: "thread",
aggregateId: THREAD_ID,
type: "thread.meta-updated",
payload: {
threadId: THREAD_ID,
title,
updatedAt: "2026-04-01T01:30:00.000Z",
},
},
});
// Reverting to turnCount 1 retains only turns whose checkpoint count is <= 1:
// turn-1 survives, turn-2 (the loaded window's newest turn) is discarded.
const revertEvent = (sequence: number): OrchestrationThreadStreamItem => ({
kind: "event",
event: {
eventId: EventId.make(`event-revert-${sequence}`),
sequence,
occurredAt: "2026-04-01T02:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
aggregateKind: "thread",
aggregateId: THREAD_ID,
type: "thread.reverted",
payload: {
threadId: THREAD_ID,
turnCount: 1,
},
},
});
describe("thread pagination state", () => {
it.effect("windows the initial load when the server advertises pagination", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
const state = yield* harness.awaitState((value) => Option.isSome(value.page));
expect(Option.getOrThrow(state.page)).toEqual({
beforeCursor: "cursor-1",
hasMore: true,
loadingOlder: false,
});
const windows = yield* Ref.get(harness.loaderWindows);
expect(windows[0]?.turnLimit).toBe(INITIAL_THREAD_USER_TURN_LIMIT);
const subscribeInput = yield* Ref.get(harness.lastSubscribeInput);
expect(subscribeInput?.turnLimit).toBe(INITIAL_THREAD_USER_TURN_LIMIT);
}),
);
it.effect("does not send a window to servers without the capability", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
paginationCapability: false,
initialResponse: Option.some({ snapshotSequence: 10, thread: BASE_THREAD }),
});
const state = yield* harness.awaitState((value) => Option.isSome(value.data));
expect(Option.isNone(state.page)).toBe(true);
const windows = yield* Ref.get(harness.loaderWindows);
expect(windows[0]).toBeUndefined();
const subscribeInput = yield* Ref.get(harness.lastSubscribeInput);
expect(subscribeInput?.turnLimit).toBeUndefined();
}),
);
it.effect("merges an older page below the loaded window and clears the cursor", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
yield* harness.awaitState((value) => Option.isSome(value.page));
expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
);
yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
const state = yield* harness.awaitState((value) => hasMessage(value, "message-old"));
const thread = Option.getOrThrow(state.data);
// Older rows land before the loaded window's rows.
expect(thread.messages.map((entry) => entry.id)).toEqual(["message-old", "message-recent"]);
expect(Option.getOrThrow(state.page)).toEqual({
beforeCursor: null,
hasMore: false,
loadingOlder: false,
});
}),
);
it.effect("discards an in-flight older page when a revert rewrites history", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
yield* harness.awaitState((value) => Option.isSome(value.page));
requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
);
// Revert lands while the page fetch is in flight and removes turn-2.
yield* Queue.offer(harness.inputs, revertEvent(11));
yield* harness.awaitState((value) => !hasMessage(value, "message-recent"));
yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
const state = yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => !page.loadingOlder }),
);
// The stale page was dropped: no resurrected rows, cursor unchanged.
expect(hasMessage(state, "message-old")).toBe(false);
expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
}),
);
it.effect("discards an in-flight older page when a fresh snapshot replaces the thread", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
yield* harness.awaitState((value) => Option.isSome(value.page));
requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
);
yield* Queue.offer(harness.inputs, {
kind: "snapshot",
snapshot: {
snapshotSequence: 20,
thread: { ...BASE_THREAD, title: "Replaced thread" },
page: { beforeCursor: "cursor-2", hasMore: true, snapshotSequence: 20 },
},
});
yield* harness.awaitState((value) =>
Option.match(value.data, {
onNone: () => false,
onSome: (thread) => thread.title === "Replaced thread",
}),
);
yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
const state = yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => !page.loadingOlder }),
);
expect(hasMessage(state, "message-old")).toBe(false);
// The replacement snapshot's cursor wins over the discarded page's.
expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-2");
}),
);
it.effect("discards an older page read from a projection behind the loaded state", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
yield* harness.awaitState((value) => Option.isSome(value.page));
requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
);
yield* harness.resolveNextPage(Option.some({ ...OLDER_PAGE, snapshotSequence: 5 }));
const state = yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => !page.loadingOlder }),
);
expect(hasMessage(state, "message-old")).toBe(false);
expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
}),
);
it.effect("a merged history page never advances the live-event dedupe sequence", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
yield* harness.awaitState((value) => Option.isSome(value.page));
requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
);
// The page was captured at a newer projection sequence (12) than the
// loaded state (10); merging it must not swallow events 11-12.
yield* harness.resolveNextPage(
Option.some({
...OLDER_PAGE,
snapshotSequence: 12,
page: { beforeCursor: null, hasMore: false, snapshotSequence: 12 },
}),
);
yield* harness.awaitState((value) => hasMessage(value, "message-old"));
// Event at sequence 11 must still apply after the merge: the revert
// discards turn-2, so the loaded window's row disappears while the
// merged older turn-1 row survives. If the merge had advanced the
// dedupe sequence to the page's 12, this event would be swallowed.
yield* Queue.offer(harness.inputs, revertEvent(11));
const state = yield* harness.awaitState(
(value) => !hasMessage(value, "message-recent") && hasMessage(value, "message-old"),
);
expect(hasMessage(state, "message-old")).toBe(true);
}),
);
it.effect("parks a page read ahead of the live state until events catch up", () =>
Effect.gen(function* () {
// A page whose thread watermark is ahead of the loaded state may
// contain streaming content the subscription has not delivered yet
// (e.g. an out-of-window subagent turn mid-stream); merging it
// immediately and then replaying those deltas would duplicate text.
// The page parks until the live state reaches the watermark.
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
yield* harness.awaitState((value) => Option.isSome(value.page));
requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
yield* harness.awaitState((value) =>
Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
);
// Page watermark 11 > loaded sequence 10: must park, not merge.
yield* harness.resolveNextPage(
Option.some({
...OLDER_PAGE,
snapshotSequence: 11,
page: { beforeCursor: null, hasMore: false, snapshotSequence: 11, threadSequence: 11 },
}),
);
// A live event at sequence 11 arrives; only then does the page merge.
yield* Queue.offer(harness.inputs, titleEvent("Advanced past watermark", 11));
const state = yield* harness.awaitState((value) => hasMessage(value, "message-old"));
expect(hasMessage(state, "message-recent")).toBe(true);
expect(Option.getOrThrow(state.page).loadingOlder).toBe(false);
}),
);
it.effect("a revert keeps the page cursor and triggers no refresh fetch", () =>
Effect.gen(function* () {
// Cursors are an (anchor, turnId) keyset derived from event content, so
// they survive the revert projector's row rewrite: the machine keeps
// the stored cursor and performs no snapshot re-fetch. The revert
// reducer's turn filtering alone handles loaded history.
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
yield* harness.awaitState((value) => Option.isSome(value.page));
yield* Queue.offer(harness.inputs, revertEvent(11));
const state = yield* harness.awaitState((value) => !hasMessage(value, "message-recent"));
expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
const windows = yield* Ref.get(harness.loaderWindows);
// Only the initial load hit the loader — no post-revert refresh fetch.
expect(windows.length).toBe(1);
}),
);
it.effect("drops a windowed cache when the server lacks the pagination capability", () =>
Effect.gen(function* () {
// Resuming a windowed cache via afterSequence against a pre-pagination
// server would render only the window forever with no way to load the
// rest: the machine must discard the cache and take a full snapshot.
const fullSnapshot: OrchestrationThreadDetailSnapshot = {
snapshotSequence: 20,
thread: { ...BASE_THREAD, title: "Full reload" },
};
const harness = yield* makeHarness({
paginationCapability: false,
cached: WINDOWED_SNAPSHOT,
initialResponse: Option.some(fullSnapshot),
});
const state = yield* harness.awaitState((value) =>
Option.match(value.data, {
onNone: () => false,
onSome: (thread) => thread.title === "Full reload",
}),
);
expect(Option.isNone(state.page)).toBe(true);
// The subscription resumed from the fresh full snapshot, not the
// discarded windowed cache's watermark, and sent no window fields.
const subscribeInput = yield* Ref.get(harness.lastSubscribeInput);
expect(subscribeInput?.turnLimit).toBeUndefined();
expect(subscribeInput?.afterSequence).toBe(20);
}),
);
it.effect("keeps a windowed cache when the server supports pagination", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: WINDOWED_SNAPSHOT });
const state = yield* harness.awaitState((value) => Option.isSome(value.page));
expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
// Wait for the subscription (recorded when the WS method is invoked)
// before asserting its input.
const subscribeInput = yield* Ref.get(harness.lastSubscribeInput).pipe(
Effect.repeat({ until: (input) => input !== undefined }),
);
expect(subscribeInput?.afterSequence).toBe(10);
}),
);
});
+393 -13
View File
@@ -2,15 +2,18 @@ import {
ORCHESTRATION_WS_METHODS,
type EnvironmentId as EnvironmentIdType,
type OrchestrationThread,
type OrchestrationThreadDetailPage,
type OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
type ThreadId as ThreadIdType,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { Atom } from "effect/unstable/reactivity";
@@ -21,13 +24,14 @@ import { EnvironmentSupervisor } from "../connection/supervisor.ts";
import * as ConnectionWakeups from "../connection/wakeups.ts";
import { EnvironmentCacheStore } from "../platform/persistence.ts";
import { subscribeDynamic } from "../rpc/client.ts";
import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts";
import { ThreadSnapshotLoader, type ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";
import { parseThreadKey, threadKey } from "./entities.ts";
import { applyThreadDetailEvent } from "./threadReducer.ts";
import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
import { followStreamInEnvironment } from "./runtime.ts";
import {
EMPTY_ENVIRONMENT_THREAD_STATE,
type EnvironmentThreadPageState,
type EnvironmentThreadState,
type EnvironmentThreadStatus,
} from "./threadState.ts";
@@ -36,6 +40,85 @@ function statusWithoutLiveData(data: Option.Option<OrchestrationThread>): Enviro
return Option.isSome(data) ? "cached" : "empty";
}
/**
* Turn window sizes for paginated thread loads: the initial page covers the
* last 10 user-anchored turns (subagent/fan-out turns ride along), each
* "load earlier" tap fetches 20 more. Sized so first paint on the heaviest
* observed threads stays around 100K gzipped while median threads load fully.
*/
export const INITIAL_THREAD_USER_TURN_LIMIT = 10;
export const OLDER_THREAD_PAGE_USER_TURN_LIMIT = 20;
function pageStateFromSnapshot(
page: OrchestrationThreadDetailPage | undefined,
): Option.Option<EnvironmentThreadPageState> {
return page === undefined
? Option.none()
: Option.some({
beforeCursor: page.beforeCursor,
hasMore: page.hasMore,
loadingOlder: false,
});
}
interface ThreadOlderTurnRequestRegistry {
/**
* Registers the live state machine for a thread. Returns the deregistration
* cleanup; registration lives exactly as long as the machine's scope, and a
* successor machine for the same thread simply replaces the entry.
*/
readonly register: (key: string, handler: () => void) => () => void;
readonly request: (key: string) => boolean;
}
function makeThreadOlderTurnRequestRegistry(): ThreadOlderTurnRequestRegistry {
const handlers = new Map<string, () => void>();
return {
register: (key, handler) => {
handlers.set(key, handler);
return () => {
if (handlers.get(key) === handler) {
handlers.delete(key);
}
};
},
request: (key) => {
const handler = handlers.get(key);
if (handler === undefined) {
return false;
}
handler();
return true;
},
};
}
const defaultOlderTurnRequestRegistry = makeThreadOlderTurnRequestRegistry();
/**
* Channel from UI actions to the live per-thread state machines. The machines
* resolve it from the Effect environment (overridable in tests); the default
* instance is shared with the sync `requestOlderThreadTurns` entry point so
* the apps get working wiring without providing anything.
*/
export class ThreadOlderTurnRequests extends Context.Reference<ThreadOlderTurnRequestRegistry>(
"@t3tools/client-runtime/state/threads/ThreadOlderTurnRequests",
{ defaultValue: () => defaultOlderTurnRequestRegistry },
) {}
/**
* Asks the live state machine for `threadId` to fetch the next older page.
* Returns false when no machine is live or no fetch was started (no cursor,
* already loading); callers render from `EnvironmentThreadState.page` and can
* treat false as "nothing to do".
*/
export function requestOlderThreadTurns(
environmentId: EnvironmentIdType,
threadId: ThreadIdType,
): boolean {
return defaultOlderTurnRequestRegistry.request(threadKey({ environmentId, threadId }));
}
function formatThreadError(cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
return error instanceof Error && error.message.trim().length > 0
@@ -73,6 +156,9 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
data: cachedThread,
status: statusWithoutLiveData(cachedThread),
error: Option.none(),
// A cached windowed snapshot restores its page cursor so "load earlier"
// works while rendering from cache; a cached full snapshot has no page.
page: Option.flatMap(cached, (snapshot) => pageStateFromSnapshot(snapshot.page)),
});
// Seed the resume cursor from the cached snapshot so a warm cache can catch up
// via `afterSequence` instead of re-downloading the full thread body.
@@ -80,6 +166,25 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
);
const awaitingCompletion = yield* Ref.make(false);
// Bumped whenever loaded history may have been rewritten out from under an
// in-flight older-page fetch (snapshot replacement, revert, deletion). A
// page response captured under an older epoch is discarded, not merged.
const historyEpoch = yield* Ref.make(0);
// Serializes stream-item application against older-page staleness checks +
// merges. Without it, a revert or snapshot processed between loadOlderTurns'
// epoch check and its merge could still slip resurrected history in.
const applyLock = yield* Semaphore.make(1);
// Whether the connected server accepts windowed reads; set per subscription
// from the session config. Gates loadOlderTurns so a reconnect to a
// pre-pagination server never sends unsupported window parameters.
const paginationSupported = yield* Ref.make(false);
// An older page whose thread watermark is ahead of the live state, parked
// until the subscription catches up (see mergeOlderPage's caller). At most
// one can exist because loadOlderTurns no-ops while loadingOlder is true.
const pendingOlderPage = yield* Ref.make<{
readonly snapshot: OrchestrationThreadDetailSnapshot;
readonly epoch: number;
} | null>(null);
const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
@@ -124,6 +229,12 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
);
const setDisconnected = Effect.gen(function* () {
yield* Ref.set(awaitingCompletion, false);
// The capability belongs to the session that advertised it. During a
// reconnect, a new prepared connection can exist before the new session's
// config arrives; leaving the old value would let loadOlderTurns send
// window parameters to a server that may not accept them (review
// finding). makeSubscribeInput re-sets it from the next session's config.
yield* Ref.set(paginationSupported, false);
yield* SubscriptionRef.update(state, (current) => ({
...current,
status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
@@ -143,28 +254,51 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
thread: OrchestrationThread,
// "keep" preserves the current page state (live events touch only loaded
// recent turns); a snapshot or merged page passes its own page state.
page: Option.Option<EnvironmentThreadPageState> | "keep",
) {
const waiting = yield* Ref.get(awaitingCompletion);
yield* SubscriptionRef.set(state, {
yield* SubscriptionRef.update(state, (current) => ({
data: Option.some(thread),
status: waiting ? "synchronizing" : "live",
status: waiting ? ("synchronizing" as const) : ("live" as const),
error: Option.none(),
});
page: page === "keep" ? current.page : page,
}));
// Active threads can update many times per second and retain large tool
// payloads. The server remains the source of truth while a turn is active;
// persist once it settles so cache encoding stays off the streaming path.
if (shouldPersistThread(thread)) {
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
yield* Queue.offer(persistence, { snapshotSequence, thread });
const currentPage = yield* SubscriptionRef.get(state).pipe(Effect.map((value) => value.page));
yield* Queue.offer(persistence, {
snapshotSequence,
thread,
// Persist the window boundary with the window's content so a cache
// restore can keep paging from where the loaded history ends.
...Option.match(currentPage, {
onNone: () => ({}),
onSome: (value) =>
({
page: {
beforeCursor: value.beforeCursor,
hasMore: value.hasMore,
snapshotSequence,
},
}) as const,
}),
});
}
});
const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
yield* Ref.set(awaitingCompletion, false);
yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
yield* SubscriptionRef.set(state, {
data: Option.none(),
status: "deleted",
error: Option.none(),
page: Option.none(),
});
yield* cache.removeThread(environmentId, threadId).pipe(
Effect.catch((error) =>
@@ -179,7 +313,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
);
});
const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
// Body of applyItem, running under applyLock.
const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
item: OrchestrationThreadStreamItem,
) {
if (item.kind === "synchronized") {
@@ -193,8 +328,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
}
if (item.kind === "snapshot") {
// A fresh snapshot replaces all loaded history, including older
// pages: a turn reverted while disconnected would otherwise survive
// in the preserved history with no event left to remove it. The
// epoch bump discards any older-page fetch racing this snapshot.
yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
yield* setThread(item.snapshot.thread);
yield* setThread(item.snapshot.thread, pageStateFromSnapshot(item.snapshot.page));
return;
}
@@ -211,12 +351,184 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
}
return;
}
if (item.event.type === "thread.reverted") {
// A revert rewrites loaded history (whole turns disappear), so an
// older-page fetch in flight may straddle the removed range; the epoch
// bump discards it. The stored page cursor stays valid: cursors are an
// (anchor, turnId) keyset derived from event content, which survives
// the revert projector's row rewrite, so no refresh is needed — the
// revert reducer's turn filtering fully handles loaded history.
yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
}
const result = applyThreadDetailEvent(current.data.value, item.event);
if (result.kind === "updated") {
yield* setThread(result.thread);
yield* setThread(result.thread, "keep");
} else if (result.kind === "deleted") {
yield* setDeleted();
}
// The event may have advanced the live state past a parked page's
// watermark; merge it as soon as that happens.
yield* tryMergePendingOlderPage();
});
// Merges a parked older page once the live state has caught up to the
// page's thread watermark, or discards it if history was rewritten
// (epoch advanced) while it waited. Must run under applyLock.
const tryMergePendingOlderPage = Effect.fn("EnvironmentThreadState.tryMergePendingOlderPage")(
function* () {
const pending = yield* Ref.get(pendingOlderPage);
if (pending === null) {
return;
}
const epochNow = yield* Ref.get(historyEpoch);
if (epochNow !== pending.epoch) {
yield* Ref.set(pendingOlderPage, null);
yield* SubscriptionRef.update(state, (value) => ({
...value,
page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
}));
return;
}
const watermark = pending.snapshot.page?.threadSequence;
const loadedSequence = yield* SubscriptionRef.get(lastSequence);
if (watermark !== undefined && watermark > loadedSequence) {
return;
}
yield* Ref.set(pendingOlderPage, null);
yield* mergeOlderPage(pending.snapshot);
},
);
const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
item: OrchestrationThreadStreamItem,
) {
yield* applyLock.withPermits(1)(applyItemLocked(item));
});
// Merges an older disjoint page below the currently loaded window. All four
// windowed collections prepend; identity dedupe guards the (server-bug or
// cursor-misuse) case of overlapping pages so a row never renders twice.
const mergeOlderPage = Effect.fn("EnvironmentThreadState.mergeOlderPage")(function* (
snapshot: OrchestrationThreadDetailSnapshot,
) {
// The merge is built inside the update callback so it composes with
// whatever thread value is current at commit time. The applyLock already
// serializes this against event application; the atomic build is defense
// in depth against future callers outside the lock.
let merged: OrchestrationThread | null = null;
yield* SubscriptionRef.update(state, (value) => {
if (Option.isNone(value.data)) {
return value;
}
const loaded = value.data.value;
const older = snapshot.thread;
const mergeById = <T extends { readonly id: string }>(
olderRows: ReadonlyArray<T>,
loadedRows: ReadonlyArray<T>,
): ReadonlyArray<T> => {
const seen = new Set(loadedRows.map((row) => row.id));
return [...olderRows.filter((row) => !seen.has(row.id)), ...loadedRows];
};
const seenCheckpoints = new Set(loaded.checkpoints.map((row) => row.turnId));
merged = {
// Thread metadata stays the loaded (newer) snapshot's; only the
// windowed collections gain rows from the older page.
...loaded,
messages: mergeById(older.messages, loaded.messages),
activities: mergeById(older.activities, loaded.activities),
proposedPlans: mergeById(older.proposedPlans, loaded.proposedPlans),
checkpoints: [
...older.checkpoints.filter((row) => !seenCheckpoints.has(row.turnId)),
...loaded.checkpoints,
],
};
return {
...value,
data: Option.some(merged),
page: pageStateFromSnapshot(snapshot.page),
};
});
// Persist the widened window under the *loaded* watermark: the merged
// content is only known consistent with the state it merged into, not
// with the page's own (possibly newer) sequence.
if (merged !== null && shouldPersistThread(merged)) {
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
yield* Queue.offer(persistence, {
snapshotSequence,
thread: merged,
...(snapshot.page === undefined ? {} : { page: { ...snapshot.page, snapshotSequence } }),
});
}
});
const loadOlderTurns = Effect.fn("EnvironmentThreadState.loadOlderTurns")(function* () {
// Gated on the connected server's capability: a reconnect to a
// pre-pagination server must never receive window parameters.
if (!(yield* Ref.get(paginationSupported))) {
return;
}
const current = yield* SubscriptionRef.get(state);
const page = Option.getOrNull(current.page);
if (page === null || page.loadingOlder || !page.hasMore || page.beforeCursor === null) {
return;
}
const prepared = Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared));
if (prepared === null) {
return;
}
const epochAtStart = yield* Ref.get(historyEpoch);
yield* SubscriptionRef.update(state, (value) => ({
...value,
page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: true })),
}));
const window: ThreadSnapshotWindow = {
turnLimit: OLDER_THREAD_PAGE_USER_TURN_LIMIT,
beforeCursor: page.beforeCursor,
};
const response = yield* snapshotLoader.load(prepared, threadId, window);
// Staleness check and merge run under the same lock as stream-item
// application, so a revert/snapshot cannot land between them (TOCTOU
// review finding) — anything that rewrites history bumps the epoch
// before this permit is acquired.
yield* applyLock.withPermits(1)(
Effect.gen(function* () {
const epochNow = yield* Ref.get(historyEpoch);
const loadedSequence = yield* SubscriptionRef.get(lastSequence);
// A page carrying a sequence older than the loaded state was read
// from a projection behind what we render; merging it could
// resurrect turns a newer snapshot or revert already removed.
const stale =
epochNow !== epochAtStart ||
Option.match(response, {
onNone: () => false,
onSome: (snapshot) => snapshot.snapshotSequence < loadedSequence,
});
if (Option.isNone(response) || stale) {
yield* SubscriptionRef.update(state, (value) => ({
...value,
page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
}));
return;
}
// A page read AHEAD of the live state may include content (e.g.
// streaming deltas of an out-of-window turn) the subscription has
// not delivered yet; merging now and then replaying those events
// would duplicate them. Park the page until the live state reaches
// the page's thread-scoped watermark; loadingOlder stays true so
// the UI shows progress and no second fetch starts. Pages from
// pre-watermark servers (threadSequence absent) merge immediately,
// preserving the old behavior.
const watermark = response.value.page?.threadSequence;
if (watermark !== undefined && watermark > loadedSequence) {
yield* Ref.set(pendingOlderPage, {
snapshot: response.value,
epoch: epochNow,
});
return;
}
yield* mergeOlderPage(response.value);
}),
);
});
yield* SubscriptionRef.changes(supervisor.state).pipe(
@@ -244,14 +556,40 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
subscribeDynamic(
ORCHESTRATION_WS_METHODS.subscribeThread,
Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
const supportsCompletionMarker = yield* session.initialConfig.pipe(
Effect.map((config) => config.threadResumeCompletionMarker === true),
Effect.orElseSucceed(() => false),
const config = yield* session.initialConfig.pipe(
Effect.orElseSucceed(
() =>
({}) as {
threadResumeCompletionMarker?: boolean;
threadSnapshotPagination?: boolean;
},
),
);
const supportsCompletionMarker = config.threadResumeCompletionMarker === true;
// Windowed loads are gated on the server capability: pre-pagination
// servers reject unknown query params, and a windowed WS fallback to
// such a server would silently hide history.
const supportsPagination = config.threadSnapshotPagination === true;
yield* Ref.set(paginationSupported, supportsPagination);
yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
yield* setSynchronizing;
let current = yield* SubscriptionRef.get(state);
// A windowed cache resuming against a server without pagination is a
// trap: afterSequence resume keeps only the window, and the missing
// older turns can never be loaded (the server has no cursor reads).
// Drop the window marker and treat the data as needing a full reload.
if (!supportsPagination && Option.isSome(current.page)) {
yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
yield* SubscriptionRef.update(state, (value) => ({
...value,
data: Option.none(),
status: value.status === "deleted" ? value.status : ("empty" as const),
page: Option.none(),
}));
yield* SubscriptionRef.set(lastSequence, 0);
current = yield* SubscriptionRef.get(state);
}
if (Option.isNone(current.data) && current.status !== "deleted") {
const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
Effect.flatMap(
@@ -267,7 +605,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
}),
),
);
const httpSnapshot = yield* snapshotLoader.load(prepared, threadId);
const httpSnapshot = yield* snapshotLoader.load(
prepared,
threadId,
supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : undefined,
);
if (Option.isSome(httpSnapshot)) {
yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
current = yield* SubscriptionRef.get(state);
@@ -288,6 +630,10 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
threadId,
...(canResume ? { afterSequence: sequence } : {}),
...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
// The WS fallback snapshot (sent when afterSequence is missing or
// the gap is too large) should be windowed the same as the HTTP
// path; without this a resume failure re-downloads the full thread.
...(supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : {}),
};
}),
{
@@ -298,13 +644,47 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
).pipe(Stream.runForEach(applyItem)),
);
// Expose loadOlderTurns to UI actions through the request registry.
// Requests funnel through a sliding queue drained serially, so mashing
// "load earlier" coalesces (loadOlderTurns itself no-ops while a fetch is
// in flight).
const olderTurnRequestRegistry = yield* ThreadOlderTurnRequests;
const olderTurnRequests = yield* Queue.sliding<void>(1);
yield* Stream.fromQueue(olderTurnRequests).pipe(
Stream.runForEach(() => loadOlderTurns()),
Effect.forkScoped,
);
const deregister = olderTurnRequestRegistry.register(
threadKey({ environmentId, threadId }),
() => {
Queue.offerUnsafe(olderTurnRequests, undefined);
},
);
yield* Effect.addFinalizer(() => Effect.sync(deregister));
yield* Effect.addFinalizer(() =>
Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
Effect.flatMap(([current, snapshotSequence]) =>
Option.match(current.data, {
onNone: () => Effect.void,
onSome: (thread) =>
shouldPersistThread(thread) ? persist({ snapshotSequence, thread }) : Effect.void,
shouldPersistThread(thread)
? persist({
snapshotSequence,
thread,
...Option.match(current.page, {
onNone: () => ({}),
onSome: (page) =>
({
page: {
beforeCursor: page.beforeCursor,
hasMore: page.hasMore,
snapshotSequence,
},
}) as const,
}),
})
: Effect.void,
}),
),
),
+11
View File
@@ -457,6 +457,16 @@ const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
threadId: ThreadId,
});
// Query-string window for windowed thread snapshots (GET payloads must encode
// to strings). Both fields optional: omitting them keeps the full-snapshot
// behavior, so pagination stays opt-in per request.
const EnvironmentOrchestrationThreadSnapshotQuery = {
turnLimit: Schema.optional(
Schema.FiniteFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1)),
),
beforeCursor: Schema.optional(TrimmedNonEmptyString),
};
export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
.add(
HttpApiEndpoint.get("snapshot", "/api/orchestration/snapshot", {
@@ -476,6 +486,7 @@ export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestr
HttpApiEndpoint.get("threadSnapshot", "/api/orchestration/threads/:threadId", {
headers: OptionalBearerHeaders,
params: EnvironmentOrchestrationThreadSnapshotParams,
payload: EnvironmentOrchestrationThreadSnapshotQuery,
success: OrchestrationThreadDetailSnapshot,
error: EnvironmentOrchestrationThreadSnapshotErrors,
}).middleware(EnvironmentAuthenticatedAuth),
+110
View File
@@ -13,6 +13,7 @@ import {
IsoDateTime,
MessageId,
NonNegativeInt,
PositiveInt,
ProjectId,
ProviderItemId,
ThreadId,
@@ -24,6 +25,7 @@ import { ProviderInstanceId } from "./providerInstance.ts";
export const ORCHESTRATION_WS_METHODS = {
dispatchCommand: "orchestration.dispatchCommand",
getWorkflowScript: "orchestration.getWorkflowScript",
getTurnDiff: "orchestration.getTurnDiff",
getFullThreadDiff: "orchestration.getFullThreadDiff",
searchThreads: "orchestration.searchThreads",
@@ -438,6 +440,12 @@ export const OrchestrationThreadShell = Schema.Struct({
hasPendingApprovals: Schema.Boolean,
hasPendingUserInput: Schema.Boolean,
hasActionableProposedPlan: Schema.Boolean,
/**
* Native background work alive after the turn settles: "working" while
* subagents/workflows run, "monitoring" when watch loops are the only
* live work. Optional so old servers/clients interop; absent = none.
*/
backgroundLiveness: Schema.optional(Schema.NullOr(Schema.Literals(["working", "monitoring"]))),
});
export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;
@@ -518,12 +526,62 @@ export const OrchestrationSubscribeThreadInput = Schema.Struct({
* snapshot or catch-up replay and before it begins emitting live events.
*/
requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
/**
* When provided, the fallback snapshot frame (sent when `afterSequence` is
* missing or the catch-up gap is too large) is windowed to the last
* `turnLimit` user-anchored turns and carries `page` metadata. Absent means
* the fallback snapshot is the full thread, preserving pre-pagination client
* behavior. Live events are unaffected either way.
*/
turnLimit: Schema.optionalKey(PositiveInt),
});
export type OrchestrationSubscribeThreadInput = typeof OrchestrationSubscribeThreadInput.Type;
/**
* Bounds a thread detail read to a window of recent turns. `turnLimit` counts
* turns with a user pending message (subagent/fan-out turns between them ride
* along), so the window always contains the last N user prompts. `beforeCursor`
* requests the disjoint page of older turns strictly before a previously
* returned cursor. Requests without a window get the full thread; pagination is
* strictly opt-in so older clients keep today's behavior on both HTTP and the
* WebSocket fallback snapshot.
*/
export const OrchestrationThreadDetailWindow = Schema.Struct({
turnLimit: Schema.optionalKey(PositiveInt),
beforeCursor: Schema.optionalKey(TrimmedNonEmptyString),
});
export type OrchestrationThreadDetailWindow = typeof OrchestrationThreadDetailWindow.Type;
/**
* Page metadata for a windowed thread detail read. `beforeCursor` is opaque and
* exclusive: passing it back returns the adjacent disjoint slice of older
* turns. `null` means the thread is fully loaded below this page. The
* `snapshotSequence` mirrors the top-level snapshot sequence so history pages
* can be sequence-checked against live state before merging.
*/
export const OrchestrationThreadDetailPage = Schema.Struct({
beforeCursor: Schema.NullOr(TrimmedNonEmptyString),
hasMore: Schema.Boolean,
snapshotSequence: NonNegativeInt,
/**
* Highest event sequence applied to THIS thread at page read time. The
* global `snapshotSequence` advances with every thread's events, so a
* client cannot wait for it via its per-thread subscription; this
* thread-scoped watermark is reachable. A client merging an older page
* must first have applied live events up to it — otherwise a streaming
* turn outside the loaded window could have deltas replayed on top of
* page content that already includes them, duplicating text.
*/
threadSequence: Schema.optionalKey(NonNegativeInt),
});
export type OrchestrationThreadDetailPage = typeof OrchestrationThreadDetailPage.Type;
export const OrchestrationThreadDetailSnapshot = Schema.Struct({
snapshotSequence: NonNegativeInt,
thread: OrchestrationThread,
// Present only on windowed responses. Absent on full snapshots (and from
// pre-pagination servers), which clients treat as fully loaded.
page: Schema.optional(OrchestrationThreadDetailPage),
});
export type OrchestrationThreadDetailSnapshot = typeof OrchestrationThreadDetailSnapshot.Type;
@@ -1464,11 +1522,63 @@ export const OrchestrationSearchThreadsResult = Schema.Struct({
});
export type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;
export const OrchestrationGetWorkflowScriptInput = Schema.Struct({
threadId: ThreadId,
/** Absolute path from the workflow's runHandles.scriptPath. The server
* re-derives containment; the client value is a hint, never trusted. */
scriptPath: TrimmedNonEmptyString,
});
export type OrchestrationGetWorkflowScriptInput = typeof OrchestrationGetWorkflowScriptInput.Type;
export const OrchestrationGetWorkflowScriptResult = Schema.Struct({
scriptPath: TrimmedNonEmptyString,
contents: Schema.String,
truncated: Schema.Boolean,
});
export type OrchestrationGetWorkflowScriptResult = typeof OrchestrationGetWorkflowScriptResult.Type;
const WORKFLOW_SCRIPT_ERROR_MESSAGES = {
"invalid-path": "Workflow scripts must be absolute .js paths.",
"root-unavailable": "Script root unavailable.",
"not-found": "Script not found.",
"outside-root": "Script path is outside the workflow scripts root.",
"not-js": "Resolved script is not a .js file.",
"not-regular-file": "Script is not a regular file.",
"changed-during-read": "Script changed between resolution and open.",
"read-failed": "Script read failed.",
} as const;
export class OrchestrationGetWorkflowScriptError extends Schema.TaggedErrorClass<OrchestrationGetWorkflowScriptError>()(
"OrchestrationGetWorkflowScriptError",
{
reason: Schema.Literals([
"invalid-path",
"root-unavailable",
"not-found",
"outside-root",
"not-js",
"not-regular-file",
"changed-during-read",
"read-failed",
]),
scriptPath: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return WORKFLOW_SCRIPT_ERROR_MESSAGES[this.reason];
}
}
export const OrchestrationRpcSchemas = {
dispatchCommand: {
input: ClientOrchestrationCommand,
output: DispatchResult,
},
getWorkflowScript: {
input: OrchestrationGetWorkflowScriptInput,
output: OrchestrationGetWorkflowScriptResult,
},
getTurnDiff: {
input: OrchestrationGetTurnDiffInput,
output: OrchestrationGetTurnDiffResult,
+20 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { ProviderRuntimeEvent } from "./providerRuntime.ts";
import { classifyTaskAgentKind, ProviderRuntimeEvent } from "./providerRuntime.ts";
const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent);
@@ -182,3 +182,22 @@ describe("ProviderRuntimeEvent", () => {
expect(parsed.payload.usage.usedTokens).toBe(31251);
});
});
describe("classifyTaskAgentKind", () => {
it("classifies agent-flavored, watch-loop, and inert types", () => {
expect(classifyTaskAgentKind({ taskType: "local_agent" })).toBe("agent");
expect(classifyTaskAgentKind({ taskType: "local_workflow" })).toBe("agent");
expect(classifyTaskAgentKind({ taskType: undefined })).toBe("agent");
expect(classifyTaskAgentKind({ taskType: "brand_new_agent_type" })).toBe("agent");
expect(classifyTaskAgentKind({ taskType: "local_bash" })).toBe("background");
expect(classifyTaskAgentKind({ taskType: "monitor" })).toBe("background");
expect(classifyTaskAgentKind({ taskType: "plan" })).toBe("background");
});
it("agent-owned tasks are background unless themselves agent-flavored", () => {
expect(classifyTaskAgentKind({ taskType: "local_bash", agentId: "owner" })).toBe("background");
expect(classifyTaskAgentKind({ taskType: undefined, agentId: "owner" })).toBe("background");
// Nested agent: outlives its parent, stays in the roster.
expect(classifyTaskAgentKind({ taskType: "local_agent", agentId: "owner" })).toBe("agent");
});
});
+174 -1
View File
@@ -176,6 +176,7 @@ const ProviderRuntimeEventType = Schema.Literals([
"user-input.resolved",
"task.started",
"task.progress",
"task.updated",
"task.completed",
"hook.started",
"hook.progress",
@@ -226,6 +227,7 @@ const UserInputRequestedType = Schema.Literal("user-input.requested");
const UserInputResolvedType = Schema.Literal("user-input.resolved");
const TaskStartedType = Schema.Literal("task.started");
const TaskProgressType = Schema.Literal("task.progress");
const TaskUpdatedType = Schema.Literal("task.updated");
const TaskCompletedType = Schema.Literal("task.completed");
const HookStartedType = Schema.Literal("hook.started");
const HookProgressType = Schema.Literal("hook.progress");
@@ -407,6 +409,13 @@ export const ItemLifecyclePayload = Schema.Struct({
title: Schema.optional(TrimmedNonEmptyStringSchema),
detail: Schema.optional(TrimmedNonEmptyStringSchema),
data: Schema.optional(Schema.Unknown),
/**
* Owning agent when this item ran inside a subagent (resolved from the
* SDK's parent_tool_use_id). Clients re-home attributed items out of the
* main timeline and into the owning agent's Agents-surface row.
*/
agentId: Schema.optional(TrimmedNonEmptyStringSchema),
parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ItemLifecyclePayload = typeof ItemLifecyclePayload.Type;
@@ -459,27 +468,180 @@ const UserInputResolvedPayload = Schema.Struct({
});
export type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type;
/**
* Typed per-task usage rollup. Field names match the orchestration-v2 subagent
* usage vocabulary (#4779) so the eventual migration is a rename, not a remap.
* Claude reports per-activation deltas; Codex reports cumulative totals — the
* merge strategy is provider-specific and lives in client-runtime.
*/
export const RuntimeTaskUsage = Schema.Struct({
totalTokens: NonNegativeInt,
inputTokens: Schema.optional(NonNegativeInt),
cachedInputTokens: Schema.optional(NonNegativeInt),
outputTokens: Schema.optional(NonNegativeInt),
reasoningOutputTokens: Schema.optional(NonNegativeInt),
toolUses: Schema.optional(NonNegativeInt),
durationMs: Schema.optional(NonNegativeInt),
});
export type RuntimeTaskUsage = typeof RuntimeTaskUsage.Type;
export const TaskWorkflowPhase = Schema.Struct({
index: NonNegativeInt,
title: TrimmedNonEmptyStringSchema,
});
export type TaskWorkflowPhase = typeof TaskWorkflowPhase.Type;
export const TaskRunHandles = Schema.Struct({
runId: Schema.optional(TrimmedNonEmptyStringSchema),
scriptPath: Schema.optional(TrimmedNonEmptyStringSchema),
transcriptDir: Schema.optional(TrimmedNonEmptyStringSchema),
/** Only http/https URLs may be stored here — sanitized at the adapter. */
sessionUrl: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type TaskRunHandles = typeof TaskRunHandles.Type;
/**
* Watch-loop task types: Monitor-tool tasks plus background shells (a shell
* that outlives its turn is in practice a watch loop). Canonical single copy —
* the server liveness registry, ingestion's agentKind stamp, and the client
* fold's legacy fallback all classify with these sets.
*/
export const MONITOR_TASK_TYPES: ReadonlySet<string> = new Set([
"monitor",
"monitor_mcp",
"local_bash",
"shell",
]);
/** Task types that are neither agents nor watch loops (plan-mode bookkeeping). */
export const INERT_TASK_TYPES: ReadonlySet<string> = new Set(["plan", "dream"]);
/**
* Agent-vs-background classification, stamped by ingestion as `agentKind` so
* persisted rows are self-describing. A deliberate denylist: the SDK's
* agent-flavored type names drift (subagent, local_agent, local_workflow, …)
* and an allowlist silently dropped real subagents when "local_agent"
* appeared. A task launched from inside a subagent (agentId set) is
* agent-internal background work UNLESS it is itself agent-flavored — a
* nested agent can outlive its parent and stays in the roster.
*/
export function classifyTaskAgentKind(input: {
readonly taskType?: string | undefined;
readonly agentId?: string | undefined;
}): "agent" | "background" {
const { taskType, agentId } = input;
const nonAgentType =
taskType !== undefined && (MONITOR_TASK_TYPES.has(taskType) || INERT_TASK_TYPES.has(taskType));
if (agentId !== undefined && agentId.trim().length > 0) {
return taskType === undefined || nonAgentType ? "background" : "agent";
}
return nonAgentType ? "background" : "agent";
}
/**
* Optional agent-identity linkage carried on every task lifecycle payload.
* Repeated on progress and terminal rows (not just start) so client folds can
* reconstruct an agent even when its start row aged out of activity retention.
* All fields optional: old emitters and old rows decode unchanged.
*/
const taskAgentLinkageFields = {
/** SDK task_type (subagent/shell/monitor/local_workflow/…), repeated on
* every row so folds can classify without the start row. */
taskType: Schema.optional(TrimmedNonEmptyStringSchema),
/**
* Server-stamped classification (classifyTaskAgentKind at ingestion).
* Clients trust this stamp outright; rows without it (legacy, pre-stamp)
* fall back to client-side heuristics.
*/
agentKind: Schema.optional(Schema.Literals(["agent", "background"])),
/**
* Owning agent when the task itself was launched from inside a subagent
* (e.g. a subagent's background shell). Clients treat such tasks as
* agent-internal and keep them out of the parent work log.
*/
agentId: Schema.optional(TrimmedNonEmptyStringSchema),
title: Schema.optional(TrimmedNonEmptyStringSchema),
role: Schema.optional(TrimmedNonEmptyStringSchema),
model: Schema.optional(TrimmedNonEmptyStringSchema),
/** Reasoning effort when known (e.g. "high"). Open string: provider vocabularies differ. */
effort: Schema.optional(TrimmedNonEmptyStringSchema),
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
parentAgentId: Schema.optional(TrimmedNonEmptyStringSchema),
workflowName: Schema.optional(TrimmedNonEmptyStringSchema),
agentIndex: Schema.optional(NonNegativeInt),
phaseIndex: Schema.optional(NonNegativeInt),
phaseTitle: Schema.optional(TrimmedNonEmptyStringSchema),
phases: Schema.optional(Schema.Array(TaskWorkflowPhase)),
attempt: Schema.optional(NonNegativeInt),
runHandles: Schema.optional(TaskRunHandles),
outputFile: Schema.optional(TrimmedNonEmptyStringSchema),
/** Codex agent hierarchy path, e.g. "/root/marlow". */
agentPath: Schema.optional(TrimmedNonEmptyStringSchema),
/**
* Set on provider-synthesized child-agent events (Codex) whose activity
* belongs in the Agents surface, never the parent timeline.
*/
timelineBypass: Schema.optional(Schema.Boolean),
} as const;
export const TaskAgentLinkage = Schema.Struct(taskAgentLinkageFields);
export type TaskAgentLinkage = typeof TaskAgentLinkage.Type;
const TaskStartedPayload = Schema.Struct({
taskId: RuntimeTaskId,
description: Schema.optional(TrimmedNonEmptyStringSchema),
taskType: Schema.optional(TrimmedNonEmptyStringSchema),
...taskAgentLinkageFields,
});
export type TaskStartedPayload = typeof TaskStartedPayload.Type;
export const RuntimeTaskStatus = Schema.Literals([
"pending",
"running",
"waiting",
"idle",
"completed",
"failed",
"cancelled",
"interrupted",
]);
export type RuntimeTaskStatus = typeof RuntimeTaskStatus.Type;
const TaskProgressPayload = Schema.Struct({
taskId: RuntimeTaskId,
description: TrimmedNonEmptyStringSchema,
summary: Schema.optional(TrimmedNonEmptyStringSchema),
usage: Schema.optional(Schema.Unknown),
typedUsage: Schema.optional(RuntimeTaskUsage),
lastToolName: Schema.optional(TrimmedNonEmptyStringSchema),
/** Present on synthesized member/child progress rows that carry state. */
status: Schema.optional(RuntimeTaskStatus),
error: Schema.optional(TrimmedNonEmptyStringSchema),
...taskAgentLinkageFields,
});
export type TaskProgressPayload = typeof TaskProgressPayload.Type;
/**
* Non-terminal status patch (from the Claude SDK's task_updated, which main
* previously dropped). killed→cancelled and paused→idle are mapped at the
* adapter so the wire only carries the shared vocabulary.
*/
const TaskUpdatedPayload = Schema.Struct({
taskId: RuntimeTaskId,
status: Schema.optional(RuntimeTaskStatus),
description: Schema.optional(TrimmedNonEmptyStringSchema),
error: Schema.optional(TrimmedNonEmptyStringSchema),
endedAt: Schema.optional(IsoDateTime),
isBackgrounded: Schema.optional(Schema.Boolean),
...taskAgentLinkageFields,
});
export type TaskUpdatedPayload = typeof TaskUpdatedPayload.Type;
const TaskCompletedPayload = Schema.Struct({
taskId: RuntimeTaskId,
status: Schema.Literals(["completed", "failed", "stopped"]),
summary: Schema.optional(TrimmedNonEmptyStringSchema),
usage: Schema.optional(Schema.Unknown),
typedUsage: Schema.optional(RuntimeTaskUsage),
...taskAgentLinkageFields,
});
export type TaskCompletedPayload = typeof TaskCompletedPayload.Type;
@@ -513,6 +675,9 @@ const ToolProgressPayload = Schema.Struct({
toolName: Schema.optional(TrimmedNonEmptyStringSchema),
summary: Schema.optional(TrimmedNonEmptyStringSchema),
elapsedSeconds: Schema.optional(Schema.Number),
/** Owning task/agent when the tool ran inside a subagent. */
taskId: Schema.optional(RuntimeTaskId),
parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ToolProgressPayload = typeof ToolProgressPayload.Type;
@@ -835,6 +1000,13 @@ const ProviderRuntimeTaskProgressEvent = Schema.Struct({
});
export type ProviderRuntimeTaskProgressEvent = typeof ProviderRuntimeTaskProgressEvent.Type;
const ProviderRuntimeTaskUpdatedEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: TaskUpdatedType,
payload: TaskUpdatedPayload,
});
export type ProviderRuntimeTaskUpdatedEvent = typeof ProviderRuntimeTaskUpdatedEvent.Type;
const ProviderRuntimeTaskCompletedEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: TaskCompletedType,
@@ -995,6 +1167,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([
ProviderRuntimeUserInputResolvedEvent,
ProviderRuntimeTaskStartedEvent,
ProviderRuntimeTaskProgressEvent,
ProviderRuntimeTaskUpdatedEvent,
ProviderRuntimeTaskCompletedEvent,
ProviderRuntimeHookStartedEvent,
ProviderRuntimeHookProgressEvent,
+11
View File
@@ -64,6 +64,7 @@ import {
OrchestrationGetTurnDiffError,
OrchestrationGetTurnDiffInput,
OrchestrationRpcSchemas,
OrchestrationGetWorkflowScriptError,
} from "./orchestration.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
import {
@@ -696,6 +697,15 @@ export const WsOrchestrationDispatchCommandRpc = Rpc.make(
},
);
export const WsOrchestrationGetWorkflowScriptRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getWorkflowScript,
{
payload: OrchestrationRpcSchemas.getWorkflowScript.input,
success: OrchestrationRpcSchemas.getWorkflowScript.output,
error: Schema.Union([OrchestrationGetWorkflowScriptError, EnvironmentAuthorizationError]),
},
);
export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getTurnDiff, {
payload: OrchestrationGetTurnDiffInput,
success: OrchestrationRpcSchemas.getTurnDiff.output,
@@ -867,6 +877,7 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeBackgroundPolicyRpc,
WsSubscribeResourceTelemetryRpc,
WsOrchestrationDispatchCommandRpc,
WsOrchestrationGetWorkflowScriptRpc,
WsOrchestrationGetTurnDiffRpc,
WsOrchestrationGetFullThreadDiffRpc,
WsOrchestrationSearchThreadsRpc,
+6
View File
@@ -434,6 +434,12 @@ export const ServerConfig = Schema.Struct({
shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
/** Whether thread subscriptions can emit an opt-in catch-up completion marker. */
threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
/**
* Whether thread detail reads accept a turn window (`turnLimit`/
* `beforeCursor`) and return `page` metadata. Clients must not send window
* fields to servers that don't advertise this.
*/
threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
});
export type ServerConfig = typeof ServerConfig.Type;