Compare commits

..
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 a40376b28f fix: dual-review pass (Fable + gpt-5.6-sol high) on rebased branch
Bot rounds (Macroscope/Bugbot):
- taskKind: explicit shell/monitor types win over parentTaskId fallback
- lastStartedAt per activation; elapsed timers exclude idle gaps
- client revision selection uses (revision ?? -1) matching server hydration
- orphan-sweep append retries once on session.exited (often the last event)
- live-strip wrapper keyed off hasLiveAgents (no phantom spacer)

gpt-5.6-sol (high):
- thread.reverted now invalidates the cached roster (no resurrecting
  reverted agents); new domain-event subscription
- endedAt: explicit > existing > first-terminal ingestion time
- roster strings bounded at 180 chars (recentActivity + currentActivity)
- task_updated.patch.description maps to name
- empty failed workflow renders its container card

Fable:
- deriveLatestAgentSnapshot picks the winner by peeking revision, decodes
  only that roster (was: full schema-decode of every roster per recompute)
- idle Codex children get their own retention cap (25) — they never reach
  terminal status mid-session, so they were unbounded
- v1 collab receivers re-checked inside the v2 diversion branch (arrival-
  order race); task usage schema committed to typed RuntimeTaskUsage;
  Claude usage carries input/output/cache breakdowns; assorted nits

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:54:59 -07:00
Theo BrowneandClaude Fable 5 e9a498e28d chore: drop test fragment superseded by dedicated coverage test from #4244
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:01:20 -07:00
Theo BrowneandClaude Fable 5 61d0c38337 fix(claude): consume undeclared background_tasks_changed silently
The SDK stream emits this roster snapshot but its subtype is absent from
the typed union, so it fell through to the unknown-subtype warning path
and rendered as a spurious error row ('no displayable text content') in
client work logs. The task_* lifecycle events carry the authoritative
per-agent data; the typed background_tasks control request remains the
reconciliation source.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 ffd01045d0 fix(ingestion): merge task usage field-wise instead of wholesale replace
A payload carrying only totalTokens (e.g. terminal task_notification)
no longer wipes previously known input/output/toolUses breakdowns.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 812aee975a fix(ingestion+claude): round-5 review — hydration revision parity, amortized refresh, queued workflow agents, kind materiality
- Hydration selects the persisted snapshot by highest revision (same rule
  as the client), so the reducer can't resume from a stale roster that
  landed later in the list
- Ordinary traffic now counts toward unhydrated threads and triggers
  amortized hydration+refresh, so a settled snapshot can't age out of
  the 500-row cap after a restart with no agent events
- Claude workflow_agent state:'start' without startedAt (queued) maps to
  pending instead of running
- kind/parentAgentId upgrades count as material transitions

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 4586d5f374 fix: address review handoff P1/P2 findings
P1:
- Claude workflow agents keyed by stable row index (parent:wf:N), not
  per-attempt agentId — queued/blocked rows now appear, retries update
  one card instead of duplicating
- agent.snapshot payloads carry a monotonic per-thread revision; client
  latest-wins selection uses it (deterministic under same-ms appends)
- Codex child turn/completed decodes turn.status: failed→failed with
  error summary, interrupted→stopped, completed→idle
- roster hydration is lazy (only on agent-touching events), no longer a
  full thread-detail load on every first event per thread

P2:
- reducer re-derives kind from event taskType/parent (no first-guess
  pinning); reactivation counts any settled→active transition
- workflow container rows excluded from worker counts; container usage
  only counted when it has no member rows
- settled cards lead with error/result, never stale activity text
- newest agents array is authoritative on the client — undecodable
  rosters no longer resurrect older running snapshots
- idle (resumable) agents no longer share the terminal retention pool
- Codex usage uses the cumulative total breakdown consistently

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 a3248a123a fix(ingestion): seed roster refresh counter from snapshot age; log append success only on success
Bugbot round 4: after restart the latest agent.snapshot can already sit
deep in the capped projection, so the refresh counter now seeds from its
actual index distance instead of zero; the 'appended' debug log moved
into the success branch so a swallowed failure no longer logs success.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 4b9b7c515d fix(ingestion): non-blocking snapshot appends + roster refresh before cap eviction
- A failed agent.snapshot append no longer aborts the rest of the
  event's ingestion (Bugbot: repeated failures were dropping message
  deltas/session status). Failures are logged, interrupts propagate, and
  the redispatch flag retries on the next event.
- While agents exist, the roster is re-published every ~400 timeline
  activities so the latest snapshot cannot age past the projector's
  500-row cap (Macroscope: hydration and client scans always find one).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 ce1f1043bf fix(ingestion): agent roster lifecycle hardening from round-2 review
- session.exited now releases the per-thread reducer state after the
  final snapshot persists (unbounded retention leak)
- failed snapshot dispatch keeps the newer in-memory roster and flags
  the thread for re-dispatch on the next event instead of discarding
  memory (previous fix could lose transitions)
- document the 500-cap hydration boundary: past the cap both server and
  clients have lost the snapshot, so empty hydration is consistent

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 0892ce3710 fix: address PR review feedback; remove HTML plan docs
- CI: client-runtime test imports @effect/vitest (vitest types unresolved
  in package context)
- CodexSessionRuntime: divert child-thread events that arrive before
  subAgentActivity registers them (probe: child status/changed lands
  first); emit a terminal event on subAgent interruption
- CodexAdapter: systemError -> failed; cumulative totalProcessedTokens
  for child usage (last-turn count can shrink on follow-ups)
- Ingestion: waiting agents counted as active in roster summaries;
  reactivation clears stale resultSummary/errorMessage; usage fields
  validated as non-negative integers; failed snapshot dispatch drops the
  hydration marker so the roster re-syncs from persisted state
- Panel/strip: idle counts as settled everywhere; phase labels show
  active counts (not '0 running'); parseTimestampDate for ISO parsing
