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
114 changed files with 2693 additions and 6873 deletions

No files matched your search

-17
View File
@@ -13,23 +13,6 @@
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## Verifying Changes in the Browser
Starting a dev server to verify changes is expected and allowed:
- `T3CODE_DEV_INSTANCE=<worktree-name> bun run dev` runs an isolated instance
with deterministic port offsets (server base `13773`, web base `5733`; the
runner probes for free ports and prints the chosen pair).
- On localhost dev servers the web UI authenticates automatically — no pairing
code needed. Just load the printed web port (e.g. `http://localhost:5733`).
This applies to fresh/headless browser profiles too.
- Dev instances sharing the default `T3CODE_HOME` (`~/.t3`) share state under
`~/.t3/dev`; a browser session carries across instances on the same hostname.
Use `localhost` consistently — it does not share cookies with `127.0.0.1`.
See `docs/reference/scripts.md` for parallel-instance details and
`docs/cloud/environment-auth.md` for how dev auto-auth is secured.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
@@ -20,7 +20,6 @@ const clientSettings: ClientSettings = {
diffIgnoreWhitespace: true,
favorites: [],
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -28,7 +27,6 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
sidebarV2Enabled: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -41,8 +41,6 @@ function makeThread(
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
@@ -28,8 +28,7 @@ export function HomeRouteScreen() {
const { savedConnectionsById } = useSavedRemoteConnections();
const navigation = useNavigation();
const [searchQuery, setSearchQuery] = useState("");
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -112,8 +111,6 @@ export function HomeRouteScreen() {
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onSettleThread={settleThread}
onUnsettleThread={unsettleThread}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
@@ -123,8 +120,6 @@ export function HomeRouteScreen() {
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
// Settled threads are live shells: opening one is plain
// navigation, and sending a message un-settles server-side.
navigation.navigate("Thread", {
environmentId: thread.environmentId,
threadId: thread.id,
+2 -384
View File
@@ -14,22 +14,18 @@ import type {
} from "@t3tools/contracts";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Platform, Pressable, ScrollView, View } from "react-native";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Platform, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { cn } from "../../lib/cn";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { environmentServerConfigsAtom } from "../../state/server";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
PendingTaskListRow,
@@ -37,8 +33,6 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
import { buildThreadListV2Items, type ThreadListV2Item } from "../threads/threadListV2";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
buildHomeListLayout,
@@ -80,9 +74,6 @@ interface HomeScreenProps {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
/** Resolves true iff the settle was dispatched and succeeded. */
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -91,10 +82,6 @@ interface HomeScreenProps {
/* ─── Layout constants ───────────────────────────────────────────────── */
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
// v2 settled-tail paging: recent history is the common lookup; the deep
// tail stays behind an explicit Show more.
const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
/**
* Top spacing between the list and the Android custom header. The Android
* header (AndroidHomeHeader) is rendered in-flow above this screen and
@@ -169,80 +156,6 @@ function HomeTopContentSpacer() {
return <View className="h-4" />;
}
function ThreadListV2ProjectScope(props: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly selectedKey: string | null;
readonly onChange: (key: string | null) => void;
}) {
if (props.projects.length === 0) return null;
return (
<ScrollView
horizontal
contentContainerStyle={{
gap: 8,
paddingHorizontal: 16,
paddingBottom: 8,
paddingTop: Platform.OS === "ios" ? 12 : 4,
}}
keyboardShouldPersistTaps="handled"
showsHorizontalScrollIndicator={false}
>
{props.projects.length > 1 ? (
<Pressable
accessibilityLabel="Show all threads"
accessibilityRole="button"
accessibilityState={{ selected: props.selectedKey === null }}
hitSlop={4}
onPress={() => props.onChange(null)}
className={cn(
"min-h-8 items-center justify-center rounded-lg border px-3",
props.selectedKey === null
? "border-border bg-subtle-strong"
: "border-black/15 dark:border-white/15",
)}
>
<Text className="text-sm font-t3-medium text-foreground">All</Text>
</Pressable>
) : null}
{props.projects.map((project) => {
const key = scopedProjectKey(project.environmentId, project.id);
const selected = props.selectedKey === key;
return (
<Pressable
key={key}
accessibilityLabel={`Show ${project.title} threads`}
accessibilityRole="button"
accessibilityState={{ selected }}
hitSlop={4}
onPress={() => props.onChange(selected ? null : key)}
className={cn(
"min-h-8 flex-row items-center gap-1.5 rounded-lg border py-1 pl-2 pr-3",
selected ? "border-border bg-subtle-strong" : "border-black/15 dark:border-white/15",
)}
>
<ProjectFavicon
environmentId={project.environmentId}
projectTitle={project.title}
size={15}
workspaceRoot={project.workspaceRoot}
/>
<Text
className={cn(
"max-w-36 text-sm font-t3-medium",
selected ? "text-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
{project.title}
</Text>
</Pressable>
);
})}
</ScrollView>
);
}
/* ─── Main screen ────────────────────────────────────────────────────── */
export function HomeScreen(props: HomeScreenProps) {
@@ -250,9 +163,6 @@ export function HomeScreen(props: HomeScreenProps) {
ReadonlyMap<string, HomeGroupDisplayState>
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled =
AsyncResult.isSuccess(preferencesResult) &&
preferencesResult.value.threadListV2Enabled === true;
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
@@ -357,193 +267,6 @@ export function HomeScreen(props: HomeScreenProps) {
return map;
}, [props.projects]);
const projectByKey = useMemo(() => {
const map = new Map<string, EnvironmentProject>();
for (const project of props.projects) {
map.set(scopedProjectKey(project.environmentId, project.id), project);
}
return map;
}, [props.projects]);
const [v2ProjectScopeKey, setV2ProjectScopeKey] = useState<string | null>(null);
const v2ScopeProjects = useMemo(
() =>
props.selectedEnvironmentId === null
? props.projects
: props.projects.filter((project) => project.environmentId === props.selectedEnvironmentId),
[props.projects, props.selectedEnvironmentId],
);
const v2ScopedProject = useMemo(
() =>
v2ProjectScopeKey === null
? null
: (v2ScopeProjects.find(
(project) => scopedProjectKey(project.environmentId, project.id) === v2ProjectScopeKey,
) ?? null),
[v2ProjectScopeKey, v2ScopeProjects],
);
useEffect(() => {
if (v2ProjectScopeKey !== null && v2ScopedProject === null) {
setV2ProjectScopeKey(null);
}
}, [v2ProjectScopeKey, v2ScopedProject]);
// Thread List v2 (beta): one flat list in creation order, no grouping.
// Settled threads collapse into a recency tail below the card block.
// Settled threads stay in the live shell stream (settled ≠ archived), so
// the partition works directly off live shells — no snapshot merging or
// optimistic holds.
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
// closed PR auto-settles its thread on the next partition (mirrors web).
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
const handleChangeRequestState = useCallback(
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
setChangeRequestStateByKey((current) => {
if ((current.get(threadKey) ?? null) === state) return current;
const next = new Map(current);
if (state === null) {
next.delete(threadKey);
} else {
next.set(threadKey, state);
}
return next;
});
},
[],
);
const handleSettleThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onSettleThread(thread);
},
[props.onSettleThread],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
// context changes so environment/search flips never inherit a deep page.
const [settledVisibleCount, setSettledVisibleCount] = useState(
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
);
const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
const lastSettledResetKeyRef = useRef(settledResetKey);
if (lastSettledResetKeyRef.current !== settledResetKey) {
lastSettledResetKeyRef.current = settledResetKey;
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
}
const showMoreSettled = useCallback(
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
[],
);
// now is quantized to the minute and ticks so the inactivity auto-settle
// boundary is actually crossed while the app stays open (mirrors web);
// without a clock dependency the partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
useEffect(() => {
if (!threadListV2Enabled) return;
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
return () => clearInterval(id);
}, [threadListV2Enabled]);
// Threads on servers without the settlement capability never classify as
// settled (the user could neither un-settle nor pin them).
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const settlementEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadSettlement === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
// Settled threads are live shells; archived threads keep their original
// "hidden from lists" meaning.
return buildThreadListV2Items({
threads: props.threads.filter((thread) => thread.archivedAt === null),
environmentId: props.selectedEnvironmentId,
projectRef:
v2ScopedProject === null
? null
: {
environmentId: v2ScopedProject.environmentId,
projectId: v2ScopedProject.id,
},
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
});
}, [
changeRequestStateByKey,
nowMinute,
settledVisibleCount,
settlementEnvironmentIds,
props.searchQuery,
props.selectedEnvironmentId,
props.threads,
threadListV2Enabled,
v2ScopedProject,
]);
const threadListV2Items = threadListV2Layout.items;
const renderV2Item = useCallback(
({ item }: { readonly item: ThreadListV2Item }) => (
<ThreadListV2Row
thread={item.thread}
variant={item.variant}
showSettledDivider={item.showSettledDivider}
project={
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
null
}
providerDriver={
serverConfigs
.get(item.thread.environmentId)
?.providers.find(
(provider) =>
provider.instanceId ===
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
)?.driver ?? null
}
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
onSettleThread={handleSettleThread}
onUnsettleThread={handleUnsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
null
}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
),
[
handleChangeRequestState,
handleDeleteThread,
handleSettleThread,
handleSwipeableClose,
handleSwipeableWillOpen,
handleUnsettleThread,
projectByKey,
projectCwdByKey,
props.onArchiveThread,
props.onSelectThread,
serverConfigs,
settlementEnvironmentIds,
],
);
const v2KeyExtractor = useCallback(
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
[],
);
const extraData = useMemo(
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
[props.savedConnectionsById, projectCwdByKey],
@@ -637,10 +360,6 @@ export function HomeScreen(props: HomeScreenProps) {
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
/* Empty states */
// The signal must ignore the search/environment filters: an active query
// that matches nothing needs the in-list "No results" state, not the
// full-page "No threads yet". Settled threads are unarchived live shells,
// so the v1 check already covers v2.
const hasAnyThreads =
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
const hasResults = projectGroups.length > 0;
@@ -717,44 +436,6 @@ export function HomeScreen(props: HomeScreenProps) {
</>
);
// v2 renders queued offline tasks above the thread cards — they are not
// thread shells, so the v2 item builder never sees them, but they must
// stay visible and deletable while their environment is offline. They
// respect the same environment scope and search filter as the list.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = props.pendingTasks.filter(
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProject === null ||
(pendingTask.message.environmentId === v2ScopedProject.environmentId &&
pendingTask.creation.projectId === v2ScopedProject.id)) &&
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
const v2ListHeader = (
<>
{listHeader}
<ThreadListV2ProjectScope
projects={v2ScopeProjects}
selectedKey={v2ProjectScopeKey}
onChange={setV2ProjectScopeKey}
/>
{v2PendingTasks.map((pendingTask, index) => (
<PendingTaskListRow
key={pendingTask.message.messageId}
variant="compact"
pendingTask={pendingTask}
environmentLabel={
props.savedConnectionsById[pendingTask.message.environmentId]?.environmentLabel ?? null
}
isLast={index === v2PendingTasks.length - 1}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
))}
</>
);
const listEmpty = !hasResults ? (
hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
@@ -767,69 +448,6 @@ export function HomeScreen(props: HomeScreenProps) {
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
)
) : null;
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
// v2 project scope, so it can be null (results elsewhere) while this list
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Pending tasks render in the header, so the
// list showing them isn't empty in the user's eyes.
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : v2ScopedProject !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProject.title}`}
detail="Choose another project or create a new task."
/>
) : (
listEmpty
);
if (threadListV2Enabled) {
return (
<View className="flex-1 bg-screen">
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<FlatList
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={{ projectByKey, serverConfigs }}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
onPress={showMoreSettled}
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-foreground-muted">
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
</Text>
</Pressable>
) : null
}
ListEmptyComponent={v2ListEmpty}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
{...scrollGateHandlers}
scrollEventThrottle={16}
contentContainerStyle={{
paddingBottom:
Platform.OS === "ios"
? Math.max(insets.bottom, 24) + 96
: Math.max(insets.bottom, 16) + 88,
}}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
return (
<View className="flex-1 bg-screen">
@@ -47,8 +47,6 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
@@ -41,8 +41,6 @@ function makeThread(
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
@@ -167,13 +167,6 @@ export function ThreadSwipeable(props: {
/** Disables NEW swipe activations (e.g. while the list scrolls). */
readonly enabled?: boolean;
readonly enableTrackpadSwipe?: boolean;
/**
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
* button stretches) or "primary" — the advertised primary action fires and
* its button stretches instead. A full swipe must always match the action
* the stretching button advertises.
*/
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeWidth: number;
readonly onDelete: () => void;
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
@@ -246,11 +239,7 @@ export function ThreadSwipeable(props: {
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
if (props.fullSwipeAction === "primary") {
props.primaryAction.onPress();
} else {
props.onDelete();
}
props.onDelete();
}
}}
overshootFriction={1}
@@ -258,7 +247,6 @@ export function ThreadSwipeable(props: {
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={props.backgroundColor}
fullSwipeAction={props.fullSwipeAction ?? "delete"}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
@@ -434,7 +422,6 @@ function SwipeActionButton(props: {
export function ThreadSwipeActions(props: {
readonly backgroundColor: ColorValue;
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
readonly onFullSwipeArmedChange: (armed: boolean) => void;
@@ -443,7 +430,6 @@ export function ThreadSwipeActions(props: {
readonly threadTitle: string;
readonly translation: SharedValue<number>;
}) {
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
useAnimatedReaction(
() => -props.translation.value >= props.fullSwipeThreshold,
(armed, previous) => {
@@ -471,7 +457,7 @@ export function ThreadSwipeActions(props: {
icon={props.primaryAction.icon}
label={props.primaryAction.label}
onPress={props.primaryAction.onPress}
stretchesOnFullSwipe={fullSwipeIsPrimary}
stretchesOnFullSwipe={false}
translation={props.translation}
/>
<SwipeActionButton
@@ -485,7 +471,7 @@ export function ThreadSwipeActions(props: {
props.swipeableMethods.close();
props.onDelete();
}}
stretchesOnFullSwipe={!fullSwipeIsPrimary}
stretchesOnFullSwipe
translation={props.translation}
/>
</View>
@@ -1,5 +1,4 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
import { useCallback, useRef } from "react";
@@ -7,37 +6,19 @@ import { Alert } from "react-native";
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
/** Version skew: never send settle/unsettle to a server that predates them
(capability defaults false on decode for older servers). */
function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSettlement === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
archive: "archived",
unarchive: "unarchived",
delete: "deleted",
settle: "settled",
unsettle: "un-settled",
};
type ThreadListAction = "archive" | "unarchive" | "delete";
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return `The thread could not be ${ACTION_VERBS[action]}.`;
const verb =
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
return `The thread could not be ${verb}.`;
}
function selectionHaptic(): void {
@@ -47,115 +28,54 @@ function selectionHaptic(): void {
function actionFailureTitle(action: ThreadListAction): string {
if (action === "archive") return "Could not archive thread";
if (action === "unarchive") return "Could not unarchive thread";
if (action === "settle") return "Could not settle thread";
if (action === "unsettle") return "Could not un-settle thread";
return "Could not delete thread";
}
/** Resolves to true iff the action was dispatched and succeeded. */
function useThreadActionExecutor(
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
) {
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
const settleMutation = useAtomCommand(threadEnvironment.settle, { reportFailure: false });
const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
const inFlightThreadKeys = useRef(new Set<string>());
const executeAction = useCallback(
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (inFlightThreadKeys.current.has(key)) {
return false;
return;
}
inFlightThreadKeys.current.add(key);
selectionHaptic();
try {
if (
(action === "settle" || action === "unsettle") &&
!environmentSupportsSettlement(thread.environmentId)
) {
Alert.alert(
actionFailureTitle(action),
"This environment's server does not support settling yet. Update the server to use Settle.",
);
return false;
}
// Settle may only target what effectiveSettled could classify as
// settled: not starting/running sessions, not threads waiting on
// approvals or user input. Anything else would hide live work.
if (action === "settle" && !canSettle(thread, { now: new Date().toISOString() })) {
Alert.alert(
actionFailureTitle(action),
"This thread still needs attention. Resolve or interrupt it first, then try again.",
);
return false;
}
// Archive keeps its original, narrower guard: never interrupt a
// thread mid-turn.
if (
action === "archive" &&
thread.session?.status === "running" &&
thread.session.activeTurnId != null
) {
Alert.alert(
actionFailureTitle(action),
"This thread is working. Interrupt it first, then try again.",
);
return false;
}
const result =
action === "unsettle"
? // reason "user" pins the thread active: auto-settle stays
// suppressed until real activity clears the pin server-side.
await unsettleMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id, reason: "user" },
})
: await (
action === "settle"
? settleMutation
: action === "archive"
? archiveMutation
: action === "unarchive"
? unarchiveMutation
: deleteMutation
)({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
const mutation =
action === "archive"
? archiveMutation
: action === "unarchive"
? unarchiveMutation
: deleteMutation;
const result = await mutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
return false;
}
// Settled threads stay in the live shell stream; only the archive
// lifecycle still feeds the archived-snapshot surface.
if (action === "archive" || action === "unarchive" || action === "delete") {
refreshArchivedThreadsForEnvironment(thread.environmentId);
return;
}
onCompleted?.(action, thread);
return true;
} finally {
inFlightThreadKeys.current.delete(key);
}
},
[
archiveMutation,
deleteMutation,
onCompleted,
settleMutation,
unarchiveMutation,
unsettleMutation,
],
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
);
return executeAction;
}
function useConfirmDeleteThread(
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
) {
return useCallback(
(thread: EnvironmentThreadShell) => {
@@ -191,8 +111,6 @@ function useConfirmDeleteThread(
export function useThreadListActions(): {
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
@@ -202,18 +120,10 @@ export function useThreadListActions(): {
},
[executeAction],
);
const settleThread = useCallback(
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
[executeAction],
);
const unsettleThread = useCallback(
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
[executeAction],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
return { archiveThread, confirmDeleteThread };
}
export function useArchivedThreadListActions(
@@ -123,8 +123,6 @@ function LocalSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
@@ -508,8 +506,6 @@ function ConfiguredSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
@@ -518,35 +514,6 @@ function ConfiguredSettingsRouteScreen() {
);
}
/**
* Device-local beta toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → Beta backed by mobile preferences.
*/
function BetaSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.threadListV2Enabled === true
: false;
return (
<View className="gap-3">
<SettingsSection title="Beta">
<SettingsSwitchRow
icon="sidebar.left"
label="Thread List v2"
value={threadListV2Enabled}
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
One flat thread list in creation order. Active work renders as cards; settled threads
collapse to compact rows. Switch back any time.
</Text>
</View>
);
}
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
@@ -1,329 +0,0 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
/**
* Thread List v2 rows mirror the web sidebar's compact tonal cards and
* receded settled tail while retaining native swipe and long-press actions.
*/
const MONO_FONT = Platform.select({
ios: "Menlo",
android: "monospace",
default: "monospace",
});
const STATUS_LABEL_BY_STATUS: Partial<
Record<ThreadListV2Status, { label: string; className: string }>
> = {
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
input: { label: "Input", className: "text-amber-700 dark:text-amber-300" },
working: { label: "Working", className: "text-blue-600 dark:text-blue-400" },
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
};
function threadTimeLabel(thread: EnvironmentThreadShell): string {
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
}
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
// its own surface (thread screen / settings) rather than crowding the row.
const CARD_MENU_ACTIONS: MenuAction[] = [
{ id: "settle", title: "Settle", image: "checkmark" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
const SLIM_MENU_ACTIONS: MenuAction[] = [
{ id: "unsettle", title: "Un-settle", image: "arrow.uturn.backward" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
// Pre-settlement servers: no lifecycle items, archive fills the gap.
const LEGACY_MENU_ACTIONS: MenuAction[] = [
{ id: "archive", title: "Archive", image: "archivebox" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider() {
const borderColor = useThemeColor("--color-border");
return (
<View className="mb-1.5 mt-4 flex-row items-center gap-2.5 px-5">
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
</View>
);
});
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
readonly showSettledDivider: boolean;
readonly project: EnvironmentProject | null;
readonly providerDriver: string | null;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
/** False on environments whose server predates thread.settle/unsettle:
swipe + menu fall back to Archive instead of failing on use. */
readonly settlementSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
merged/closed work (mirrors web's onChangeRequestState). */
readonly onChangeRequestState?: (
threadKey: string,
state: "open" | "closed" | "merged" | null,
) => void;
readonly projectCwd?: string | null;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
}) {
const { width: windowWidth } = useWindowDimensions();
const {
thread,
variant,
onSelectThread,
onDeleteThread,
onSettleThread,
onUnsettleThread,
onArchiveThread,
onChangeRequestState,
} = props;
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
const threadKey = `${thread.environmentId}:${thread.id}`;
useEffect(() => {
onChangeRequestState?.(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
const screenColor = useThemeColor("--color-screen");
const status = resolveThreadListV2Status(thread);
const statusLabel = STATUS_LABEL_BY_STATUS[status];
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete, handleSettle, handleUnsettle],
);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
// row can un-settle — explicit settles clear the override, auto-settled
// rows get pinned active until real activity clears the pin.
const canUnsettle = variant === "slim";
const primaryAction = useMemo(() => {
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
// rows cannot occur here — unsupported environments never classify as
// settled.)
if (!props.settlementSupported) {
return {
accessibilityLabel: `Archive ${thread.title}`,
icon: "archivebox" as const,
label: "Archive",
onPress: handleArchive,
};
}
return canUnsettle
? {
accessibilityLabel: `Un-settle ${thread.title}`,
icon: "arrow.uturn.backward" as const,
label: "Un-settle",
onPress: handleUnsettle,
}
: {
accessibilityLabel: `Settle ${thread.title}`,
icon: "checkmark" as const,
label: "Settle",
onPress: handleSettle,
};
}, [
canUnsettle,
handleArchive,
handleSettle,
handleUnsettle,
props.settlementSupported,
thread.title,
]);
const rowContent = (close: () => void) =>
variant === "card" ? (
<Pressable
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityLabel={thread.title}
accessibilityRole="button"
onPress={() => {
close();
onSelectThread(thread);
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
<View className="bg-screen px-4 py-1">
<View
className={cn(
"overflow-hidden",
status === "ready"
? "bg-black/[0.025] dark:bg-white/[0.025]"
: "bg-black/[0.04] dark:bg-white/[0.04]",
)}
style={{ borderRadius: 12, borderCurve: "continuous", minHeight: 84 }}
>
<View className="px-3 py-2.5">
<View className="flex-row items-center gap-1.5">
{props.project ? (
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
<Text
className="flex-1 text-sm font-t3-medium text-foreground-muted"
numberOfLines={1}
>
{props.project?.title ?? ""}
</Text>
<Text
className={cn(
"text-xs tabular-nums",
statusLabel?.className ?? "text-foreground-tertiary",
)}
>
{statusLabel?.label ?? timeLabel}
</Text>
</View>
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={2}>
{thread.title}
</Text>
<View className="mt-1 flex-row items-center gap-2">
{status === "failed" && thread.session?.lastError ? (
<Text
className="flex-1 text-xs text-red-600/80 dark:text-red-400/80"
numberOfLines={1}
>
{thread.session.lastError}
</Text>
) : thread.branch ? (
<Text
className="flex-1 text-xs text-foreground-muted"
numberOfLines={1}
style={{ fontFamily: MONO_FONT }}
>
{thread.branch}
</Text>
) : (
<View className="flex-1" />
)}
{props.providerDriver ? (
<View className="opacity-60">
<ProviderIcon provider={props.providerDriver} size={14} />
</View>
) : null}
</View>
</View>
</View>
</View>
</Pressable>
) : (
<Pressable
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityLabel={thread.title}
accessibilityRole="button"
className="bg-screen"
onPress={() => {
close();
onSelectThread(thread);
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
{/* Settled history recedes: dimmed favicon + muted title. */}
<View className="min-h-[44px] flex-row items-center gap-2.5 px-5 py-2">
{props.project ? (
<View className="opacity-40">
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
</View>
) : null}
<Text className="flex-1 text-base text-foreground-muted" numberOfLines={1}>
{thread.title}
</Text>
<Text
className="text-sm tabular-nums text-foreground-tertiary"
style={{ fontFamily: MONO_FONT }}
>
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
</Pressable>
);
return (
<>
{props.showSettledDivider ? <ThreadListV2SettledDivider /> : null}
<ThreadSwipeable
backgroundColor={screenColor}
enableTrackpadSwipe
// Full swipe commits the advertised lifecycle action (Settle /
// Un-settle), never the destructive delete.
fullSwipeAction="primary"
fullSwipeWidth={windowWidth - 32}
onDelete={handleDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={primaryAction}
resetKey={`${thread.environmentId}:${thread.id}`}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={thread.title}
>
{(close) => (
<ControlPillMenu
actions={
!props.settlementSupported
? LEGACY_MENU_ACTIONS
: canUnsettle
? SLIM_MENU_ACTIONS
: CARD_MENU_ACTIONS
}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
{rowContent(close)}
</ControlPillMenu>
)}
</ThreadSwipeable>
</>
);
});
@@ -1,220 +0,0 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
buildThreadListV2Items,
resolveThreadListV2Status,
sortThreadsForListV2,
} from "./threadListV2";
const environmentId = EnvironmentId.make("environment-1");
function makeThread(
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
): EnvironmentThreadShell {
return {
environmentId,
projectId: ProjectId.make("project-1"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
}
const NOW = "2026-06-02T00:00:00.000Z";
describe("resolveThreadListV2Status", () => {
it("prioritizes approval over a running session", () => {
const thread = makeThread({
id: ThreadId.make("t"),
title: "t",
hasPendingApprovals: true,
session: {
threadId: ThreadId.make("t"),
status: "running",
providerName: "Codex",
providerInstanceId: ProviderInstanceId.make("codex"),
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: NOW,
},
});
expect(resolveThreadListV2Status(thread)).toBe("approval");
});
it("resolves ready for quiescent threads", () => {
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
"ready",
);
});
});
describe("sortThreadsForListV2", () => {
it("orders by creation time, newest first, ignoring activity", () => {
const sorted = sortThreadsForListV2([
{ id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" },
{ id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
{ id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
]);
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
});
});
describe("buildThreadListV2Items", () => {
it("partitions settled threads into a slim tail with one divider", () => {
const { items } = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("settled"),
title: "Settled",
settledOverride: "settled",
settledAt: NOW,
}),
makeThread({
id: ThreadId.make("settled-2"),
title: "Settled 2",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
["active", "card"],
["settled", "slim"],
["settled-2", "slim"],
]);
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
});
it("keeps cards in creation order while settled sorts by recency", () => {
const { items } = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("older-created"),
title: "Older",
createdAt: "2026-06-01T08:00:00.000Z",
updatedAt: NOW, // recent activity must NOT promote it
}),
makeThread({
id: ThreadId.make("newer-created"),
title: "Newer",
createdAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
});
it("keeps settled threads in the tail and filters by search query", () => {
const { items } = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("match"), title: "Fix login bug" }),
makeThread({ id: ThreadId.make("miss"), title: "Greeting" }),
makeThread({
id: ThreadId.make("settled"),
title: "Fix login again",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "login",
now: NOW,
});
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
["match", "card"],
["settled", "slim"],
]);
});
it("scopes the flat list to one project", () => {
const otherProjectId = ProjectId.make("project-2");
const { items } = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("included"), title: "Included" }),
makeThread({
id: ThreadId.make("excluded"),
projectId: otherProjectId,
title: "Excluded",
}),
],
environmentId: null,
projectRef: { environmentId, projectId: ProjectId.make("project-1") },
searchQuery: "",
now: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
});
});
describe("buildThreadListV2Items settled paging", () => {
it("caps the settled tail at settledLimit and reports the hidden count", () => {
const threads = [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
...Array.from({ length: 4 }, (_, index) =>
makeThread({
id: ThreadId.make(`settled-${index}`),
title: `Settled ${index}`,
settledOverride: "settled",
settledAt: NOW,
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
// A turn adopted the message (same requestedAt): without it the
// thread reads as a queued turn start, which never settles.
latestTurn: {
turnId: TurnId.make(`turn-${index}`),
state: "completed",
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
startedAt: `2026-06-01T0${index}:00:00.000Z`,
completedAt: `2026-06-01T0${index}:10:00.000Z`,
assistantMessageId: null,
},
}),
),
];
const layout = buildThreadListV2Items({
threads,
environmentId: null,
searchQuery: "",
settledLimit: 2,
now: NOW,
});
expect(layout.hiddenSettledCount).toBe(2);
expect(layout.items.filter((item) => item.variant === "slim")).toHaveLength(2);
// Most recent settled first — the hidden ones are the oldest.
expect(layout.items.map((item) => item.thread.id)).toEqual([
"active",
"settled-3",
"settled-2",
]);
});
});
@@ -1,167 +0,0 @@
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
/**
* Thread List v2 model, ported from the web sidebar v2
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
*
* Four visual states, three colors: color is reserved for "act now"
* (approval), "in motion" (working), and "broken" (failed). Ready is the
* unlabeled resting state.
*/
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
export function resolveThreadListV2Status(
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
): ThreadListV2Status {
if (thread.hasPendingApprovals) {
return "approval";
}
if (thread.hasPendingUserInput) {
return "input";
}
if (thread.session?.status === "running" || thread.session?.status === "starting") {
return "working";
}
if (thread.session?.status === "error") {
return "failed";
}
return "ready";
}
/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
poison the whole ordering, so it sinks to the epoch instead. */
function parseTimestampMs(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? 0 : parsed;
}
/** First VALID timestamp wins: a present-yet-malformed string falls through
to the next candidate rather than sinking the row to the epoch. */
function firstValidTimestampMs(...candidates: ReadonlyArray<string | null | undefined>): number {
for (const candidate of candidates) {
if (candidate == null) continue;
const parsed = Date.parse(candidate);
if (!Number.isNaN(parsed)) return parsed;
}
return 0;
}
/**
* v2 sort: static creation order, newest thread on top. Activity NEVER
* reorders the list — a row holds its position from open until settled, so
* the screen only moves at lifecycle transitions. Mirrors web's
* sortThreadsForSidebarV2.
*/
export function sortThreadsForListV2<T extends { readonly id: string; readonly createdAt: string }>(
threads: readonly T[],
): T[] {
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023
// change-by-copy array methods.
return [...threads].sort(
(left, right) =>
parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
left.id.localeCompare(right.id),
);
}
export interface ThreadListV2Item {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
/** First settled row after the card block draws the SETTLED divider. */
readonly showSettledDivider: boolean;
readonly isLast: boolean;
}
export interface ThreadListV2Layout {
readonly items: ThreadListV2Item[];
/** Settled threads beyond the render limit (behind "Show more"). */
readonly hiddenSettledCount: number;
}
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
* the default is fixed here rather than user-configurable.
*/
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly environmentId: EnvironmentId | null;
readonly projectRef?: {
readonly environmentId: EnvironmentId;
readonly projectId: ProjectId;
} | null;
readonly searchQuery: string;
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
/** Environments whose server supports thread.settle/unsettle. Threads on
other environments never classify as settled — the user could neither
un-settle nor pin them. Absent = no gating (tests). */
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
/** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */
readonly now?: string;
}): ThreadListV2Layout {
const now = input.now ?? new Date().toISOString();
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const query = input.searchQuery.trim().toLocaleLowerCase();
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
for (const thread of input.threads) {
// Callers pass live (unarchived) shells; settled threads are among them
// and partition into the tail via effectiveSettled.
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
if (
input.projectRef != null &&
(thread.environmentId !== input.projectRef.environmentId ||
thread.projectId !== input.projectRef.projectId)
) {
continue;
}
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
) {
settled.push(thread);
} else {
active.push(thread);
}
}
const orderedActive = sortThreadsForListV2(active);
const orderedSettled = [...settled].sort(
(left, right) =>
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
);
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
const visibleSettled =
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
const items: ThreadListV2Item[] = [];
for (const thread of orderedActive) {
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
}
for (const [index, thread] of visibleSettled.entries()) {
items.push({
thread,
variant: "slim",
showSettledDivider: index === 0,
isLast: false,
});
}
const last = items.at(-1);
if (last) {
items[items.length - 1] = { ...last, isLast: true };
}
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
}
@@ -38,8 +38,6 @@ function makeThread(
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
@@ -50,8 +50,6 @@ function makeThread(
checkpoints: [],
session: null,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
+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));
@@ -22,12 +22,6 @@ export interface Preferences {
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted into per
* device.
*/
readonly threadListV2Enabled?: boolean;
}
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
@@ -77,7 +71,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
threadListV2Enabled?: boolean;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -104,9 +97,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
(key): key is string => typeof key === "string",
);
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
}
return preferences;
}
@@ -58,8 +58,6 @@ function threadDetailToShell(
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
archivedAt: thread.archivedAt,
settledOverride: thread.settledOverride,
settledAt: thread.settledAt,
session: thread.session,
latestUserMessageAt: latestUserMessageAt(thread),
hasPendingApprovals: false,
-18
View File
@@ -37,7 +37,6 @@ import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sql
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
export const INTERNAL_DEV_AUTO_BOOTSTRAP_SUBJECT = "dev-auto-bootstrap";
export interface IssuedPairingLink {
readonly id: string;
@@ -447,10 +446,6 @@ export class EnvironmentAuth extends Context.Service<
AuthPairingCredentialResult,
ServerAuthInternalError
>;
readonly issueDevAutoPairingCredential: () => Effect.Effect<
AuthPairingCredentialResult,
ServerAuthInternalError
>;
readonly listPairingLinks: (input?: {
readonly excludeSubjects?: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
@@ -798,7 +793,6 @@ export const make = Effect.gen(function* () {
Effect.map((pairingLinks) => {
const excludedSubjects = input?.excludeSubjects ?? [
INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
INTERNAL_DEV_AUTO_BOOTSTRAP_SUBJECT,
];
return pairingLinks
.filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
@@ -880,17 +874,6 @@ export const make = Effect.gen(function* () {
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
// Same administrative grant as startup pairing, under its own subject so
// dev-auto sessions are identifiable and excluded from pairing-link
// listings. Only reachable through the guarded dev-only HTTP endpoint.
const issueDevAutoPairingCredential: EnvironmentAuth["Service"]["issueDevAutoPairingCredential"] =
() =>
issuePairingCredentialForSubject({
scopes: AuthAdministrativeScopes,
subject: INTERNAL_DEV_AUTO_BOOTSTRAP_SUBJECT,
label: "dev-auto",
}).pipe(Effect.withSpan("EnvironmentAuth.issueDevAutoPairingCredential"));
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
listSessions().pipe(
Effect.map((clientSessions) =>
@@ -981,7 +964,6 @@ export const make = Effect.gen(function* () {
createPairingLink,
issuePairingCredential,
issueStartupPairingCredential,
issueDevAutoPairingCredential,
listPairingLinks,
revokePairingLink,
issueSession,
-139
View File
@@ -1,139 +0,0 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { isDevPairingEligible, validateDevPairingRequestHeaders } from "./devPairing.ts";
const descriptorWithPolicy = (policy: ServerAuthDescriptor["policy"]): ServerAuthDescriptor => ({
policy,
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
sessionCookieName: "t3_session",
});
const devUrl = new URL("http://localhost:5733");
describe("isDevPairingEligible", () => {
it("is eligible only for loopback web-dev servers", () => {
assert.isTrue(
isDevPairingEligible({ mode: "web", devUrl }, descriptorWithPolicy("loopback-browser")),
);
});
it("rejects production configurations (no devUrl)", () => {
assert.isFalse(
isDevPairingEligible(
{ mode: "web", devUrl: undefined },
descriptorWithPolicy("loopback-browser"),
),
);
});
it("rejects desktop mode even with a loopback devUrl", () => {
assert.isFalse(
isDevPairingEligible(
{ mode: "desktop", devUrl },
descriptorWithPolicy("desktop-managed-local"),
),
);
assert.isFalse(
isDevPairingEligible({ mode: "desktop", devUrl }, descriptorWithPolicy("loopback-browser")),
);
});
it("rejects remote-reachable policies", () => {
assert.isFalse(
isDevPairingEligible({ mode: "web", devUrl }, descriptorWithPolicy("remote-reachable")),
);
});
it("rejects non-loopback dev URLs so --dev-url cannot become an auth root", () => {
assert.isFalse(
isDevPairingEligible(
{ mode: "web", devUrl: new URL("https://some-site.example") },
descriptorWithPolicy("loopback-browser"),
),
);
assert.isFalse(
isDevPairingEligible(
{ mode: "web", devUrl: new URL("http://192.168.1.20:5733") },
descriptorWithPolicy("loopback-browser"),
),
);
});
it("accepts loopback dev URL variants", () => {
for (const url of ["http://127.0.0.1:5733", "http://[::1]:5733"]) {
assert.isTrue(
isDevPairingEligible(
{ mode: "web", devUrl: new URL(url) },
descriptorWithPolicy("loopback-browser"),
),
url,
);
}
});
});
describe("validateDevPairingRequestHeaders", () => {
it("accepts an exact dev-origin Origin with a loopback Host", () => {
assert.equal(
validateDevPairingRequestHeaders({
originHeader: "http://localhost:5733",
hostHeader: "localhost:13773",
devUrl,
}),
null,
);
});
it("rejects missing, null, or foreign Origins", () => {
for (const originHeader of [undefined, "", "null", "https://evil.example"]) {
assert.equal(
validateDevPairingRequestHeaders({
originHeader,
hostHeader: "localhost:13773",
devUrl,
}),
"origin_mismatch",
String(originHeader),
);
}
});
it("rejects Origins that differ from the dev origin only by port or scheme", () => {
for (const originHeader of [
"http://localhost:5734",
"https://localhost:5733",
"http://127.0.0.1:5733",
]) {
assert.equal(
validateDevPairingRequestHeaders({
originHeader,
hostHeader: "localhost:13773",
devUrl,
}),
"origin_mismatch",
originHeader,
);
}
});
it("rejects non-loopback Hosts (DNS rebinding) even with a matching Origin", () => {
assert.equal(
validateDevPairingRequestHeaders({
originHeader: "http://localhost:5733",
hostHeader: "evil.example:13773",
devUrl,
}),
"host_not_loopback",
);
assert.equal(
validateDevPairingRequestHeaders({
originHeader: "http://localhost:5733",
hostHeader: undefined,
devUrl,
}),
"host_not_loopback",
);
});
});
-47
View File
@@ -1,47 +0,0 @@
/**
* devPairing - Eligibility and request validation for dev-mode silent pairing.
*
* The dev pairing endpoint mints an administrative one-time credential with no
* prior authentication, so eligibility is deliberately narrow: a web-mode dev
* server, bound to loopback (policy "loopback-browser"), whose configured dev
* URL is itself loopback. Request-level checks then require a browser-attached
* Origin matching the dev origin exactly — the Origin header survives the Vite
* dev proxy unmodified, which Host-based checks do not — plus a loopback Host
* as anti-DNS-rebinding defense for direct requests.
*
* @module devPairing
*/
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import type { ServerConfig } from "../config.ts";
import { isLoopbackHost, isLoopbackHostHeader, normalizeHost } from "../netHost.ts";
export interface DevPairingConfigInput {
readonly mode: ServerConfig["Service"]["mode"];
readonly devUrl: URL | undefined;
}
export const isDevPairingEligible = (
config: DevPairingConfigInput,
descriptor: ServerAuthDescriptor,
): boolean =>
config.mode === "web" &&
config.devUrl !== undefined &&
isLoopbackHost(normalizeHost(config.devUrl.hostname)) &&
descriptor.policy === "loopback-browser";
export type DevPairingRequestRejection = "origin_mismatch" | "host_not_loopback";
export const validateDevPairingRequestHeaders = (input: {
readonly originHeader: string | undefined;
readonly hostHeader: string | undefined;
readonly devUrl: URL;
}): DevPairingRequestRejection | null => {
if (!input.originHeader || input.originHeader.trim() !== input.devUrl.origin) {
return "origin_mismatch";
}
if (!isLoopbackHostHeader(input.hostHeader)) {
return "host_not_loopback";
}
return null;
};
+1 -44
View File
@@ -39,8 +39,6 @@ import * as SessionStore from "./SessionStore.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts";
import { deriveAuthClientMetadata } from "./utils.ts";
import { verifyRequestDpopProof } from "./dpop.ts";
import { isDevPairingEligible, validateDevPairingRequestHeaders } from "./devPairing.ts";
import * as ServerConfig from "../config.ts";
const CREDENTIAL_RESPONSE_HEADERS = {
"cache-control": "no-store",
@@ -127,9 +125,7 @@ export function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope
);
}
function failEnvironmentOperationForbidden(
reason: "current_session_revoke_not_allowed" | "dev_pairing_request_rejected",
) {
function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_allowed") {
return currentEnvironmentTraceId.pipe(
Effect.flatMap((traceId) =>
Effect.fail(
@@ -335,45 +331,6 @@ export const authHttpApiLayer = HttpApiBuilder.group(
),
),
)
.handle(
"devPairingCredential",
Effect.fn("environment.auth.devPairingCredential")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
const config = yield* ServerConfig.ServerConfig;
const descriptor = yield* serverAuth.getDescriptor();
// Ineligible configurations answer not_found so the endpoint is
// indistinguishable from absent outside local web dev. The
// handler must exist unconditionally: unregistered paths fall
// into the SPA/redirect wildcard route, not a 404.
if (!isDevPairingEligible(config, descriptor) || config.devUrl === undefined) {
return yield* failEnvironmentNotFound("dev_pairing_not_available");
}
const request = yield* HttpServerRequest.HttpServerRequest;
const rejection = validateDevPairingRequestHeaders({
originHeader: request.headers["origin"],
hostHeader: request.headers["host"],
devUrl: config.devUrl,
});
if (rejection !== null) {
yield* Effect.logWarning("rejected dev pairing request", {
rejection,
origin: request.headers["origin"] ?? null,
host: request.headers["host"] ?? null,
});
return yield* failEnvironmentOperationForbidden("dev_pairing_request_rejected");
}
yield* appendCredentialResponseHeaders;
return yield* serverAuth.issueDevAutoPairingCredential();
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("dev_pairing_credential_issuance_failed", error),
),
),
)
.handle(
"pairingCredential",
Effect.fn("environment.auth.pairingCredential")(
@@ -136,7 +136,6 @@ export const make = Effect.gen(function* () {
capabilities: {
repositoryIdentity: true,
connectionProbe: true,
threadSettlement: true,
},
};
-71
View File
@@ -1,71 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { isLoopbackHost, isLoopbackHostHeader, parseHostHeaderHostname } from "./netHost.ts";
describe("parseHostHeaderHostname", () => {
it("extracts hostnames from host headers with and without ports", () => {
assert.equal(parseHostHeaderHostname("localhost"), "localhost");
assert.equal(parseHostHeaderHostname("localhost:13773"), "localhost");
assert.equal(parseHostHeaderHostname("127.0.0.1:13773"), "127.0.0.1");
assert.equal(parseHostHeaderHostname("[::1]:13773"), "[::1]");
assert.equal(parseHostHeaderHostname("example.com:8080"), "example.com");
assert.equal(parseHostHeaderHostname(" LOCALHOST:13773 "), "localhost");
});
it("returns null for missing or malformed host headers", () => {
assert.equal(parseHostHeaderHostname(undefined), null);
assert.equal(parseHostHeaderHostname(""), null);
assert.equal(parseHostHeaderHostname(" "), null);
assert.equal(parseHostHeaderHostname("exa mple.com"), null);
assert.equal(parseHostHeaderHostname("http://example.com"), null);
});
});
describe("isLoopbackHostHeader", () => {
it("accepts loopback host headers, with ports and brackets", () => {
assert.isTrue(isLoopbackHostHeader("localhost"));
assert.isTrue(isLoopbackHostHeader("localhost:13773"));
assert.isTrue(isLoopbackHostHeader("127.0.0.1:13773"));
assert.isTrue(isLoopbackHostHeader("127.5.5.5"));
assert.isTrue(isLoopbackHostHeader("127.5.5.5:8080"));
assert.isTrue(isLoopbackHostHeader("[::1]:13773"));
assert.isTrue(isLoopbackHostHeader("[::1]"));
});
it("rejects non-loopback and malformed host headers (fails closed)", () => {
assert.isFalse(isLoopbackHostHeader("evil.example"));
assert.isFalse(isLoopbackHostHeader("evil.example:13773"));
assert.isFalse(isLoopbackHostHeader("localhost.evil.example"));
assert.isFalse(isLoopbackHostHeader("127.attacker.example"));
assert.isFalse(isLoopbackHostHeader("127.attacker.example:13773"));
assert.isFalse(isLoopbackHostHeader("10.0.0.5:13773"));
assert.isFalse(isLoopbackHostHeader("[::2]:13773"));
assert.isFalse(isLoopbackHostHeader(undefined));
assert.isFalse(isLoopbackHostHeader(""));
assert.isFalse(isLoopbackHostHeader("exa mple.com"));
});
});
describe("isLoopbackHost", () => {
it("keeps the config-host semantics: undefined means loopback", () => {
assert.isTrue(isLoopbackHost(undefined));
assert.isTrue(isLoopbackHost(""));
assert.isTrue(isLoopbackHost("localhost"));
assert.isTrue(isLoopbackHost("127.0.0.1"));
assert.isTrue(isLoopbackHost("127.99.0.1"));
assert.isTrue(isLoopbackHost("::1"));
assert.isTrue(isLoopbackHost("[::1]"));
assert.isFalse(isLoopbackHost("0.0.0.0"));
assert.isFalse(isLoopbackHost("192.168.1.10"));
});
it("only accepts real 127.0.0.0/8 addresses, not 127.* DNS names", () => {
assert.isFalse(isLoopbackHost("127.attacker.example"));
assert.isFalse(isLoopbackHost("127.0.0.999"));
assert.isFalse(isLoopbackHost("127.0.0"));
assert.isFalse(isLoopbackHost("127.0.0.0.1"));
assert.isFalse(isLoopbackHost("127.0.0.-1"));
assert.isTrue(isLoopbackHost("127.0.0.0"));
assert.isTrue(isLoopbackHost("127.255.255.255"));
});
});
-71
View File
@@ -1,71 +0,0 @@
/**
* netHost - Pure host/hostname predicates and parsing.
*
* Dependency-free so it can be imported from auth modules, startup code, and
* HTTP layers without creating module cycles.
*
* @module netHost
*/
// Strict 127.0.0.0/8 check: a prefix test would also accept DNS names like
// "127.attacker.example", which must not count as loopback anywhere this is
// used as a security boundary.
const isLoopbackIpv4 = (host: string): boolean => {
const octets = host.split(".");
if (octets.length !== 4) {
return false;
}
const values = octets.map((octet) => (/^\d{1,3}$/.test(octet) ? Number(octet) : -1));
return values[0] === 127 && values.every((value) => value >= 0 && value <= 255);
};
export const isLoopbackHost = (host: string | undefined): boolean => {
if (!host || host.length === 0) {
return true;
}
return host === "localhost" || host === "::1" || host === "[::1]" || isLoopbackIpv4(host);
};
export const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
export const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
export const normalizeHost = (host: string): string =>
host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
/**
* Extracts the hostname from a raw `Host` request header, handling ports,
* bracketed IPv6 literals, and surrounding whitespace. Returns null for
* missing or malformed values.
*/
export const parseHostHeaderHostname = (hostHeader: string | undefined): string | null => {
const trimmed = hostHeader?.trim().toLowerCase();
if (!trimmed || trimmed.includes("/")) {
return null;
}
// URL handles `host[:port]` and `[v6]:port` uniformly and rejects garbage.
try {
const parsed = new URL(`http://${trimmed}`);
return parsed.hostname.length > 0 ? parsed.hostname : null;
} catch {
return null;
}
};
/**
* True when a raw `Host` request header names a loopback host. Malformed or
* missing headers are NOT loopback: this is used as an auth guard, so parse
* failures must fail closed (unlike `isLoopbackHost`, whose undefined input
* means "no bind host configured" and defaults open).
*/
export const isLoopbackHostHeader = (hostHeader: string | undefined): boolean => {
const hostname = parseHostHeaderHostname(hostHeader);
if (hostname === null) {
return false;
}
return isLoopbackHost(normalizeHost(hostname));
};
@@ -146,8 +146,6 @@ describe("OrchestrationEngine", () => {
createdAt: "2026-03-03T00:00:02.000Z",
updatedAt: "2026-03-03T00:00:03.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -171,70 +171,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
for (const row of stateRows) {
assert.equal(row.lastAppliedSequence, 3);
}
// Settled lifecycle through the DB pipeline: thread.settled writes the
// override + timestamp, thread.unsettled(user) flips to the active pin.
yield* eventStore.append({
type: "thread.settled",
eventId: EventId.make("evt-settle-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: CommandId.make("cmd-settle-1"),
causationEventId: null,
correlationId: CommandId.make("cmd-settle-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
settledAt: "2026-01-01T00:00:01.000Z",
updatedAt: "2026-01-01T00:00:01.000Z",
},
});
yield* projectionPipeline.bootstrap;
const settledRows = yield* sql<{
readonly settledOverride: string | null;
readonly settledAt: string | null;
}>`
SELECT
settled_override AS "settledOverride",
settled_at AS "settledAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(settledRows, [
{ settledOverride: "settled", settledAt: "2026-01-01T00:00:01.000Z" },
]);
yield* eventStore.append({
type: "thread.unsettled",
eventId: EventId.make("evt-unsettle-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:02.000Z",
commandId: CommandId.make("cmd-unsettle-1"),
causationEventId: null,
correlationId: CommandId.make("cmd-unsettle-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
reason: "user",
updatedAt: "2026-01-01T00:00:02.000Z",
},
});
yield* projectionPipeline.bootstrap;
const unsettledRows = yield* sql<{
readonly settledOverride: string | null;
readonly settledAt: string | null;
}>`
SELECT
settled_override AS "settledOverride",
settled_at AS "settledAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]);
}),
);
});
@@ -607,8 +607,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
archivedAt: null,
settledOverride: null,
settledAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -647,38 +645,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.settled": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
settledOverride: "settled",
settledAt: event.payload.settledAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unsettled": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
settledOverride: event.payload.reason === "user" ? "active" : null,
settledAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -308,8 +308,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [
{
@@ -420,8 +418,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
@@ -566,115 +562,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect("keeps settled threads in the shell snapshot with non-null settlement fields", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-settled-test',
'Settled Test',
'/tmp/settled-test',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-06T00:00:00.000Z',
'2026-04-06T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
created_at,
updated_at,
archived_at,
settled_override,
settled_at,
deleted_at
)
VALUES (
'thread-settled',
'project-settled-test',
'Settled Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-06T00:00:02.000Z',
'2026-04-06T00:00:05.000Z',
NULL,
'settled',
'2026-04-06T00:00:04.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z')
`;
// Settled ≠ archived: the thread must appear in the LIVE shell
// snapshot, carrying its settlement fields through the row aliases.
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.deepEqual(
shellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-settled")],
);
assert.equal(shellSnapshot.threads[0]?.settledOverride, "settled");
assert.equal(shellSnapshot.threads[0]?.settledAt, "2026-04-06T00:00:04.000Z");
// And the full command read model carries them too.
const readModel = yield* snapshotQuery.getCommandReadModel();
const thread = readModel.threads.find(
(candidate) => candidate.id === ThreadId.make("thread-settled"),
);
assert.equal(thread?.settledOverride, "settled");
assert.equal(thread?.settledAt, "2026-04-06T00:00:04.000Z");
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
@@ -334,8 +334,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -364,8 +362,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -396,8 +392,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -760,8 +754,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -1194,8 +1186,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1394,8 +1384,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
deletedAt: row.deletedAt,
messages: [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1525,8 +1513,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1661,8 +1647,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1903,8 +1887,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
@@ -1999,8 +1981,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
deletedAt: null,
messages: messageRows.map((row) => {
const message = {
@@ -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 });
-4
View File
@@ -4,13 +4,11 @@ import {
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
ThreadSettledPayload as ContractsThreadSettledPayloadSchema,
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -31,13 +29,11 @@ export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
export const ThreadSettledPayload = ContractsThreadSettledPayloadSchema;
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -68,8 +68,6 @@ const readModel: OrchestrationReadModel = {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -93,8 +91,6 @@ const readModel: OrchestrationReadModel = {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -1,521 +0,0 @@
import {
CommandId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
type OrchestrationSession,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-01-01T00:00:00.000Z";
const SETTLED_AT = "2025-12-30T00:00:00.000Z";
function makeReadModel(
settledOverride: OrchestrationThread["settledOverride"],
archivedAt: string | null = null,
session: OrchestrationSession | null = null,
activities: OrchestrationThread["activities"] = [],
messages: OrchestrationThread["messages"] = [],
): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt,
settledOverride,
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
deletedAt: null,
messages,
proposedPlans: [],
activities,
checkpoints: [],
session,
},
],
updatedAt: NOW,
};
}
function makeSession(status: OrchestrationSession["status"]): OrchestrationSession {
return {
threadId: ThreadId.make("thread-1"),
status,
providerName: "Codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: NOW,
};
}
it.layer(NodeServices.layer)("settled thread decider", (it) => {
it.effect("settles active threads and re-emits idempotently for settled ones", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.settled");
if (events[0]?.type === "thread.settled") {
expect(events[0].payload.settledAt).toBe(events[0].payload.updatedAt);
}
// Already settled: the engine rejects zero-event commands, so idempotency
// is by re-emission — preserving the original settledAt.
const reEmit = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-again"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel("settled"),
});
const reEmitEvents = Array.isArray(reEmit) ? reEmit : [reEmit];
expect(reEmitEvents).toHaveLength(1);
expect(reEmitEvents[0]?.type).toBe("thread.settled");
if (reEmitEvents[0]?.type === "thread.settled") {
expect(reEmitEvents[0].payload.settledAt).toBe(SETTLED_AT);
// updatedAt must NOT rewind to the historical settledAt: sorting and
// relative-time labels key on it.
expect(reEmitEvents[0].payload.updatedAt).not.toBe(SETTLED_AT);
}
}),
);
it.effect("rejects settling a thread with a live session", () =>
Effect.gen(function* () {
for (const status of ["starting", "running"] as const) {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make(`cmd-settle-live-${status}`),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, makeSession(status)),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}
// Stopped/error sessions are settleable — only live work is protected.
const settled = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-stopped"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, makeSession("stopped")),
});
const settledEvents = Array.isArray(settled) ? settled : [settled];
expect(settledEvents[0]?.type).toBe("thread.settled");
}),
);
it.effect("rejects settling a thread with an open approval or user-input request", () =>
Effect.gen(function* () {
const requestActivity = (kind: string, requestId: string, at: string) =>
({
id: EventId.make(`activity-${requestId}-${kind}`),
tone: "approval" as const,
kind,
summary: kind,
payload: { requestId },
turnId: null,
createdAt: at,
}) as OrchestrationThread["activities"][number];
// Open approval request: settle rejected.
const openError = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-pending"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, null, [
requestActivity("approval.requested", "req-1", NOW),
]),
}).pipe(Effect.flip);
expect(openError._tag).toBe("OrchestrationCommandInvariantError");
// Same request later resolved: settleable again.
const settled = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-resolved"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, null, [
requestActivity("approval.requested", "req-1", NOW),
requestActivity("approval.resolved", "req-1", NOW),
]),
});
const settledEvents = Array.isArray(settled) ? settled : [settled];
expect(settledEvents[0]?.type).toBe("thread.settled");
// Open user-input request: also rejected.
const inputError = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-pending-input"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, null, [
requestActivity("user-input.requested", "req-2", NOW),
]),
}).pipe(Effect.flip);
expect(inputError._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("clears an open request when its respond failure marks it stale", () =>
Effect.gen(function* () {
const activity = (
kind: string,
requestId: string,
payload: Record<string, unknown>,
): OrchestrationThread["activities"][number] =>
({
id: EventId.make(`activity-${requestId}-${kind}`),
tone: "approval" as const,
kind,
summary: kind,
payload: { requestId, ...payload },
turnId: null,
createdAt: NOW,
}) as OrchestrationThread["activities"][number];
// Stale-failure detail clears the request — mirrors the projection's
// pending accounting, which is what the client's canSettle sees.
const settled = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-stale-failed"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, null, [
activity("approval.requested", "req-1", {}),
activity("provider.approval.respond.failed", "req-1", {
detail: "Unknown pending approval request req-1",
}),
activity("user-input.requested", "req-2", {}),
activity("provider.user-input.respond.failed", "req-2", {
detail: "stale pending user-input request req-2",
}),
]),
});
const settledEvents = Array.isArray(settled) ? settled : [settled];
expect(settledEvents[0]?.type).toBe("thread.settled");
// A non-stale respond failure (transient provider error) keeps the
// request open: the user can retry, so it is still blocked-on-you.
const stillOpen = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-transient-failed"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, null, [
activity("approval.requested", "req-3", {}),
activity("provider.approval.respond.failed", "req-3", {
detail: "provider connection reset",
}),
]),
}).pipe(Effect.flip);
expect(stillOpen._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("bounds the queued-turn grace window against client clock skew", () =>
Effect.gen(function* () {
const userMessage = (createdAt: string): OrchestrationThread["messages"][number] => ({
id: MessageId.make("message-queued"),
role: "user",
text: "Continue",
turnId: null,
streaming: false,
createdAt,
updatedAt: createdAt,
});
// The decider's clock is the Effect test clock, pinned to the epoch:
// timestamps here are relative to 1970-01-01T00:00:00.000Z.
// Within the grace window: genuinely queued, settle rejected.
const queuedError = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-queued"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, null, [], [userMessage("1969-12-31T23:59:30.000Z")]),
}).pipe(Effect.flip);
expect(queuedError._tag).toBe("OrchestrationCommandInvariantError");
// Message timestamp far in the FUTURE (client clock ahead of server):
// a negative age must not read as queued forever — past the grace
// bound in either direction the thread is settleable.
const skewed = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-skewed"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, null, null, [], [userMessage("1970-01-01T01:00:00.000Z")]),
});
const skewedEvents = Array.isArray(skewed) ? skewed : [skewed];
expect(skewedEvents[0]?.type).toBe("thread.settled");
}),
);
it.effect("rejects settling and unsettling archived threads", () =>
Effect.gen(function* () {
const settleError = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-archived"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null, NOW),
}).pipe(Effect.flip);
expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
const unsettleError = yield* decideOrchestrationCommand({
command: {
type: "thread.unsettle",
commandId: CommandId.make("cmd-unsettle-archived"),
threadId: ThreadId.make("thread-1"),
reason: "user",
},
readModel: makeReadModel("settled", NOW),
}).pipe(Effect.flip);
expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
Effect.gen(function* () {
const userEvent = yield* decideOrchestrationCommand({
command: {
type: "thread.unsettle",
commandId: CommandId.make("cmd-unsettle-user"),
threadId: ThreadId.make("thread-1"),
reason: "user",
},
readModel: makeReadModel("settled"),
});
const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
expect(userEvents).toHaveLength(1);
expect(userEvents[0]?.type).toBe("thread.unsettled");
if (userEvents[0]?.type === "thread.unsettled") {
expect(userEvents[0].payload.reason).toBe("user");
}
// Re-dispatching against the already-reached state re-emits rather than
// producing zero events (the engine rejects empty commands).
const userAgain = yield* decideOrchestrationCommand({
command: {
type: "thread.unsettle",
commandId: CommandId.make("cmd-unsettle-user-again"),
threadId: ThreadId.make("thread-1"),
reason: "user",
},
readModel: makeReadModel("active"),
});
const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
expect(userAgainEvents).toHaveLength(1);
expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
}),
);
it.effect("prepends activity unsets for turn starts and live session updates", () =>
Effect.gen(function* () {
const turnResult = yield* decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-1"),
role: "user",
text: "Continue",
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: NOW,
},
readModel: makeReadModel("settled"),
});
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
expect(turnEvents.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.message-sent",
"thread.turn-start-requested",
]);
const sessionResult = yield* decideOrchestrationCommand({
command: {
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set"),
threadId: ThreadId.make("thread-1"),
session: makeSession("running"),
createdAt: NOW,
},
// A keep-active pin is also an override: real activity clears it
// back to neutral so auto-settle can apply again later.
readModel: makeReadModel("active"),
});
const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
expect(sessionEvents.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.session-set",
]);
}),
);
it.effect("clears a keep-active pin on real activity", () =>
Effect.gen(function* () {
const turnResult = yield* decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: CommandId.make("cmd-active-turn-start"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-active"),
role: "user",
text: "Continue",
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: NOW,
},
readModel: makeReadModel("active"),
});
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
// The pin exists to suppress AUTO-settle, not to survive real work:
// activity resets it to neutral, restoring the default lifecycle.
expect(turnEvents.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.message-sent",
"thread.turn-start-requested",
]);
const activityResult = yield* decideOrchestrationCommand({
command: {
type: "thread.activity.append",
commandId: CommandId.make("cmd-active-approval"),
threadId: ThreadId.make("thread-1"),
activity: {
id: EventId.make("activity-active"),
tone: "approval",
kind: "approval.requested",
summary: "Command approval requested",
payload: null,
turnId: null,
createdAt: NOW,
},
createdAt: NOW,
},
readModel: makeReadModel("active"),
});
const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
expect(activityEvents.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.activity-appended",
]);
}),
);
it.effect("does not unsettle for session stop/error status writes", () =>
Effect.gen(function* () {
for (const status of ["stopped", "error", "ready", "idle"] as const) {
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.session.set",
commandId: CommandId.make(`cmd-session-${status}`),
threadId: ThreadId.make("thread-1"),
session: makeSession(status),
createdAt: NOW,
},
readModel: makeReadModel("settled"),
});
const events = Array.isArray(result) ? result : [result];
expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
}
}),
);
it.effect("unsettles for approval and user-input activities but not others", () =>
Effect.gen(function* () {
const approvalResult = yield* decideOrchestrationCommand({
command: {
type: "thread.activity.append",
commandId: CommandId.make("cmd-activity-approval"),
threadId: ThreadId.make("thread-1"),
activity: {
id: EventId.make("activity-1"),
tone: "approval",
kind: "approval.requested",
summary: "Command approval requested",
payload: null,
turnId: null,
createdAt: NOW,
},
createdAt: NOW,
},
readModel: makeReadModel("settled"),
});
const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
expect(approvalEvents.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.activity-appended",
]);
const routineResult = yield* decideOrchestrationCommand({
command: {
type: "thread.activity.append",
commandId: CommandId.make("cmd-activity-routine"),
threadId: ThreadId.make("thread-1"),
activity: {
id: EventId.make("activity-2"),
tone: "info",
kind: "tool.completed",
summary: "Tool completed",
payload: null,
turnId: null,
createdAt: NOW,
},
createdAt: NOW,
},
readModel: makeReadModel("settled"),
});
const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
}),
);
});
+5 -254
View File
@@ -24,61 +24,6 @@ import { projectEvent } from "./projector.ts";
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
// Session adoption takes seconds; a user message still unadopted after this
// window is a failed/stale start, not pending work. Mirrors the client's
// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
/**
* Blocked-on-you work derived from the thread's retained activities: an
* approval or user-input request with no later resolution for the same
* requestId. The server-side twin of the shell's hasPendingApprovals /
* hasPendingUserInput flags, which the decider read model does not carry.
* The clearing rules MUST match ProjectionPipeline's pending accounting —
* resolved activities always clear, respond.failed clears only when the
* failure detail marks the request stale/unknown — or settle would be
* rejected on threads whose shell flags read as clear.
*/
function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): boolean {
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
if (detail === null) return false;
return (
detail.includes("stale pending approval request") ||
detail.includes("unknown pending approval request") ||
detail.includes("unknown pending permission request") ||
detail.includes("stale pending user-input request") ||
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request")
);
}
function hasOpenBlockingRequest(thread: {
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
}): boolean {
const openRequestIds = new Set<string>();
for (const activity of thread.activities) {
const payload =
typeof activity.payload === "object" && activity.payload !== null
? (activity.payload as Record<string, unknown>)
: null;
const requestId = typeof payload?.requestId === "string" ? payload.requestId : null;
if (requestId === null) continue;
if (activity.kind === "approval.requested" || activity.kind === "user-input.requested") {
openRequestIds.add(requestId);
} else if (activity.kind === "approval.resolved" || activity.kind === "user-input.resolved") {
openRequestIds.delete(requestId);
} else if (
(activity.kind === "provider.approval.respond.failed" ||
activity.kind === "provider.user-input.respond.failed") &&
isStaleRequestFailureDetail(payload)
) {
openRequestIds.delete(requestId);
}
}
return openRequestIds.size > 0;
}
function withEventBase(
input: Pick<OrchestrationCommand, "commandId"> & {
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
@@ -382,132 +327,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.settle": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Server-side twin of the client's canSettle session check: a stale
// or raced client must not settle a thread whose session is coming
// alive or working.
if (thread.session?.status === "starting" || thread.session?.status === "running") {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has an active session and cannot be settled`,
}),
);
}
// Pending approval / user-input requests are blocked-on-you work: a
// raced or stale client must not park them behind a settled override
// that would surface only after the request resolves.
if (hasOpenBlockingRequest(thread)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be settled`,
}),
);
}
const occurredAt = yield* nowIso;
// A queued turn start — a user message no turn has picked up yet — is
// work in flight even though session is still null (turn.start emits
// message-sent + turn-start-requested; the session arrives later).
// Settling in that window would hide just-requested work. Detection
// mirrors the client's hasQueuedTurnStart: the newest user message is
// strictly newer than every latestTurn timestamp (adoption stamps the
// new turn's requestedAt with the message time, clearing this), and
// only within the adoption grace window — historical threads whose
// last user message postdates their turn timestamps (older-server
// data, mid-turn messages) must stay settleable. A failed session
// start (status "error") clears the block immediately.
const latestUserMessageAtMs = thread.messages.reduce(
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
);
const latestTurnAtMs =
thread.latestTurn === null
? Number.NEGATIVE_INFINITY
: Math.max(
...[
thread.latestTurn.requestedAt,
thread.latestTurn.startedAt,
thread.latestTurn.completedAt,
].map((candidate) =>
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
),
);
// The age check is bounded on BOTH sides: message timestamps are
// client-supplied, so a client clock ahead of the server yields a
// negative age. Without the lower bound that negative age satisfies
// `<= grace` for as long as the skew lasts, extending the settle
// block far past the intended two minutes.
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
const hasQueuedTurnStart =
thread.session?.status !== "error" &&
Number.isFinite(latestUserMessageAtMs) &&
latestUserMessageAtMs > latestTurnAtMs &&
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
if (hasQueuedTurnStart) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has a queued turn start and cannot be settled`,
}),
);
}
// Settling an already-settled thread re-emits with the original
// settledAt: the engine rejects zero-event commands, and bulk-settle /
// double-click must stay silent no-ops rather than surface errors.
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.settled",
payload: {
threadId: command.threadId,
settledAt: alreadySettled ? thread.settledAt : occurredAt,
// A re-emission is a projected no-op: keep the existing updatedAt
// so duplicate settles neither rewind nor churn ordering. A fresh
// settle stamps the command time.
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
},
};
}
case "thread.unsettle": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Idempotent by re-emission (see thread.settle): reducing the event a
// second time lands on the same override state. A re-emission keeps
// the existing updatedAt so duplicates do not churn ordering.
const alreadyPinnedActive = thread.settledOverride === "active";
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: command.reason,
updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
@@ -660,27 +479,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
createdAt: command.createdAt,
},
};
// Real activity resets ANY override: it wakes an explicitly settled
// thread, and it clears a keep-active pin back to neutral so the
// thread can auto-settle again after this burst of work goes stale.
if (targetThread.settledOverride === null) {
return [userMessageEvent, turnStartRequestedEvent];
}
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
};
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
return [userMessageEvent, turnStartRequestedEvent];
}
case "thread.turn.interrupt": {
@@ -801,12 +600,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.session.set": {
const thread = yield* requireThread({
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
@@ -820,30 +619,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
session: command.session,
},
};
// Only a session coming alive is activity worth waking a settled thread
// for — status writes like ready/stopped/error arrive after the fact and
// must not fight a user's explicit settle.
const isSessionActivity =
command.session.status === "starting" || command.session.status === "running";
// Real activity resets ANY override (settled wakes, active unpins).
if (thread.settledOverride === null || !isSessionActivity) {
return sessionSetEvent;
}
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
};
return [unsettledEvent, sessionSetEvent];
}
case "thread.message.assistant.delta": {
@@ -970,7 +745,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.activity.append": {
const thread = yield* requireThread({
yield* requireThread({
readModel,
command,
threadId: command.threadId,
@@ -983,7 +758,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
? ((command.activity.payload as { requestId: string })
.requestId as OrchestrationEvent["metadata"]["requestId"])
: undefined;
const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
@@ -997,30 +772,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
activity: command.activity,
},
};
// An approval or user-input request is blocked-on-you work — it must
// never stay hidden inside a settled slim row.
const wakesSettledThread =
command.activity.kind === "approval.requested" ||
command.activity.kind === "user-input.requested";
// Real activity resets ANY override (settled wakes, active unpins).
if (thread.settledOverride === null || !wakesSettledThread) {
return activityAppendedEvent;
}
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
};
return [unsettledEvent, activityAppendedEvent];
}
default: {
@@ -1,88 +0,0 @@
import {
CommandId,
EventId,
ProjectId,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
function makeEvent(input: {
readonly sequence: number;
readonly type: OrchestrationEvent["type"];
readonly payload: unknown;
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
type: input.type,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:00.000Z",
commandId: CommandId.make(`command-${input.sequence}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: input.payload as never,
} as OrchestrationEvent;
}
it.effect("projects settled lifecycle events", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const created = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
const settled = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.settled",
payload: { threadId: ThreadId.make("thread-1"), settledAt: now, updatedAt: now },
}),
);
expect(settled.threads[0]?.settledOverride).toBe("settled");
expect(settled.threads[0]?.settledAt).toBe(now);
const userUnsettled = yield* projectEvent(
settled,
makeEvent({
sequence: 3,
type: "thread.unsettled",
payload: { threadId: ThreadId.make("thread-1"), reason: "user", updatedAt: now },
}),
);
expect(userUnsettled.threads[0]?.settledOverride).toBe("active");
expect(userUnsettled.threads[0]?.settledAt).toBeNull();
const activityUnsettled = yield* projectEvent(
userUnsettled,
makeEvent({
sequence: 4,
type: "thread.unsettled",
payload: { threadId: ThreadId.make("thread-1"), reason: "activity", updatedAt: now },
}),
);
expect(activityUnsettled.threads[0]?.settledOverride).toBeNull();
expect(activityUnsettled.threads[0]?.settledAt).toBeNull();
}),
);
@@ -89,8 +89,6 @@ describe("orchestration projector", () => {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -22,9 +22,7 @@ import {
ThreadMetaUpdatedPayload,
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -288,8 +286,6 @@ export function projectEvent(
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -341,30 +337,6 @@ export function projectEvent(
})),
);
case "thread.settled":
return decodeForEvent(ThreadSettledPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
settledOverride: "settled",
settledAt: payload.settledAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unsettled":
return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
settledOverride: payload.reason === "user" ? "active" : null,
settledAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -91,8 +91,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -130,58 +128,4 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
});
}),
);
it.effect("round-trips non-null settlement values through the thread row", () =>
Effect.gen(function* () {
const threads = yield* ProjectionThreadRepository;
yield* threads.upsert({
threadId: ThreadId.make("thread-settled"),
projectId: ProjectId.make("project-1"),
title: "Settled thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurnId: null,
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-25T00:00:00.000Z",
archivedAt: null,
settledOverride: "settled",
settledAt: "2026-03-25T00:00:00.000Z",
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
hasActionableProposedPlan: 0,
deletedAt: null,
});
const persisted = yield* threads.getById({
threadId: ThreadId.make("thread-settled"),
});
const row = Option.getOrNull(persisted);
if (!row) {
return yield* Effect.die("Expected settled projection_threads row to exist.");
}
assert.strictEqual(row.settledOverride, "settled");
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
// Un-settle to the keep-active pin and confirm the flip persists.
yield* threads.upsert({
...row,
settledOverride: "active",
settledAt: null,
});
const repersisted = yield* threads.getById({
threadId: ThreadId.make("thread-settled"),
});
const updated = Option.getOrNull(repersisted);
assert.strictEqual(updated?.settledOverride, "active");
assert.strictEqual(updated?.settledAt, null);
}),
);
});
@@ -43,8 +43,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
created_at,
updated_at,
archived_at,
settled_override,
settled_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
@@ -64,8 +62,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.createdAt},
${row.updatedAt},
${row.archivedAt},
${row.settledOverride},
${row.settledAt},
${row.latestUserMessageAt},
${row.pendingApprovalCount},
${row.pendingUserInputCount},
@@ -85,8 +81,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
created_at = excluded.created_at,
updated_at = excluded.updated_at,
archived_at = excluded.archived_at,
settled_override = excluded.settled_override,
settled_at = excluded.settled_at,
latest_user_message_at = excluded.latest_user_message_at,
pending_approval_count = excluded.pending_approval_count,
pending_user_input_count = excluded.pending_user_input_count,
@@ -113,8 +107,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -143,8 +135,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -45,7 +45,6 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
/**
* Migration loader with all migrations defined inline.
@@ -90,7 +89,6 @@ export const migrationEntries = [
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
[31, "AuthAuthorizationScopes", Migration0031],
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionThreadsSettled", Migration0033],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -1,23 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "settled_override")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN settled_override TEXT
`;
}
if (!columns.some((column) => column.name === "settled_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN settled_at TEXT
`;
}
});
@@ -36,8 +36,6 @@ export const ProjectionThread = Schema.Struct({
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
archivedAt: Schema.NullOr(IsoDateTime),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
settledAt: Schema.NullOr(IsoDateTime),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
pendingApprovalCount: NonNegativeInt,
pendingUserInputCount: NonNegativeInt,
@@ -1704,6 +1704,124 @@ 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()),
Effect.provide(harness.layer),
);
});
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()),
+239 -10
View File
@@ -704,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)
@@ -2388,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();
@@ -2676,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),
@@ -2703,17 +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;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
}
case "task_notification": {
const record = message as unknown as Record<string, unknown>;
const usage = normalizeRuntimeTaskUsage(record.usage);
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2729,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,
@@ -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 [];
@@ -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;
@@ -100,8 +100,6 @@ function makeReadModel(
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
@@ -305,8 +305,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
@@ -453,8 +451,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
session: {
threadId,
status: "running",
@@ -611,8 +607,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
session: {
threadId,
status: "running",
-201
View File
@@ -164,8 +164,6 @@ const makeDefaultOrchestrationReadModel = () => {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -195,8 +193,6 @@ const makeDefaultOrchestrationThreadShell = (
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
@@ -3424,201 +3420,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
const DEV_PAIRING_PATH = "/api/auth/dev-pairing-token";
const devPairingEligibleConfig = {
mode: "web",
host: "127.0.0.1",
devUrl: new URL("http://localhost:5733"),
desktopBootstrapToken: undefined,
} as const;
const devOriginHeaders = {
"content-type": "application/json",
origin: "http://localhost:5733",
} as const;
const postDevPairing = (headers: Record<string, string>) =>
Effect.gen(function* () {
const url = yield* getHttpServerUrl(DEV_PAIRING_PATH);
return yield* fetchEffect(url, {
method: "POST",
headers,
body: jsonRequestBody({}),
});
});
it.effect("mints an admin-scope dev pairing credential for the dev origin", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({ config: devPairingEligibleConfig });
const response = yield* postDevPairing({ ...devOriginHeaders });
const body = (yield* response.json) as {
readonly credential: string;
readonly expiresAt: string;
};
assert.equal(response.status, 200);
assert.equal(response.headers["cache-control"], "no-store");
assert.isTrue(body.credential.length > 0);
// The credential exchanges into a session with administrative scopes.
const sessionCookie = yield* getAuthenticatedSessionCookieHeader(body.credential);
const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
headers: { cookie: sessionCookie },
body: yield* HttpBody.json({}),
});
assert.equal(pairingResponse.status, 200);
// One-time: a second exchange of the same credential fails.
const reused = yield* bootstrapBrowserSession(body.credential);
assert.equal(reused.response.status, 401);
// The dev-auto subject is excluded from the pairing-link listing.
const listResponse = yield* HttpClient.get("/api/auth/pairing-links", {
headers: { cookie: sessionCookie },
});
const listedLinks = (yield* listResponse.json) as ReadonlyArray<{
readonly subject: string;
}>;
assert.equal(listResponse.status, 200);
assert.isFalse(listedLinks.some((entry) => entry.subject === "dev-auto-bootstrap"));
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("rejects dev pairing requests with a missing or foreign Origin", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({ config: devPairingEligibleConfig });
for (const origin of [undefined, "https://evil.example", "null"]) {
const response = yield* postDevPairing({
"content-type": "application/json",
...(origin === undefined ? {} : { origin }),
});
const body = (yield* response.json) as {
readonly _tag: string;
readonly reason: string;
};
assert.equal(response.status, 403, String(origin));
assert.equal(body._tag, "EnvironmentOperationForbiddenError");
assert.equal(body.reason, "dev_pairing_request_rejected");
}
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("rejects dev pairing requests whose Host header is not loopback", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({ config: devPairingEligibleConfig });
const url = new URL(yield* getHttpServerUrl(DEV_PAIRING_PATH));
// fetch() silently drops forbidden Host overrides, so drive node:http
// directly to simulate the DNS-rebinding request shape.
const rebound = yield* Effect.promise(async () => {
const NodeHttp = await import("node:http");
return await new Promise<{ status: number; body: string }>((resolve, reject) => {
const request = NodeHttp.request(
{
host: url.hostname,
port: url.port,
path: url.pathname,
method: "POST",
headers: {
"content-type": "application/json",
origin: devOriginHeaders.origin,
host: "evil.example",
},
},
(response) => {
const chunks: Buffer[] = [];
response.on("data", (chunk) =>
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)),
);
response.on("end", () =>
resolve({
status: response.statusCode ?? 0,
body: Buffer.concat(chunks).toString("utf8"),
}),
);
},
);
request.on("error", reject);
request.end(JSON.stringify({}));
});
});
assert.equal(rebound.status, 403);
assert.include(rebound.body, "dev_pairing_request_rejected");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("answers not_found for dev pairing outside eligible dev configurations", () =>
Effect.gen(function* () {
const assertNotAvailable = Effect.fn(function* () {
const response = yield* postDevPairing({ ...devOriginHeaders });
const body = (yield* response.json) as {
readonly _tag: string;
readonly reason: string;
};
assert.equal(response.status, 404);
assert.equal(body._tag, "EnvironmentResourceNotFoundError");
assert.equal(body.reason, "dev_pairing_not_available");
});
// Production shape: no devUrl.
yield* buildAppUnderTest({
config: { ...devPairingEligibleConfig, devUrl: undefined },
});
yield* assertNotAvailable();
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("answers not_found for dev pairing on remote-reachable and desktop servers", () =>
Effect.gen(function* () {
const assertNotAvailable = Effect.fn(function* () {
const response = yield* postDevPairing({ ...devOriginHeaders });
assert.equal(response.status, 404);
});
yield* buildAppUnderTest({
config: { ...devPairingEligibleConfig, host: "0.0.0.0" },
});
yield* assertNotAvailable();
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("answers not_found for dev pairing with a non-loopback dev URL", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
config: {
...devPairingEligibleConfig,
devUrl: new URL("https://some-site.example"),
},
});
const response = yield* postDevPairing({
"content-type": "application/json",
origin: "https://some-site.example",
});
assert.equal(response.status, 404);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("answers not_found for dev pairing in desktop mode", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
config: {
mode: "desktop",
host: "127.0.0.1",
devUrl: new URL("http://127.0.0.1:5733"),
},
});
const response = yield* postDevPairing({
"content-type": "application/json",
origin: "http://127.0.0.1:5733",
});
assert.equal(response.status, 404);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("rejects pairing credential requests without access management scope", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
@@ -5698,8 +5499,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -11,7 +11,6 @@ import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as ServerConfig from "./config.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
@@ -108,115 +107,6 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
),
);
const startupTargetAuthMock = (input: {
readonly policy: "loopback-browser" | "remote-reachable" | "desktop-managed-local";
readonly onIssueStartupPairingUrl?: (baseUrl: string) => void;
}) =>
({
getDescriptor: () =>
Effect.succeed({
policy: input.policy,
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
sessionCookieName: "t3_session",
}),
issueStartupPairingUrl: (baseUrl: string) => {
input.onIssueStartupPairingUrl?.(baseUrl);
return Effect.succeed(`${baseUrl}pair#token=STARTUP`);
},
}) as never;
it.effect(
"opens the plain dev URL without minting a credential when silent pairing is eligible",
() =>
Effect.gen(function* () {
const result = yield* ServerRuntimeStartup.resolveStartupBrowserTarget.pipe(
Effect.provideService(ServerConfig.ServerConfig, {
mode: "web",
host: "127.0.0.1",
port: 13773,
devUrl: new URL("http://localhost:5733/"),
} as never),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
startupTargetAuthMock({
policy: "loopback-browser",
onIssueStartupPairingUrl: () => {
throw new Error("must not mint a startup credential in eligible dev");
},
}),
),
);
assert.deepStrictEqual(result, {
target: "http://localhost:5733/",
requiresPairing: false,
});
}),
);
it.effect("still mints a startup pairing URL for non-dev web servers", () =>
Effect.gen(function* () {
const result = yield* ServerRuntimeStartup.resolveStartupBrowserTarget.pipe(
Effect.provideService(ServerConfig.ServerConfig, {
mode: "web",
host: "127.0.0.1",
port: 3773,
devUrl: undefined,
} as never),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
startupTargetAuthMock({ policy: "loopback-browser" }),
),
);
assert.isTrue(result.requiresPairing);
assert.include(result.target, "pair#token=STARTUP");
}),
);
it.effect("still mints a startup pairing URL for remote-reachable dev servers", () =>
Effect.gen(function* () {
const result = yield* ServerRuntimeStartup.resolveStartupBrowserTarget.pipe(
Effect.provideService(ServerConfig.ServerConfig, {
mode: "web",
host: "0.0.0.0",
port: 13773,
devUrl: new URL("http://localhost:5733/"),
} as never),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
startupTargetAuthMock({ policy: "remote-reachable" }),
),
);
assert.isTrue(result.requiresPairing);
assert.include(result.target, "pair#token=STARTUP");
}),
);
it.effect("desktop startup keeps the plain target without pairing", () =>
Effect.gen(function* () {
const result = yield* ServerRuntimeStartup.resolveStartupBrowserTarget.pipe(
Effect.provideService(ServerConfig.ServerConfig, {
mode: "desktop",
host: "127.0.0.1",
port: 13773,
devUrl: new URL("http://127.0.0.1:5733/"),
} as never),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
startupTargetAuthMock({ policy: "desktop-managed-local" }),
),
);
assert.deepStrictEqual(result, {
target: "http://127.0.0.1:5733/",
requiresPairing: false,
});
}),
);
it.effect("resolveWelcomeBase derives cwd and project name from server config", () =>
Effect.gen(function* () {
const welcome = yield* ServerRuntimeStartup.resolveWelcomeBase.pipe(
+11 -27
View File
@@ -40,7 +40,6 @@ import {
isWildcardHost,
issueHeadlessServeAccessInfo,
} from "./startupAccess.ts";
import { isDevPairingEligible } from "./auth/devPairing.ts";
export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
"ServerRuntimeStartupError",
@@ -250,7 +249,7 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
} as const;
});
export const resolveStartupBrowserTarget = Effect.gen(function* () {
const resolveStartupBrowserTarget = Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const localUrl = `http://localhost:${serverConfig.port}`;
@@ -259,22 +258,11 @@ export const resolveStartupBrowserTarget = Effect.gen(function* () {
? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
: localUrl;
const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
if (serverConfig.mode === "desktop") {
return { target: baseTarget, requiresPairing: false };
}
// Silent-pairing-eligible dev servers self-authenticate on page load, so
// open the plain URL. Minting a /pair#token URL here would leave an
// unconsumed administrative credential in the URL and terminal scrollback:
// the silent path authenticates before /pair could consume the token, and
// /pair redirects away from authenticated sessions without exchanging it.
const descriptor = yield* serverAuth.getDescriptor();
if (isDevPairingEligible(serverConfig, descriptor)) {
return { target: baseTarget, requiresPairing: false };
}
return {
target: yield* serverAuth.issueStartupPairingUrl(baseTarget),
requiresPairing: true,
};
return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
Effect.flatMap((target) =>
target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
),
);
});
const maybeOpenBrowser = (target: string) =>
@@ -468,17 +456,13 @@ export const make = Effect.gen(function* () {
);
} else {
yield* Effect.logDebug("startup phase: browser open check");
const startupBrowser = yield* resolveStartupBrowserTarget;
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
if (serverConfig.mode !== "desktop") {
yield* startupBrowser.requiresPairing
? Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
Effect.annotateLogs({ pairingUrl: startupBrowser.target }),
)
: Effect.logInfo("T3 Code dev server ready.").pipe(
Effect.annotateLogs({ url: startupBrowser.target }),
);
yield* Effect.logInfo(
"Authentication required. Open T3 Code using the pairing URL.",
).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
}
yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowser.target));
yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
}
yield* Effect.logDebug("startup phase: complete");
}),
+23 -3
View File
@@ -6,9 +6,6 @@ import { HttpServer } from "effect/unstable/http";
import { ServerConfig } from "./config.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { formatHostForUrl, isWildcardHost, normalizeHost } from "./netHost.ts";
export { isLoopbackHost, isWildcardHost, formatHostForUrl } from "./netHost.ts";
export interface HeadlessServeAccessInfo {
readonly connectionString: string;
@@ -18,6 +15,29 @@ export interface HeadlessServeAccessInfo {
type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
export const isLoopbackHost = (host: string | undefined): boolean => {
if (!host || host.length === 0) {
return true;
}
return (
host === "localhost" ||
host === "127.0.0.1" ||
host === "::1" ||
host === "[::1]" ||
host.startsWith("127.")
);
};
export const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
export const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
const normalizeHost = (host: string): string =>
host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
const isIpv4Family = (family: string | number): boolean => family === "IPv4" || family === 4;
const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6;
+1 -133
View File
@@ -1,6 +1,5 @@
import {
EnvironmentAuthInvalidError,
EnvironmentResourceNotFoundError,
type AuthBrowserSessionResult,
type AuthCreatePairingCredentialInput,
type AuthSessionState,
@@ -105,15 +104,6 @@ async function installAuthApi(input: {
readonly label?: string;
readonly expiresAt: DateTime.Utc;
}>;
readonly devPairingCredential?: () => Effect.Effect<
{
readonly id: string;
readonly credential: string;
readonly label?: string;
readonly expiresAt: DateTime.Utc;
},
EnvironmentResourceNotFoundError
>;
}) {
const testApi = await installEnvironmentHttpTest({
...(input.session ? { session: () => Effect.succeed(input.session!()) } : {}),
@@ -123,24 +113,11 @@ async function installAuthApi(input: {
...(input.pairingCredential
? { pairingCredential: (payload) => input.pairingCredential!(payload) }
: {}),
// Vitest runs with import.meta.env.DEV, so unauthenticated web scenarios
// attempt silent dev pairing; default to "not available" (the production
// shape) unless a test opts in.
devPairingCredential:
input.devPairingCredential ?? (() => Effect.fail(devPairingNotAvailableError())),
});
disposeHttpTest = testApi.dispose;
return testApi;
}
function devPairingNotAvailableError() {
return new EnvironmentResourceNotFoundError({
code: "not_found",
reason: "dev_pairing_not_available",
traceId: "test-trace",
});
}
describe("resolveInitialServerAuthGateState", () => {
beforeEach(() => {
vi.restoreAllMocks();
@@ -261,114 +238,6 @@ describe("resolveInitialServerAuthGateState", () => {
});
});
it("silently pairs through the dev pairing endpoint when the server offers it", async () => {
const nextSession = sequence(
unauthenticatedSession(LOOPBACK_AUTH),
authenticatedSession(LOOPBACK_AUTH),
);
const testApi = await installAuthApi({
session: nextSession,
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
devPairingCredential: () =>
Effect.succeed({
id: "dev-auto-1",
credential: "DEV-AUTO-CREDENTIAL",
expiresAt: SESSION_EXPIRES_AT,
}),
});
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "authenticated",
});
expect(testApi.calls.devPairingCredential).toBe(1);
expect(testApi.calls.browserSession).toEqual([{ credential: "DEV-AUTO-CREDENTIAL" }]);
});
it("falls back to the pairing screen silently when dev pairing is not available", async () => {
const testApi = await installAuthApi({
session: () => unauthenticatedSession(LOOPBACK_AUTH),
});
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: LOOPBACK_AUTH,
});
expect(testApi.calls.devPairingCredential).toBe(1);
expect(testApi.calls.browserSession).toEqual([]);
});
it("skips dev pairing when an explicit pairing token is present in the URL", async () => {
const testApi = await installAuthApi({
session: () => unauthenticatedSession(LOOPBACK_AUTH),
});
installTestBrowser("http://localhost:5733/pair#token=EXPLICIT");
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: LOOPBACK_AUTH,
});
expect(testApi.calls.devPairingCredential).toBe(0);
});
it("skips dev pairing in desktop-bridge contexts", async () => {
const testApi = await installAuthApi({
session: () => unauthenticatedSession(DESKTOP_AUTH),
});
const testWindow = installTestBrowser("http://127.0.0.1:5733/");
testWindow.desktopBridge = {
getLocalEnvironmentBootstraps: () => [],
} as unknown as DesktopBridge;
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: DESKTOP_AUTH,
});
expect(testApi.calls.devPairingCredential).toBe(0);
});
it("retries dev pairing after a reauthentication reset", async () => {
const nextSession = sequence(
unauthenticatedSession(LOOPBACK_AUTH),
unauthenticatedSession(LOOPBACK_AUTH),
authenticatedSession(LOOPBACK_AUTH),
);
let available = false;
const testApi = await installAuthApi({
session: nextSession,
browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
devPairingCredential: () =>
available
? Effect.succeed({
id: "dev-auto-2",
credential: "DEV-AUTO-RETRY",
expiresAt: SESSION_EXPIRES_AT,
})
: Effect.fail(devPairingNotAvailableError()),
});
const { resolveInitialServerAuthGateState, reauthenticatePrimaryEnvironment } =
await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: LOOPBACK_AUTH,
});
available = true;
await expect(reauthenticatePrimaryEnvironment()).resolves.toEqual({
status: "authenticated",
});
expect(testApi.calls.devPairingCredential).toBe(2);
});
it("retries transient auth session bootstrap failures after restart", async () => {
vi.useFakeTimers();
let attempts = 0;
@@ -397,8 +266,7 @@ describe("resolveInitialServerAuthGateState", () => {
status: "requires-auth",
auth: LOOPBACK_AUTH,
});
// 3 transient failures + 1 session success + 1 silent dev-pairing attempt.
expect(attempts).toBe(5);
expect(attempts).toBe(4);
});
it("takes a pairing token from the location hash and strips it immediately", async () => {
+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;
+2 -12
View File
@@ -8,9 +8,7 @@ import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import { useClientSettings } from "../hooks/useSettings";
import ThreadSidebar from "./Sidebar";
import ThreadSidebarV2 from "./SidebarV2";
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import {
resolveInitialThreadSidebarWidth,
@@ -100,12 +98,7 @@ function SidebarControl() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
// Settings routes render the settings nav, which lives in the v1 component
// and is identical for both sidebars — so v1 stays mounted there.
const pathname = useLocation({ select: (location) => location.pathname });
const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
const useSidebarV2 = sidebarV2Enabled && !isOnSettings;
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(window.innerWidth);
@@ -164,10 +157,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
<Sidebar
side="left"
collapsible="offcanvas"
className={cn(
"border-r border-border text-foreground",
useSidebarV2 ? "app-sidebar" : "bg-card",
)}
className="border-r border-border bg-card text-foreground"
resizable={{
maxWidth: sidebarMaximumWidth,
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
@@ -178,7 +168,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
onResize: setSidebarWidth,
}}
>
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
<ThreadSidebar />
<SidebarRail />
</Sidebar>
{children}
@@ -49,8 +49,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
latestTurn: null,
branch: null,
@@ -45,8 +45,6 @@ export function buildLocalDraftThread(
createdAt: draftThread.createdAt,
updatedAt: draftThread.createdAt,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
latestTurn: null,
branch: draftThread.branch,
+45 -1
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}
@@ -5220,7 +5258,6 @@ function ChatViewContent(props: ChatViewProps) {
{...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.title}
activeProjectCwd={activeProject?.workspaceRoot ?? null}
openInCwd={gitCwd}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
@@ -5353,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={
@@ -5549,6 +5591,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
@@ -5576,6 +5619,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
@@ -24,8 +24,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
proposedPlans: [],
createdAt: "2026-03-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
updatedAt: "2026-03-01T00:00:00.000Z",
latestTurn: 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}
@@ -18,10 +18,8 @@ import {
resolveSidebarNewThreadEnvMode,
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveSidebarV2Status,
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
sortThreadsForSidebarV2,
sortProjectsForSidebar,
sortScopedProjectsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
@@ -636,100 +634,6 @@ describe("isContextMenuPointerDown", () => {
});
});
describe("resolveSidebarV2Status", () => {
const session = {
threadId: ThreadId.make("thread-1"),
status: "running" as const,
providerName: "Codex",
providerInstanceId: ProviderInstanceId.make("codex"),
runtimeMode: DEFAULT_RUNTIME_MODE,
activeTurnId: "turn-1" as never,
lastError: null,
updatedAt: "2026-03-09T10:00:00.000Z",
};
const idle = { hasPendingApprovals: false, hasPendingUserInput: false };
it("prioritizes approval over a running session", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, session })).toBe(
"approval",
);
});
it("prioritizes awaiting input over a running session, below approval", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, session })).toBe("input");
expect(
resolveSidebarV2Status({
...idle,
hasPendingApprovals: true,
hasPendingUserInput: true,
session,
}),
).toBe("approval");
});
it("reports working for running and starting sessions", () => {
expect(resolveSidebarV2Status({ ...idle, session })).toBe("working");
expect(
resolveSidebarV2Status({
...idle,
session: { ...session, status: "starting" as const },
}),
).toBe("working");
});
it("reports failed only while the session status is error", () => {
expect(
resolveSidebarV2Status({
...idle,
session: { ...session, status: "error" as const, lastError: "boom" },
}),
).toBe("failed");
expect(
resolveSidebarV2Status({
...idle,
session: { ...session, status: "stopped" as const, lastError: "persisted" },
}),
).toBe("ready");
expect(
resolveSidebarV2Status({
...idle,
session: { ...session, status: "ready" as const, lastError: "persisted" },
}),
).toBe("ready");
});
it("defaults to ready with no session", () => {
expect(resolveSidebarV2Status({ ...idle, session: null })).toBe("ready");
});
});
describe("sortThreadsForSidebarV2", () => {
const sortable = (input: { id: string; createdAt: string }) => ({
id: input.id,
createdAt: input.createdAt,
});
it("orders by creation time, newest first, ignoring activity", () => {
const sorted = sortThreadsForSidebarV2([
sortable({ id: "oldest", createdAt: "2026-03-09T08:00:00.000Z" }),
sortable({ id: "newest", createdAt: "2026-03-09T12:00:00.000Z" }),
sortable({ id: "middle", createdAt: "2026-03-09T10:00:00.000Z" }),
]);
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
});
it("breaks creation-time ties by id so the order is stable", () => {
const sorted = sortThreadsForSidebarV2([
sortable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z" }),
sortable({ id: "a", createdAt: "2026-03-09T10:00:00.000Z" }),
]);
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
});
});
describe("resolveThreadStatusPill", () => {
const baseThread = {
hasActionableProposedPlan: false,
@@ -996,8 +900,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
proposedPlans: [],
createdAt: "2026-03-09T10:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
updatedAt: "2026-03-09T10:00:00.000Z",
latestTurn: null,
-65
View File
@@ -417,71 +417,6 @@ export function resolveThreadRowClassName(input: {
return cn(baseClassName, "text-muted-foreground hover:bg-accent hover:text-foreground");
}
// ── Sidebar v2 status model ─────────────────────────────────────────
// Five visual states, three colors: color is reserved for "act now"
// (approval), "in motion" (working), and "broken" (failed). Ready is the
// unlabeled resting state — the agent stopped and is waiting on the user,
// whether it finished, asked a question, or proposed a plan.
// Unread completion is tracked separately: it describes whether a ready
// thread needs attention, not what the thread is currently doing.
export type SidebarV2Status = "approval" | "input" | "working" | "failed" | "ready";
type SidebarV2StatusInput = Pick<
SidebarThreadSummary,
"hasPendingApprovals" | "hasPendingUserInput" | "session"
>;
export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {
if (thread.hasPendingApprovals) {
return "approval";
}
if (thread.hasPendingUserInput) {
return "input";
}
if (thread.session?.status === "running" || thread.session?.status === "starting") {
return "working";
}
if (thread.session?.status === "error") {
return "failed";
}
return "ready";
}
/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
poison the whole ordering, so it sinks to the epoch instead. */
export function parseTimestampMs(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? 0 : parsed;
}
/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
yet-malformed string must also fall through to the next candidate rather
than sink the row to the epoch. */
export function firstValidTimestampMs(
...candidates: ReadonlyArray<string | null | undefined>
): number {
for (const candidate of candidates) {
if (candidate == null) continue;
const parsed = Date.parse(candidate);
if (!Number.isNaN(parsed)) return parsed;
}
return 0;
}
// v2 sort: static creation order, newest thread on top. Activity NEVER
// reorders the list — a row holds its position from open until settled, so
// the screen only moves at lifecycle transitions. Status (including pending
// approval) is carried by each card's edge strip, not by position.
export function sortThreadsForSidebarV2<
T extends { readonly id: string; readonly createdAt: string },
>(threads: readonly T[]): T[] {
return [...threads].toSorted(
(left, right) =>
parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
left.id.localeCompare(right.id),
);
}
export function resolveThreadStatusPill(input: {
thread: ThreadStatusInput;
}): ThreadStatusPill | null {
+118 -4
View File
@@ -8,6 +8,7 @@ import {
Globe2Icon,
LoaderIcon,
SearchIcon,
SettingsIcon,
SquarePenIcon,
TerminalIcon,
TriangleAlertIcon,
@@ -62,7 +63,7 @@ import {
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router";
import { Link, useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router";
import {
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
MIN_SIDEBAR_THREAD_PREVIEW_COUNT,
@@ -73,9 +74,10 @@ import {
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { useOpenPrLink } from "../lib/openPullRequestLink";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isMacPlatform } from "../lib/utils";
import { cn, isMacPlatform } from "../lib/utils";
import {
readThreadShell,
useProject,
@@ -124,6 +126,7 @@ import {
import { stackedThreadToast, toastManager } from "./ui/toast";
import { formatRelativeTimeLabel } from "../timestampFormat";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import { SidebarStageBackdrop, resolveSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import { Kbd } from "./ui/kbd";
import {
getArm64IntelBuildWarningDescription,
@@ -166,7 +169,9 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./u
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import {
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
@@ -174,6 +179,7 @@ import {
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarSeparator,
SidebarTrigger,
useSidebar,
} from "./ui/sidebar";
import { useThreadSelectionStore } from "../threadSelectionStore";
@@ -188,6 +194,7 @@ import {
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
@@ -197,12 +204,12 @@ import {
ThreadStatusPill,
} from "./Sidebar.logic";
import { sortThreads } from "../lib/threadSort";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { primaryServerKeybindingsAtom } from "../state/server";
import { primaryServerConfigAtom, primaryServerKeybindingsAtom } from "../state/server";
import {
derivePhysicalProjectKey,
deriveProjectGroupingOverrideKey,
@@ -216,6 +223,7 @@ import {
type SidebarProjectGroupMember,
type SidebarProjectSnapshot,
} from "../sidebarProjectGrouping";
import { SidebarProviderUpdatePill } from "./sidebar/SidebarProviderUpdatePill";
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
updated_at: "Last user message",
created_at: "Created at",
@@ -2779,6 +2787,112 @@ function SortableProjectItem({
);
}
const SidebarChromeHeader = memo(function SidebarChromeHeader({
isElectron,
}: {
isElectron: boolean;
}) {
const stageLabel = useSidebarStageLabel();
const backdropVariant = resolveSidebarStageBackdropVariant(stageLabel);
return (
<SidebarHeader
className={cn(
"@container/sidebar-header relative h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0",
isElectron && "drag-region",
)}
>
{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}
<SidebarTrigger
className={cn(
"relative z-10 md:hidden",
backdropVariant && "hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
)}
/>
<SidebarBrand onBackdrop={backdropVariant !== null} />
</SidebarHeader>
);
});
function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
return (
<Link
aria-label="Go to threads"
className={cn(
"sidebar-brand relative z-10 ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2",
onBackdrop ? "text-white" : "text-foreground",
)}
to="/"
>
<T3Wordmark />
<span
className={cn(
"truncate text-sm font-medium tracking-tight",
onBackdrop ? "text-white/70" : "text-muted-foreground",
)}
>
Code
</span>
</Link>
);
}
function useSidebarStageLabel() {
const primaryServerVersion =
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
return resolveSidebarStageBadgeLabel({
primaryServerVersion,
fallbackStageLabel: APP_STAGE_LABEL,
});
}
function T3Wordmark() {
return (
<svg
aria-label="T3"
className="h-2.5 w-auto shrink-0"
viewBox="15.5309 37 94.3941 56.96"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
fill="currentColor"
/>
</svg>
);
}
const SidebarChromeFooter = memo(function SidebarChromeFooter() {
const navigate = useNavigate();
const { isMobile, setOpenMobile } = useSidebar();
const handleSettingsClick = useCallback(() => {
if (isMobile) {
setOpenMobile(false);
}
void navigate({ to: "/settings" });
}, [isMobile, navigate, setOpenMobile]);
return (
<SidebarFooter className="p-2">
<SidebarProviderUpdatePill />
<SidebarUpdatePill />
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={handleSettingsClick}
>
<SettingsIcon className="size-3.5" />
<span className="text-xs">Settings</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
);
});
interface SidebarProjectsContentProps {
showArm64IntelBuildWarning: boolean;
arm64IntelBuildWarningDescription: string | null;
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;
@@ -2143,10 +2143,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
ref={composerSurfaceRef}
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-foreground/40",
isDragOverComposer
? "border-primary/70 bg-accent/45"
: "border-black/12 dark:border-white/12",
"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",
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
@@ -16,7 +16,6 @@ import ProjectScriptsControl, {
} from "../ProjectScriptsControl";
import { OpenInPicker } from "./OpenInPicker";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { ProjectFavicon } from "../ProjectFavicon";
import { cn } from "~/lib/utils";
interface ChatHeaderProps {
@@ -25,7 +24,6 @@ interface ChatHeaderProps {
draftId?: DraftId;
activeThreadTitle: string;
activeProjectName: string | undefined;
activeProjectCwd: string | null;
openInCwd: string | null;
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
preferredScriptId: string | null;
@@ -60,7 +58,6 @@ export const ChatHeader = memo(function ChatHeader({
draftId,
activeThreadTitle,
activeProjectName,
activeProjectCwd,
openInCwd,
activeProjectScripts,
preferredScriptId,
@@ -82,26 +79,6 @@ export const ChatHeader = memo(function ChatHeader({
return (
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
{/* The project always leads the header: knowing which project a
thread lives in is priority zero, and the thread title alone
doesn't answer it. */}
{activeProjectName ? (
<span className="inline-flex shrink-0 items-center gap-2">
<span className="inline-flex min-w-0 items-center gap-1.5">
<ProjectFavicon
environmentId={activeThreadEnvironmentId}
cwd={activeProjectCwd ?? ""}
className="size-3.5"
/>
<span className="max-w-40 truncate text-sm font-medium text-muted-foreground">
{activeProjectName}
</span>
</span>
<span aria-hidden className="text-muted-foreground/40">
/
</span>
</span>
) : null}
<Tooltip>
<TooltipTrigger
render={
@@ -1,108 +0,0 @@
import { useEffect, useState } from "react";
import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
import { Input } from "../ui/input";
import { Switch } from "../ui/switch";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
const AUTO_SETTLE_MIN_DAYS = 1;
const AUTO_SETTLE_MAX_DAYS = 90;
const AUTO_SETTLE_DEFAULT_DAYS = 3;
function AutoSettleDaysInput({
value,
onCommit,
}: {
value: number;
onCommit: (days: number) => void;
}) {
// Local draft so the field can be emptied mid-edit; the setting only moves
// on valid input and snaps back to the persisted value on blur.
const [draft, setDraft] = useState(String(value));
useEffect(() => {
setDraft(String(value));
}, [value]);
return (
<Input
type="number"
min={AUTO_SETTLE_MIN_DAYS}
max={AUTO_SETTLE_MAX_DAYS}
className="w-full sm:w-24"
value={draft}
onChange={(event) => {
setDraft(event.target.value);
// Number(), not parseInt: "3.5" must be rejected (not truncated to a
// committed 3 while the field shows 3.5) — commit only when the
// persisted value matches the displayed one.
const parsed = Number(event.target.value);
if (
Number.isInteger(parsed) &&
parsed >= AUTO_SETTLE_MIN_DAYS &&
parsed <= AUTO_SETTLE_MAX_DAYS
) {
onCommit(parsed);
}
}}
onBlur={() => setDraft(String(value))}
aria-label="Days of inactivity before auto-settle"
/>
);
}
export function BetaSettingsPanel() {
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const sidebarAutoSettleAfterDays = useClientSettings(
(settings) => settings.sidebarAutoSettleAfterDays,
);
const updateSettings = useUpdateClientSettings();
return (
<SettingsPageContainer>
<SettingsSection title="Beta features">
<SettingsRow
title="Sidebar v2"
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
control={
<Switch
checked={sidebarV2Enabled}
onCheckedChange={(checked) => updateSettings({ sidebarV2Enabled: Boolean(checked) })}
aria-label="Enable the sidebar v2 beta"
/>
}
/>
{sidebarV2Enabled ? (
<>
<SettingsRow
title="Auto-settle inactive threads"
description="Threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
control={
<Switch
checked={sidebarAutoSettleAfterDays !== null}
onCheckedChange={(checked) =>
updateSettings({
sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null,
})
}
aria-label="Auto-settle inactive threads"
/>
}
/>
{sidebarAutoSettleAfterDays !== null ? (
<SettingsRow
title="Days of inactivity before auto-settle"
description="Any new activity un-settles a thread automatically."
control={
<AutoSettleDaysInput
value={sidebarAutoSettleAfterDays}
onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })}
/>
}
/>
) : null}
</>
) : null}
</SettingsSection>
</SettingsPageContainer>
);
}
@@ -3,7 +3,6 @@ import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
FlaskConicalIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
@@ -29,7 +28,6 @@ export type SettingsSectionPath =
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/beta"
| "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
@@ -42,7 +40,6 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Beta", to: "/settings/beta", icon: FlaskConicalIcon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
@@ -1,127 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import { SettingsIcon } from "lucide-react";
import { memo, useCallback } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { APP_STAGE_LABEL } from "../../branding";
import { cn } from "../../lib/utils";
import { primaryServerConfigAtom } from "../../state/server";
import { resolveSidebarStageBadgeLabel } from "../Sidebar.logic";
import { SidebarStageBackdrop, resolveSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
import {
SidebarFooter,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarTrigger,
useSidebar,
} from "../ui/sidebar";
import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill";
import { SidebarUpdatePill } from "./SidebarUpdatePill";
export const SidebarChromeHeader = memo(function SidebarChromeHeader({
isElectron,
}: {
isElectron: boolean;
}) {
const stageLabel = useSidebarStageLabel();
const backdropVariant = resolveSidebarStageBackdropVariant(stageLabel);
return (
<SidebarHeader
className={cn(
"@container/sidebar-header relative h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0",
isElectron && "drag-region",
)}
>
{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}
<SidebarTrigger
className={cn(
"relative z-10 md:hidden",
backdropVariant && "hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
)}
/>
<SidebarBrand onBackdrop={backdropVariant !== null} />
</SidebarHeader>
);
});
function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
return (
<Link
aria-label="Go to threads"
className={cn(
"sidebar-brand relative z-10 ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2",
onBackdrop ? "text-white" : "text-foreground",
)}
to="/"
>
<T3Wordmark />
<span
className={cn(
"truncate text-sm font-medium tracking-tight",
onBackdrop ? "text-white/70" : "text-muted-foreground",
)}
>
Code
</span>
</Link>
);
}
function useSidebarStageLabel() {
const primaryServerVersion =
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
return resolveSidebarStageBadgeLabel({
primaryServerVersion,
fallbackStageLabel: APP_STAGE_LABEL,
});
}
function T3Wordmark() {
return (
<svg
aria-label="T3"
className="h-2.5 w-auto shrink-0"
viewBox="15.5309 37 94.3941 56.96"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
fill="currentColor"
/>
</svg>
);
}
export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
const navigate = useNavigate();
const { isMobile, setOpenMobile } = useSidebar();
const handleSettingsClick = useCallback(() => {
if (isMobile) {
setOpenMobile(false);
}
void navigate({ to: "/settings" });
}, [isMobile, navigate, setOpenMobile]);
return (
<SidebarFooter className="p-2">
<SidebarProviderUpdatePill />
<SidebarUpdatePill />
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={handleSettingsClick}
>
<SettingsIcon className="size-3.5" />
<span className="text-xs">Settings</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
);
});
-49
View File
@@ -21,7 +21,6 @@ import {
import { PrimaryEnvironmentHttpClient } from "./httpClient";
import { runPrimaryHttp } from "../../lib/runtime";
import { isHostedStaticApp } from "../../hostedPairing";
const PrimaryEnvironmentRequestOperation = Schema.Literals([
"fetch-session-state",
@@ -318,51 +317,6 @@ function isTransientBootstrapError(error: unknown): boolean {
return error instanceof DOMException && error.name === "AbortError";
}
// Dev-only silent pairing: local web-dev servers expose a guarded endpoint
// that mints a one-time pairing credential for the dev origin, so fresh
// browser contexts authenticate without a pairing code. Any failure means
// "not available" (prod, remote, guard rejection) and the caller falls back
// to the normal pairing screen — never surface an error for this path.
// import.meta.env.DEV keeps the request out of production bundles entirely.
function shouldAttemptDevPairing(auth: AuthSessionState["auth"]): boolean {
return (
import.meta.env.DEV &&
auth.policy === "loopback-browser" &&
!isHostedStaticApp() &&
window.desktopBridge === undefined &&
peekPairingTokenFromUrl() === null
);
}
async function fetchDevPairingCredential(): Promise<string | null> {
try {
const result = await runPrimaryHttp(
PrimaryEnvironmentHttpClient.pipe(
Effect.flatMap((client) => client.auth.devPairingCredential({ payload: {} })),
),
);
return typeof result.credential === "string" && result.credential.length > 0
? result.credential
: null;
} catch {
return null;
}
}
async function attemptSilentDevPairing(): Promise<boolean> {
const credential = await fetchDevPairingCredential();
if (credential === null) {
return false;
}
try {
await exchangeBootstrapCredential(credential);
await waitForAuthenticatedSessionAfterBootstrap();
return true;
} catch {
return false;
}
}
async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
const bootstrapCredential = getDesktopBootstrapCredential();
const currentSession = await fetchSessionState();
@@ -371,9 +325,6 @@ async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
}
if (!bootstrapCredential) {
if (shouldAttemptDevPairing(currentSession.auth) && (await attemptSilentDevPairing())) {
return { status: "authenticated" };
}
return {
status: "requires-auth",
auth: currentSession.auth,
+2 -107
View File
@@ -4,7 +4,6 @@ import {
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
@@ -20,12 +19,7 @@ import { vcsEnvironment } from "../state/vcs";
import { useNewThreadHandler } from "./useHandleNewThread";
import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
import { readLocalApi } from "../localApi";
import {
readEnvironmentSupportsSettlement,
readEnvironmentThreadRefs,
readProject,
readThreadShell,
} from "../state/entities";
import { readEnvironmentThreadRefs, readProject, readThreadShell } from "../state/entities";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
@@ -45,30 +39,6 @@ export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArc
}
}
export class ThreadSettlementUnsupportedError extends Schema.TaggedErrorClass<ThreadSettlementUnsupportedError>()(
"ThreadSettlementUnsupportedError",
{
environmentId: EnvironmentId,
threadId: ThreadId,
},
) {
override get message(): string {
return "This environment's server does not support settling yet. Update the server to use Settle.";
}
}
export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSettleBlockedError>()(
"ThreadSettleBlockedError",
{
environmentId: EnvironmentId,
threadId: ThreadId,
},
) {
override get message(): string {
return "This thread still needs attention. Resolve or interrupt it first, then try again.";
}
}
export function useThreadActions() {
const closeTerminal = useAtomCommand(terminalEnvironment.close);
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
@@ -80,12 +50,6 @@ export function useThreadActions() {
const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
reportFailure: false,
});
const settleThreadMutation = useAtomCommand(threadEnvironment.settle, {
reportFailure: false,
});
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
reportFailure: false,
});
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
@@ -381,66 +345,6 @@ export function useThreadActions() {
],
);
const settleThread = useCallback(
async (target: ScopedThreadRef) => {
// Version skew: never send the command to a server that predates it —
// the raw protocol rejection would read as a random failure.
if (!readEnvironmentSupportsSettlement(target.environmentId)) {
return AsyncResult.failure(
Cause.fail(
new ThreadSettlementUnsupportedError({
environmentId: target.environmentId,
threadId: target.threadId,
}),
),
);
}
const resolved = resolveThreadTarget(target);
// Settle may only target what effectiveSettled could classify as
// settled: not starting/running sessions, not threads waiting on
// approvals or user input. Anything else would hide live work.
if (resolved && !canSettle(resolved.thread, { now: new Date().toISOString() })) {
return AsyncResult.failure(
Cause.fail(
new ThreadSettleBlockedError({
environmentId: resolved.threadRef.environmentId,
threadId: resolved.threadRef.threadId,
}),
),
);
}
// Settle is a high-frequency lifecycle action and stays silent — no
// toast.
return settleThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
},
[resolveThreadTarget, settleThreadMutation],
);
const unsettleThread = useCallback(
async (target: ScopedThreadRef) => {
if (!readEnvironmentSupportsSettlement(target.environmentId)) {
return AsyncResult.failure(
Cause.fail(
new ThreadSettlementUnsupportedError({
environmentId: target.environmentId,
threadId: target.threadId,
}),
),
);
}
// reason "user" pins the thread active: auto-settle (PR merged /
// inactivity) stays suppressed until real activity clears the pin.
return unsettleThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId, reason: "user" },
});
},
[unsettleThreadMutation],
);
const confirmAndDeleteThread = useCallback(
async (target: ScopedThreadRef) => {
const localApi = readLocalApi();
@@ -475,16 +379,7 @@ export function useThreadActions() {
unarchiveThread,
deleteThread,
confirmAndDeleteThread,
settleThread,
unsettleThread,
}),
[
archiveThread,
confirmAndDeleteThread,
deleteThread,
settleThread,
unarchiveThread,
unsettleThread,
],
[archiveThread, confirmAndDeleteThread, deleteThread, unarchiveThread],
);
}
+10 -63
View File
@@ -108,11 +108,11 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
@theme inline {
--animate-skeleton: skeleton 2s -1s infinite linear;
/* Duty-cycled indicator animations: long holds with stepped ramps, so the
compositor updates discrete frames instead of every vsync. */
/* Duty-cycled indicator animations: long opacity holds with short stepped
ramps, so the compositor only produces frames while the value changes
(~20% of the cycle) instead of every vsync. Keep flat holds dominant. */
--animate-status-pulse: status-pulse 2s infinite;
--animate-status-ping: status-ping 2s infinite;
--animate-sidebar-working-text: sidebar-working-text 3.4s infinite;
--font-sans:
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
sans-serif;
@@ -185,21 +185,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
scale: 2;
}
}
@keyframes sidebar-working-text {
0%,
36% {
opacity: 1;
animation-timing-function: steps(10);
}
50%,
86% {
opacity: 0.75;
animation-timing-function: steps(10);
}
100% {
opacity: 1;
}
}
}
@layer base {
@@ -247,11 +232,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
}
/* Stage-channel sidebar art; ::after ramps to the sidebar bg color and the
mask lets the surface grain show through at the boundary. Panels whose
background differs from the app chrome (e.g. sidebar v2) override
--sidebar-stage-fade so the art fades into their own surface color. */
mask lets the surface grain show through at the boundary. */
.sidebar-stage-backdrop {
--stage-fade: var(--sidebar-stage-fade, var(--app-chrome-background));
mask-image: linear-gradient(to bottom, black 0%, black 55%, transparent 92%);
-webkit-mask-image: linear-gradient(to bottom, black 0%, black 55%, transparent 92%);
}
@@ -264,12 +246,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
to bottom,
transparent 0%,
transparent 28%,
color-mix(in srgb, var(--stage-fade) 10%, transparent) 40%,
color-mix(in srgb, var(--stage-fade) 30%, transparent) 52%,
color-mix(in srgb, var(--stage-fade) 58%, transparent) 64%,
color-mix(in srgb, var(--stage-fade) 82%, transparent) 75%,
color-mix(in srgb, var(--stage-fade) 96%, transparent) 85%,
var(--stage-fade) 93%
color-mix(in srgb, var(--app-chrome-background) 10%, transparent) 40%,
color-mix(in srgb, var(--app-chrome-background) 30%, transparent) 52%,
color-mix(in srgb, var(--app-chrome-background) 58%, transparent) 64%,
color-mix(in srgb, var(--app-chrome-background) 82%, transparent) 75%,
color-mix(in srgb, var(--app-chrome-background) 96%, transparent) 85%,
var(--app-chrome-background) 93%
);
}
@@ -468,41 +450,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
}
}
/* Give the navigation rail its own cool graphite surface instead of borrowing
the workspace card color. The scoped semantic tokens keep sidebar v2's
controls in the same palette without changing v1 or the settings nav. */
.app-sidebar {
--background: oklch(0.965 0.009 265);
--foreground: oklch(0.27 0.025 265);
--card: oklch(0.945 0.014 265);
--card-foreground: var(--foreground);
--accent: oklch(0.875 0.008 265);
--accent-foreground: oklch(0.24 0.012 265);
--muted: oklch(0.9 0.018 265);
--muted-foreground: oklch(0.49 0.03 265);
--border: oklch(0.72 0.025 265 / 28%);
--input: oklch(0.62 0.03 265 / 28%);
--sidebar-stage-fade: var(--card);
background-color: var(--card);
}
.dark .app-sidebar {
--background: #000;
--foreground: #f1f3f7;
--card: #000;
--card-foreground: var(--foreground);
--accent: #191a1d;
--accent-foreground: #f7f9ff;
--muted: #0a0a0a;
--muted-foreground: #a3a3a3;
--border: rgb(255 255 255 / 14%);
--input: rgb(255 255 255 / 18%);
/* The stage-channel header art must ramp to THIS panel's surface, not the
global chrome background, or the fade shows a seam (same rule as the
light palette above). */
--sidebar-stage-fade: var(--card);
}
body {
font-family:
"DM Sans Variable",
@@ -6,7 +6,6 @@ import {
resolveNewDraftStartFromOrigin,
startNewLocalThreadFromContext,
startNewThreadFromContext,
startNewThreadInProjectFromContext,
type ChatThreadActionContext,
} from "./chatThreadActions";
@@ -118,26 +117,6 @@ describe("chatThreadActions", () => {
});
});
it("does not carry branch or worktree context into a different project", async () => {
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
const targetProjectRef = scopeProjectRef(ENVIRONMENT_ID, FALLBACK_PROJECT_ID);
await startNewThreadInProjectFromContext(
createContext({
activeThread: {
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
branch: "feature/refactor",
worktreePath: "/tmp/worktree",
},
handleNewThread,
}),
targetProjectRef,
);
expect(handleNewThread).toHaveBeenCalledWith(targetProjectRef);
});
it("delegates the target environment defaults to the new-thread handler", async () => {
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
-8
View File
@@ -75,14 +75,6 @@ export async function startNewThreadInProjectFromContext(
context: ChatThreadActionContext,
projectRef: ScopedProjectRef,
): Promise<void> {
const contextualProjectRef = resolveThreadActionProjectRef(context);
const matchesContext =
contextualProjectRef?.environmentId === projectRef.environmentId &&
contextualProjectRef.projectId === projectRef.projectId;
if (!matchesContext) {
await context.handleNewThread(projectRef);
return;
}
await context.handleNewThread(projectRef, buildContextualThreadOptions(context));
}
-2
View File
@@ -26,8 +26,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
proposedPlans: [],
createdAt: "2026-03-09T10:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
updatedAt: "2026-03-09T10:00:00.000Z",
latestTurn: null,
-14
View File
@@ -1,14 +0,0 @@
// Tiny event bus connecting the global chat.new shortcut (handled in the
// _chat route layout) to SidebarV2's project picker dialog. The route layer
// can't render the picker itself — it lives with the sidebar — and the
// sidebar can't own the window keydown handler without racing the layout's.
const NEW_THREAD_PICKER_EVENT = "t3code:open-new-thread-picker";
export function openNewThreadPicker(): void {
window.dispatchEvent(new CustomEvent(NEW_THREAD_PICKER_EVENT));
}
export function onOpenNewThreadPicker(listener: () => void): () => void {
window.addEventListener(NEW_THREAD_PICKER_EVENT, listener);
return () => window.removeEventListener(NEW_THREAD_PICKER_EVENT, listener);
}
+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 };
}
};
-21
View File
@@ -20,7 +20,6 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
@@ -80,11 +79,6 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
path: '/connections',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsBetaRoute = SettingsBetaRouteImport.update({
id: '/beta',
path: '/beta',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
id: '/archived',
path: '/archived',
@@ -114,7 +108,6 @@ export interface FileRoutesByFullPath {
'/settings': typeof SettingsRouteWithChildren
'/connect/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -130,7 +123,6 @@ export interface FileRoutesByTo {
'/settings': typeof SettingsRouteWithChildren
'/connect/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -149,7 +141,6 @@ export interface FileRoutesById {
'/settings': typeof SettingsRouteWithChildren
'/connect_/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -169,7 +160,6 @@ export interface FileRouteTypes {
| '/settings'
| '/connect/callback'
| '/settings/archived'
| '/settings/beta'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -185,7 +175,6 @@ export interface FileRouteTypes {
| '/settings'
| '/connect/callback'
| '/settings/archived'
| '/settings/beta'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -203,7 +192,6 @@ export interface FileRouteTypes {
| '/settings'
| '/connect_/callback'
| '/settings/archived'
| '/settings/beta'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -302,13 +290,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsConnectionsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/beta': {
id: '/settings/beta'
path: '/beta'
fullPath: '/settings/beta'
preLoaderRoute: typeof SettingsBetaRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/archived': {
id: '/settings/archived'
path: '/archived'
@@ -356,7 +337,6 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
interface SettingsRouteChildren {
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsBetaRoute: typeof SettingsBetaRoute
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
@@ -367,7 +347,6 @@ interface SettingsRouteChildren {
const SettingsRouteChildren: SettingsRouteChildren = {
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsBetaRoute: SettingsBetaRoute,
SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
-14
View File
@@ -3,9 +3,6 @@ import { useAtomValue } from "@effect/atom-react";
import { useEffect } from "react";
import { isCommandPaletteOpen } from "../commandPaletteContext";
import { useClientSettings } from "../hooks/useSettings";
import { openNewThreadPicker } from "../newThreadPickerBus";
import { useProjects } from "../state/entities";
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import {
@@ -28,8 +25,6 @@ function ChatRouteGlobalShortcuts() {
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
useHandleNewThread();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const projectCount = useProjects().length;
const terminalOpen = useTerminalUiStateStore((state) =>
routeThreadRef
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
@@ -80,13 +75,6 @@ function ChatRouteGlobalShortcuts() {
if (command === "chat.new") {
event.preventDefault();
event.stopPropagation();
// Sidebar v2 routes creation through its project picker whenever
// there is a real choice to make; v1 (and single-project setups)
// keep the immediate contextual create.
if (sidebarV2Enabled && projectCount > 1) {
openNewThreadPicker();
return;
}
void startNewThreadFromContext({
activeDraftThread,
activeThread: activeThread ?? undefined,
@@ -152,10 +140,8 @@ function ChatRouteGlobalShortcuts() {
keybindings,
defaultProjectRef,
previewOpen,
projectCount,
routeThreadRef,
selectedThreadKeysSize,
sidebarV2Enabled,
terminalOpen,
]);
-11
View File
@@ -1,11 +0,0 @@
import { createFileRoute } from "@tanstack/react-router";
import { BetaSettingsPanel } from "../components/settings/BetaSettingsPanel";
function SettingsBetaRoute() {
return <BetaSettingsPanel />;
}
export const Route = createFileRoute("/settings/beta")({
component: SettingsBetaRoute,
});
+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));
-10
View File
@@ -185,16 +185,6 @@ export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell |
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
}
/** Whether the environment's server understands thread.settle/unsettle.
False for pre-settlement servers (capability defaults false on decode),
so clients under version skew fall back instead of erroring. */
export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSettlement === true
);
}
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
}
+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;
}
-2
View File
@@ -26,8 +26,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
createdAt: "2026-02-13T00:00:00.000Z",
updatedAt: "2026-02-13T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
latestTurn: null,
branch: null,
-17
View File
@@ -12,7 +12,6 @@ import {
type AuthSessionState,
type ExecutionEnvironmentDescriptor,
type EnvironmentAuthInvalidError,
type EnvironmentResourceNotFoundError,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import type * as Context from "effect/Context";
@@ -36,10 +35,6 @@ interface EnvironmentHttpTestScenario {
readonly pairingCredential?: (
payload: AuthCreatePairingCredentialInput,
) => Effect.Effect<AuthPairingCredentialResult>;
readonly devPairingCredential?: () => Effect.Effect<
AuthPairingCredentialResult,
EnvironmentResourceNotFoundError
>;
}
export interface EnvironmentHttpTestCalls {
@@ -47,7 +42,6 @@ export interface EnvironmentHttpTestCalls {
session: number;
browserSession: Array<AuthBrowserSessionRequest>;
pairingCredential: Array<AuthCreatePairingCredentialInput>;
devPairingCredential: number;
}
const unexpectedEndpoint = (endpoint: string) =>
@@ -72,7 +66,6 @@ export async function installEnvironmentHttpTest(scenario: EnvironmentHttpTestSc
session: 0,
browserSession: [],
pairingCredential: [],
devPairingCredential: 0,
};
const client = await Effect.runPromise(
@@ -108,16 +101,6 @@ export async function installEnvironmentHttpTest(scenario: EnvironmentHttpTestSc
)
.handle("token", () => unexpectedEndpoint("auth.token"))
.handle("webSocketTicket", () => unexpectedEndpoint("auth.webSocketTicket"))
.handle(
"devPairingCredential",
Effect.fn("test.environment.auth.devPairingCredential")(function* () {
calls.devPairingCredential += 1;
return yield* (
scenario.devPairingCredential?.() ??
unexpectedEndpoint("auth.devPairingCredential")
);
}),
)
.handle(
"pairingCredential",
Effect.fn("test.environment.auth.pairingCredential")(function* ({ payload }) {
-33
View File
@@ -82,39 +82,6 @@ currently dispatches an orchestration operation, so clients performing it also
need `orchestration:operate`. Creating a ticket is not
authorization to call every RPC method.
### Dev-Mode Silent Pairing
`POST /api/auth/dev-pairing-token` lets the web app authenticate automatically
against a **local development** server, so contributors and coding agents never
handle pairing codes in dev. It mints an ordinary one-time, five-minute
bootstrap credential (administrative scopes, subject `dev-auto-bootstrap`,
hidden from the pairing-links listing) that the client immediately exchanges
through the normal browser-session flow.
The endpoint answers `404 dev_pairing_not_available` unless all of the
following hold:
- the server runs in web mode with a configured dev URL (`bun run dev`),
- the dev URL's hostname is loopback (`--dev-url` never becomes an auth root),
- the auth policy is exactly `loopback-browser` (excludes desktop dev and any
non-loopback bind host).
Eligible requests are then authenticated per-request: the browser-attached
`Origin` header must exactly equal the dev origin (this survives the Vite dev
proxy, which rewrites `Host` but not `Origin`), and the parsed `Host` header
must be loopback (DNS-rebinding defense for direct requests). Failures answer
`403 dev_pairing_request_rejected`. Because the payload is JSON, the request is
preflighted, so unauthorized web origins cannot even trigger credential
issuance. Local non-browser processes can forge these headers, but they can
already read the dev state directory directly, so no privilege is gained.
When silent pairing is eligible, server startup opens the plain dev URL instead
of minting a `/pair#token=...` startup credential (the silent path would leave
that administrative token unconsumed in the URL and terminal scrollback). All
other startup shapes are unchanged, and the `/pair` screen remains the flow for
production, remote access, and explicit pairing links; an explicit `#token` in
the URL always takes precedence over silent pairing.
## Standards Alignment
- Bearer access tokens are used through the `Authorization: Bearer` scheme from
+1 -12
View File
@@ -4,7 +4,7 @@
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
- `vp run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
- Web dev commands do not auto-open a browser. Local web-dev servers authenticate the UI automatically, so open the plain dev URL printed by the server. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
- Pass dev-runner flags directly after the root task name, for example:
`vp run dev --home-dir /tmp/t3code-dev`
- `vp run start` — Runs the production server (serves built web app as static files).
@@ -45,14 +45,3 @@ Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports
- Example: `T3CODE_DEV_INSTANCE=branch-a vp run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
### Authentication across dev instances
Local web-dev servers support silent pairing: the web app authenticates
automatically on load, with no pairing code (see the dev-mode section in
`docs/cloud/environment-auth.md` for the guards). Additionally, all dev
instances sharing a `T3CODE_HOME` share the session store and signing secret
under `<T3CODE_HOME>/dev`, so a browser session created against one instance
verifies against every other. Cookies are host-scoped: sessions carry across
ports on the same hostname, but `localhost` and `127.0.0.1` do not share
cookies — use one hostname consistently.
+4 -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"
@@ -127,10 +131,6 @@
"types": "./src/state/threadSort.ts",
"default": "./src/state/threadSort.ts"
},
"./state/thread-settled": {
"types": "./src/state/threadSettled.ts",
"default": "./src/state/threadSettled.ts"
},
"./state/vcs": {
"types": "./src/state/vcs.ts",
"default": "./src/state/vcs.ts"
@@ -21,13 +21,7 @@ import {
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import * as RpcSession from "../rpc/session.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import {
archiveThread,
createProject,
settleThread,
stopThreadSession,
unsettleThread,
} from "./commands.ts";
import { archiveThread, createProject, stopThreadSession } from "./commands.ts";
const TEST_CRYPTO_LAYER = Layer.succeed(
Crypto.Crypto,
@@ -140,35 +134,4 @@ describe("environment commands", () => {
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("dispatches settle and unsettle commands without timestamps", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
yield* settleThread({
commandId: CommandId.make("settle-command"),
threadId: ThreadId.make("thread-1"),
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
yield* unsettleThread({
commandId: CommandId.make("unsettle-command"),
threadId: ThreadId.make("thread-1"),
reason: "user",
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(dispatched).toEqual([
{
type: "thread.settle",
commandId: "settle-command",
threadId: "thread-1",
},
{
type: "thread.unsettle",
commandId: "unsettle-command",
threadId: "thread-1",
reason: "user",
},
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
});
@@ -35,8 +35,6 @@ export type CreateThreadInput = CommandInput<"thread.create">;
export type DeleteThreadInput = CommandInput<"thread.delete">;
export type ArchiveThreadInput = CommandInput<"thread.archive">;
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
export type SettleThreadInput = CommandInput<"thread.settle">;
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
@@ -155,26 +153,6 @@ export const unarchiveThread: (input: UnarchiveThreadInput) => CommandEffect = E
});
});
export const settleThread: (input: SettleThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.settleThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.settle",
commandId: yield* commandId(input),
});
});
export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.unsettleThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.unsettle",
commandId: yield* commandId(input),
});
});
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.updateThreadMetadata",
)(function* (input) {
@@ -96,8 +96,6 @@ const THREAD_SHELL = {
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
@@ -36,8 +36,6 @@ const stubThread = {
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
@@ -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}`;
}
@@ -12,11 +12,9 @@ import {
type RevertThreadCheckpointInput,
type SetThreadInteractionModeInput,
type SetThreadRuntimeModeInput,
type SettleThreadInput,
type StartThreadTurnInput,
type StopThreadSessionInput,
type UnarchiveThreadInput,
type UnsettleThreadInput,
type UpdateThreadMetadataInput,
archiveThread,
createThread,
@@ -27,11 +25,9 @@ import {
revertThreadCheckpoint,
setThreadInteractionMode,
setThreadRuntimeMode,
settleThread,
startThreadTurn,
stopThreadSession,
unarchiveThread,
unsettleThread,
updateThreadMetadata,
} from "../operations/commands.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
@@ -46,11 +42,9 @@ export type {
RevertThreadCheckpointInput,
SetThreadInteractionModeInput,
SetThreadRuntimeModeInput,
SettleThreadInput,
StartThreadTurnInput,
StopThreadSessionInput,
UnarchiveThreadInput,
UnsettleThreadInput,
UpdateThreadMetadataInput,
} from "../operations/commands.ts";
@@ -88,18 +82,6 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
settle: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:settle",
execute: (input: SettleThreadInput) => settleThread(input),
scheduler,
concurrency,
}),
unsettle: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:unsettle",
execute: (input: UnsettleThreadInput) => unsettleThread(input),
scheduler,
concurrency,
}),
updateMetadata: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:update-metadata",
execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),
@@ -57,8 +57,6 @@ export function mergeEnvironmentThread(
createdAt: shell.createdAt,
updatedAt: shell.updatedAt,
archivedAt: shell.archivedAt,
settledOverride: shell.settledOverride,
settledAt: shell.settledAt,
session: shell.session,
};
}
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more