- Drop docs/project/plans HTML files

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 f99429b371 fix: emit running on Codex wait resolution; hide agent.snapshot in mobile work log
Codex review P2: active-with-no-flags thread status now maps back to
running so agents don't stay 'waiting' after an approval resolves.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 c513a4031d fix(web): truncate long agent-type badges in agent cards
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 877bcca698 test(client-runtime): thread agent derivation tests against persisted payload
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 5472e9dadb feat(server): Claude agent lifecycle fields + ingestion agent roster reducer
ClaudeAdapter carries subagent linkage (agentType/toolUseId/workflowName/
prompt/outputFile), handles task_updated, parses workflow_progress into
child workflow_agent task events, normalizes task usage, and captures
Workflow tool results (scriptPath/runId). Ingestion folds task.* events
into per-thread ThreadAgentSnapshot rosters with material-transition
filtering, projection hydration, orphan sweep, and 50-cap retention,
appended as agent.snapshot activities.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 20:00:02 -07:00
Theo BrowneandClaude Fable 5 7e898d22df feat(codex): track v2 collab child threads as agent telemetry
CodexSessionRuntime learns children from subAgentActivity items (probe:
no child thread/started arrives) and diverts their notifications into
synthetic collab/agentActivity events; CodexAdapter maps those to
timeline-bypassing task.* events (turn lifecycle, waiting flags, token
usage, item summaries). turn/completed maps to idle, not terminal.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 19:59:36 -07:00
Theo BrowneandClaude Fable 5 45783d5fab feat(web): agents panel, live strip, and thread-agent derivation
New right-panel 'agents' surface (Option A) + collapsed live strip near the
composer (Option B). Roster derived latest-wins from agent.snapshot
activities via shared client-runtime helpers.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 19:59:36 -07:00
Theo BrowneandClaude Fable 5 f49c1a97ca feat(contracts): thread agent snapshot schemas for subagent observability
ThreadAgentSnapshot + agent.snapshot activity payload, typed task usage,
task.updated runtime event, and agent-linkage fields on task payloads.
Includes the reviewed HTML plans.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-21 19:59:36 -07:00
Theo BrowneandClaude Fable 5 6f34ad3e87 fix(claude): handle all SDK stream messages; stop spurious work-log warning rows (#4244)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 19:58:39 -07:00
Theo BrowneandClaude Fable 5 62cf461759 fix: better defaults — Claude 1M context, Codex gpt-5.6, worktrees from origin main (#4240)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 17:13:44 -07:00
Theo BrowneandClaude Fable 5 23c18fda7a fix(web): keep composer editable while disconnected (#4241)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 14:29:23 -07:00
Theo BrowneandClaude Fable 5 c0bb237345 fix(web): always show environment chip for remote projects (#4217)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-20 18:27:57 -07:00
54 changed files with 3401 additions and 1156 deletions

No files matched your search

@@ -57,11 +57,11 @@ describe("ElectronProtocol", () => {
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' data: http: https: ws: wss:",
"connect-src 'self' http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
@@ -212,18 +212,10 @@ describe("ElectronProtocol", () => {
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], [
"'self'",
"data:",
"http:",
"https:",
"ws:",
"wss:",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
@@ -71,8 +71,6 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
const scriptSources = [
"'self'",
"'unsafe-inline'",
// Required to compile the ghostty-web terminal's WebAssembly module.
"'wasm-unsafe-eval'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
@@ -81,8 +79,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
// data: allows ghostty-web to fetch its embedded WebAssembly payload.
const connectSources = ["'self'", "data:", "http:", "https:", "ws:", "wss:"];
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
return [
"default-src 'self'",
@@ -58,6 +58,8 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
function pendingTaskDraftKey(messageId: string): string {
return `pending-task:${messageId}`;
}
@@ -348,7 +350,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
// Keep the user's explicit choice separate from the resolved display value:
// only the explicit flag is ever written back to the draft, so the resolved
// value keeps tracking the server setting when the config loads late.
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
draftStartFromOrigin ??
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
true;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
@@ -368,6 +377,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
const selectedModelKey = selectedModel
@@ -475,13 +485,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending;
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
const availableBranches = useMemo(
() =>
pipe(
branchState.data?.refs ?? [],
allBranchRefs,
Arr.filter((branch) => !branch.isRemote),
),
[branchState.data?.refs],
[allBranchRefs],
);
const filteredBranches = useMemo(() => {
@@ -543,11 +554,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
@@ -560,11 +571,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
);
const setStartFromOrigin = useCallback(
@@ -597,14 +608,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
// availableBranches filters out — search the unfiltered refs for it.
const preferredBranch =
allBranchRefs.find((branch) => branch.isDefault) ??
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -696,7 +709,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode: mode,
branch: workspaceSelection?.branch ?? null,
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
// The draft only carries the flag when the user touched it; fall
// back to the resolved default (server settings) so queued tasks
// drain with the same origin mode the composer displayed.
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
? { startFromOrigin: true }
: {}),
},
createdAt: metadata.createdAt,
};
@@ -707,6 +725,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
],
);
+3
View File
@@ -15,6 +15,7 @@ export type ModelOption = {
readonly providerKey: string;
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -78,6 +79,7 @@ export function buildModelOptions(
providerKey: provider.instanceId,
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -107,6 +109,7 @@ export function buildModelOptions(
providerKey: fallbackModelSelection.instanceId,
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
capabilities: null,
selection: fallbackModelSelection,
});
+1
View File
@@ -238,6 +238,7 @@ function deriveWorkLogEntries(
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.kind === "agent.snapshot") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
@@ -9,6 +9,8 @@ import {
ProviderRuntimeEvent,
ProviderSession,
ProviderInstanceId,
RuntimeTaskId,
type ThreadAgentSnapshot,
} from "@t3tools/contracts";
import {
ApprovalRequestId,
@@ -43,7 +45,11 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import {
foldTaskAgentEvent,
ProviderRuntimeIngestionLive,
pruneSettledAgents,
} from "./ProviderRuntimeIngestion.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
@@ -318,6 +324,133 @@ describe("ProviderRuntimeIngestion", () => {
};
}
it("folds material transitions, reactivations, and settled retention", () => {
const agents = new Map<string, ThreadAgentSnapshot>();
const started: Extract<ProviderRuntimeEvent, { type: "task.started" }> = {
type: "task.started",
eventId: asEventId("agent-started"),
provider: ProviderDriverKind.make("claudeAgent"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:00.000Z",
payload: {
taskId: RuntimeTaskId.make("agent-1"),
description: "Reviewer",
taskType: "local_agent",
},
};
expect(foldTaskAgentEvent(agents, started)).toBe(true);
const usageTick: Extract<ProviderRuntimeEvent, { type: "task.progress" }> = {
...started,
type: "task.progress",
eventId: asEventId("agent-progress"),
createdAt: "2026-01-01T00:00:01.000Z",
payload: {
taskId: RuntimeTaskId.make("agent-1"),
description: "Reviewer",
usage: { totalTokens: 10 },
},
};
expect(foldTaskAgentEvent(agents, usageTick)).toBe(false);
const completed: Extract<ProviderRuntimeEvent, { type: "task.completed" }> = {
...started,
type: "task.completed",
eventId: asEventId("agent-completed"),
createdAt: "2026-01-01T00:00:02.000Z",
payload: { taskId: RuntimeTaskId.make("agent-1"), status: "completed" },
};
expect(foldTaskAgentEvent(agents, completed)).toBe(true);
expect(
foldTaskAgentEvent(agents, { ...started, eventId: asEventId("agent-reactivated") }),
).toBe(true);
expect(agents.get("agent-1")?.activationCount).toBe(2);
for (let index = 0; index < 51; index += 1) {
agents.set(`settled-${index}`, {
agentId: `settled-${index}`,
provider: ProviderDriverKind.make("claudeAgent"),
kind: "subagent",
name: `Agent ${index}`,
status: "completed",
firstStartedAt: `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`,
lastActivityAt: `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`,
activationCount: 1,
recentActivity: [],
updatedAt: `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`,
});
}
pruneSettledAgents(agents);
expect(
Array.from(agents.values()).filter((agent) => agent.status === "completed"),
).toHaveLength(50);
expect(agents.has("settled-0")).toBe(false);
});
it("appends latest-wins agent rosters only on material changes and sweeps orphans", async () => {
const harness = await createHarness();
harness.emit({
type: "task.started",
eventId: asEventId("evt-agent-start"),
provider: ProviderDriverKind.make("claudeAgent"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:01.000Z",
payload: { taskId: "agent-1", description: "Reviewer", taskType: "local_agent" },
});
await harness.drain();
harness.emit({
type: "task.progress",
eventId: asEventId("evt-agent-usage"),
provider: ProviderDriverKind.make("claudeAgent"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:02.000Z",
payload: { taskId: "agent-1", description: "Reviewer", usage: { totalTokens: 10 } },
});
await harness.drain();
let thread = (await harness.readModel()).threads.find((entry) => entry.id === "thread-1");
expect(
thread?.activities.filter((activity) => activity.kind === "agent.snapshot"),
).toHaveLength(1);
harness.emit({
type: "session.exited",
eventId: asEventId("evt-session-exit-agents"),
provider: ProviderDriverKind.make("claudeAgent"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:03.000Z",
payload: { reason: "process_exit" },
});
await harness.drain();
thread = (await harness.readModel()).threads.find((entry) => entry.id === "thread-1");
const snapshots =
thread?.activities.filter((activity) => activity.kind === "agent.snapshot") ?? [];
expect(snapshots).toHaveLength(2);
const latest = snapshots.at(-1)?.payload as { agents: Array<ThreadAgentSnapshot> } | undefined;
expect(latest?.agents).toHaveLength(1);
expect(latest?.agents[0]?.status).toBe("stopped");
expect(latest?.agents[0]?.errorMessage).toBe("orphaned on session exit");
// The session-exit sweep releases the in-memory roster; a later session on
// the same thread re-hydrates from the persisted snapshot instead of the
// evicted map (agent-1 stays stopped, not resurrected).
harness.emit({
type: "task.started",
eventId: asEventId("evt-agent-restart"),
provider: ProviderDriverKind.make("claudeAgent"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:04.000Z",
payload: { taskId: "agent-2", description: "Follow-up", taskType: "local_agent" },
});
await harness.drain();
thread = (await harness.readModel()).threads.find((entry) => entry.id === "thread-1");
const rehydrated =
thread?.activities.filter((activity) => activity.kind === "agent.snapshot") ?? [];
expect(rehydrated).toHaveLength(3);
const roster = rehydrated.at(-1)?.payload as { agents: Array<ThreadAgentSnapshot> } | undefined;
expect(roster?.agents.map((agent) => [agent.agentId, agent.status])).toEqual([
["agent-1", "stopped"],
["agent-2", "running"],
]);
});
it("maps turn started/completed events into thread session updates", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2,6 +2,7 @@ import {
ApprovalRequestId,
type AssistantDeliveryMode,
CommandId,
EventId,
MessageId,
type OrchestrationEvent,
type OrchestrationMessage,
@@ -9,6 +10,12 @@ import {
CheckpointRef,
isToolLifecycleItemType,
ThreadId,
THREAD_AGENTS_ACTIVITY_KIND,
THREAD_AGENT_RECENT_ACTIVITY_LIMIT,
THREAD_AGENT_TERMINAL_STATUSES,
type ThreadAgentSnapshot,
type ThreadAgentStatus,
type ThreadAgentUsage,
type ThreadTokenUsageSnapshot,
TurnId,
type OrchestrationCheckpointSummary,
@@ -41,6 +48,269 @@ import { ServerSettingsService } from "../../serverSettings.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
const AGENT_SETTLED_RETENTION_LIMIT = 50;
const AGENT_IDLE_RETENTION_LIMIT = 25;
const AGENT_USAGE_MATERIAL_STEP = 25_000;
// Fields must satisfy the contract's NonNegativeInt or the persisted roster
// row becomes undecodable on the client.
function usageCount(value: unknown): number | undefined {
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
}
function taskUsage(value: unknown): ThreadAgentUsage | undefined {
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
const usage = value as Record<string, unknown>;
const totalTokens = usageCount(usage.totalTokens);
if (totalTokens === undefined) return undefined;
const inputTokens = usageCount(usage.inputTokens);
const cachedInputTokens = usageCount(usage.cachedInputTokens);
const outputTokens = usageCount(usage.outputTokens);
const reasoningOutputTokens = usageCount(usage.reasoningOutputTokens);
const toolUses = usageCount(usage.toolUses);
return {
totalTokens,
...(inputTokens !== undefined ? { inputTokens } : {}),
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(outputTokens !== undefined ? { outputTokens } : {}),
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
...(toolUses !== undefined ? { toolUses } : {}),
};
}
function taskStatus(event: ProviderRuntimeEvent): ThreadAgentStatus | undefined {
if (event.type === "task.started") return "running";
if (event.type === "task.completed") return event.payload.status;
if (event.type !== "task.updated" || !event.payload.status) return undefined;
return event.payload.status === "killed"
? "stopped"
: event.payload.status === "paused"
? "idle"
: event.payload.status;
}
function taskKind(taskType: string | undefined, parentTaskId: string | undefined) {
if (taskType === "local_agent") return "subagent" as const;
if (taskType === "local_workflow") return "workflow" as const;
if (taskType === "workflow_agent") return "workflow_agent" as const;
if (taskType === "local_bash" || taskType === "shell") return "shell" as const;
if (taskType === "monitor") return "monitor" as const;
// Parent linkage is only a workflow-membership hint when the type itself is
// unknown — a nested shell/monitor task keeps its explicit kind above.
if (parentTaskId) return "workflow_agent" as const;
return "other" as const;
}
function isTaskAgentEvent(
event: ProviderRuntimeEvent,
): event is Extract<
ProviderRuntimeEvent,
{ type: "task.started" | "task.progress" | "task.updated" | "task.completed" }
> {
return (
event.type === "task.started" ||
event.type === "task.progress" ||
event.type === "task.updated" ||
event.type === "task.completed"
);
}
function workflowPhasesEqual(
left: ThreadAgentSnapshot["phases"],
right: ThreadAgentSnapshot["phases"],
): boolean {
return (
left === right ||
(left !== undefined &&
right !== undefined &&
left.length === right.length &&
left.every(
(phase, index) =>
phase.index === right[index]?.index && phase.title === right[index]?.title,
))
);
}
const AGENT_TEXT_LIMIT = 180;
/** Roster snapshots duplicate these strings on every append — keep them small. */
function boundAgentText(value: string): string {
return value.length > AGENT_TEXT_LIMIT ? `${value.slice(0, AGENT_TEXT_LIMIT - 1)}…` : value;
}
export function foldTaskAgentEvent(
agents: Map<string, ThreadAgentSnapshot>,
event: Extract<
ProviderRuntimeEvent,
{ type: "task.started" | "task.progress" | "task.updated" | "task.completed" }
>,
): boolean {
const payload = event.payload;
const previous = agents.get(payload.taskId);
const status = taskStatus(event) ?? previous?.status ?? "running";
const description = "description" in payload ? payload.description : undefined;
const summary = "summary" in payload ? payload.summary : undefined;
const nextUsage = "usage" in payload ? taskUsage(payload.usage) : undefined;
const lastToolName = "lastToolName" in payload ? payload.lastToolName : undefined;
const settledNow = status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(status);
// A settled agent's card shows its result/error, not a stale in-flight
// activity line ("Reading files…" on a failed card).
const rawCurrentActivity = settledNow
? undefined
: (summary ?? lastToolName ?? previous?.currentActivity);
const currentActivity =
rawCurrentActivity === undefined ? undefined : boundAgentText(rawCurrentActivity);
const activityChanged =
(summary !== undefined && summary !== previous?.currentActivity) ||
(lastToolName !== undefined && lastToolName !== previous?.lastToolName);
const recentActivity = activityChanged
? [
...(previous?.recentActivity ?? []),
{
at: event.createdAt,
// Bounded: Codex child item summaries can carry full command/item
// text, and each entry is duplicated into every roster snapshot.
summary: boundAgentText(summary ?? lastToolName ?? "Activity updated"),
},
].slice(-THREAD_AGENT_RECENT_ACTIVITY_LIMIT)
: (previous?.recentActivity ?? []);
const wasSettled =
previous !== undefined &&
(previous.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(previous.status));
// Any non-settled status counts as a fresh activation — an idle Codex agent
// resumed via a waiting approval still increments, not just idle→running.
const reactivated =
wasSettled && status !== "idle" && !THREAD_AGENT_TERMINAL_STATUSES.has(status);
const explicitEndTime = event.type === "task.updated" ? event.payload.endTime : undefined;
const terminal = THREAD_AGENT_TERMINAL_STATUSES.has(status);
// Re-derive kind whenever this event carries a taskType/parent — a child
// registered from an early notification (before its parent linkage arrived)
// must not stay pinned to a first-guess "other".
const eventKind = taskKind(
"taskType" in payload ? payload.taskType : undefined,
payload.parentTaskId,
);
const next: ThreadAgentSnapshot = {
agentId: payload.taskId,
provider: event.provider,
kind: eventKind !== "other" ? eventKind : (previous?.kind ?? eventKind),
name: payload.name ?? description ?? payload.workflowName ?? previous?.name ?? payload.taskId,
...((payload.agentType ?? previous?.agentType)
? { agentType: payload.agentType ?? previous?.agentType }
: {}),
...((payload.model ?? previous?.model) ? { model: payload.model ?? previous?.model } : {}),
status,
...(currentActivity ? { currentActivity } : {}),
...((lastToolName ?? previous?.lastToolName)
? { lastToolName: lastToolName ?? previous?.lastToolName }
: {}),
// Merge field-wise: a payload carrying only totalTokens (e.g. a terminal
// Claude task_notification) must not wipe previously known breakdowns.
...(nextUsage || previous?.usage
? { usage: { ...previous?.usage, ...nextUsage } as ThreadAgentUsage }
: {}),
firstStartedAt: previous?.firstStartedAt ?? event.createdAt,
// Reset per activation so live timers exclude idle gaps between runs.
lastStartedAt: reactivated
? event.createdAt
: (previous?.lastStartedAt ?? previous?.firstStartedAt ?? event.createdAt),
lastActivityAt: event.createdAt,
// Prefer the provider's explicit end time, then an already-recorded one;
// only stamp ingestion time on the FIRST terminal transition so duplicate
// terminal events don't keep sliding the end forward.
...(!reactivated &&
(explicitEndTime ?? previous?.endedAt ?? (terminal ? event.createdAt : undefined))
? {
endedAt: explicitEndTime ?? previous?.endedAt ?? (terminal ? event.createdAt : undefined),
}
: {}),
activationCount: previous ? previous.activationCount + (reactivated ? 1 : 0) : 1,
...((event.turnId ?? previous?.lastTurnId)
? { lastTurnId: TurnId.make(String(event.turnId ?? previous?.lastTurnId)) }
: {}),
...((payload.parentTaskId ?? previous?.parentAgentId)
? { parentAgentId: payload.parentTaskId ?? previous?.parentAgentId }
: {}),
...(payload.phaseIndex !== undefined || previous?.phaseIndex !== undefined
? { phaseIndex: payload.phaseIndex ?? previous?.phaseIndex }
: {}),
...((payload.phaseTitle ?? previous?.phaseTitle)
? { phaseTitle: payload.phaseTitle ?? previous?.phaseTitle }
: {}),
...((payload.phases ?? previous?.phases) ? { phases: payload.phases ?? previous?.phases } : {}),
...((payload.scriptPath ?? previous?.scriptPath)
? { scriptPath: payload.scriptPath ?? previous?.scriptPath }
: {}),
...((payload.runId ?? previous?.runId) ? { runId: payload.runId ?? previous?.runId } : {}),
...((payload.outputFile ?? previous?.outputFile)
? { outputFile: payload.outputFile ?? previous?.outputFile }
: {}),
// A re-activated agent starts a fresh run: prior result/error text would
// read as the live run's output, so clear both unless this event sets them.
...(event.type === "task.completed" && event.payload.summary
? { resultSummary: event.payload.summary }
: !reactivated && previous?.resultSummary
? { resultSummary: previous.resultSummary }
: {}),
...(event.type === "task.updated" && event.payload.errorMessage
? { errorMessage: event.payload.errorMessage }
: !reactivated && previous?.errorMessage
? { errorMessage: previous.errorMessage }
: {}),
recentActivity,
updatedAt: event.createdAt,
};
agents.set(payload.taskId, next);
if (!previous) return true;
const usageStepChanged =
Math.floor((previous.usage?.totalTokens ?? 0) / AGENT_USAGE_MATERIAL_STEP) !==
Math.floor((next.usage?.totalTokens ?? 0) / AGENT_USAGE_MATERIAL_STEP);
return (
previous.status !== next.status ||
previous.kind !== next.kind ||
previous.parentAgentId !== next.parentAgentId ||
previous.name !== next.name ||
previous.model !== next.model ||
previous.phaseIndex !== next.phaseIndex ||
previous.phaseTitle !== next.phaseTitle ||
!workflowPhasesEqual(previous.phases, next.phases) ||
previous.currentActivity !== next.currentActivity ||
activityChanged ||
usageStepChanged ||
previous.endedAt !== next.endedAt ||
previous.resultSummary !== next.resultSummary ||
previous.errorMessage !== next.errorMessage ||
previous.scriptPath !== next.scriptPath ||
previous.runId !== next.runId ||
previous.outputFile !== next.outputFile
);
}
export function pruneSettledAgents(agents: Map<string, ThreadAgentSnapshot>): void {
// Terminal agents are history and compete for the standard retention pool.
const settled = Array.from(agents.values())
.filter((agent) => THREAD_AGENT_TERMINAL_STATUSES.has(agent.status))
.sort((left, right) => left.lastActivityAt.localeCompare(right.lastActivityAt));
for (const agent of settled.slice(
0,
Math.max(0, settled.length - AGENT_SETTLED_RETENTION_LIMIT),
)) {
agents.delete(agent.agentId);
}
// Idle agents are resumable identities, so they get their own (generous)
// cap rather than sharing the terminal pool — but Codex children end every
// run idle and never terminal until close/interrupt, so without a bound a
// long session accumulates them all and every material append persists the
// full roster. Evicting oldest-idle is safe: a resumed identity
// re-registers from its next event (the activation counter tolerates the
// restart).
const idle = Array.from(agents.values())
.filter((agent) => agent.status === "idle")
.sort((left, right) => left.lastActivityAt.localeCompare(right.lastActivityAt));
for (const agent of idle.slice(0, Math.max(0, idle.length - AGENT_IDLE_RETENTION_LIMIT))) {
agents.delete(agent.agentId);
}
}
// Fallback when the in-memory description cache no longer has the task name
// (server restart, session-exit sweep, TTL/capacity eviction): earlier
@@ -94,9 +364,9 @@ const TASK_DESCRIPTION_BY_TASK_TTL = Duration.minutes(120);
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
type TurnStartRequestedDomainEvent = Extract<
type IngestionDomainEvent = Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" }
{ type: "thread.turn-start-requested" | "thread.reverted" }
>;
type RuntimeIngestionInput =
@@ -106,7 +376,7 @@ type RuntimeIngestionInput =
}
| {
source: "domain";
event: TurnStartRequestedDomainEvent;
event: IngestionDomainEvent;
};
function toTurnId(value: TurnId | string | undefined): TurnId | undefined {
@@ -310,6 +580,12 @@ export function runtimeEventToActivities(
event: ProviderRuntimeEvent,
taskTitle?: string,
): ReadonlyArray<OrchestrationThreadActivity> {
if (
(isTaskAgentEvent(event) && event.payload.timelineBypass === true) ||
event.type === "task.updated"
) {
return [];
}
const maybeSequence = (() => {
const eventWithSequence = event as ProviderRuntimeEvent & { sessionSequence?: number };
return eventWithSequence.sessionSequence !== undefined
@@ -693,6 +969,23 @@ const make = Effect.gen(function* () {
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
const agentsByThread = new Map<ThreadId, Map<string, ThreadAgentSnapshot>>();
const hydratedAgentThreads = new Set<ThreadId>();
// Threads whose latest roster failed to persist: the in-memory state is
// newer than the last agent.snapshot activity, so the next event must
// re-dispatch even if it is not material on its own.
const pendingRosterRedispatch = new Set<ThreadId>();
// Activities appended per thread since its last agent.snapshot. The
// activities projection keeps only the newest 500 rows; refreshing the
// roster before the last snapshot can age out guarantees hydration (and the
// client's latest-wins scan) always finds one while agents exist.
const activitiesSinceAgentSnapshot = new Map<ThreadId, number>();
const AGENT_SNAPSHOT_REFRESH_ACTIVITY_COUNT = 400;
// Monotonic per-thread roster revision. Snapshot activities carry it so the
// client picks the newest roster deterministically even when two appends
// share a createdAt millisecond. Seeded from the hydrated snapshot.
const agentRosterRevision = new Map<ThreadId, number>();
let agentSnapshotDispatchCount = 0;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
@@ -1305,6 +1598,181 @@ const make = Effect.gen(function* () {
return loadedThreadDetail;
});
// Hydrate lazily: on agent-touching events, or amortized once ordinary
// traffic has appended enough activities that a persisted snapshot
// could be approaching the 500-row cap. Never on every first event —
// message deltas after a restart must not each trigger a full
// thread-detail load through the serialized ingestion worker.
const eventTouchesAgents = isTaskAgentEvent(event) || event.type === "session.exited";
const activityPressure =
(activitiesSinceAgentSnapshot.get(thread.id) ?? 0) >= AGENT_SNAPSHOT_REFRESH_ACTIVITY_COUNT;
if ((eventTouchesAgents || activityPressure) && !hydratedAgentThreads.has(thread.id)) {
const detail = yield* getLoadedThreadDetail();
const activityList = detail?.activities ?? [];
// Select the snapshot the same way the client does — highest revision
// wins, list position breaks ties — so the reducer never resumes from
// a stale lower-revision roster that landed later in the list.
let latestSnapshotIndex = -1;
let bestRevision = -1;
for (let index = 0; index < activityList.length; index += 1) {
const activity = activityList[index];
if (!activity || activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) continue;
const revision =
activity.payload !== null &&
typeof activity.payload === "object" &&
typeof (activity.payload as { revision?: unknown }).revision === "number"
? ((activity.payload as { revision: number }).revision ?? -1)
: -1;
if (revision >= bestRevision) {
bestRevision = revision;
latestSnapshotIndex = index;
}
}
const latestSnapshot =
latestSnapshotIndex >= 0 ? activityList[latestSnapshotIndex] : undefined;
// Seed the refresh counter with the snapshot's actual age in the
// capped projection — after a restart it may already sit hundreds of
// rows deep, and starting from zero would let it age out before the
// first refresh.
activitiesSinceAgentSnapshot.set(
thread.id,
latestSnapshotIndex >= 0 ? activityList.length - 1 - latestSnapshotIndex : 0,
);
if (bestRevision >= 0) {
agentRosterRevision.set(thread.id, bestRevision);
}
const payload =
latestSnapshot?.payload !== null && typeof latestSnapshot?.payload === "object"
? (latestSnapshot.payload as { agents?: unknown })
: undefined;
const agents = new Map<string, ThreadAgentSnapshot>();
if (Array.isArray(payload?.agents)) {
for (const candidate of payload.agents) {
if (
candidate !== null &&
typeof candidate === "object" &&
typeof (candidate as { agentId?: unknown }).agentId === "string"
) {
const agent = candidate as ThreadAgentSnapshot;
agents.set(agent.agentId, agent);
}
}
}
agentsByThread.set(thread.id, agents);
hydratedAgentThreads.add(thread.id);
}
const threadAgents = agentsByThread.get(thread.id) ?? new Map<string, ThreadAgentSnapshot>();
agentsByThread.set(thread.id, threadAgents);
let agentRosterMaterial = false;
if (isTaskAgentEvent(event)) {
agentRosterMaterial = foldTaskAgentEvent(threadAgents, event);
} else if (event.type === "session.exited") {
for (const [agentId, agent] of threadAgents) {
if (THREAD_AGENT_TERMINAL_STATUSES.has(agent.status)) continue;
threadAgents.set(agentId, {
...agent,
status: "stopped",
endedAt: event.createdAt,
lastActivityAt: event.createdAt,
errorMessage: "orphaned on session exit",
updatedAt: event.createdAt,
});
agentRosterMaterial = true;
}
}
if (pendingRosterRedispatch.has(thread.id) && threadAgents.size > 0) {
agentRosterMaterial = true;
}
if (
!agentRosterMaterial &&
threadAgents.size > 0 &&
(activitiesSinceAgentSnapshot.get(thread.id) ?? 0) >= AGENT_SNAPSHOT_REFRESH_ACTIVITY_COUNT
) {
agentRosterMaterial = true;
}
if (agentRosterMaterial) {
pruneSettledAgents(threadAgents);
const roster = Array.from(threadAgents.values());
// "active" covers everything non-settled (running/pending/waiting) so a
// roster of blocked agents doesn't read as "0 agents settled".
const active = roster.filter(
(agent) => agent.status !== "idle" && !THREAD_AGENT_TERMINAL_STATUSES.has(agent.status),
).length;
const settled = roster.length - active;
const count = active > 0 ? active : settled;
const summary = `${count} ${count === 1 ? "agent" : "agents"} ${active > 0 ? "active" : "settled"}`;
const nextRevision = (agentRosterRevision.get(thread.id) ?? 0) + 1;
const snapshotUuid = yield* crypto.randomUUIDv4;
const activity: OrchestrationThreadActivity = {
id: EventId.make(`${event.eventId}:agent-snapshot:${snapshotUuid}`),
createdAt: event.createdAt,
tone: "info",
kind: THREAD_AGENTS_ACTIVITY_KIND,
summary,
payload: { agents: roster, revision: nextRevision },
turnId: toTurnId(event.turnId) ?? null,
};
// The in-memory roster is authoritative (already folded); if the
// append fails, keep it and flag the thread so the NEXT event
// re-dispatches the full roster — discarding memory here would lose
// transitions newer than the last persisted snapshot. The failure is
// swallowed (logged) rather than raised: agent observability must
// never block the rest of this event's ingestion (message deltas,
// session status, timeline activities). Interrupts still propagate.
pendingRosterRedispatch.add(thread.id);
const appendSnapshot = orchestrationEngine
.dispatch({
type: "thread.activity.append",
commandId: yield* providerCommandId(event, "agent-snapshot-append"),
threadId: thread.id,
activity,
createdAt: activity.createdAt,
})
.pipe(
Effect.andThen(
Effect.gen(function* () {
pendingRosterRedispatch.delete(thread.id);
activitiesSinceAgentSnapshot.set(thread.id, 0);
agentRosterRevision.set(thread.id, nextRevision);
agentSnapshotDispatchCount += 1;
yield* Effect.logDebug("provider agent snapshot appended", {
threadId: thread.id,
agentCount: roster.length,
dispatchCount: agentSnapshotDispatchCount,
});
}),
),
);
// session.exited is often the thread's LAST event — the usual
// "re-dispatch on the next event" recovery never fires, so retry the
// final orphan-sweep roster once before giving up on it.
yield* appendSnapshot.pipe(
event.type === "session.exited"
? Effect.retry({ times: 1 })
: (effect: typeof appendSnapshot) => effect,
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause)
: Effect.logWarning("provider agent snapshot append failed; will re-dispatch", {
threadId: thread.id,
agentCount: roster.length,
cause: Cause.pretty(cause),
}),
),
);
}
// Sessions are done producing agent events once they exit; release the
// per-thread reducer state. A later session re-hydrates from the
// persisted snapshot (the exit sweep above just wrote the final roster).
if (event.type === "session.exited" && !pendingRosterRedispatch.has(thread.id)) {
agentsByThread.delete(thread.id);
hydratedAgentThreads.delete(thread.id);
activitiesSinceAgentSnapshot.delete(thread.id);
agentRosterRevision.delete(thread.id);
}
const now = event.createdAt;
const eventTurnId = toTurnId(event.turnId);
const activeTurnId = thread.session?.activeTurnId ?? null;
@@ -1759,6 +2227,19 @@ const make = Effect.gen(function* () {
}
const activities = runtimeEventToActivities(event, taskTitle);
// Count for hydrated threads with a live roster AND for not-yet-hydrated
// threads: the counter is what triggers amortized hydration under
// ordinary traffic after a restart, so a persisted snapshot gets
// refreshed before it can age out of the capped projection.
if (
activities.length > 0 &&
(!hydratedAgentThreads.has(thread.id) || agentsByThread.get(thread.id)?.size)
) {
activitiesSinceAgentSnapshot.set(
thread.id,
(activitiesSinceAgentSnapshot.get(thread.id) ?? 0) + activities.length,
);
}
yield* Effect.forEach(activities, (activity) =>
providerCommandId(event, "thread-activity-append").pipe(
Effect.flatMap((commandId) =>
@@ -1774,7 +2255,22 @@ const make = Effect.gen(function* () {
).pipe(Effect.asVoid);
});
const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
const processDomainEvent = (event: IngestionDomainEvent) =>
Effect.sync(() => {
if (event.type !== "thread.reverted") {
return;
}
// A checkpoint revert pruned reverted-turn activities (including agent
// snapshots) from the projection. Drop the cached roster so the next
// agent event rehydrates from post-revert state instead of folding a
// stale map and resurrecting reverted agents.
const threadId = event.payload.threadId;
agentsByThread.delete(threadId);
hydratedAgentThreads.delete(threadId);
activitiesSinceAgentSnapshot.delete(threadId);
agentRosterRevision.delete(threadId);
pendingRosterRedispatch.delete(threadId);
});
const processInput = (input: RuntimeIngestionInput) =>
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
@@ -1805,7 +2301,7 @@ const make = Effect.gen(function* () {
);
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.turn-start-requested") {
if (event.type !== "thread.turn-start-requested" && event.type !== "thread.reverted") {
return Effect.void;
}
return worker.enqueue({ source: "domain", event });
@@ -1704,6 +1704,11 @@ describe("ClaudeAdapterLive", () => {
"Code reviewer checked the migration edge cases.",
);
assert.equal(progressEvent.payload.description, "Running background teammate");
assert.deepEqual(progressEvent.payload.usage, {
totalTokens: 123,
toolUses: 4,
durationMs: 987,
});
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
@@ -1711,6 +1716,246 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("carries Claude task linkage, updates, and workflow progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => runtimeEvents.push(event)),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "workflow-1",
description: "Run checks",
task_type: "local_workflow",
subagent_type: "Workflow",
tool_use_id: "tool-1",
workflow_name: "Verification",
prompt: "Check the repository",
session_id: "session",
uuid: "started",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_progress",
task_id: "workflow-1",
description: "Run checks",
subagent_type: "Workflow",
tool_use_id: "tool-1",
usage: { total_tokens: 12, tool_uses: 2, duration_ms: 30 },
workflow_progress: [
{ type: "workflow_phase", index: 0, title: "Inspect" },
{
type: "workflow_agent",
index: 1,
label: "Reviewer",
phaseIndex: 0,
phaseTitle: "Inspect",
agentId: "agent-1",
model: "claude-sonnet",
state: "start",
attempt: 1,
tokens: 7,
toolCalls: 1,
lastToolName: "Read",
},
],
session_id: "session",
uuid: "progress",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_updated",
task_id: "workflow-1",
patch: {
status: "paused",
end_time: 1_700_000_000_000,
is_backgrounded: true,
error: "waiting",
},
session_id: "session",
uuid: "updated",
} as unknown as SDKMessage);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Effect.yieldNow;
runtimeEventsFiber.interruptUnsafe();
const started = runtimeEvents.find((event) => event.type === "task.started");
assert.equal(started?.type, "task.started");
if (started?.type === "task.started") {
assert.equal(started.payload.name, "Run checks");
assert.equal(started.payload.agentType, "Workflow");
assert.equal(started.payload.toolUseId, "tool-1");
assert.equal(started.payload.workflowName, "Verification");
assert.equal(started.payload.prompt, "Check the repository");
}
const phasePatch = runtimeEvents.find(
(event) => event.type === "task.updated" && event.payload.phases !== undefined,
);
assert.equal(phasePatch?.type, "task.updated");
if (phasePatch?.type === "task.updated") {
assert.deepEqual(phasePatch.payload.phases, [{ index: 0, title: "Inspect" }]);
}
const child = runtimeEvents.find(
(event) => event.type === "task.started" && event.payload.taskId === "workflow-1:wf:1",
);
assert.equal(child?.type, "task.started");
if (child?.type === "task.started") {
assert.equal(child.payload.parentTaskId, "workflow-1");
assert.equal(child.payload.timelineBypass, true);
assert.equal(child.payload.taskType, "workflow_agent");
}
const statusPatch = runtimeEvents.find(
(event) => event.type === "task.updated" && event.payload.status === "paused",
);
assert.equal(statusPatch?.type, "task.updated");
if (statusPatch?.type === "task.updated") {
assert.equal(statusPatch.payload.endTime, "2023-11-14T22:13:20.000Z");
assert.equal(statusPatch.payload.isBackgrounded, true);
assert.equal(statusPatch.payload.errorMessage, "waiting");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => runtimeEvents.push(event)),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
// Undeclared wire-only roster snapshot + every typed UX-internal
// subtype and top-level type consumed silently: none may surface as
// unknown-subtype warnings.
for (const message of [
{
type: "system",
subtype: "background_tasks_changed",
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "task_updated",
task_id: "t1",
patch: { status: "running" },
session_id: "session",
uuid: "tu",
},
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
{
type: "system",
subtype: "notification",
key: "context",
text: "low priority note",
priority: "low",
session_id: "session",
uuid: "notif",
},
]) {
harness.query.emit(message as unknown as SDKMessage);
}
// High-priority notifications DO surface as a warning row.
harness.query.emit({
type: "system",
subtype: "notification",
key: "limit",
text: "context window nearly full",
priority: "high",
session_id: "session",
uuid: "notif-high",
} as unknown as SDKMessage);
// session_state_changed maps to the matching session states.
for (const [state, uuid] of [
["running", "ssc-run"],
["requires_action", "ssc-req"],
["idle", "ssc-idle"],
]) {
harness.query.emit({
type: "system",
subtype: "session_state_changed",
state,
session_id: "session",
uuid,
} as unknown as SDKMessage);
}
// api_retry maps to a session heartbeat, not a warning row.
harness.query.emit({
type: "system",
subtype: "api_retry",
attempt: 3,
max_retries: 10,
retry_delay_ms: 1000,
error_status: 502,
error: { type: "api_error" },
session_id: "session",
uuid: "retry",
} as unknown as SDKMessage);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
// Exactly one warning: the high-priority notification. Nothing else.
assert.deepEqual(
warnings.map((event) => event.payload.message),
["context window nearly full"],
);
const sessionStates = runtimeEvents
.filter((event) => event.type === "session.state.changed")
.map((event) =>
event.type === "session.state.changed"
? `${event.payload.state}:${event.payload.reason ?? ""}`
: "",
)
.filter(
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
);
assert.deepEqual(sessionStates, [
"running:session_state:running",
"waiting:session_state:requires_action",
"ready:session_state:idle",
]);
const heartbeat = runtimeEvents.find(
(event) =>
event.type === "session.state.changed" &&
typeof event.payload.reason === "string" &&
event.payload.reason.startsWith("api_retry:"),
);
assert.equal(heartbeat?.type, "session.state.changed");
runtimeEventsFiber.interruptUnsafe();
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits thread token usage updates from Claude task progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -3045,7 +3290,7 @@ describe("ClaudeAdapterLive", () => {
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3143,10 +3388,11 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "200k" }],
),
attachments: [],
});
+325 -23
View File
@@ -77,6 +77,7 @@ import {
isClaudeUltracodeEffort,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeContextWindow,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
@@ -341,24 +342,18 @@ function selectedClaudeContextWindow(
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
// Always 1M at the API; these models expose no contextWindow option.
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return 1_000_000;
case "200k":
return 200_000;
default:
return undefined;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
@@ -709,6 +704,38 @@ function readString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function readNonNegativeInteger(value: unknown): number | undefined {
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
}
function epochMillisToIso(value: number): string {
return DateTime.formatIso(DateTime.makeUnsafe(value));
}
function normalizeRuntimeTaskUsage(value: unknown) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
return undefined;
}
const usage = value as Record<string, unknown>;
const totalTokens = readNonNegativeInteger(usage.total_tokens);
if (totalTokens === undefined) {
return undefined;
}
const toolUses = readNonNegativeInteger(usage.tool_uses);
const durationMs = readNonNegativeInteger(usage.duration_ms);
const inputTokens = readNonNegativeInteger(usage.input_tokens);
const outputTokens = readNonNegativeInteger(usage.output_tokens);
const cachedInputTokens = readNonNegativeInteger(usage.cache_read_input_tokens);
return {
totalTokens,
...(inputTokens !== undefined ? { inputTokens } : {}),
...(outputTokens !== undefined ? { outputTokens } : {}),
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(toolUses !== undefined ? { toolUses } : {}),
...(durationMs !== undefined ? { durationMs } : {}),
};
}
function readStringArray(value: unknown): Array<string> {
return Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0)
@@ -2393,6 +2420,33 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
if (!toolResult.isError && tool.toolName === "Workflow" && toolUseResult) {
const taskId = readString(toolUseResult.taskId);
if (taskId) {
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "task.updated",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: context.turnState.turnId } : {}),
payload: {
taskId: RuntimeTaskId.make(taskId),
...(readString(toolUseResult.scriptPath)
? { scriptPath: readString(toolUseResult.scriptPath) }
: {}),
...(readString(toolUseResult.runId)
? { runId: readString(toolUseResult.runId) }
: {}),
...(readString(toolUseResult.workflowName)
? { workflowName: readString(toolUseResult.workflowName) }
: {}),
},
});
}
}
const streamKind = toolResultStreamKind(tool.itemType);
if (streamKind && toolResult.text.length > 0 && context.turnState) {
const deltaStamp = yield* makeEventStamp();
@@ -2590,6 +2644,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
};
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
// be switch cases): consumed intentionally without emitting, otherwise
// they fall through to the unknown-subtype warning and surface as spurious
// 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;
}
switch (message.subtype) {
case "init":
yield* offerRuntimeEvent({
@@ -2670,18 +2735,33 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
case "task_started":
case "task_started": {
const record = message as unknown as Record<string, unknown>;
const agentType = readString(record.subagent_type);
const toolUseId = readString(record.tool_use_id);
const workflowName = readString(record.workflow_name);
const prompt = readString(record.prompt);
yield* offerRuntimeEvent({
...base,
type: "task.started",
payload: {
taskId: RuntimeTaskId.make(message.task_id),
description: message.description,
name: message.description,
...(message.task_type ? { taskType: message.task_type } : {}),
...(agentType ? { agentType } : {}),
...(toolUseId ? { toolUseId } : {}),
...(workflowName ? { workflowName } : {}),
...(prompt ? { prompt } : {}),
},
});
return;
case "task_progress":
}
case "task_progress": {
const record = message as unknown as Record<string, unknown>;
const agentType = readString(record.subagent_type);
const toolUseId = readString(record.tool_use_id);
const usage = normalizeRuntimeTaskUsage(record.usage);
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2697,12 +2777,165 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
taskId: RuntimeTaskId.make(message.task_id),
description: message.description,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(usage ? { usage } : {}),
...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
...(agentType ? { agentType } : {}),
...(toolUseId ? { toolUseId } : {}),
},
});
const workflowProgress = record.workflow_progress;
if (Array.isArray(workflowProgress)) {
const phases = workflowProgress.flatMap((entry) => {
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return [];
const item = entry as Record<string, unknown>;
if (item.type !== "workflow_phase") return [];
const index = readNonNegativeInteger(item.index);
const title = readString(item.title);
return index !== undefined && title ? [{ index, title }] : [];
});
if (phases.length > 0) {
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: stamp.eventId,
createdAt: stamp.createdAt,
type: "task.updated",
payload: {
taskId: RuntimeTaskId.make(message.task_id),
phases,
timelineBypass: true,
},
});
}
for (const entry of workflowProgress) {
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
const item = entry as Record<string, unknown>;
if (item.type !== "workflow_agent") continue;
// `index` is the stable identity: queued/blocked/pre-spawn-error
// events carry no agentId yet, and retries keep the index while
// minting a new agentId per attempt. Keying on agentId would drop
// queued agents and duplicate cards across retries.
const index = readNonNegativeInteger(item.index);
const label = readString(item.label);
if (index === undefined || !label) continue;
const state = readString(item.state);
const childUsage = readNonNegativeInteger(item.tokens);
const childToolUses = readNonNegativeInteger(item.toolCalls);
const childPayload = {
taskId: RuntimeTaskId.make(`${message.task_id}:wf:${index}`),
description: label,
name: label,
taskType: "workflow_agent",
parentTaskId: RuntimeTaskId.make(message.task_id),
timelineBypass: true as const,
...(readString(item.model) ? { model: readString(item.model) } : {}),
...(readNonNegativeInteger(item.phaseIndex) !== undefined
? { phaseIndex: readNonNegativeInteger(item.phaseIndex) }
: {}),
...(readString(item.phaseTitle) ? { phaseTitle: readString(item.phaseTitle) } : {}),
...(readNonNegativeInteger(item.attempt) !== undefined
? { attempt: readNonNegativeInteger(item.attempt) }
: {}),
...(readString(item.lastToolName)
? { lastToolName: readString(item.lastToolName) }
: {}),
...(childUsage !== undefined
? {
usage: {
totalTokens: childUsage,
...(childToolUses !== undefined ? { toolUses: childToolUses } : {}),
},
}
: {}),
};
const stamp = yield* makeEventStamp();
if (state === "start") {
yield* offerRuntimeEvent({
...base,
eventId: stamp.eventId,
createdAt: stamp.createdAt,
type: "task.started",
payload: childPayload,
});
// The CLI emits state:"start" both when queueing (queuedAt only)
// and when execution begins (startedAt set). A queued agent must
// not show as running in the panel.
if (readNonNegativeInteger(item.startedAt) === undefined) {
const pendingStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: pendingStamp.eventId,
createdAt: pendingStamp.createdAt,
type: "task.updated",
payload: {
taskId: childPayload.taskId,
status: "pending",
timelineBypass: true,
},
});
}
} else if (state === "done" || state === "error") {
yield* offerRuntimeEvent({
...base,
eventId: stamp.eventId,
createdAt: stamp.createdAt,
type: "task.completed",
payload: {
...childPayload,
status: state === "done" ? "completed" : "failed",
...(readString(item.error) ? { summary: readString(item.error) } : {}),
},
});
} else {
yield* offerRuntimeEvent({
...base,
eventId: stamp.eventId,
createdAt: stamp.createdAt,
type: "task.progress",
payload: childPayload,
});
}
}
}
return;
}
case "task_updated": {
const record = message as unknown as Record<string, unknown>;
// SDK shape: {task_id, patch: {status?, description?, end_time?, is_backgrounded?, error?}}
const patch =
record.patch !== null && typeof record.patch === "object" && !Array.isArray(record.patch)
? (record.patch as Record<string, unknown>)
: {};
const status = readString(patch.status);
const patchedDescription = readString(patch.description);
const endTime =
typeof patch.end_time === "number" ? epochMillisToIso(patch.end_time) : undefined;
yield* offerRuntimeEvent({
...base,
type: "task.updated",
payload: {
taskId: RuntimeTaskId.make(String(record.task_id)),
...(status === "pending" ||
status === "running" ||
status === "completed" ||
status === "failed" ||
status === "killed" ||
status === "paused"
? { status }
: {}),
...(endTime ? { endTime } : {}),
...(patchedDescription ? { name: patchedDescription } : {}),
...(typeof patch.is_backgrounded === "boolean"
? { isBackgrounded: patch.is_backgrounded }
: {}),
...(readString(patch.error) ? { errorMessage: readString(patch.error) } : {}),
},
});
return;
case "task_notification":
}
case "task_notification": {
const record = message as unknown as Record<string, unknown>;
const usage = normalizeRuntimeTaskUsage(record.usage);
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2718,10 +2951,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
taskId: RuntimeTaskId.make(message.task_id),
status: message.status,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(usage ? { usage } : {}),
...(readString(record.output_file)
? { outputFile: readString(record.output_file) }
: {}),
...(readString(record.tool_use_id)
? { toolUseId: readString(record.tool_use_id) }
: {}),
},
});
return;
}
case "files_persisted":
yield* offerRuntimeEvent({
...base,
@@ -2746,6 +2986,52 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
case "thinking_tokens":
return;
case "api_retry":
// Transport-level retry heartbeat. Surfacing each attempt as a
// warning row spammed the work log (10 rows during a 502 storm);
// the terminal result/error path reports the actual failure. Keep
// the session visibly alive instead.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state: "running",
reason: `api_retry:${message.attempt}/${message.max_retries}`,
},
});
return;
case "session_state_changed":
// Authoritative turn-over signal from the CLI.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state:
message.state === "running"
? "running"
: message.state === "requires_action"
? "waiting"
: "ready",
reason: `session_state:${message.state}`,
},
});
return;
case "notification":
// User-facing CLI notification (e.g. context-limit warnings). Only
// high-priority ones warrant a work-log row.
if (message.priority === "high" || message.priority === "immediate") {
yield* emitRuntimeWarning(context, message.text, message);
}
return;
// Inner protocol/UX details with no T3 surface today — consumed
// deliberately so they don't masquerade as unknown-subtype warnings.
case "model_refusal_fallback":
case "local_command_output":
case "plugin_install":
case "commands_changed":
case "memory_recall":
case "elicitation_complete":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
@@ -2765,13 +3051,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
message,
);
return;
default:
default: {
// Exhaustiveness guard: every subtype in the SDK's typed union is
// handled above, so `message` narrows to never here — a new SDK
// release adding a subtype fails this typecheck instead of silently
// warning at runtime. The runtime fallback still catches undeclared
// wire-only subtypes (like background_tasks_changed used to be).
message satisfies never;
const unknownMessage = message as never as { subtype: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
message,
);
return;
}
}
});
@@ -2879,13 +3173,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
return;
default:
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
return;
default: {
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
// message types fail typecheck here instead of warning at runtime.
message satisfies never;
const unknownMessage = message as never as { type: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
message,
);
return;
}
}
});
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -214,6 +214,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -243,6 +244,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -369,8 +371,22 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
return effort === "ultracode";
}
export function resolveClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): string | undefined {
const caps = getClaudeModelCapabilities(modelSelection?.model);
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
});
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
const value = getProviderOptionCurrentValue(descriptor);
return typeof value === "string" ? value : undefined;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
@@ -555,6 +555,129 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps collab/agentActivity turn lifecycle to timeline-bypassing task events", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
yield* runtime.emit({
id: asEventId("evt-collab-turn-start"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
method: "collab/agentActivity",
threadId: asThreadId("thread-1"),
payload: {
agentThreadId: "child-thread-1",
agentPath: "/root/marlow",
method: "turn/started",
params: { threadId: "child-thread-1", turn: { id: "child-turn-1" } },
},
});
const firstEvent = yield* Fiber.join(firstEventFiber);
NodeAssert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
NodeAssert.equal(firstEvent.value.type, "task.started");
if (firstEvent.value.type !== "task.started") {
return;
}
NodeAssert.equal(firstEvent.value.payload.taskId, "child-thread-1");
NodeAssert.equal(firstEvent.value.payload.name, "marlow");
NodeAssert.equal(firstEvent.value.payload.timelineBypass, true);
}),
);
it.effect("maps collab child turn/completed to an idle task.updated", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
yield* runtime.emit({
id: asEventId("evt-collab-turn-complete"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:01.000Z",
method: "collab/agentActivity",
threadId: asThreadId("thread-1"),
payload: {
agentThreadId: "child-thread-1",
agentPath: "/root/marlow",
method: "turn/completed",
params: { threadId: "child-thread-1", turn: { id: "child-turn-1" } },
},
});
const firstEvent = yield* Fiber.join(firstEventFiber);
NodeAssert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
NodeAssert.equal(firstEvent.value.type, "task.updated");
if (firstEvent.value.type !== "task.updated") {
return;
}
NodeAssert.equal(firstEvent.value.payload.status, "idle");
NodeAssert.equal(firstEvent.value.payload.timelineBypass, true);
}),
);
it.effect("maps collab child token usage to task.progress with normalized usage", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
yield* runtime.emit({
id: asEventId("evt-collab-usage"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:02.000Z",
method: "collab/agentActivity",
threadId: asThreadId("thread-1"),
payload: {
agentThreadId: "child-thread-1",
agentPath: "/root/marlow",
method: "thread/tokenUsage/updated",
params: {
threadId: "child-thread-1",
turnId: "child-turn-1",
tokenUsage: {
total: {
totalTokens: 4200,
inputTokens: 4000,
cachedInputTokens: 1000,
outputTokens: 200,
reasoningOutputTokens: 50,
},
last: {
totalTokens: 4200,
inputTokens: 4000,
cachedInputTokens: 1000,
outputTokens: 200,
reasoningOutputTokens: 50,
},
modelContextWindow: 272_000,
},
},
},
});
const firstEvent = yield* Fiber.join(firstEventFiber);
NodeAssert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
NodeAssert.equal(firstEvent.value.type, "task.progress");
if (firstEvent.value.type !== "task.progress") {
return;
}
const usage = firstEvent.value.payload.usage as { totalTokens?: number } | undefined;
NodeAssert.equal(usage?.totalTokens, 4200);
}),
);
it.effect("labels MCP lifecycle entries with server and tool names", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
@@ -20,6 +20,7 @@ import {
type ProviderUserInputAnswers,
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
ProviderApprovalDecision,
ThreadId,
ProviderSendTurnInput,
@@ -494,10 +495,212 @@ function mapItemLifecycle(
};
}
/**
* Codex v2 collab child threads have no task lifecycle of their own — the
* session runtime intercepts their notifications and forwards them wrapped as
* `collab/agentActivity`. Translate into the shared `task.*` family so the
* ingestion agent reducer treats Codex children like Claude subagents. All
* synthesized events set `timelineBypass` so they never become timeline rows.
*
* Probe-verified mapping (codex-cli 0.144.1): children emit no
* `thread/started`; their first event is `thread/status/changed`. Nicknames
* arrive via the parent's `subAgentActivity.agentPath` (`/root/<nickname>`).
* `turn/completed` means idle-and-resumable, not terminal.
*/
function mapCollabAgentActivity(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): ReadonlyArray<ProviderRuntimeEvent> {
const wrapper =
event.payload !== null && typeof event.payload === "object"
? (event.payload as {
agentThreadId?: unknown;
agentPath?: unknown;
method?: unknown;
params?: unknown;
})
: undefined;
if (!wrapper || typeof wrapper.agentThreadId !== "string" || typeof wrapper.method !== "string") {
return [];
}
const agentThreadId = wrapper.agentThreadId;
const agentPath = typeof wrapper.agentPath === "string" ? wrapper.agentPath : undefined;
// "/root/marlow" → "marlow"
const nickname = agentPath?.split("/").filter(Boolean).at(-1);
const inner: ProviderEvent = {
...event,
method: wrapper.method,
...(wrapper.params !== undefined ? { payload: wrapper.params } : {}),
};
const base = {
...runtimeEventBase(event, canonicalThreadId),
payload: {
taskId: RuntimeTaskId.make(agentThreadId),
description: nickname ?? agentThreadId,
name: nickname ?? agentThreadId,
taskType: "local_agent",
timelineBypass: true,
},
} as const;
switch (wrapper.method) {
case "turn/started":
return [{ ...base, type: "task.started", payload: { ...base.payload } }];
case "turn/completed": {
const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, inner.payload);
const turnStatus = payload?.turn.status;
const errorMessage = payload?.turn.error?.message;
if (turnStatus === "failed") {
return [
{
...base,
type: "task.completed",
payload: {
taskId: base.payload.taskId,
status: "failed",
...(errorMessage ? { summary: errorMessage } : {}),
timelineBypass: true,
},
},
];
}
if (turnStatus === "interrupted") {
return [
{
...base,
type: "task.completed",
payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true },
},
];
}
// completed (or unparseable payload): the identity is idle-and-resumable.
return [
{
...base,
type: "task.updated",
payload: { taskId: base.payload.taskId, status: "idle", timelineBypass: true },
},
];
}
case "subAgent/interrupted":
return [
{
...base,
type: "task.completed",
payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true },
},
];
case "thread/status/changed": {
const payload = readPayload(
EffectCodexSchema.V2ThreadStatusChangedNotification,
inner.payload,
);
const status = payload?.status;
if (!status) return [];
if (status.type === "active") {
// Flags (waitingOnApproval/waitingOnUserInput) mean blocked; active
// with no flags means the wait resolved and the agent is running again.
return [
{
...base,
type: "task.updated",
payload: {
taskId: base.payload.taskId,
status: status.activeFlags.length > 0 ? "waiting" : "running",
timelineBypass: true,
},
},
];
}
if (status.type === "systemError") {
return [
{
...base,
type: "task.completed",
payload: {
taskId: base.payload.taskId,
status: "failed",
summary: "Codex reported a system error for this agent",
timelineBypass: true,
},
},
];
}
// notLoaded/idle are covered by turn lifecycle events.
return [];
}
case "thread/closed":
return [
{
...base,
type: "task.completed",
payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true },
},
];
case "thread/tokenUsage/updated": {
const payload = readPayload(
EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,
inner.payload,
);
// All fields from the cumulative `total` breakdown — mixing the
// cumulative total with `last` (per-turn) breakdowns would make the
// numbers internally inconsistent, and `last` can shrink on follow-ups.
const total = payload?.tokenUsage.total;
if (!total || total.totalTokens <= 0) return [];
return [
{
...base,
type: "task.progress",
payload: {
...base.payload,
usage: {
totalTokens: total.totalTokens,
inputTokens: total.inputTokens,
cachedInputTokens: total.cachedInputTokens,
outputTokens: total.outputTokens,
reasoningOutputTokens: total.reasoningOutputTokens,
},
},
},
];
}
case "item/started":
case "item/completed": {
const payload =
readPayload(EffectCodexSchema.V2ItemStartedNotification, inner.payload) ??
readPayload(EffectCodexSchema.V2ItemCompletedNotification, inner.payload);
const item = payload?.item;
if (!item) return [];
const itemType = toCanonicalItemType(item.type);
const title = itemTitle(itemType, item);
const detail = itemDetail(itemType, item);
const summary = detail ?? title;
if (!summary) return [];
return [
{
...base,
type: "task.progress",
payload: {
...base.payload,
description: summary,
summary,
...(title ? { lastToolName: title } : {}),
},
},
];
}
default:
return [];
}
}
function mapToRuntimeEvents(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): ReadonlyArray<ProviderRuntimeEvent> {
if (event.kind === "notification" && event.method === "collab/agentActivity") {
return mapCollabAgentActivity(event, canonicalThreadId);
}
if (event.kind === "error") {
if (!event.message) {
return [];
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -102,3 +102,45 @@ it("uses standard routing when the catalog has no default service tier", () => {
},
]);
});
it("marks the most preferred available model as default", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
[
{ slug: "gpt-5.6-terra", isDefault: true },
{ slug: "gpt-5.4", isDefault: undefined },
],
);
});
it("prefers sol over terra when both are available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
});
it("keeps Codex's own default when no preferred model is available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
it("ignores custom models that shadow a preferred slug", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
@@ -22,7 +22,7 @@ import type {
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
import { ServerSettingsError } from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -189,10 +189,36 @@ function parseCodexModelListResponse(
slug: model.model,
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
/**
* Prefer our own default-model ranking when one of the preferred slugs is in
* the live catalog; otherwise keep whatever Codex itself flagged as default.
*/
export function applyPreferredCodexDefaultModel(
models: ReadonlyArray<ServerProviderModel>,
): ReadonlyArray<ServerProviderModel> {
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
models.some((model) => model.slug === slug && !model.isCustom),
);
if (!preferredSlug) {
return models;
}
return models.map((model) => {
if (model.slug === preferredSlug) {
return model.isDefault ? model : { ...model, isDefault: true };
}
if (!model.isDefault) {
return model;
}
const { isDefault: _isDefault, ...rest } = model;
return rest;
});
}
function appendCustomCodexModels(
models: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
@@ -376,7 +402,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
return {
account: accountResponse,
version,
models: appendCustomCodexModels(models, input.customModels ?? []),
models: applyPreferredCodexDefaultModel(
appendCustomCodexModels(models, input.customModels ?? []),
),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
});
@@ -585,6 +585,41 @@ function readRouteFields(notification: CodexServerNotification): {
}
}
interface CollabChildAgent {
readonly agentPath: string | undefined;
readonly interrupted: boolean;
}
/**
* v2 collab children announce themselves only via `subAgentActivity` items on
* the parent stream (the probe shows no child `thread/started`, and v2
* `collabAgentToolCall` items carry empty receiver lists). Track them so their
* notifications can be folded into agent telemetry instead of leaking into the
* parent timeline as unattributed items. Returns the interruption transition
* when this notification carries one, so the caller can emit a terminal event.
*/
function rememberSubAgentActivity(
childAgents: Map<string, CollabChildAgent>,
notification: CodexServerNotification,
): { readonly agentThreadId: string; readonly agentPath: string } | undefined {
if (notification.method !== "item/started" && notification.method !== "item/completed") {
return undefined;
}
const item = notification.params.item;
if (item.type !== "subAgentActivity") {
return undefined;
}
const interrupted = item.kind === "interrupted";
const previous = childAgents.get(item.agentThreadId);
childAgents.set(item.agentThreadId, { agentPath: item.agentPath, interrupted });
return interrupted && !previous?.interrupted
? { agentThreadId: item.agentThreadId, agentPath: item.agentPath }
: undefined;
}
/** Synthetic method carrying an intercepted child-thread notification. */
export const COLLAB_AGENT_ACTIVITY_METHOD = "collab/agentActivity";
function rememberCollabReceiverTurns(
collabReceiverTurns: Map<string, TurnId>,
notification: CodexServerNotification,
@@ -708,6 +743,7 @@ 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, CollabChildAgent>());
const closedRef = yield* Ref.make(false);
// `~` is not shell-expanded when env vars are set via
@@ -829,14 +865,76 @@ export const makeCodexSessionRuntime = (
const payload = notification.params;
const route = readRouteFields(notification);
const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef);
const childParentTurnId = (() => {
const providerConversationId = readNotificationThreadId(notification);
return providerConversationId
? collabReceiverTurns.get(providerConversationId)
: undefined;
})();
const collabChildAgents = yield* Ref.get(collabChildAgentsRef);
const notificationThreadId = readNotificationThreadId(notification);
const childParentTurnId = notificationThreadId
? collabReceiverTurns.get(notificationThreadId)
: undefined;
rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);
const interruption = rememberSubAgentActivity(collabChildAgents, notification);
yield* Ref.set(collabChildAgentsRef, collabChildAgents);
if (interruption) {
// Surface the interruption as its own child event so the agent
// tracker can terminalize the child (the child thread itself goes
// silent when interrupted).
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
method: COLLAB_AGENT_ACTIVITY_METHOD,
payload: {
agentThreadId: interruption.agentThreadId,
agentPath: interruption.agentPath,
method: "subAgent/interrupted",
},
});
}
// v2 collab child threads: their notifications arrive on this
// connection keyed by the child threadId. Divert the whole stream into
// a synthetic collab/agentActivity event for the agent tracker and keep
// it out of the parent timeline. A child's first event can arrive
// BEFORE the parent's subAgentActivity registers it (probe: child
// thread/status/changed lands first), so any thread that is neither
// the session's own provider thread nor a v1 collab receiver is
// treated as an unregistered child.
const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
// Re-check v1 receiver registration on every notification: if a
// thread was provisionally classified as a v2 child before the
// parent's collabAgentToolCall arrived, hand it back to the v1
// suppression path once the receiver registration lands.
const knownChild =
notificationThreadId && !collabReceiverTurns.has(notificationThreadId)
? collabChildAgents.get(notificationThreadId)
: undefined;
const isForeignThread =
notificationThreadId !== undefined &&
providerThreadId !== undefined &&
notificationThreadId !== providerThreadId &&
!collabReceiverTurns.has(notificationThreadId);
if (notificationThreadId && (knownChild || isForeignThread)) {
if (!knownChild) {
yield* Ref.update(collabChildAgentsRef, (current) => {
const next = new Map(current);
next.set(notificationThreadId, { agentPath: undefined, interrupted: false });
return next;
});
}
yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
method: COLLAB_AGENT_ACTIVITY_METHOD,
payload: {
agentThreadId: notificationThreadId,
...(knownChild?.agentPath ? { agentPath: knownChild.agentPath } : {}),
method: notification.method,
params: payload,
},
});
return;
}
if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) {
yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
return;
@@ -1,76 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
ghosttyThemeSearchPaths,
parseGhosttyConfig,
splitThemeSelection,
} from "./ghosttyStyle.ts";
const posixPath = {
isAbsolute: (value: string) => value.startsWith("/"),
join: (...segments: ReadonlyArray<string>) =>
segments
.map((segment, index) =>
index === 0 ? segment.replace(/\/$/, "") : segment.replace(/^\//, ""),
)
.join("/"),
};
const windowsPath = {
isAbsolute: (value: string) => /^[A-Za-z]:[\\/]/.test(value),
join: (...segments: ReadonlyArray<string>) => segments.join("\\"),
};
describe("parseGhosttyConfig", () => {
it("omits empty scalar color assignments", () => {
const config = parseGhosttyConfig(`
background =
foreground = ""
cursor-color = #c0ffee
`);
expect(config.colors.background).toBeUndefined();
expect(config.colors.foreground).toBeUndefined();
expect(config.colors.cursor).toBe("#c0ffee");
});
});
describe("splitThemeSelection", () => {
it("keeps a Windows absolute theme path as a bare selection", () => {
expect(splitThemeSelection("C:/Users/Alex/Ghostty Themes/t3code")).toEqual({
light: "C:/Users/Alex/Ghostty Themes/t3code",
dark: "C:/Users/Alex/Ghostty Themes/t3code",
});
});
it("still parses explicit light and dark theme selections", () => {
expect(splitThemeSelection("light:Day,dark:Night")).toEqual({
light: "Day",
dark: "Night",
});
});
});
describe("ghosttyThemeSearchPaths", () => {
it("searches beside the macOS Application Support config", () => {
const candidates = ghosttyThemeSearchPaths(posixPath, {
home: "/Users/alex",
xdgConfigHome: "/Users/alex/.config",
themeName: "t3code",
});
expect(candidates).toContain(
"/Users/alex/Library/Application Support/com.mitchellh.ghostty/themes/t3code",
);
});
it("tries an absolute theme file before named-theme directories", () => {
const candidates = ghosttyThemeSearchPaths(windowsPath, {
home: "C:\\Users\\alex",
xdgConfigHome: "C:\\Users\\alex\\.config",
themeName: "D:\\themes\\t3code",
});
expect(candidates[0]).toBe("D:\\themes\\t3code");
});
});
-289
View File
@@ -1,289 +0,0 @@
import * as NodeOS from "node:os";
import type { ServerTerminalStyle, ServerTerminalThemeColors } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
const PALETTE_SIZE = 16;
interface GhosttyConfigValues {
readonly fontFamily: ReadonlyArray<string>;
readonly fontSize: number | undefined;
readonly theme: string | undefined;
readonly colors: MutableThemeColors;
}
interface MutableThemeColors {
background?: string | undefined;
foreground?: string | undefined;
cursor?: string | undefined;
selectionBackground?: string | undefined;
selectionForeground?: string | undefined;
palette: Array<string>;
}
function emptyColors(): MutableThemeColors {
return { palette: Array.from({ length: PALETTE_SIZE }, () => "") };
}
function stripQuotes(value: string): string {
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
return value.slice(1, -1);
}
return value;
}
function applyColorEntry(colors: MutableThemeColors, key: string, value: string): void {
// Empty assignments are resets, not colors. Keeping an empty scalar here
// would later violate ServerConfig's TrimmedNonEmptyString schema and make
// the whole server.getConfig response fail to encode.
if (value.length === 0) return;
switch (key) {
case "background":
colors.background = value;
return;
case "foreground":
colors.foreground = value;
return;
case "cursor-color":
colors.cursor = value;
return;
case "selection-background":
colors.selectionBackground = value;
return;
case "selection-foreground":
colors.selectionForeground = value;
return;
case "palette": {
const match = value.match(/^(\d+)\s*=\s*(\S+)$/);
if (!match) return;
const index = Number(match[1]);
if (!Number.isInteger(index) || index < 0 || index >= PALETTE_SIZE) return;
colors.palette[index] = match[2] ?? "";
return;
}
default:
return;
}
}
/** Parse Ghostty's `key = value` config format, keeping only what the web terminal uses. */
export function parseGhosttyConfig(source: string): GhosttyConfigValues {
const fontFamily: Array<string> = [];
let fontSize: number | undefined;
let theme: string | undefined;
const colors = emptyColors();
for (const rawLine of source.split("\n")) {
const line = rawLine.trim();
if (line.length === 0 || line.startsWith("#")) continue;
const separatorIndex = line.indexOf("=");
if (separatorIndex <= 0) continue;
const key = line.slice(0, separatorIndex).trim();
const value = stripQuotes(line.slice(separatorIndex + 1).trim());
switch (key) {
case "font-family":
// Repeated entries build a fallback chain; an empty value resets it.
if (value.length === 0) {
fontFamily.length = 0;
} else {
fontFamily.push(value);
}
break;
case "font-size": {
const parsed = Number(value);
if (Number.isFinite(parsed) && parsed > 0) {
fontSize = parsed;
}
break;
}
case "theme":
theme = value.length > 0 ? value : undefined;
break;
default:
applyColorEntry(colors, key, value);
break;
}
}
return { fontFamily, fontSize, theme, colors };
}
/** Split `theme = light:A,dark:B` into per-mode names; a bare name applies to both. */
export function splitThemeSelection(theme: string): { light?: string; dark?: string } {
const result: { light?: string; dark?: string } = {};
let hasModeSelection = false;
for (const part of theme.split(",")) {
const match = /^\s*(light|dark):(.*)$/.exec(part);
if (!match) continue;
const mode = match[1];
const name = (match[2] ?? "").trim();
if (name.length === 0) continue;
hasModeSelection = true;
if (mode === "light") result.light = name;
if (mode === "dark") result.dark = name;
}
// A colon is also part of a Windows drive path (C:/theme), and may be part
// of another valid bare theme identifier. Only enter per-mode parsing when
// an explicit light: or dark: selection was recognized.
return hasModeSelection ? result : { light: theme, dark: theme };
}
function hasAnyColor(colors: MutableThemeColors): boolean {
return (
colors.background !== undefined ||
colors.foreground !== undefined ||
colors.cursor !== undefined ||
colors.selectionBackground !== undefined ||
colors.selectionForeground !== undefined ||
colors.palette.some((entry) => entry.length > 0)
);
}
function mergeColors(base: MutableThemeColors, override: MutableThemeColors): MutableThemeColors {
return {
background: override.background ?? base.background,
foreground: override.foreground ?? base.foreground,
cursor: override.cursor ?? base.cursor,
selectionBackground: override.selectionBackground ?? base.selectionBackground,
selectionForeground: override.selectionForeground ?? base.selectionForeground,
palette: base.palette.map((entry, index) => {
const overrideEntry = override.palette[index] ?? "";
return overrideEntry.length > 0 ? overrideEntry : entry;
}),
};
}
function toThemeColors(colors: MutableThemeColors): ServerTerminalThemeColors | undefined {
if (!hasAnyColor(colors)) return undefined;
return {
...(colors.background !== undefined ? { background: colors.background } : {}),
...(colors.foreground !== undefined ? { foreground: colors.foreground } : {}),
...(colors.cursor !== undefined ? { cursor: colors.cursor } : {}),
...(colors.selectionBackground !== undefined
? { selectionBackground: colors.selectionBackground }
: {}),
...(colors.selectionForeground !== undefined
? { selectionForeground: colors.selectionForeground }
: {}),
palette: colors.palette,
};
}
// Bundled theme locations by platform: the macOS app bundle and the
// Linux system resource dirs documented by Ghostty.
const GHOSTTY_SYSTEM_THEME_DIRS = [
"/Applications/Ghostty.app/Contents/Resources/ghostty/themes",
"/usr/share/ghostty/themes",
"/usr/local/share/ghostty/themes",
];
export function ghosttyThemeSearchPaths(
path: Pick<Path.Path, "isAbsolute" | "join">,
input: { readonly home: string; readonly xdgConfigHome: string; readonly themeName: string },
): ReadonlyArray<string> {
return [
...(path.isAbsolute(input.themeName) ? [input.themeName] : []),
path.join(input.xdgConfigHome, "ghostty", "themes", input.themeName),
path.join(
input.home,
"Library",
"Application Support",
"com.mitchellh.ghostty",
"themes",
input.themeName,
),
...GHOSTTY_SYSTEM_THEME_DIRS.map((dir) => path.join(dir, input.themeName)),
];
}
/**
* Load terminal font and theme colors from the user's local Ghostty config.
* Best effort by design: any missing file or parse problem yields `undefined`
* so the client falls back to its built-in terminal appearance.
*/
export const loadGhosttyTerminalStyle: Effect.Effect<
ServerTerminalStyle | undefined,
never,
FileSystem.FileSystem | Path.Path
> = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = NodeOS.homedir();
// Per the XDG spec an empty XDG_CONFIG_HOME must be treated as unset.
const xdgConfigHomeEnv = process.env["XDG_CONFIG_HOME"];
const xdgConfigHome =
xdgConfigHomeEnv !== undefined && xdgConfigHomeEnv.length > 0
? xdgConfigHomeEnv
: path.join(home, ".config");
const readFirstExisting = (candidates: ReadonlyArray<string>) =>
Effect.gen(function* () {
for (const candidate of candidates) {
const exists = yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (!exists) continue;
const content = yield* fs
.readFileString(candidate)
.pipe(Effect.orElseSucceed(() => undefined));
if (content !== undefined) return content;
}
return undefined;
});
// Ghostty reads the XDG config first and the macOS Application Support
// config after it, so later files override earlier values. It also accepts
// config.ghostty as the file name. Merge every location that exists instead
// of stopping at the first match.
const configDirs = [
path.join(xdgConfigHome, "ghostty"),
path.join(home, "Library", "Application Support", "com.mitchellh.ghostty"),
];
const configSources: Array<string> = [];
for (const dir of configDirs) {
// Read both file names when they coexist so neither shadows the other;
// Ghostty loads config.ghostty before config, so config wins conflicts.
for (const candidate of [path.join(dir, "config.ghostty"), path.join(dir, "config")]) {
const source = yield* readFirstExisting([candidate]);
if (source !== undefined) configSources.push(source);
}
}
if (configSources.length === 0) return undefined;
const config = parseGhosttyConfig(configSources.join("\n"));
const loadThemeColors = (themeName: string) =>
Effect.gen(function* () {
const themeSource = yield* readFirstExisting(
ghosttyThemeSearchPaths(path, { home, xdgConfigHome, themeName }),
);
if (themeSource === undefined) return emptyColors();
return parseGhosttyConfig(themeSource).colors;
});
const themeSelection = config.theme ? splitThemeSelection(config.theme) : {};
const resolveModeColors = (themeName: string | undefined) =>
Effect.gen(function* () {
const themeColors = themeName ? yield* loadThemeColors(themeName) : emptyColors();
// Explicit colors in the user config override the selected theme.
return toThemeColors(mergeColors(themeColors, config.colors));
});
const light = yield* resolveModeColors(themeSelection.light);
const dark = yield* resolveModeColors(themeSelection.dark);
const style: ServerTerminalStyle = {
...(config.fontFamily.length > 0 ? { fontFamily: config.fontFamily } : {}),
...(config.fontSize !== undefined ? { fontSize: config.fontSize } : {}),
...(light !== undefined ? { light } : {}),
...(dark !== undefined ? { dark } : {}),
};
const hasAnyValue =
style.fontFamily !== undefined ||
style.fontSize !== undefined ||
style.light !== undefined ||
style.dark !== undefined;
return hasAnyValue ? style : undefined;
}).pipe(Effect.orElseSucceed(() => undefined));
@@ -596,6 +596,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("marks the origin default ref as default when no local copy exists", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
yield* git(cwd, ["branch", "-D", initialBranch]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const refs = yield* driver.listRefs({ cwd });
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
assert.equal(remoteDefault?.isRemote, true);
assert.equal(remoteDefault?.isDefault, true);
}),
);
it.effect("creates, checks out, renames, and lists refs", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+14 -2
View File
@@ -2217,7 +2217,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
name: refName.name,
current: false,
isRemote: true,
isDefault: false,
// origin/HEAD's target is the repo default even when no local
// copy of the default branch exists.
isDefault:
defaultBranch !== null &&
parsedRemoteRef?.remoteName === "origin" &&
parsedRemoteRef.branchName === defaultBranch,
worktreePath: null,
};
if (parsedRemoteRef) {
@@ -2232,9 +2237,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
})
: [];
const allBranches = input.includeMatchingRemoteRefs
const combinedBranches = input.includeMatchingRemoteRefs
? [...localBranches, ...remoteBranches]
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
// Keep current/default refs on the first page even when the default
// only exists as origin/<default> (remote refs sort after all locals).
const allBranches = combinedBranches.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
return aPriority - bPriority;
});
const branchesForKind =
input.refKind === "local"
? allBranches.filter((ref) => !ref.isRemote)
-3
View File
@@ -81,7 +81,6 @@ import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
import { loadGhosttyTerminalStyle } from "./terminal/ghosttyStyle.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -1066,7 +1065,6 @@ const makeWsRpcLayer = (
const loadServerConfig = Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.loadConfigState;
const terminalStyle = yield* loadGhosttyTerminalStyle;
const providers = yield* providerRegistry.getProviders;
const settings = ServerSettings.redactServerSettingsForClient(
yield* serverSettings.getSettings,
@@ -1083,7 +1081,6 @@ const makeWsRpcLayer = (
issues: keybindingsConfig.issues,
providers,
availableEditors: yield* externalLauncher.resolveAvailableEditors(),
...(terminalStyle !== undefined ? { terminalStyle } : {}),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
+2 -1
View File
@@ -31,9 +31,10 @@
"@t3tools/shared": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-router": "^1.160.2",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"ghostty-web": "0.4.0",
"jose": "catalog:",
"lexical": "^0.41.0",
"lucide-react": "^0.564.0",
+348
View File
@@ -0,0 +1,348 @@
import { memo, useEffect, useRef, useState } from "react";
import type { ThreadAgentSnapshot } from "@t3tools/contracts";
import {
deriveAgentPanelState,
formatAgentTokenCount,
isTerminalAgentStatus,
type AgentPanelGroup,
type AgentPanelPhase,
} from "@t3tools/client-runtime/state/thread-agents";
import { BotIcon, BracesIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { ScrollArea } from "./ui/scroll-area";
import { formatDuration } from "../session-logic";
import { parseTimestampDate } from "../timestampFormat";
interface AgentsPanelProps {
agents: ReadonlyArray<ThreadAgentSnapshot>;
onOpenScript?: (scriptPath: string) => void;
mode?: "sheet" | "sidebar" | "embedded";
}
const STATUS_DOT_CLASS: Record<ThreadAgentSnapshot["status"], string> = {
pending: "bg-muted-foreground/40",
running: "bg-sky-500 animate-status-pulse",
waiting: "bg-warning animate-status-pulse",
idle: "bg-sky-500/50",
completed: "bg-success",
failed: "bg-destructive",
stopped: "bg-muted-foreground/60",
};
const STATUS_LABEL: Record<ThreadAgentSnapshot["status"], string> = {
pending: "Queued",
running: "Running",
waiting: "Waiting",
idle: "Idle · resumable",
completed: "Completed",
failed: "Failed",
stopped: "Stopped",
};
function AgentStatusDot({ status }: { status: ThreadAgentSnapshot["status"] }) {
return (
<span
className={cn("size-1.75 shrink-0 rounded-full", STATUS_DOT_CLASS[status])}
role="img"
aria-label={STATUS_LABEL[status]}
/>
);
}
/**
* Self-ticking elapsed label (WorkingTimer pattern): writes its own text node
* so per-second updates never cause React commits. Frozen once `endedAt` is
* set or the agent settles.
*/
function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) {
const textRef = useRef<HTMLSpanElement>(null);
const settled = isTerminalAgentStatus(agent.status) || agent.status === "idle";
// Current-activation start (falls back to firstStartedAt for pre-field
// snapshots) so a resumed agent's timer excludes prior runs and idle gaps.
const startMs =
parseTimestampDate(agent.lastStartedAt ?? agent.firstStartedAt)?.getTime() ?? null;
const endMs =
(agent.endedAt ? parseTimestampDate(agent.endedAt)?.getTime() : null) ??
(settled ? (parseTimestampDate(agent.lastActivityAt)?.getTime() ?? null) : null);
const initialText =
startMs === null ? null : formatDuration(Math.max(0, (endMs ?? Date.now()) - startMs));
useEffect(() => {
if (startMs === null || endMs !== null) return;
const update = () => {
if (textRef.current) {
textRef.current.textContent = formatDuration(Math.max(0, Date.now() - startMs));
}
};
update();
const id = setInterval(update, 1000);
return () => clearInterval(id);
}, [startMs, endMs]);
if (initialText === null) {
return null;
}
return (
<span ref={textRef} className="font-mono text-[11px] tabular-nums text-muted-foreground">
{initialText}
</span>
);
}
function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) {
const [expanded, setExpanded] = useState(false);
const settled = isTerminalAgentStatus(agent.status);
// Settled cards lead with outcome (error first); live cards with activity.
const activity =
agent.status === "waiting"
? "Waiting on approval or input"
: settled || agent.status === "idle"
? (agent.errorMessage ??
agent.resultSummary ??
agent.currentActivity ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null))
: (agent.currentActivity ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
agent.resultSummary ??
agent.errorMessage);
const hasFeed = agent.recentActivity.length > 0;
return (
<button
type="button"
onClick={() => hasFeed && setExpanded((value) => !value)}
className={cn(
"w-full rounded-lg border border-border/60 bg-card px-3 py-2 text-left",
hasFeed && "cursor-pointer hover:border-border",
settled && "opacity-70",
)}
>
<div className="flex items-center gap-2">
<AgentStatusDot status={agent.status} />
<span className="min-w-0 truncate text-[12.5px] font-semibold">{agent.name}</span>
{agent.agentType ? (
<Badge variant="secondary" size="sm" className="min-w-0 max-w-28 shrink truncate">
{agent.agentType}
</Badge>
) : null}
{agent.model ? (
<Badge variant="outline" size="sm" className="shrink-0 text-muted-foreground">
{agent.model}
</Badge>
) : null}
<span className="ml-auto shrink-0">
<AgentElapsed agent={agent} />
</span>
{agent.status === "completed" ? (
<CheckIcon className="size-3 shrink-0 text-success" />
) : null}
</div>
{activity ? (
<div
className={cn(
"mt-1 truncate text-[11.5px]",
agent.status === "failed" ? "text-destructive-foreground" : "text-muted-foreground",
)}
>
{activity}
</div>
) : null}
<div className="mt-1.5 flex items-center gap-2 text-[11px] text-muted-foreground">
{agent.usage ? (
<span className="font-mono tabular-nums text-foreground">
{formatAgentTokenCount(agent.usage.totalTokens)}{" "}
<span className="text-muted-foreground">tok</span>
{agent.status === "running" ? <span className="text-sky-500"> ↑</span> : null}
</span>
) : null}
{agent.usage?.toolUses ? (
<>
<span className="text-border">·</span>
<span>{agent.usage.toolUses} tools</span>
</>
) : null}
{agent.activationCount > 1 ? (
<>
<span className="text-border">·</span>
<span>run {agent.activationCount}</span>
</>
) : null}
{hasFeed ? (
<span className="ml-auto text-muted-foreground/70">
{expanded ? (
<ChevronDownIcon className="size-3" />
) : (
<ChevronRightIcon className="size-3" />
)}
</span>
) : null}
</div>
{expanded && hasFeed ? (
<div className="mt-2 space-y-0.5 border-t border-border/60 pt-2">
{agent.recentActivity.toReversed().map((entry) => (
<div key={`${entry.at}-${entry.summary}`} className="flex gap-2 text-[11px]">
<span className="shrink-0 font-mono tabular-nums text-muted-foreground/60">
{entry.at.slice(11, 19)}
</span>
<span className="truncate text-muted-foreground">{entry.summary}</span>
</div>
))}
</div>
) : null}
</button>
);
}
function PhaseHeader({ phase }: { phase: AgentPanelPhase }) {
// "active" (not just status==="running"): a phase whose agents are all
// pending/waiting is still in progress and must not read "0 running".
const doneCount = phase.agents.filter(
(agent) => agent.status === "idle" || isTerminalAgentStatus(agent.status),
).length;
const activeCount = phase.agents.length - doneCount;
return (
<div className="flex items-center gap-2 px-1 pt-2 pb-1 text-[10px] text-muted-foreground">
<span
className={cn(
"font-bold tracking-wider uppercase",
phase.status === "done" && "text-success-foreground",
phase.status === "running" && "text-sky-500",
phase.status === "pending" && "opacity-50",
)}
>
{phase.status === "done" ? "✓ " : ""}
{phase.title}
</span>
{phase.status === "running" ? (
<span>
{activeCount} active{doneCount > 0 ? ` · ${doneCount} done` : ""}
</span>
) : phase.status === "pending" ? (
<span>pending</span>
) : null}
<span className="h-px flex-1 bg-border/60" />
</div>
);
}
function AgentGroup({
group,
onOpenScript,
}: {
group: AgentPanelGroup;
onOpenScript?: ((scriptPath: string) => void) | undefined;
}) {
const scriptPath = group.workflow?.scriptPath;
return (
<div>
<div className="flex items-center gap-2 px-1 pb-1 text-[10.5px] font-bold tracking-wider text-muted-foreground uppercase">
{group.workflow ? (
<>
<span className="truncate">Workflow · {group.workflow.name}</span>
{scriptPath && onOpenScript ? (
<span
role="button"
tabIndex={0}
onClick={(event) => {
event.stopPropagation();
onOpenScript(scriptPath);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.stopPropagation();
onOpenScript(scriptPath);
}
}}
className="inline-flex cursor-pointer items-center gap-1 font-mono text-[10px] font-medium tracking-normal text-primary normal-case hover:underline"
>
<BracesIcon className="size-3" /> script
</span>
) : null}
</>
) : (
<span>Direct spawns</span>
)}
<span className="h-px flex-1 bg-border/60" />
</div>
{/* A failed/errored workflow with no member rows would otherwise render
as a bare header — surface the container itself so its status and
error are visible. */}
{group.workflow &&
group.rest.length === 0 &&
group.phases.every((phase) => phase.agents.length === 0) &&
(group.workflow.status === "failed" ||
group.workflow.status === "stopped" ||
group.workflow.errorMessage) ? (
<div className="space-y-1.5">
<AgentCard agent={group.workflow} />
</div>
) : null}
{group.phases.map((phase) => (
<div key={phase.index}>
<PhaseHeader phase={phase} />
<div className="space-y-1.5">
{phase.agents.map((agent) => (
<AgentCard key={agent.agentId} agent={agent} />
))}
</div>
</div>
))}
{group.rest.length > 0 ? (
<div className={cn("space-y-1.5", group.phases.length > 0 && "pt-2")}>
{group.rest.map((agent) => (
<AgentCard key={agent.agentId} agent={agent} />
))}
</div>
) : null}
</div>
);
}
const AgentsPanel = memo(function AgentsPanel({ agents, onOpenScript, mode }: AgentsPanelProps) {
const state = deriveAgentPanelState(agents);
if (agents.length === 0) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
<BotIcon className="size-8 text-muted-foreground/40" />
<p className="text-sm font-medium">No agents yet</p>
<p className="text-xs text-muted-foreground">
When this thread spawns subagents or runs a workflow, they show up here with live status
and token usage.
</p>
</div>
);
}
return (
<div className={cn("flex h-full min-h-0 flex-col", mode === "embedded" && "bg-transparent")}>
<ScrollArea className="min-h-0 flex-1">
<div className="space-y-4 p-3">
{state.groups.map((group, index) => (
<AgentGroup
key={group.workflow?.agentId ?? `direct-${index}`}
group={group}
onOpenScript={onOpenScript}
/>
))}
</div>
</ScrollArea>
<div className="flex items-center gap-3 border-t border-border/60 px-3.5 py-2 text-[11px] text-muted-foreground">
{state.runningCount > 0 ? (
<span className="flex items-center gap-1.5">
<span className="size-1.75 rounded-full bg-sky-500 animate-status-pulse" />
{state.runningCount} running
</span>
) : null}
{state.waitingCount > 0 ? <span>{state.waitingCount} waiting</span> : null}
{state.settledCount > 0 ? <span>{state.settledCount} settled</span> : null}
<span className="ml-auto font-mono tabular-nums">
Σ {formatAgentTokenCount(state.totalTokens)} tok
</span>
</div>
</div>
);
});
export default AgentsPanel;
@@ -12,6 +12,7 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -119,6 +120,44 @@ describe("resolveEnvironmentOptionLabel", () => {
});
});
describe("shouldShowEnvironmentIndicator", () => {
it("shows the indicator whenever multiple environments are pickable", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: true,
}),
).toBe(true);
});
it("shows a sole remote environment so the user knows where the project runs", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: false },
canPickEnvironment: false,
}),
).toBe(true);
});
it("hides a sole primary (this-device) environment", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: false,
}),
).toBe(false);
});
it("hides the indicator when the active environment is unknown", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: null,
canPickEnvironment: false,
}),
).toBe(false);
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
@@ -42,6 +42,17 @@ export function resolveEnvironmentOptionLabel(input: {
return runtimeLabel ?? savedLabel ?? input.environmentId;
}
// A remote (non-primary) environment is always surfaced, even when it is the
// only environment available: with a single connected machine there is nothing
// to pick, but the user still needs to see where the project runs.
export function shouldShowEnvironmentIndicator(input: {
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
canPickEnvironment: boolean;
}): boolean {
if (input.canPickEnvironment) return true;
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
+14 -4
View File
@@ -20,6 +20,7 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
@@ -60,6 +61,7 @@ interface MobileRunContextSelectorProps {
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[] | undefined;
showEnvironmentPicker: boolean;
showEnvironmentIndicator: boolean;
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -72,6 +74,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
environmentId,
availableEnvironments,
showEnvironmentPicker,
showEnvironmentIndicator,
onEnvironmentChange,
effectiveEnvMode,
activeWorktreePath,
@@ -94,7 +97,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
: resolveCurrentWorkspaceLabel(activeWorktreePath);
const isLocked = envLocked || envModeLocked;
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const icon = showEnvironmentPicker ? (
const icon = showEnvironmentIndicator ? (
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
<span className="inline-flex shrink-0 items-center gap-0.5">
@@ -108,7 +111,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<>
{icon}
<span className="min-w-0 truncate">
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
</span>
</>
);
@@ -234,6 +237,12 @@ export const BranchToolbar = memo(function BranchToolbar({
const showEnvironmentPicker = Boolean(
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
);
const activeEnvironmentOption =
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: showEnvironmentPicker,
});
const isMobile = useIsMobile();
if (!hasActiveThread || !activeProject) return null;
@@ -247,6 +256,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
@@ -254,13 +264,13 @@ export const BranchToolbar = memo(function BranchToolbar({
/>
) : (
<div className="flex min-w-0 shrink-0 items-center gap-1">
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
{showEnvironmentIndicator && availableEnvironments && (
<>
<BranchToolbarEnvironmentSelector
envLocked={envLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
onEnvironmentChange={onEnvironmentChange}
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
</>
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
});
};
// Default the worktree base to the repo default branch (origin/HEAD), only
// falling back to the checked-out branch when no default is known.
const defaultBranchName = useMemo(
() => refs.find((refName) => refName.isDefault)?.name ?? null,
[refs],
);
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
!worktreeBaseBranchCandidate
) {
return;
}
setThreadBranch(currentGitBranch, null);
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
setThreadBranch(worktreeBaseBranchCandidate, null);
}, [
activeThreadBranch,
activeWorktreePath,
effectiveEnvMode,
setThreadBranch,
worktreeBaseBranchCandidate,
]);
// ---------------------------------------------------------------------------
// Combobox / list plumbing
@@ -17,7 +17,9 @@ interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange: (environmentId: EnvironmentId) => void;
// Absent when there is only one environment to show: the indicator still
// renders (as a static label) so remote projects are always identifiable.
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
@@ -39,7 +41,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
[availableEnvironments],
);
if (envLocked) {
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeEnvironment?.isPrimary ? (
+45
View File
@@ -85,6 +85,7 @@ import {
hasActionableProposedPlan,
isLatestTurnSettled,
} from "../session-logic";
import { deriveLatestAgentSnapshot } from "@t3tools/client-runtime/state/thread-agents";
import { type LegendListRef } from "@legendapp/list/react";
import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";
import {
@@ -136,6 +137,8 @@ import { RightPanelTabs } from "./RightPanelTabs";
import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import AgentsPanel from "./AgentsPanel";
import AgentsLiveStrip from "./chat/AgentsLiveStrip";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
@@ -1862,6 +1865,20 @@ function ChatViewContent(props: ChatViewProps) {
const phase = derivePhase(activeThread?.session ?? null);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const threadAgents = useMemo(
() => deriveLatestAgentSnapshot(threadActivities),
[threadActivities],
);
// Mirrors AgentsLiveStrip's own visibility rule so the wrapper doesn't
// reserve space (mb-1.5) after all agents settle.
const hasLiveAgents = useMemo(
() =>
threadAgents.some(
(agent) =>
agent.status === "running" || agent.status === "pending" || agent.status === "waiting",
),
[threadAgents],
);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
[threadActivities],
@@ -2926,6 +2943,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;
@@ -2933,6 +2954,21 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeProject, activeThreadRef],
);
// Workflow scripts live in the provider's session directory, outside the
// workspace root the file surface can read. Open in-workspace paths in the
// file surface; copy the absolute path otherwise.
const openAgentScript = useCallback(
(scriptPath: string) => {
if (activeWorkspaceRoot && scriptPath.startsWith(`${activeWorkspaceRoot}/`)) {
openFileSurface(scriptPath.slice(activeWorkspaceRoot.length + 1));
return;
}
void navigator.clipboard.writeText(scriptPath).then(() => {
toastManager.add({ title: "Script path copied", description: scriptPath });
});
},
[activeWorkspaceRoot, openFileSurface],
);
const togglePreviewPanel = useCallback(() => {
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
if (previewPanelOpen) {
@@ -5150,6 +5186,8 @@ function ChatViewContent(props: ChatViewProps) {
initialGitScope={initialDiffPanelGitScope}
/>
</Suspense>
) : activeRightPanelSurface?.kind === "agents" ? (
<AgentsPanel agents={threadAgents} onOpenScript={openAgentScript} mode="embedded" />
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
@@ -5352,6 +5390,11 @@ function ChatViewContent(props: ChatViewProps) {
) : (
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
)}
{hasLiveAgents ? (
<div className="mb-1.5">
<AgentsLiveStrip agents={threadAgents} onOpen={addAgentsSurface} />
</div>
) : null}
<div
className="relative"
style={
@@ -5548,6 +5591,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
@@ -5575,6 +5619,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
+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.5 shrink-0" />;
case "plan":
return <ClipboardList className="size-3.5 shrink-0" />;
case "agents":
return <Bot className="size-3.5 shrink-0" />;
}
}
@@ -470,6 +484,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<FileDiff />
Diff
</SurfaceMenuItem>
<SurfaceMenuItem available onClick={props.onAddAgents}>
<Bot />
Agents
</SurfaceMenuItem>
</MenuPopup>
</Menu>
) : null}
@@ -484,6 +502,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}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,70 @@
import { memo } from "react";
import type { ThreadAgentSnapshot } from "@t3tools/contracts";
import {
deriveAgentPanelState,
formatAgentTokenCount,
} from "@t3tools/client-runtime/state/thread-agents";
import { BotIcon, ChevronRightIcon } from "lucide-react";
import { cn } from "~/lib/utils";
/**
* Collapsed one-line agent roster shown near the composer while agents are
* live. Clicking opens the Agents panel — this strip is awareness only.
*/
const AgentsLiveStrip = memo(function AgentsLiveStrip({
agents,
onOpen,
}: {
agents: ReadonlyArray<ThreadAgentSnapshot>;
onOpen: () => void;
}) {
const state = deriveAgentPanelState(agents);
const liveCount = state.runningCount + state.waitingCount;
if (liveCount === 0) {
// Parent wrappers must not reserve space when nothing renders (the
// caller keys visibility off hasLiveAgents with the same derivation).
return null;
}
const runningPhase = state.groups
.flatMap((group) => group.phases)
.find((phase) => phase.status === "running");
return (
<button
type="button"
onClick={onOpen}
className={cn(
"flex w-full items-center gap-2 rounded-xl border border-border/60 px-3 py-1.5",
"bg-card/60 text-left text-xs transition-colors hover:border-border hover:bg-card",
)}
aria-label={`${liveCount} agents active — open agents panel`}
>
<span className="size-1.75 shrink-0 rounded-full bg-sky-500 animate-status-pulse" />
<BotIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="font-semibold">
{liveCount} agent{liveCount === 1 ? "" : "s"}
</span>
{state.waitingCount > 0 ? (
<span className="text-warning-foreground">{state.waitingCount} waiting</span>
) : null}
{runningPhase ? (
<span className="truncate text-muted-foreground">
{runningPhase.title} ·{" "}
{
runningPhase.agents.filter(
(a) => a.status === "running" || a.status === "pending" || a.status === "waiting",
).length
}{" "}
active
</span>
) : null}
<span className="ml-auto shrink-0 font-mono text-[11px] tabular-nums text-muted-foreground">
Σ {formatAgentTokenCount(state.totalTokens)}
</span>
<ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />
</button>
);
});
export default AgentsLiveStrip;
+8 -12
View File
@@ -1159,6 +1159,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
environmentUnavailable !== null ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
@@ -1697,7 +1698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
if (!isMobileViewport) return false;
if (isSendBusy || isConnecting || phase === "running") return false;
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
return false;
}
if (activePendingProgress) {
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
}
@@ -1706,6 +1709,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingProgress,
activePendingResolvedAnswers,
composerSendState.hasSendableContent,
environmentUnavailable,
isConnecting,
isMobileViewport,
isSendBusy,
@@ -1892,8 +1896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
projectSelectionRequired
) {
return false;
}
@@ -2101,8 +2104,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
isComposerModelPickerOpen,
readComposerSnapshot,
@@ -2144,7 +2145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2502,12 +2503,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
}
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
/>
{showMobilePendingAnswerActions ? (
<div
+1
View File
@@ -8,6 +8,7 @@ import { createHashHistory, createBrowserHistory } from "@tanstack/react-router"
import "@fontsource-variable/dm-sans/index.css";
import "@fontsource/jetbrains-mono/400.css";
import "@fontsource/jetbrains-mono/500.css";
import "@xterm/xterm/css/xterm.css";
import "./index.css";
import { isElectron } from "./env";
+4
View File
@@ -75,6 +75,7 @@ export interface AppModelOption {
shortName?: string;
subProvider?: string;
isCustom: boolean;
isDefault?: boolean;
}
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
@@ -85,6 +86,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
};
if (model.shortName) option.shortName = model.shortName;
if (model.subProvider) option.subProvider = model.subProvider;
if (model.isDefault) option.isDefault = true;
return option;
}
@@ -247,7 +249,9 @@ export function resolveAppModelSelectionForInstance(
const options = getAppModelOptionsForInstance(settings, entry);
return (
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
options.find((option) => option.isDefault)?.slug ??
options[0]?.slug ??
entry.models.find((model) => model.isDefault)?.slug ??
entry.models[0]?.slug ??
null
);
+1
View File
@@ -92,6 +92,7 @@ export function getDefaultServerModel(
): string {
const models = getProviderModels(providers, provider);
return (
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
models.find((model) => !model.isCustom)?.slug ??
models[0]?.slug ??
DEFAULT_MODEL_BY_PROVIDER[provider] ??
+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 };
}
};
+1
View File
@@ -633,6 +633,7 @@ export function deriveWorkLogEntries(
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.kind === "agent.snapshot") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
-35
View File
@@ -1,35 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { shouldFocusTerminalAfterSetup } from "./terminal-focus";
describe("shouldFocusTerminalAfterSetup", () => {
it("focuses the active terminal on its first setup", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: true,
hasMounted: false,
restorePreviousTerminalFocus: false,
}),
).toBe(true);
});
it("does not steal focus when terminal style causes a remount", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: true,
hasMounted: true,
restorePreviousTerminalFocus: false,
}),
).toBe(false);
});
it("restores focus when the terminal itself was focused before remount", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: false,
hasMounted: true,
restorePreviousTerminalFocus: true,
}),
).toBe(true);
});
});
-7
View File
@@ -1,7 +0,0 @@
export function shouldFocusTerminalAfterSetup(input: {
readonly autoFocus: boolean;
readonly hasMounted: boolean;
readonly restorePreviousTerminalFocus: boolean;
}): boolean {
return input.restorePreviousTerminalFocus || (!input.hasMounted && input.autoFocus);
}
-18
View File
@@ -37,24 +37,6 @@ describe("extractTerminalLinks", () => {
]);
});
it("finds non-http scheme urls", () => {
const line = "email mailto:[email protected] or clone ssh://[email protected]/t3/t3code.git now";
expect(extractTerminalLinks(line)).toEqual([
{
kind: "url",
text: "mailto:[email protected]",
start: 6,
end: 28,
},
{
kind: "url",
text: "ssh://[email protected]/t3/t3code.git",
start: 38,
end: 72,
},
]);
});
it("trims trailing punctuation from links", () => {
const line = "(https://example.com/docs), ./src/main.ts:12.";
expect(extractTerminalLinks(line)).toEqual([
+1 -4
View File
@@ -36,10 +36,7 @@ export interface WrappedTerminalLinkLine {
segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
}
// Also matches the non-http schemes ghostty and other terminals linkify;
// authority-style schemes require // while opaque ones take a bare payload.
const URL_PATTERN =
/(?:https?|ftp|ssh|git|gemini|gopher):\/\/[^\s"'`<>]+|(?:mailto|tel|news|magnet):[^\s"'`<>:][^\s"'`<>]*/g;
const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
const FILE_PATH_PATTERN =
/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
+1 -1
View File
@@ -40,7 +40,7 @@ function getTimestampFormatter(
return formatter;
}
function parseTimestampDate(isoDate: string): Date | null {
export function parseTimestampDate(isoDate: string): Date | null {
const date = new Date(isoDate);
return Number.isNaN(date.getTime()) ? null : date;
}
+4
View File
@@ -119,6 +119,10 @@
"types": "./src/state/terminal.ts",
"default": "./src/state/terminal.ts"
},
"./state/thread-agents": {
"types": "./src/state/threadAgents.ts",
"default": "./src/state/threadAgents.ts"
},
"./state/threads": {
"types": "./src/state/threads.ts",
"default": "./src/state/threads.ts"
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
DEFAULT_MODEL,
EnvironmentId,
ProjectId,
CommandId,
@@ -139,7 +140,7 @@ describe("add project shared logic", () => {
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: "codex",
model: "gpt-5.4",
model: DEFAULT_MODEL,
},
});
});
@@ -0,0 +1,134 @@
import { describe, expect, it } from "@effect/vitest";
import type { OrchestrationThreadActivity, ThreadAgentSnapshot } from "@t3tools/contracts";
import {
deriveAgentPanelState,
deriveLatestAgentSnapshot,
formatAgentTokenCount,
} from "./threadAgents.ts";
// Shape captured from a real server run (integrated verification, 2026-07-20).
const persistedAgent = {
agentId: "a732c41b4b7ba7742",
provider: "claudeAgent",
kind: "subagent",
name: "Say hi",
agentType: "general-purpose",
status: "completed",
usage: { totalTokens: 22_798, toolUses: 0 },
firstStartedAt: "2026-07-21T03:52:02.264Z",
lastActivityAt: "2026-07-21T03:52:03.936Z",
endedAt: "2026-07-21T03:52:03.936Z",
activationCount: 1,
lastTurnId: "45609775-4b3b-4444-879d-1d9f25a1b954",
resultSummary: "Hi! How can I help you today?",
recentActivity: [],
updatedAt: "2026-07-21T03:52:03.936Z",
};
function activity(kind: string, payload: unknown, sequence: number): OrchestrationThreadActivity {
return {
id: `evt-${sequence}`,
tone: "info",
kind,
summary: "agents",
payload,
turnId: null,
sequence,
createdAt: "2026-07-21T03:52:03.936Z",
} as OrchestrationThreadActivity;
}
describe("deriveLatestAgentSnapshot", () => {
it("decodes a persisted server payload and returns the newest roster", () => {
const agents = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [{ ...persistedAgent, status: "running" }] }, 1),
activity("context-window.updated", { usedTokens: 10 }, 2),
activity("agent.snapshot", { agents: [persistedAgent] }, 3),
]);
expect(agents).toHaveLength(1);
expect(agents[0]?.status).toBe("completed");
expect(agents[0]?.usage?.totalTokens).toBe(22_798);
expect(agents[0]?.resultSummary).toBe("Hi! How can I help you today?");
});
it("treats the newest agents array as authoritative even when its rows fail to decode", () => {
// Falling back to the older roster would resurrect a stale "running"
// snapshot; an undecodable newest roster must yield an empty panel.
const agents = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [persistedAgent], revision: 1 }, 1),
activity("agent.snapshot", { agents: [{ bogus: true }], revision: 2 }, 2),
]);
expect(agents).toHaveLength(0);
});
it("skips bad rows within a roster while keeping decodable ones", () => {
const agents = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [persistedAgent, { bogus: true }], revision: 1 }, 1),
]);
expect(agents).toHaveLength(1);
expect(agents[0]?.agentId).toBe(persistedAgent.agentId);
});
it("selects the highest revision regardless of list position", () => {
const older = { ...persistedAgent, status: "running" };
const agents = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [persistedAgent], revision: 5 }, 1),
activity("agent.snapshot", { agents: [older], revision: 4 }, 2),
]);
expect(agents[0]?.status).toBe("completed");
});
it("returns an empty roster when no snapshot activity exists", () => {
expect(deriveLatestAgentSnapshot([activity("task.progress", {}, 1)])).toHaveLength(0);
});
});
describe("deriveAgentPanelState", () => {
const base = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [persistedAgent] }, 1),
]);
it("counts settled agents and sums tokens", () => {
const state = deriveAgentPanelState(base);
expect(state.settledCount).toBe(1);
expect(state.runningCount).toBe(0);
expect(state.totalTokens).toBe(22_798);
expect(state.groups).toHaveLength(1);
expect(state.groups[0]?.workflow).toBeNull();
});
it("groups workflow members under declared phases with derived status", () => {
const workflow: ThreadAgentSnapshot = {
...(base[0] as ThreadAgentSnapshot),
agentId: "wf-1",
kind: "workflow",
name: "audit",
status: "running",
phases: [
{ index: 0, title: "Audit" },
{ index: 1, title: "Verify" },
],
};
const member: ThreadAgentSnapshot = {
...(base[0] as ThreadAgentSnapshot),
agentId: "wa-1",
kind: "workflow_agent",
parentAgentId: "wf-1",
phaseIndex: 0,
status: "completed",
};
const state = deriveAgentPanelState([workflow, member]);
const group = state.groups[0];
expect(group?.workflow?.agentId).toBe("wf-1");
expect(group?.phases[0]?.status).toBe("done");
expect(group?.phases[1]?.status).toBe("pending");
});
});
describe("formatAgentTokenCount", () => {
it("formats counts at k/M scale", () => {
expect(formatAgentTokenCount(950)).toBe("950");
expect(formatAgentTokenCount(22_798)).toBe("22.8k");
expect(formatAgentTokenCount(1_200_000)).toBe("1.2M");
});
});
@@ -0,0 +1,197 @@
/**
* Derivation helpers for the thread agent roster.
*
* The server ships the full per-thread roster latest-wins in the payload of
* `agent.snapshot` activities (see `@t3tools/contracts` ThreadAgentsActivityPayload).
* Mirrors the `context-window.updated` pattern: select the newest roster
* (highest revision), decode tolerantly, skip rows that fail to decode.
*/
import {
THREAD_AGENT_TERMINAL_STATUSES,
THREAD_AGENTS_ACTIVITY_KIND,
ThreadAgentSnapshot,
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
const decodeAgent = Schema.decodeUnknownOption(ThreadAgentSnapshot);
interface RosterCandidate {
readonly payload: { readonly agents: ReadonlyArray<unknown> };
readonly revision: number;
}
function peekRoster(payload: unknown): RosterCandidate | undefined {
if (payload === null || typeof payload !== "object") {
return undefined;
}
const record = payload as { agents?: unknown; revision?: unknown };
if (!Array.isArray(record.agents)) {
return undefined;
}
return {
payload: record as RosterCandidate["payload"],
// Missing revision ranks lowest (-1), mirroring server hydration: a
// revision-less legacy roster never beats a revisioned one, and among
// equals the later list position wins.
revision:
typeof record.revision === "number" && Number.isInteger(record.revision)
? record.revision
: -1,
};
}
export function deriveLatestAgentSnapshot(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<ThreadAgentSnapshot> {
// Two passes so only ONE roster is schema-decoded per recompute: rosters
// can dominate the 500-row activity window in busy sessions, and this runs
// inside a useMemo that re-fires on every activities change. Winner =
// highest revision, later list position breaking ties.
let best: RosterCandidate | undefined;
for (const activity of activities) {
if (activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) {
continue;
}
const candidate = peekRoster(activity.payload);
if (candidate && (!best || candidate.revision >= best.revision)) {
best = candidate;
}
}
if (!best) {
return [];
}
// The winning roster is authoritative: rows decode per-element (one bad row
// is skipped, the rest kept), and a fully undecodable roster yields an
// empty panel rather than resurrecting an older snapshot.
const decoded: ThreadAgentSnapshot[] = [];
for (const candidate of best.payload.agents) {
const result = decodeAgent(candidate);
if (result._tag === "Some") {
decoded.push(result.value);
}
}
return decoded;
}
export function isTerminalAgentStatus(status: ThreadAgentSnapshot["status"]): boolean {
return THREAD_AGENT_TERMINAL_STATUSES.has(status);
}
export interface AgentPanelGroup {
/** The workflow snapshot this group belongs to, or null for direct spawns. */
readonly workflow: ThreadAgentSnapshot | null;
/** Phase sections in declared order; agents without a phase land in `rest`. */
readonly phases: ReadonlyArray<AgentPanelPhase>;
readonly rest: ReadonlyArray<ThreadAgentSnapshot>;
}
export interface AgentPanelPhase {
readonly index: number;
readonly title: string;
readonly status: "pending" | "running" | "done";
readonly agents: ReadonlyArray<ThreadAgentSnapshot>;
}
export interface AgentPanelState {
readonly groups: ReadonlyArray<AgentPanelGroup>;
readonly runningCount: number;
readonly waitingCount: number;
readonly settledCount: number;
readonly totalTokens: number;
}
function isSettledAgentStatus(status: ThreadAgentSnapshot["status"]): boolean {
// idle counts as settled for phase/summary purposes: the run finished even
// though the agent identity could be resumed.
return status === "idle" || isTerminalAgentStatus(status);
}
function phaseStatus(agents: ReadonlyArray<ThreadAgentSnapshot>): "pending" | "running" | "done" {
if (agents.length === 0) return "pending";
if (agents.every((agent) => isSettledAgentStatus(agent.status))) return "done";
return "running";
}
export function deriveAgentPanelState(agents: ReadonlyArray<ThreadAgentSnapshot>): AgentPanelState {
const workflows = agents.filter((agent) => agent.kind === "workflow");
const byParent = new Map<string, ThreadAgentSnapshot[]>();
const direct: ThreadAgentSnapshot[] = [];
for (const agent of agents) {
if (agent.kind === "workflow") continue;
if (agent.parentAgentId) {
const list = byParent.get(agent.parentAgentId) ?? [];
list.push(agent);
byParent.set(agent.parentAgentId, list);
} else {
direct.push(agent);
}
}
const groups: AgentPanelGroup[] = [];
for (const workflow of workflows) {
const members = byParent.get(workflow.agentId) ?? [];
byParent.delete(workflow.agentId);
const declaredPhases = workflow.phases ?? [];
const phases: AgentPanelPhase[] = declaredPhases.map((phase) => {
const phaseAgents = members.filter((agent) => agent.phaseIndex === phase.index);
return {
index: phase.index,
title: phase.title,
status: phaseStatus(phaseAgents),
agents: phaseAgents,
};
});
const inDeclaredPhase = new Set(
phases.flatMap((phase) => phase.agents.map((agent) => agent.agentId)),
);
groups.push({
workflow,
phases,
rest: members.filter((agent) => !inDeclaredPhase.has(agent.agentId)),
});
}
// Orphaned parent groups (parent never materialized) fold into direct spawns.
for (const list of byParent.values()) {
direct.push(...list);
}
if (direct.length > 0) {
groups.push({ workflow: null, phases: [], rest: direct });
}
// Workflow container rows are grouping chrome, not workers: they are
// excluded from worker counts, and a container's own usage only counts when
// it has no member rows to avoid double-counting the same tokens.
const workflowsWithMembers = new Set(
agents.flatMap((agent) =>
agent.kind !== "workflow" && agent.parentAgentId ? [agent.parentAgentId] : [],
),
);
let runningCount = 0;
let waitingCount = 0;
let settledCount = 0;
let totalTokens = 0;
for (const agent of agents) {
const isContainer = agent.kind === "workflow";
if (!isContainer) {
if (agent.status === "running" || agent.status === "pending") runningCount += 1;
else if (agent.status === "waiting") waitingCount += 1;
else settledCount += 1; // idle + terminal
}
if (!isContainer || !workflowsWithMembers.has(agent.agentId)) {
totalTokens += agent.usage?.totalTokens ?? 0;
}
}
return { groups, runningCount, waitingCount, settledCount, totalTokens };
}
export function formatAgentTokenCount(totalTokens: number): string {
if (totalTokens >= 1_000_000) {
return `${(totalTokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
}
if (totalTokens >= 1_000) {
return `${(totalTokens / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
}
return `${totalTokens}`;
}
+1
View File
@@ -18,6 +18,7 @@ export * from "./git.ts";
export * from "./vcs.ts";
export * from "./sourceControl.ts";
export * from "./orchestration.ts";
export * from "./threadAgents.ts";
export * from "./editor.ts";
export * from "./project.ts";
export * from "./filesystem.ts";
+12 -2
View File
@@ -133,8 +133,18 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
export const DEFAULT_MODEL = "gpt-5.4";
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
export const DEFAULT_MODEL = "gpt-5.6-sol";
/**
* Codex default-model preference, most preferred first. The provider snapshot
* marks the first of these present in the live `model/list` response as
* default; when none are available, Codex's own `isDefault` flag wins.
*/
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
"gpt-5.6-sol",
"gpt-5.6-terra",
];
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
+87 -2
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");
@@ -459,10 +461,56 @@ const UserInputResolvedPayload = Schema.Struct({
});
export type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type;
/**
* Typed task usage rollup. `usage` on task events was historically
* `Schema.Unknown` (raw Claude SDK shape); emitters now normalize to this.
*/
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;
/**
* Agent-linkage fields shared by the task lifecycle payloads. Optional and
* additive: pre-existing emitters that only set taskId/description remain
* valid.
*
* `timelineBypass: true` marks events synthesized purely to feed the agent
* reducer (e.g. Codex child-thread activity): ingestion must skip the
* activity-timeline projection for them, otherwise child fleets would spray
* a row per tool call into the transcript.
*/
const TaskAgentLinkage = {
name: Schema.optional(TrimmedNonEmptyStringSchema),
agentType: Schema.optional(TrimmedNonEmptyStringSchema),
model: Schema.optional(TrimmedNonEmptyStringSchema),
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
parentTaskId: Schema.optional(RuntimeTaskId),
workflowName: Schema.optional(TrimmedNonEmptyStringSchema),
phaseIndex: Schema.optional(NonNegativeInt),
phaseTitle: Schema.optional(TrimmedNonEmptyStringSchema),
phases: Schema.optional(
Schema.Array(Schema.Struct({ index: NonNegativeInt, title: TrimmedNonEmptyStringSchema })),
),
attempt: Schema.optional(NonNegativeInt),
scriptPath: Schema.optional(TrimmedNonEmptyStringSchema),
runId: Schema.optional(TrimmedNonEmptyStringSchema),
outputFile: Schema.optional(TrimmedNonEmptyStringSchema),
timelineBypass: Schema.optional(Schema.Boolean),
} as const;
const TaskStartedPayload = Schema.Struct({
taskId: RuntimeTaskId,
description: Schema.optional(TrimmedNonEmptyStringSchema),
taskType: Schema.optional(TrimmedNonEmptyStringSchema),
prompt: Schema.optional(TrimmedNonEmptyStringSchema),
...TaskAgentLinkage,
});
export type TaskStartedPayload = typeof TaskStartedPayload.Type;
@@ -470,16 +518,45 @@ const TaskProgressPayload = Schema.Struct({
taskId: RuntimeTaskId,
description: TrimmedNonEmptyStringSchema,
summary: Schema.optional(TrimmedNonEmptyStringSchema),
usage: Schema.optional(Schema.Unknown),
usage: Schema.optional(RuntimeTaskUsage),
lastToolName: Schema.optional(TrimmedNonEmptyStringSchema),
...TaskAgentLinkage,
});
export type TaskProgressPayload = typeof TaskProgressPayload.Type;
/**
* Non-terminal state patch (Claude `task_updated`): running/paused flips,
* backgrounding, error text, end time.
*/
const TaskUpdatedPayload = Schema.Struct({
taskId: RuntimeTaskId,
// "idle" = finished a run but resumable (Codex agents between activations);
// "waiting" = blocked on approval/user input.
status: Schema.optional(
Schema.Literals([
"pending",
"running",
"completed",
"failed",
"killed",
"paused",
"idle",
"waiting",
]),
),
endTime: Schema.optional(IsoDateTime),
isBackgrounded: Schema.optional(Schema.Boolean),
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
...TaskAgentLinkage,
});
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),
usage: Schema.optional(RuntimeTaskUsage),
...TaskAgentLinkage,
});
export type TaskCompletedPayload = typeof TaskCompletedPayload.Type;
@@ -835,6 +912,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 +1079,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([
ProviderRuntimeUserInputResolvedEvent,
ProviderRuntimeTaskStartedEvent,
ProviderRuntimeTaskProgressEvent,
ProviderRuntimeTaskUpdatedEvent,
ProviderRuntimeTaskCompletedEvent,
ProviderRuntimeHookStartedEvent,
ProviderRuntimeHookProgressEvent,
+1 -24
View File
@@ -64,6 +64,7 @@ export const ServerProviderModel = Schema.Struct({
shortName: Schema.optional(TrimmedNonEmptyString),
subProvider: Schema.optional(TrimmedNonEmptyString),
isCustom: Schema.Boolean,
isDefault: Schema.optional(Schema.Boolean),
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
@@ -406,28 +407,6 @@ export const ServerSignalProcessResult = Schema.Struct({
});
export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
/** Terminal colors parsed from the user's Ghostty theme (hex strings like "#1e1e2e"). */
export const ServerTerminalThemeColors = Schema.Struct({
background: Schema.optional(TrimmedNonEmptyString),
foreground: Schema.optional(TrimmedNonEmptyString),
cursor: Schema.optional(TrimmedNonEmptyString),
selectionBackground: Schema.optional(TrimmedNonEmptyString),
selectionForeground: Schema.optional(TrimmedNonEmptyString),
/** ANSI palette slots 0-15; empty string for slots the theme does not define. */
palette: Schema.optional(Schema.Array(Schema.String)),
});
export type ServerTerminalThemeColors = typeof ServerTerminalThemeColors.Type;
/** Terminal appearance derived from the user's local Ghostty config, when present. */
export const ServerTerminalStyle = Schema.Struct({
/** font-family fallback chain in config order. */
fontFamily: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
fontSize: Schema.optional(Schema.Number),
light: Schema.optional(ServerTerminalThemeColors),
dark: Schema.optional(ServerTerminalThemeColors),
});
export type ServerTerminalStyle = typeof ServerTerminalStyle.Type;
export const ServerConfig = Schema.Struct({
environment: ExecutionEnvironmentDescriptor,
auth: ServerAuthDescriptor,
@@ -443,8 +422,6 @@ 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),
/** Absent when no Ghostty config exists or it cannot be read. */
terminalStyle: Schema.optional(ServerTerminalStyle),
});
export type ServerConfig = typeof ServerConfig.Type;
+4 -4
View File
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
});
describe("ServerSettings worktree defaults", () => {
it("defaults start-from-origin off for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
it("defaults start-from-origin on for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
});
it("accepts start-from-origin updates", () => {
expect(
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
).toBe(true);
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
).toBe(false);
});
});
+1 -1
View File
@@ -382,7 +382,7 @@ export const ServerSettings = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.withDecodingDefault(Effect.succeed(true)),
),
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
textGenerationModelSelection: ModelSelection.pipe(
+145
View File
@@ -0,0 +1,145 @@
import * as Schema from "effect/Schema";
import {
ApprovalRequestId,
IsoDateTime,
NonNegativeInt,
TrimmedNonEmptyString,
TurnId,
} from "./baseSchemas.ts";
import { ProviderDriverKind } from "./providerInstance.ts";
/**
* `ThreadAgentSnapshot` — one delegated worker (subagent, workflow, workflow
* agent, background shell, monitor) observed on a thread.
*
* The snapshot models a stable *identity* with rollups across its activations:
* a Codex collab agent is a durable, re-activatable child thread (follow-ups
* re-run it), while a Claude task is a one-shot execution. `status: "idle"`
* captures the Codex "finished a run but resumable" state, which is distinct
* from the terminal `completed`.
*
* Transport: the full per-thread roster is carried latest-wins in the payload
* of an `agent.snapshot` thread activity (see `ThreadAgentsActivityPayload`).
* There is no dedicated wire event — the activity channel's open `kind` string
* and unknown payload are the compatibility surface, mirroring how
* `context-window.updated` ships token snapshots today.
*/
export const ThreadAgentStatus = Schema.Literals([
// Not yet running (workflow agent queued behind a phase, Codex pendingInit).
"pending",
"running",
// Blocked on an approval or user-input request.
"waiting",
// Finished a run but resumable (Codex agents between activations; Claude paused).
"idle",
"completed",
"failed",
"stopped",
]);
export type ThreadAgentStatus = typeof ThreadAgentStatus.Type;
export const THREAD_AGENT_TERMINAL_STATUSES: ReadonlySet<ThreadAgentStatus> = new Set([
"completed",
"failed",
"stopped",
]);
export const ThreadAgentKind = Schema.Literals([
"subagent",
"workflow",
"workflow_agent",
"shell",
"monitor",
"other",
]);
export type ThreadAgentKind = typeof ThreadAgentKind.Type;
/** Cumulative usage across all of an agent's activations. */
export const ThreadAgentUsage = Schema.Struct({
totalTokens: NonNegativeInt,
inputTokens: Schema.optional(NonNegativeInt),
cachedInputTokens: Schema.optional(NonNegativeInt),
outputTokens: Schema.optional(NonNegativeInt),
reasoningOutputTokens: Schema.optional(NonNegativeInt),
toolUses: Schema.optional(NonNegativeInt),
});
export type ThreadAgentUsage = typeof ThreadAgentUsage.Type;
export const ThreadAgentActivityEntry = Schema.Struct({
at: IsoDateTime,
summary: TrimmedNonEmptyString,
});
export type ThreadAgentActivityEntry = typeof ThreadAgentActivityEntry.Type;
/** Ordered workflow phase, present only on `kind: "workflow"` snapshots. */
export const ThreadAgentWorkflowPhase = Schema.Struct({
index: NonNegativeInt,
title: TrimmedNonEmptyString,
});
export type ThreadAgentWorkflowPhase = typeof ThreadAgentWorkflowPhase.Type;
export const THREAD_AGENT_RECENT_ACTIVITY_LIMIT = 6;
export const ThreadAgentSnapshot = Schema.Struct({
// Stable identity: Claude task_id, Codex child thread id. Provider
// discriminates the id space so cross-provider collisions are impossible.
agentId: TrimmedNonEmptyString,
provider: ProviderDriverKind,
kind: ThreadAgentKind,
name: TrimmedNonEmptyString,
// Provider agent type: Claude subagent_type ("Explore"), Codex agent_role
// ("explorer").
agentType: Schema.optional(TrimmedNonEmptyString),
model: Schema.optional(TrimmedNonEmptyString),
status: ThreadAgentStatus,
currentActivity: Schema.optional(TrimmedNonEmptyString),
lastToolName: Schema.optional(TrimmedNonEmptyString),
usage: Schema.optional(ThreadAgentUsage),
firstStartedAt: IsoDateTime,
// Start of the CURRENT activation. Live elapsed timers derive from this so
// idle gaps between resumptions don't inflate the display; absent on
// pre-field snapshots (clients fall back to firstStartedAt).
lastStartedAt: Schema.optional(IsoDateTime),
lastActivityAt: IsoDateTime,
// Cleared when a re-activation (Codex follow-up) starts a new run.
endedAt: Schema.optional(IsoDateTime),
// Codex follow-ups and Claude workflow retry attempts.
activationCount: NonNegativeInt,
spawnTurnId: Schema.optional(TurnId),
lastTurnId: Schema.optional(TurnId),
parentAgentId: Schema.optional(TrimmedNonEmptyString),
// Workflow phase membership. Index is authoritative; title is display-only
// (titles can repeat across phases).
phaseIndex: Schema.optional(NonNegativeInt),
phaseTitle: Schema.optional(TrimmedNonEmptyString),
// kind === "workflow" only.
phases: Schema.optional(Schema.Array(ThreadAgentWorkflowPhase)),
scriptPath: Schema.optional(TrimmedNonEmptyString),
runId: Schema.optional(TrimmedNonEmptyString),
// Reserved for the approval deep-link milestone; no emitter populates it yet.
approvalRequestId: Schema.optional(ApprovalRequestId),
// Claude transcript/output path; reserved for the transcript drill-in milestone.
outputFile: Schema.optional(TrimmedNonEmptyString),
resultSummary: Schema.optional(TrimmedNonEmptyString),
errorMessage: Schema.optional(TrimmedNonEmptyString),
recentActivity: Schema.Array(ThreadAgentActivityEntry),
// Staleness watermark: how fresh this record is, independent of transport
// state. Clients compare against their sync watermark.
updatedAt: IsoDateTime,
});
export type ThreadAgentSnapshot = typeof ThreadAgentSnapshot.Type;
export const THREAD_AGENTS_ACTIVITY_KIND = "agent.snapshot";
/**
* Payload of an `agent.snapshot` thread activity: the complete latest-wins
* roster for the thread. Decoded tolerantly on the client — a row that fails
* to decode is ignored, never fatal.
*/
export const ThreadAgentsActivityPayload = Schema.Struct({
agents: Schema.Array(ThreadAgentSnapshot),
// Monotonic per-thread revision: latest-wins selection uses the highest
// revision (not list position), making same-timestamp appends deterministic.
revision: Schema.optional(NonNegativeInt),
});
export type ThreadAgentsActivityPayload = typeof ThreadAgentsActivityPayload.Type;
+74 -8
View File
@@ -6,12 +6,30 @@ settings:
catalogs:
default:
'@effect/openapi-generator':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78
'@effect/tsgo':
specifier: 0.13.2
version: 0.13.2
'@noble/curves':
specifier: 1.9.1
version: 1.9.1
'@noble/hashes':
specifier: 1.8.0
version: 1.8.0
'@pierre/diffs':
specifier: 1.3.0-beta.5
version: 1.3.0-beta.5
'@typescript/native-preview':
specifier: 7.0.0-dev.20260604.1
version: 7.0.0-dev.20260604.1
jose:
specifier: 6.2.2
version: 6.2.2
typescript:
specifier: ~6.0.3
version: 6.0.3
vite-plus:
specifier: 0.2.2
version: 0.2.2
@@ -544,15 +562,18 @@ importers:
'@tanstack/react-router':
specifier: ^1.160.2
version: 1.170.10([email protected]([email protected]))([email protected])
'@xterm/addon-fit':
specifier: ^0.11.0
version: 0.11.0
'@xterm/xterm':
specifier: ^6.0.0
version: 6.0.0
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
effect:
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
ghostty-web:
specifier: 0.4.0
version: 0.4.0
jose:
specifier: 'catalog:'
version: 6.2.2
@@ -3279,48 +3300,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-p4Y/+RYk9Bk5WO+zHSUXAClRmZ2fbJCejMuCAsU2HhyME4jqf6Ftt/mJYEwIah1wGCBDYOB7wEGV1x5bCEZ6hA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-By6tRALAZsno0F4zedmtG+wdMvJiJmJoXM4d3+A9zHE4HRXLqXITwRH8mgrlcXc5yJM2g2W3riRPwTYdgemZLQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-skYeG+RgvyzspqVEBsEprL90OYYZfoVNqB3HcCNR6QDJyXKOzfDRT3zncnHmUaFluIlBHuY23mU1b5WGgR98hA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-FFgACrZOXAXUh5KQh2mt1CDOVOZmn+QzHP71wM9QobNwyQvoFfyAeefVUltW83g3sm7LTiH3yfFqLLVUpA5ZFQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-Nm/BAOfQeFiiKd502mZn/GAVKJwtd0RdCg17G3Wz/WSOIQmDi3+7/SZH4BHn1Ye5KvTVH3ua8WvfwLLycNIuvA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-BiSy5Ku3mQqyxS6YIqAJgd403wEUWvI7kerfzPxc2l/txZVmZM0pSj7oDM+4bGBExowxOi7o73jEam1W0EDTZg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-BCRkJiotz5s9afLYD2LuMvzAoDYx9H17E/YbDyu4xK7l4zHDPeny9ErSXL//i/nJyaOwRk08x4b8cgJC00+JDg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-4Oaxe1qrGgXfpCJ1C/ERJ2iCtV2rN1R79ga9fsfyVHfSQRu/hVW780u2KDqZWFZ/iGTHODJji0JemxqFZ63eIQ==}
@@ -3423,48 +3452,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-JGHS9Mnr7iWyyLDxgCv1MhzVpAckgptg00F2gnxt/GD7lQ2SW1BRcxHqhSTaSdDpjWRrBkBxMMh4+Hn3aVtExg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-AOYgBZqxNshrg83P9v0RYv+m8s10Cqkj4/PxXFDhcS3k7FqsIG5+CxErshZCIN7G8iy4Y+VGfAsuEdar8AcbBg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-QMybPS5ij3/vrKG67mqzHwW++91sYxK/PPUVi6SBtNCEzW4niS52fVBdXbQ6nou0wWbUPEpx8Sl/ZjtgE3clXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-gOc3W7JV0PXRpIL7stUlLe3Wa9Gp0Kdlup87IT3gHDvPKck2xNgMIl/Gs2lldYY2lyXZDC4rWi3hmoLUobkgbQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-rpGxph+FjjHcYI5q6uxB3Az+tnfmEnDbSA8+PK9ZE/VzyUAkvBOMeuY7ZQMhu5mpZH7YQDsTdW6Cx4kV/msc6w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-WND+uhf/Ko13SLqQMWQUgsZuLvYYEvL0ZKgg0tgGYfLqxG7l8Ju123fHDMJyYSDl5E3bUbpFUuii/OvMreFQzw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-SrpbrUL70nG9vh6zP4/oKHWgLuHquwsr7MW9XOn0olBVgh10Uqr8qscKhQoBGEn6olK/IUpn5GSKcdQ5AjUhGA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-qkrsEn6NmgFKr7U/QnezQMb+q/vzAy0Dd9Y95gQGQTyjzDLN+HRZMuM5u70iyH4nBLCfKBzhjMsYCehKay2jyg==}
@@ -4000,6 +4037,7 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-QoSx2EkyrrdZ6kcyE8stqZ62t0Yra8Fs5ia9lOxJrh6TMQJK7gQKmscdTHf7pOXKREKrVwOtJcQG3qVSfc866A==}
@@ -4013,12 +4051,14 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-uwNwFpwKeNiZawfAWBgg0VIztPTV3ihhh1vV334h9ivnNLorxnQMU6Fz8wG1Zb4Qh9LC1/MkcyT3YlDXG3Rsgg==}
@@ -4032,12 +4072,14 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-zY1bul7OWr7DFBiJ++wofXvnr8B45ce3QsQUhKrIhXsygAh7bTkwyeM1bi1a2g5C/yC/N8TZyGDEoMfm/l9mpg==}
@@ -4051,12 +4093,14 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0frlsT/f4Ft6I7SMESTKnF3cZsdicQn1dCMkF/jT9wDLE+gGoiQfv1nmT9e+s7s/fekvvy6tZM2jHvI2tkbJDQ==}
@@ -4070,12 +4114,14 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-XABVmGp9Tg0WspTVvwduTc4fpqy6JnAUrSQe6OuyqD/03nI7r0O9OWUkMIwFrjKAIqolvqoA4ZrJppgwE0Gxmw==}
@@ -4089,12 +4135,14 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-bV4fzswuzVcKD90o/VM6QqKxnxlDq0g2BISDLNVmxrnhpv1DDbyPhCIjYfvzYLV+MvkKKnQt2Q6AO86SEBULUQ==}
@@ -4108,6 +4156,7 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==}
@@ -4567,6 +4616,7 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==}
@@ -4580,6 +4630,7 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==}
@@ -4593,6 +4644,7 @@ packages:
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==}
@@ -4606,6 +4658,7 @@ packages:
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==}
@@ -5072,24 +5125,28 @@ packages:
engines: {node: '>=20.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-YGtvTHT7qP4c5pZmM4kLL78/d8hj2NS150R92cR2SVOW/l9Ilq5R5WrEiMA4k5Ea3B++IJWZT5MRFI0tW9qlcg==}
engines: {node: '>=20.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-FvaMI/vsy4PVM+Qd73K+KM8blfCAfaoZaGaGWNrrlMryhyPThXPnHoB1AQcrKbEAWb+z2fc4zLS4sH+8uI65fw==}
engines: {node: '>=20.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-ZsMochHqXqxj2sGTJNJzz3vabppbe4BFgZAjJfsnVzkwR7jv6c5p1BM71LFWxP4qd5LL0TJT7lbeRhALlI44RQ==}
engines: {node: '>=20.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-noBNyJufux0cf18eDpQLOQUZ1Kybfx9zlr+yQ6gAnxMEsQXSvYqZgWymfRDesBE3G/0XB5bg+AUtWijp3TwVcw==}
@@ -5137,6 +5194,12 @@ packages:
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
'@xterm/[email protected]':
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
'@xterm/[email protected]':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
'@yuuang/[email protected]':
resolution: {integrity: sha512-eDYLT0kVBkp7e2BwdRDmt6N1rkeDPUHDefk3ZX0/nok+GLsqfy1WBoSL3Yg7HVXN1EyW8OBVc2uK8Zq8HbmaSA==}
engines: {node: '>= 12'}
@@ -6983,9 +7046,6 @@ packages:
resolution: {integrity: sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-0puDBik2qapbD/QQBW9o5ZHfXnZBqZWx/ctBiVtKZ6ZLds4NYb+wZuw1cRLXZk9zYovIQ908z3rvFhexAvc5Hg==}
[email protected]:
resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==}
@@ -7612,6 +7672,7 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-jmUQVx4331m6LIX+0wUhBbmMX7TCfjF5FoOH6SD1CttzuYlGNVpA7QnrmLxrsub43ClTINfGSYyHe2HWeLl5CQ==}
@@ -7632,6 +7693,7 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-piWx3z4wN8J8z3+O5kO74+yr6ze/dKmPnI7vLqfSqI8bccaTGY5xiSGVIJBDd5K5BHlvVLpUB3S2YCfelyJ1bw==}
@@ -7652,6 +7714,7 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-rRomAK7eIkL+tHY0YPxbc5Dra2gXlI63HL+v1Pdi1a3sC+tJTcFrHX+E86sulgAXeI7rSzDYhPSeHHjqFhqfeQ==}
@@ -7672,6 +7735,7 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-mSL4rqPi4iXq5YVqzSsJgMVFENoa4nGTT/GjO2c0Yl9OuQfPsIfncvLrEW6RbbB24WtZ3xP/2CCmI3tNkNV4oA==}
@@ -15134,6 +15198,10 @@ snapshots:
'@xmldom/[email protected]': {}
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
'@yuuang/[email protected]':
optional: true
@@ -17455,8 +17523,6 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: