@devries-cameron20 / t3code-1 / commits / 0d266fbe52
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(pi): show extension status in existing controls (#23901)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Yash Singh <saiansh2525@gmail.com>

Wout Stiens committed Nov 6, 2026 at 05:36 UTC 0d266fbe5211a9b6cdf2290b328fcb37c545194e
22 files changed +1341 -48
apps/mobile/src/components/ui/Dialog.android.tsx
+4 -1
@@ -10,6 +10,7 @@ import {
10 Text,
11 useNativeState,
12 } from "@expo/ui/jetpack-compose";
13 +import { verticalScroll } from "@expo/ui/jetpack-compose/modifiers";
14
15 import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";
16 import { useScaledTextRole } from "../../features/settings/appearance/useScaledTextRole";
@@ -252,7 +253,9 @@ function DialogPresentation(props: DialogPresentationProps) {
253 </AlertDialog.Text>
254 ) : props.request.message ? (
255 <AlertDialog.Text>
255 - <Text style={bodyTypography}>{props.request.message}</Text>
256 + <Text modifiers={[verticalScroll()]} style={bodyTypography}>
257 + {props.request.message}
258 + </Text>
259 </AlertDialog.Text>
260 ) : null}
261 {actions.length > 1 ? (
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+22
@@ -208,6 +208,7 @@ import type { ThreadContentPresentation } from "./threadContentPresentation";
208 import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
209 import { useOpenLinkedThread } from "./useOpenLinkedThread";
210 import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";
211 +import type { OrchestrationV2ProviderSession } from "@t3tools/contracts";
212
213 export interface ThreadDetailScreenProps {
214 readonly header?: React.ReactNode;
@@ -240,6 +241,7 @@ export interface ThreadDetailScreenProps {
241 readonly activeWorkStartedAt: string | null;
242 readonly runlessWorkActive?: boolean;
243 readonly providerSubagentStatus?: ProviderSubagentStatus | null;
244 + readonly extensionStatuses?: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>;
245 readonly isCompacting: boolean;
246 readonly creationState:
247 | {
@@ -735,6 +737,13 @@ function ThreadDetailBody(
737 const pendingBackgroundWork = presentPendingBackgroundWork(
738 props.selectedThread.pendingBackgroundTasks,
739 );
740 + const extensionStatus = props.extensionStatuses?.length
741 + ? {
742 + label: `Pi · ${props.extensionStatuses.map((status) => status.text).join(" · ")}`,
743 + onPress: () =>
744 + Dialog.alert("Pi", props.extensionStatuses?.map((status) => status.text).join("\n\n")),
745 + }
746 + : null;
747 const floatingStatus = ((): FloatingWorkingStatus | null => {
748 const connectionStatus = connectionFloatingStatus({
749 connectionError: connectionRetrying ? retryConnectionError : props.connectionError,
@@ -864,6 +873,9 @@ function ThreadDetailBody(
873 accessibilityLabel: `${goal.title}: ${goal.objective}`,
874 };
875 }
876 + if (extensionStatus !== null && contentPresentationKind === "ready") {
877 + return { kind: "extension", ...extensionStatus };
878 + }
879 return null;
880 })();
881 const showWorkingControl = floatingStatus !== null;
@@ -1602,6 +1614,16 @@ function ThreadDetailBody(
1614 <FloatingWorkingControl
1615 colorScheme={isDarkMode ? "dark" : "light"}
1616 status={floatingStatus}
1617 + extensionStatus={
1618 + floatingStatus !== null &&
1619 + (floatingStatus.kind === "working" ||
1620 + floatingStatus.kind === "compacting" ||
1621 + floatingStatus.kind === "background" ||
1622 + floatingStatus.kind === "goal" ||
1623 + floatingStatus.kind === "lifecycle")
1624 + ? extensionStatus
1625 + : null
1626 + }
1627 lift={floatingControlLift}
1628 devicePreview={
1629 devicePreviews.length > 0
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+1
@@ -991,6 +991,7 @@ function ThreadRouteContent(
991 }
992 isCompacting={composer.isCompacting}
993 runlessWorkActive={composer.runlessWorkActive}
994 + extensionStatuses={composer.extensionStatuses}
995 providerSubagentStatus={composer.providerSubagentStatus}
996 creationState={creationState}
997 setupWorkingStartedAt={
apps/mobile/src/features/threads/floating-working-control.tsx
+59 -8
@@ -69,6 +69,7 @@ export const FLOATING_WORKING_CONTROL_COVERAGE = CONTROL_OVERLAY_OFFSET + CONTRO
69 export function FloatingWorkingControl(props: {
70 readonly colorScheme: "light" | "dark";
71 readonly status: FloatingWorkingStatus | null;
72 + readonly extensionStatus?: { readonly label: string; readonly onPress: () => void } | null;
73 readonly devicePreview: { readonly count: number; readonly onPress: () => void } | null;
74 readonly browserPreview: { readonly count: number; readonly onPress: () => void } | null;
75 readonly showScrollToEnd: boolean;
@@ -84,6 +85,10 @@ export function FloatingWorkingControl(props: {
85 const [overlayWidth, setOverlayWidth] = useState(windowWidth);
86 const [queueWidth, setQueueWidth] = useState(0);
87 const [actionWidth, setActionWidth] = useState(0);
88 + const [extensionWidth, setExtensionWidth] = useState(0);
89 + const extensionStatus = props.extensionStatus ?? null;
90 + const extensionOnly = props.status?.kind === "extension";
91 + const useGlass = NATIVE_LIQUID_GLASS_SUPPORTED && !extensionOnly;
92 const action =
93 props.status?.kind === "background" ||
94 props.status?.kind === "lifecycle" ||
@@ -96,7 +101,7 @@ export function FloatingWorkingControl(props: {
101 const [previewWidth, setPreviewWidth] = useState(0);
102 const agents = props.agents;
103 const hasAgents = agents !== null;
99 - const labelWidth = Math.max(
104 + const availableLabelWidth = Math.max(
105 0,
106 Math.min(overlayWidth, windowWidth) -
107 CONTROL_HEIGHT -
@@ -106,6 +111,10 @@ export function FloatingWorkingControl(props: {
111 (hasAgents ? agentsWidth : 0) -
112 (hasPreview ? previewWidth : 0),
113 );
114 + const labelWidth = Math.max(
115 + 0,
116 + availableLabelWidth - (extensionStatus === null ? 0 : extensionWidth),
117 + );
118 const separationProgress = useSharedValue(props.showScrollToEnd ? 1 : 0);
119
120 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- animates the Reanimated separation value when scroll-to-end visibility changes
@@ -163,10 +172,16 @@ export function FloatingWorkingControl(props: {
172 (props.devicePreview !== null && props.browserPreview !== null);
173 const statusInteractive =
174 props.status?.kind === "connection" ||
175 + props.status?.kind === "extension" ||
176 props.status?.kind === "child-input" ||
177 props.status?.kind === "background";
178 const capsuleInteractive =
169 - statusInteractive || action !== null || hasQueue || hasAgents || hasPreview;
179 + statusInteractive ||
180 + extensionStatus !== null ||
181 + action !== null ||
182 + hasQueue ||
183 + hasAgents ||
184 + hasPreview;
185 const statusContent =
186 props.status !== null ? (
187 <View
@@ -181,7 +196,9 @@ export function FloatingWorkingControl(props: {
196 >
197 <FloatingStatusLabel
198 key={
184 - props.status.kind === "working" || props.status.kind === "compacting"
199 + props.status.kind === "working" ||
200 + props.status.kind === "compacting" ||
201 + props.status.kind === "extension"
202 ? props.status.kind
203 : `${props.status.kind}:${props.status.label}`
204 }
@@ -195,6 +212,22 @@ export function FloatingWorkingControl(props: {
212 const capsuleContent = (
213 <View className="flex-row items-center">
214 {statusContent}
215 + {extensionStatus !== null ? (
216 + <Pressable
217 + accessibilityRole="button"
218 + accessibilityLabel={extensionStatus.label}
219 + accessibilityHint="Shows the full Pi status"
220 + onPress={extensionStatus.onPress}
221 + onLayout={(event) => setExtensionWidth(settleWidth(event.nativeEvent.layout.width))}
222 + style={{ maxWidth: availableLabelWidth * 0.5 }}
223 + className="h-11 flex-row items-center px-3 active:opacity-70"
224 + >
225 + {hasStatus ? <View className="absolute left-0 h-4 w-px bg-border" /> : null}
226 + <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
227 + {extensionStatus.label}
228 + </Text>
229 + </Pressable>
230 + ) : null}
231 {action !== null ? (
232 <View
233 onLayout={(event) => setActionWidth(settleWidth(event.nativeEvent.layout.width))}
@@ -273,10 +306,10 @@ export function FloatingWorkingControl(props: {
306 className="absolute left-0 right-0 z-20 items-center"
307 style={[{ top: -CONTROL_OVERLAY_OFFSET }, liftStyle]}
308 onLayout={(event) => setOverlayWidth(event.nativeEvent.layout.width)}
276 - entering={NATIVE_LIQUID_GLASS_SUPPORTED || reducedMotion ? undefined : CONTROL_ENTERING}
277 - exiting={NATIVE_LIQUID_GLASS_SUPPORTED || reducedMotion ? undefined : CONTROL_EXITING}
309 + entering={useGlass || extensionOnly || reducedMotion ? undefined : CONTROL_ENTERING}
310 + exiting={useGlass || extensionOnly || reducedMotion ? undefined : CONTROL_EXITING}
311 >
279 - {hasCapsule && NATIVE_LIQUID_GLASS_SUPPORTED ? (
312 + {hasCapsule && useGlass ? (
313 <UniwindGlassContainer
314 spacing={GLASS_MERGE_SPACING}
315 pointerEvents="box-none"
@@ -374,6 +407,23 @@ function FloatingStatusLabel(props: {
407 readonly status: FloatingWorkingStatus;
408 readonly onLayout: (event: LayoutChangeEvent) => void;
409 }) {
410 + if (props.status.kind === "extension") {
411 + return (
412 + <StatusLabelRow
413 + accessibilityLabel={props.status.label}
414 + accessibilityRole="button"
415 + onPress={props.status.onPress}
416 + onLayout={props.onLayout}
417 + className="gap-1.5"
418 + animated={false}
419 + >
420 + <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
421 + {props.status.label}
422 + </Text>
423 + <SymbolView name="chevron.down" size={10} tintColorClassName="accent-foreground" />
424 + </StatusLabelRow>
425 + );
426 + }
427 if (props.status.kind === "syncing") {
428 return (
429 <StatusLabelRow
@@ -546,6 +596,7 @@ function FloatingStatusLabel(props: {
596 }
597
598 function StatusLabelRow(props: {
599 + readonly animated?: boolean;
600 readonly accessibilityLabel?: string;
601 readonly accessibilityRole?: "button";
602 readonly className?: string;
@@ -558,8 +609,8 @@ function StatusLabelRow(props: {
609 return (
610 <Animated.View
611 className="absolute max-w-full"
561 - entering={reducedMotion ? undefined : LABEL_ENTERING}
562 - exiting={reducedMotion ? undefined : LABEL_EXITING}
612 + entering={props.animated === false || reducedMotion ? undefined : LABEL_ENTERING}
613 + exiting={props.animated === false || reducedMotion ? undefined : LABEL_EXITING}
614 onLayout={props.onLayout}
615 >
616 {props.onPress ? (
apps/mobile/src/features/threads/floating-working-status.ts
+1
@@ -38,6 +38,7 @@ export type FloatingWorkingStatus =
38 readonly action: FloatingStatusAction | null;
39 }
40 | { readonly kind: "goal"; readonly label: string; readonly accessibilityLabel: string }
41 + | { readonly kind: "extension"; readonly label: string; readonly onPress: () => void }
42 | { readonly kind: "preparing"; readonly label: string }
43 | {
44 readonly kind: "connection";
apps/mobile/src/state/use-thread-composer-state.ts
+4
@@ -9,6 +9,7 @@ import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thre
9 import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
10 import {
11 deriveProviderSubagentStatus,
12 + deriveProviderExtensionStatuses,
13 deriveResumableRunId,
14 deriveRunlessWorkStartedAt,
15 deriveThreadActivityRun,
@@ -874,6 +875,9 @@ export function useThreadComposerState(input: {
875 dispatchingQueuedMessageId,
876 activeWorkStartedAt,
877 runlessWorkActive,
878 + extensionStatuses: deriveProviderExtensionStatuses(
879 + selectedThreadProjection?.projection ?? null,
880 + ),
881 providerSubagentStatus,
882 isCompacting,
883 composerDraftKey,
apps/server/src/orchestration-v2/ProjectionRecovery.test.ts
+98
@@ -21,6 +21,7 @@ import {
21 import * as DateTime from "effect/DateTime";
22 import * as Effect from "effect/Effect";
23 import * as Layer from "effect/Layer";
24 +import * as Stream from "effect/Stream";
25 import * as SqlClient from "effect/sql/SqlClient";
26 import * as Statement from "effect/sql/Statement";
27
@@ -263,6 +264,103 @@ it.effect("stops a session its thread detached, which kept its live status", ()
264 }).pipe(Effect.provide(layerRecoveryTest)),
265 );
266
267 +it.effect.each(["attached", "detached", "replaced"] as const)(
268 + "recovers attached sessions without restoring detached errors, session=%s",
269 + (state) =>
270 + Effect.gen(function* () {
271 + const projections = yield* ProjectionStore.ProjectionStoreV2;
272 + const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
273 + const now = yield* DateTime.now;
274 + const threadId = yield* createThread("failed-status-session");
275 + const providerSessionId = ProviderSessionId.make("session:recovery:failed-status");
276 + const session = {
277 + id: providerSessionId,
278 + driver,
279 + providerInstanceId,
280 + status: "error" as const,
281 + cwd: "/workspace",
282 + model: modelSelection.model,
283 + capabilities: CodexProviderCapabilitiesV2,
284 + extensionStatuses: [{ key: "watch", text: "Watching" }],
285 + createdAt: now,
286 + updatedAt: now,
287 + lastError: "Rate limited",
288 + };
289 + yield* projections.apply({
290 + id: EventId.make("event:recovery:failed-status:attached"),
291 + type: "provider-session.attached",
292 + threadId,
293 + driver,
294 + providerInstanceId,
295 + occurredAt: now,
296 + payload: session,
297 + });
298 + if (state !== "attached") {
299 + yield* projections.apply({
300 + id: EventId.make("event:recovery:failed-status:detached"),
301 + type: "provider-session.detached",
302 + threadId,
303 + driver,
304 + providerInstanceId,
305 + occurredAt: now,
306 + payload: { providerSessionId, detachedAt: now, reason: "Thread settled." },
307 + });
308 + }
309 + const replacementSessionId = ProviderSessionId.make("session:recovery:replacement");
310 + if (state === "replaced") {
311 + yield* projections.apply({
312 + id: EventId.make("event:recovery:replacement:attached"),
313 + type: "provider-session.attached",
314 + threadId,
315 + driver,
316 + providerInstanceId,
317 + occurredAt: now,
318 + payload: {
319 + ...session,
320 + id: replacementSessionId,
321 + status: "ready",
322 + extensionStatuses: [],
323 + lastError: null,
324 + },
325 + });
326 + yield* createRun(threadId, "completed");
327 + }
328 + assert.deepEqual(
329 + yield* projections.getRecoveryThreadIds("runtime"),
330 + state === "detached" ? [] : [threadId],
331 + );
332 + yield* recovery.reconcile("startup");
333 + const eventStore = yield* EventStore.EventStoreV2;
334 + const stored = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
335 + const sessionUpdates = stored.flatMap(({ event }) =>
336 + event.type === "provider-session.updated"
337 + ? [
338 + {
339 + id: event.payload.id,
340 + status: event.payload.status,
341 + lastError: event.payload.lastError,
342 + extensionStatuses: event.payload.extensionStatuses,
343 + },
344 + ]
345 + : [],
346 + );
347 + assert.deepEqual(
348 + sessionUpdates,
349 + state === "detached"
350 + ? []
351 + : [
352 + {
353 + id: state === "attached" ? providerSessionId : replacementSessionId,
354 + status: state === "attached" ? "error" : "stopped",
355 + lastError: state === "attached" ? "Rate limited" : null,
356 + extensionStatuses: [],
357 + },
358 + ],
359 + );
360 + assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), []);
361 + }).pipe(Effect.provide(layerRecoveryTest)),
362 +);
363 +
364 it.effect("selects unfinished recovery work without reading settled thread histories", () =>
365 Effect.gen(function* () {
366 const projections = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+6
@@ -4200,6 +4200,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4200 CROSS JOIN orchestration_v2_projection_provider_session_bindings AS bindings
4201 ON bindings.provider_session_id = sessions.provider_session_id
4202 WHERE sessions.status NOT IN ('stopped', 'error')
4203 + OR (sessions.status = 'error' AND CASE WHEN json_valid(sessions.payload_json)
4204 + THEN json_array_length(sessions.payload_json, '$.extensionStatuses') > 0
4205 + ELSE 0 END)
4206 UNION
4207 -- A detach drops the binding but keeps the session's status.
4208 SELECT sessions.thread_id
@@ -4702,6 +4705,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4705 )
4706 AND (
4707 session.status NOT IN ('stopped', 'error')
4708 + OR (session.status = 'error' AND CASE WHEN json_valid(session.payload_json)
4709 + THEN json_array_length(session.payload_json, '$.extensionStatuses') > 0
4710 + ELSE 0 END)
4711 OR session.provider_session_id IN (
4712 SELECT provider_thread.provider_session_id
4713 FROM orchestration_v2_projection_provider_threads AS provider_thread
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
+8
@@ -684,6 +684,7 @@ it.effect(
684 driver: ProviderDriverKind.make("codex"),
685 providerInstanceId: ProviderInstanceId.make("codex"),
686 status: "ready",
687 + extensionStatuses: [{ key: "watch", text: "Watching" }],
688 },
689 ],
690 providerThreads: [
@@ -798,6 +799,13 @@ it.effect(
799 );
800 const messageEvent = events.find((event) => event.type === "message.updated");
801 assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
802 + const stoppedSession = events.find((event) => event.type === "provider-session.updated");
803 + assert.deepEqual(
804 + stoppedSession?.type === "provider-session.updated"
805 + ? stoppedSession.payload.extensionStatuses
806 + : undefined,
807 + [],
808 + );
809 assert.deepEqual(
810 events.flatMap((event) =>
811 event.type === "turn-item.updated" && "streaming" in event.payload
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+10 -2
@@ -701,7 +701,9 @@ export const make = Effect.gen(function* () {
701 });
702 }
703 for (const session of projection.providerSessions.filter(
704 - (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
704 + (candidate) =>
705 + (candidate.status !== "stopped" && candidate.status !== "error") ||
706 + (candidate.status === "error" && (candidate.extensionStatuses?.length ?? 0) > 0),
707 )) {
708 events.push({
709 id: yield* allocateEventId(),
@@ -710,7 +712,13 @@ export const make = Effect.gen(function* () {
712 driver: session.driver,
713 providerInstanceId: session.providerInstanceId,
714 occurredAt: now,
713 - payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
715 + payload: {
716 + ...session,
717 + status: session.status === "error" ? "error" : "stopped",
718 + ...(session.extensionStatuses === undefined ? {} : { extensionStatuses: [] }),
719 + updatedAt: now,
720 + lastError: session.status === "error" ? session.lastError : null,
721 + },
722 });
723 }
724 for (const [providerThreadId, work] of cancelledBackgroundWork) {
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+261 -7
@@ -423,6 +423,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
423 options: {
424 readonly failEventStream?: boolean;
425 readonly capabilities?: OrchestrationV2ProviderCapabilities;
426 + readonly extensionStatuses?: OrchestrationV2ProviderSession["extensionStatuses"];
427 readonly mcpConfigs?: Ref.Ref<
428 ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
429 >;
@@ -479,11 +480,16 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
480 }
481 const now = yield* DateTime.now;
482 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>();
482 - const session = makeProviderSession({
483 - providerSessionId: input.providerSessionId,
484 - now,
485 - ...(options.capabilities === undefined ? {} : { capabilities: options.capabilities }),
486 - });
483 + let session: OrchestrationV2ProviderSession = {
484 + ...makeProviderSession({
485 + providerSessionId: input.providerSessionId,
486 + now,
487 + ...(options.capabilities === undefined ? {} : { capabilities: options.capabilities }),
488 + }),
489 + ...(options.extensionStatuses === undefined
490 + ? {}
491 + : { extensionStatuses: options.extensionStatuses }),
492 + };
493 yield* Ref.update(state, (current) => {
494 const eventQueues = new Map(current.eventQueues);
495 eventQueues.set(String(input.providerSessionId), events);
@@ -502,7 +508,9 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
508 instanceId: ProviderInstanceId.make("codex"),
509 driver: CODEX_DRIVER,
510 providerSessionId: input.providerSessionId,
505 - providerSession: session,
511 + get providerSession() {
512 + return session;
513 + },
514 events: options.failEventStream
515 ? Stream.fail(
516 new ProviderAdapter.ProviderAdapterEventStreamError({
@@ -511,7 +519,13 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
519 cause: "process exited",
520 }),
521 )
514 - : Stream.fromQueue(events),
522 + : Stream.fromQueue(events).pipe(
523 + Stream.tap((event) =>
524 + Effect.sync(() => {
525 + if (event.type === "provider_session.updated") session = event.providerSession;
526 + }),
527 + ),
528 + ),
529 ...(options.backgroundTasksEndWithProcess === false
530 ? {}
531 : { backgroundTasksEndWithProcess: true as const }),
@@ -563,6 +577,7 @@ function layerTest(input: {
577 readonly maxIdlePinMs?: number;
578 readonly failEventStream?: boolean;
579 readonly capabilities?: OrchestrationV2ProviderCapabilities;
580 + readonly extensionStatuses?: OrchestrationV2ProviderSession["extensionStatuses"];
581 readonly mcpConfigs?: Ref.Ref<
582 ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
583 >;
@@ -604,6 +619,9 @@ function layerTest(input: {
619 makeProviderAdapter(input.state, {
620 failEventStream: input.failEventStream ?? false,
621 ...(input.capabilities === undefined ? {} : { capabilities: input.capabilities }),
622 + ...(input.extensionStatuses === undefined
623 + ? {}
624 + : { extensionStatuses: input.extensionStatuses }),
625 ...(input.mcpConfigs === undefined ? {} : { mcpConfigs: input.mcpConfigs }),
626 ...(input.beforeOpen === undefined ? {} : { beforeOpen: input.beforeOpen }),
627 ...(input.hasPendingBackgroundWork === undefined
@@ -1657,6 +1675,242 @@ it.effect("ProviderSessionManagerV2 stops a session still opening when its layer
1675 }),
1676 );
1677
1678 +it.effect(
1679 + "ProviderSessionManagerV2 projects idle extension statuses and rejects a retired runtime's updates",
1680 + () =>
1681 + Effect.gen(function* () {
1682 + const state = yield* Ref.make(emptyState);
1683 + yield* Effect.gen(function* () {
1684 + const eventSink = yield* EventSink.EventSinkV2;
1685 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
1686 + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
1687 + const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1688 + const threadId = ThreadId.make("thread-extension-status");
1689 + const providerSessionId = yield* idAllocator.allocate.providerSession({
1690 + providerInstanceId: modelSelection.instanceId,
1691 + threadId,
1692 + });
1693 + yield* eventSink.write({
1694 + events: [
1695 + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }),
1696 + ],
1697 + });
1698 + const runtime = yield* manager.open({
1699 + threadId,
1700 + providerSessionId,
1701 + modelSelection,
1702 + runtimePolicy,
1703 + });
1704 + const firstClient = yield* runtime.subscribeEvents!;
1705 + const secondClient = yield* runtime.subscribeEvents!;
1706 + const oldQueue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId));
1707 + assert.isDefined(oldQueue);
1708 + const statuses = [{ key: "watch", text: "Watching 4 files" }];
1709 + yield* Queue.offer(oldQueue!, {
1710 + type: "provider_session.updated",
1711 + driver: CODEX_DRIVER,
1712 + providerSession: { ...runtime.providerSession, extensionStatuses: statuses },
1713 + });
1714 + yield* Effect.all([
1715 + firstClient.events.pipe(Stream.runHead),
1716 + secondClient.events.pipe(Stream.runHead),
1717 + ]);
1718 + assert.deepEqual(
1719 + (yield* projectionStore.getThreadProjection(threadId)).providerSessions.at(-1)
1720 + ?.extensionStatuses,
1721 + statuses,
1722 + );
1723 + const reused = yield* manager.open({
1724 + threadId,
1725 + providerSessionId,
1726 + modelSelection,
1727 + runtimePolicy,
1728 + });
1729 + assert.deepEqual(reused.providerSession.extensionStatuses, statuses);
1730 + yield* eventSink.write({
1731 + events: [
1732 + {
1733 + id: yield* idAllocator.allocate.event({ threadId, providerSessionId }),
1734 + type: "provider-session.updated",
1735 + threadId,
1736 + driver: CODEX_DRIVER,
1737 + providerInstanceId: modelSelection.instanceId,
1738 + occurredAt: yield* DateTime.now,
1739 + payload: reused.providerSession,
1740 + },
1741 + ],
1742 + });
1743 + assert.deepEqual(
1744 + (yield* projectionStore.getThreadProjection(threadId)).providerSessions.at(-1)
1745 + ?.extensionStatuses,
1746 + statuses,
1747 + );
1748 + yield* manager.close(providerSessionId);
1749 + assert.deepEqual(
1750 + (yield* projectionStore.getThreadProjection(threadId)).providerSessions.at(-1)
1751 + ?.extensionStatuses,
1752 + [],
1753 + );
1754 + const replacement = yield* manager.open({
1755 + threadId,
1756 + providerSessionId,
1757 + modelSelection,
1758 + runtimePolicy,
1759 + });
1760 + const replacementClient = yield* replacement.subscribeEvents!;
1761 + const newQueue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId));
1762 + assert.isDefined(newQueue);
1763 + yield* Queue.offer(oldQueue!, {
1764 + type: "provider_session.updated",
1765 + driver: CODEX_DRIVER,
1766 + providerSession: {
1767 + ...runtime.providerSession,
1768 + extensionStatuses: [{ key: "stale", text: "Old session" }],
1769 + },
1770 + });
1771 + yield* Queue.offer(newQueue!, {
1772 + type: "provider_session.updated",
1773 + driver: CODEX_DRIVER,
1774 + providerSession: {
1775 + ...replacement.providerSession,
1776 + extensionStatuses: [{ key: "new", text: "New session" }],
1777 + },
1778 + });
1779 + yield* replacementClient.events.pipe(Stream.runHead);
1780 + assert.deepEqual(
1781 + (yield* projectionStore.getThreadProjection(threadId)).providerSessions.at(-1)
1782 + ?.extensionStatuses,
1783 + [{ key: "new", text: "New session" }],
1784 + );
1785 + assert.lengthOf((yield* projectionStore.getThreadProjection(threadId)).messages, 0);
1786 + assert.lengthOf((yield* projectionStore.getThreadProjection(threadId)).turnItems, 0);
1787 + }).pipe(
1788 + Effect.provide(
1789 + layerTest({
1790 + state,
1791 + idleTimeoutMs: 60_000,
1792 + extensionStatuses: [{ key: "initial", text: "Watching" }],
1793 + }),
1794 + ),
1795 + );
1796 + }),
1797 +);
1798 +
1799 +it.effect.each(["session metadata", "session status changes", "provider work"] as const)(
1800 + "ProviderSessionManagerV2 expires idle sessions according to %s",
1801 + (activity) =>
1802 + Effect.gen(function* () {
1803 + const state = yield* Ref.make(emptyState);
1804 + yield* Effect.gen(function* () {
1805 + const eventSink = yield* EventSink.EventSinkV2;
1806 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
1807 + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
1808 + const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1809 + const threadId = ThreadId.make("thread-session-metadata-idle");
1810 + const providerSessionId = yield* idAllocator.allocate.providerSession({
1811 + providerInstanceId: modelSelection.instanceId,
1812 + threadId,
1813 + });
1814 + yield* eventSink.write({
1815 + events: [
1816 + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }),
1817 + ],
1818 + });
1819 + const runtime = yield* manager.open({
1820 + threadId,
1821 + providerSessionId,
1822 + modelSelection,
1823 + runtimePolicy,
1824 + });
1825 + const subscriber = yield* runtime.subscribeEvents!;
1826 + const observed = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
1827 + yield* subscriber.events.pipe(
1828 + Stream.runForEach((event) => Queue.offer(observed, event)),
1829 + Effect.ignore,
1830 + Effect.forkScoped,
1831 + );
1832 + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId));
1833 + assert.isDefined(queue);
1834 + const waitingSession = { ...runtime.providerSession, status: "waiting" as const };
1835 + yield* Queue.offer(queue!, {
1836 + type: "provider_session.updated",
1837 + driver: CODEX_DRIVER,
1838 + providerSession: waitingSession,
1839 + });
1840 + yield* Queue.take(observed);
1841 +
1842 + for (const text of ["Watching 1 file", "Watching 2 files"]) {
1843 + yield* TestClock.adjust("300 millis");
1844 + yield* Queue.offer(queue!, {
1845 + type: "provider_session.updated",
1846 + driver: CODEX_DRIVER,
1847 + providerSession: {
1848 + ...waitingSession,
1849 + extensionStatuses: [{ key: "watch", text }],
1850 + },
1851 + });
1852 + yield* Queue.take(observed);
1853 + }
1854 + yield* TestClock.adjust("300 millis");
1855 + const statuses = [{ key: "watch", text: "Watching 3 files" }];
1856 + yield* Queue.offer(
1857 + queue!,
1858 + activity === "provider work"
1859 + ? {
1860 + type: "provider_thread.updated",
1861 + driver: CODEX_DRIVER,
1862 + providerThread: makeProviderThread({
1863 + idAllocator,
1864 + threadId,
1865 + providerSessionId,
1866 + now: yield* DateTime.now,
1867 + }),
1868 + }
1869 + : {
1870 + type: "provider_session.updated",
1871 + driver: CODEX_DRIVER,
1872 + providerSession: {
1873 + ...waitingSession,
1874 + status: activity === "session status changes" ? "ready" : "waiting",
1875 + extensionStatuses: statuses,
1876 + },
1877 + },
1878 + );
1879 + yield* Queue.take(observed);
1880 + if (activity !== "provider work") {
1881 + assert.deepEqual(
1882 + (yield* projectionStore.getThreadProjection(threadId)).providerSessions.at(-1)
1883 + ?.extensionStatuses,
1884 + statuses,
1885 + );
1886 + }
1887 + const afterSequence = yield* eventSink.latestSequence({ threadId });
1888 + yield* TestClock.adjust("100 millis");
1889 + assert.equal(yield* manager.isLive(providerSessionId), activity !== "session metadata");
1890 + if (activity !== "session metadata") {
1891 + yield* TestClock.adjust("900 millis");
1892 + }
1893 + assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
1894 + yield* eventSink
1895 + .stream({ threadId, afterSequence, eventType: "provider-session.updated" })
1896 + .pipe(
1897 + Stream.filter(
1898 + (stored) =>
1899 + stored.event.type === "provider-session.updated" &&
1900 + stored.event.payload.status === "stopped",
1901 + ),
1902 + Stream.runHead,
1903 + );
1904 + assert.deepEqual(
1905 + (yield* projectionStore.getThreadProjection(threadId)).providerSessions.at(-1)
1906 + ?.extensionStatuses,
1907 + [],
1908 + );
1909 + assert.equal((yield* Ref.get(state)).closeCount, 1);
1910 + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000 })));
1911 + }),
1912 +);
1913 +
1914 it.effect("ProviderSessionManagerV2 interrupts event subscriptions on server shutdown", () =>
1915 Effect.gen(function* () {
1916 const state = yield* Ref.make(emptyState);
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+19 -7
@@ -621,6 +621,9 @@ export const layerWithOptions = (
621 const payload: OrchestrationV2ProviderSession = {
622 ...input.entry.runtime.providerSession,
623 status: releaseStatusFor(input.reason),
624 + ...(input.entry.runtime.providerSession.extensionStatuses === undefined
625 + ? {}
626 + : { extensionStatuses: [] }),
627 updatedAt: now,
628 lastError:
629 input.reason === "runtime_error" ? (input.detail ?? "Provider runtime failed.") : null,
@@ -1202,8 +1205,8 @@ export const layerWithOptions = (
1205
1206 // Provider activity restarts the pin budget, so background work that keeps
1207 // reporting progress (a long Claude workflow) is never cut off; only work
1205 - // that went silent for maxIdlePinMs is released. This runs for every
1206 - // provider event, so keep it untraced.
1208 + // that went silent for maxIdlePinMs is released. Progress events can be
1209 + // frequent, so keep this untraced.
1210 const scheduleIdleReleaseInternal = Effect.fnUntraced(function* (
1211 providerSessionId: ProviderSessionId,
1212 options?: { readonly providerActivity?: boolean },
@@ -1710,6 +1713,10 @@ export const layerWithOptions = (
1713 });
1714 return {
1715 ...runtime,
1716 + // Pi replaces its session snapshot as metadata changes.
1717 + get providerSession() {
1718 + return runtime.providerSession;
1719 + },
1720 subscribeEvents,
1721 events: Stream.unwrap(
1722 subscribeEvents.pipe(Effect.map((subscription) => subscription.events)),
@@ -1942,6 +1949,7 @@ export const layerWithOptions = (
1949
1950 const startEventPump = (entry: LiveSessionEntry) => {
1951 let stoppedByProvider = false;
1952 + let lastSessionStatus = entry.runtime.providerSession.status;
1953 return entry.runtime.events.pipe(
1954 Stream.runForEach((event) => {
1955 if (shutdownSignal.received) return Effect.void;
@@ -1958,11 +1966,13 @@ export const layerWithOptions = (
1966 itemId: event.turnItem.id,
1967 })
1968 : Effect.void;
1961 - if (
1969 + // Metadata can change while idle without extending the runtime's lifetime.
1970 + const metadataOnly =
1971 event.type === "provider_session.updated" &&
1963 - event.providerSession.status === "stopped"
1964 - ) {
1965 - stoppedByProvider = true;
1972 + event.providerSession.status === lastSessionStatus;
1973 + if (event.type === "provider_session.updated") {
1974 + lastSessionStatus = event.providerSession.status;
1975 + if (lastSessionStatus === "stopped") stoppedByProvider = true;
1976 }
1977 return observeActivity(
1978 entry.runtime.providerSessionId,
@@ -1972,7 +1982,9 @@ export const layerWithOptions = (
1982 event.providerThreadId,
1983 event.runOrdinal,
1984 )
1975 - : touchActivity(entry.runtime.providerSessionId, { providerActivity: true }),
1985 + : metadataOnly
1986 + ? Effect.void
1987 + : touchActivity(entry.runtime.providerSessionId, { providerActivity: true }),
1988 ).pipe(
1989 Effect.andThen(
1990 event.type === "provider_session.updated"
apps/server/src/storageCleanup.test.ts
+107 -1
@@ -7,6 +7,7 @@ import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 +import * as Queue from "effect/Queue";
11 import type * as Path from "effect/Path";
12 import type * as Scope from "effect/Scope";
13 import * as Stream from "effect/Stream";
@@ -345,6 +346,7 @@ const cleanupFixture = (
346 let editBeforeRemoval = false;
347 let openSessionCwd: string | null = null;
348 let sessionLive = true;
349 + let sessionLiveChecks = 0;
350 let onLiveCheck: Effect.Effect<void> = Effect.void;
351 let outboxStatus: string | null = null;
352 let fullStatusCalls = 0;
@@ -416,7 +418,10 @@ const cleanupFixture = (
418 } as unknown as ProjectionStore.ProjectionStoreV2["Service"]),
419 Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, {
420 isLive: () =>
419 - Effect.sync(() => sessionLive).pipe(Effect.tap(() => Effect.suspend(() => onLiveCheck))),
421 + Effect.sync(() => {
422 + sessionLiveChecks++;
423 + return sessionLive;
424 + }).pipe(Effect.tap(() => Effect.suspend(() => onLiveCheck))),
425 } as unknown as ProviderSessionManager.ProviderSessionManagerV2["Service"]),
426 Effect.provideService(Orchestrator.OrchestratorV2, {
427 streamDomainEvents: Stream.suspend(() => events),
@@ -551,6 +556,7 @@ const cleanupFixture = (
556 }) ?? Effect.void,
557 fullStatusCalls: () => fullStatusCalls,
558 snapshotReads: () => snapshotReads,
559 + sessionLiveChecks: () => sessionLiveChecks,
560 activate: (domainEvents: Stream.Stream<OrchestrationV2DomainEvent>) => {
561 events = domainEvents;
562 return Deferred.succeed(activated, undefined);
@@ -1897,6 +1903,106 @@ describe("orphan worktree reports", () => {
1903 });
1904
1905 describe("storage cleanup reports and local file policies", () => {
1906 + it.effect.each([true, false])(
1907 + "sweeps on runtime retirement rather than live error metadata, worktreeOnDelete=%s",
1908 + (worktreeOnDelete) =>
1909 + runCleanupTest(
1910 + Effect.gen(function* () {
1911 + const fixture = yield* cleanupFixture({
1912 + ...DEFAULT_SERVER_SETTINGS.storageCleanup,
1913 + worktreeAfterDays: 8,
1914 + worktreeOnDelete,
1915 + });
1916 + fixture.setThreads([]);
1917 + fixture.setDeletedThreads([
1918 + shell({ branch: "feature", worktreePath: fixture.worktree, deletedAt: at(0) }),
1919 + ]);
1920 + yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "agent edit\n");
1921 + const events = yield* Queue.unbounded<{
1922 + readonly event: OrchestrationV2DomainEvent;
1923 + readonly processed: Deferred.Deferred<void>;
1924 + }>();
1925 + yield* fixture.activate(
1926 + Stream.fromQueue(events).pipe(
1927 + Stream.flatMap(({ event, processed }) =>
1928 + Stream.succeed(event).pipe(
1929 + Stream.concat(
1930 + // The next pull acknowledges that the listener handled this event.
1931 + Stream.fromEffect(Deferred.succeed(processed, undefined)).pipe(Stream.drain),
1932 + ),
1933 + ),
1934 + ),
1935 + ),
1936 + );
1937 + yield* fixture.service.reports.pipe(
1938 + Stream.filter((report) => report !== null),
1939 + Stream.take(1),
1940 + Stream.runDrain,
1941 + );
1942 + yield* fixture.service.drain;
1943 + const startupReads = fixture.snapshotReads();
1944 + const publish = Effect.fn("StorageCleanupTest.publish")(function* (
1945 + event: OrchestrationV2DomainEvent,
1946 + ) {
1947 + const processed = yield* Deferred.make<void>();
1948 + yield* Queue.offer(events, { event, processed });
1949 + yield* Deferred.await(processed);
1950 + yield* fixture.service.drain;
1951 + });
1952 + const sessionUpdated = (
1953 + status: "ready" | "error" | "stopped",
1954 + text: string,
1955 + ): OrchestrationV2DomainEvent => ({
1956 + id: EventId.make(`event:session:${status}:${text}`),
1957 + type: "provider-session.updated",
1958 + threadId: ThreadId.make("thread-1"),
1959 + occurredAt: at(0),
1960 + payload: {
1961 + id: ProviderSessionId.make("session-1"),
1962 + driver: ProviderDriverKind.make("pi"),
1963 + providerInstanceId: ProviderInstanceId.make("pi"),
1964 + status,
1965 + cwd: fixture.worktree,
1966 + model: null,
1967 + capabilities: CodexProviderCapabilitiesV2,
1968 + extensionStatuses: text === "" ? [] : [{ key: "watch", text }],
1969 + createdAt: at(-DAY_MS),
1970 + updatedAt: at(0),
1971 + lastError: status === "error" ? "Rate limited" : null,
1972 + },
1973 + });
1974 + yield* publish(sessionUpdated("ready", "Watching"));
1975 + expect(fixture.snapshotReads()).toBe(startupReads);
1976 + expect(fixture.sessionLiveChecks()).toBe(0);
1977 + for (let index = 0; index < 5; index++) {
1978 + yield* publish(sessionUpdated("error", `Watching ${index} files`));
1979 + expect(fixture.snapshotReads()).toBe(startupReads);
1980 + }
1981 + expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 5 : 0);
1982 +
1983 + // Release removes the live entry before publishing its final error update.
1984 + fixture.setSessionLive(false);
1985 + yield* publish(sessionUpdated("error", ""));
1986 + expect(fixture.snapshotReads()).toBe(startupReads + Number(worktreeOnDelete));
1987 + expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0);
1988 +
1989 + yield* publish(sessionUpdated("stopped", ""));
1990 + expect(fixture.snapshotReads()).toBe(startupReads + 2 * Number(worktreeOnDelete));
1991 + expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0);
1992 +
1993 + fixture.setSessionLive(true);
1994 + yield* publish({
1995 + id: EventId.make("event:thread:deleted"),
1996 + type: "thread.deleted",
1997 + threadId: ThreadId.make("thread-1"),
1998 + occurredAt: at(0),
1999 + payload: { ...shell({ deletedAt: at(0) }), lastVisitedAt: null },
2000 + });
2001 + expect(fixture.snapshotReads()).toBe(startupReads + 3 * Number(worktreeOnDelete));
2002 + expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0);
2003 + }),
2004 + ),
2005 + );
2006 it.effect("automatically removes an eligible archived thread checkout", () =>
2007 runCleanupTest(
2008 Effect.gen(function* () {
apps/server/src/storageCleanup.ts
+6 -3
@@ -1446,9 +1446,12 @@ const make = Effect.gen(function* () {
1446 )
1447 return Effect.void;
1448 }
1449 - return anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
1450 - ? requestSweep
1451 - : Effect.void;
1449 + if (!anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)) return Effect.void;
1450 + return event.type === "provider-session.updated" && event.payload.status === "error"
1451 + ? providerSessions
1452 + .isLive(event.payload.id)
1453 + .pipe(Effect.flatMap((live) => (live ? Effect.void : requestSweep)))
1454 + : requestSweep;
1455 }).pipe(
1456 Effect.catchCause((cause) =>
1457 Effect.logWarning("Storage cleanup event stream failed", { cause }),
apps/web/src/components/ChatView.tsx
+8 -1
@@ -75,6 +75,7 @@ import {
75 } from "@t3tools/contracts";
76 import {
77 deriveProviderSubagentStatus,
78 + deriveProviderExtensionStatuses,
79 deriveReportedModelSelection,
80 deriveResumableRunId,
81 formatModelSelectionEffort,
@@ -358,7 +359,7 @@ import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
359 import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
360 import { ChatRightPanel } from "./chat/ChatRightPanel";
361 import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting";
361 -import { branchMismatchBannerItem } from "./chat/ThreadActivityBanners";
362 +import { branchMismatchBannerItem, extensionStatusBannerItem } from "./chat/ThreadActivityBanners";
363 import { ThreadNow } from "./chat/ThreadNow";
364 import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
365 import { useDelayedStatus } from "../hooks/useDelayedStatus";
@@ -2619,6 +2620,10 @@ export default function ChatView(props: ChatViewProps) {
2620 ]
2621 : [];
2622 const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner];
2623 + const extensionStatusBanner = extensionStatusBannerItem(
2624 + deriveProviderExtensionStatuses(serverProjection),
2625 + );
2626 + const extensionStatusItems = extensionStatusBanner === null ? [] : [extensionStatusBanner];
2627 const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner];
2628 const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem];
2629 // An approval's feedback goes to that approval; the armed session waits for the next message.
@@ -2631,6 +2636,7 @@ export default function ChatView(props: ChatViewProps) {
2636 ...feedbackBannerItems,
2637 ...fallbackItems,
2638 ...limitRecoveryItems,
2639 + ...extensionStatusItems,
2640 ...usageLimitsItems,
2641 ...projectCloneItems,
2642 ...freshSessionItems,
@@ -2641,6 +2647,7 @@ export default function ChatView(props: ChatViewProps) {
2647 ...feedbackBannerItems,
2648 ...fallbackItems,
2649 ...limitRecoveryItems,
2650 + ...extensionStatusItems,
2651 ...usageLimitsItems,
2652 ...projectCloneItems,
2653 ...freshSessionItems,
apps/web/src/components/chat/ThreadActivityBanners.tsx
+13
@@ -2,6 +2,7 @@ import type {
2 EnvironmentId,
3 OrchestrationV2PendingBackgroundTask,
4 OrchestrationV2ProviderGoal,
5 + OrchestrationV2ProviderSession,
6 ThreadId,
7 } from "@t3tools/contracts";
8 import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell";
@@ -31,6 +32,18 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
32 import type { ComposerBannerStackItem } from "./ComposerBannerStack";
33 import type { ThreadNowItem } from "./ThreadNow";
34
35 +export function extensionStatusBannerItem(
36 + statuses: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>,
37 +): ComposerBannerStackItem | null {
38 + if (statuses.length === 0) return null;
39 + return {
40 + id: "pi-extension-status",
41 + variant: "default",
42 + icon: <span>▸</span>,
43 + title: <output>{`Pi · ${statuses.map((status) => status.text).join(" · ")}`}</output>,
44 + };
45 +}
46 +
47 /** Subagents and side chats waiting on the user, unless the parent is itself waiting on them. */
48 export function childInputNowItem(input: {
49 readonly childThreadInputs: ReadonlyArray<EnvironmentThreadShell>;
docs/user/providers-pi.md
+2 -2
@@ -49,8 +49,8 @@ loads for the current workspace; selecting one uses Pi's native skill expansion.
49
50 Pi loads its normal user extensions, and project extensions once the folder is trusted in Pi.
51 Blocking `select`, `confirm`, `input`, and `editor` dialogs work in T3 Code. Notifications appear in
52 -the work log. Pi terminal decoration such as titles, status lines, and widgets does not have a T3
53 -Code equivalent.
52 +the work log. Extensions can publish status text near the composer. Terminal titles and generic
53 +widgets do not have a T3 Code equivalent.
54
55 ## Permission Modes
56
packages/client-runtime/src/state/threadExecution.test.ts
+72
@@ -23,6 +23,7 @@ import {
23 deriveReportedModelSelection,
24 deriveLatestThreadRun,
25 deriveProviderSubagentStatus,
26 + deriveProviderExtensionStatuses,
27 deriveResumableRunId,
28 deriveRunlessWorkStartedAt,
29 deriveThreadActivityRun,
@@ -58,6 +59,77 @@ function run(id: string, ordinal: number, status: OrchestrationV2RunStatus) {
59 }
60
61 describe("thread execution presentation", () => {
62 + it("shows extension statuses only from the selected provider's current live session", () => {
63 + const instanceId = v2Projection.thread.modelSelection.instanceId;
64 + const providerThreadId = ProviderThreadId.make("native-status-thread");
65 + const sessionId = ProviderSessionId.make("native-status-session");
66 + const statuses = [{ key: "watch", text: "Watching" }];
67 + const projection = {
68 + thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId },
69 + providerThreads: [
70 + { id: providerThreadId, providerSessionId: sessionId, providerInstanceId: instanceId },
71 + ],
72 + providerSessions: [
73 + {
74 + id: sessionId,
75 + providerInstanceId: instanceId,
76 + status: "ready" as const,
77 + extensionStatuses: statuses,
78 + },
79 + ],
80 + };
81 + expect(deriveProviderExtensionStatuses(projection)).toEqual(statuses);
82 + expect(
83 + deriveProviderExtensionStatuses({
84 + ...projection,
85 + providerSessions: [
86 + ...projection.providerSessions,
87 + {
88 + ...projection.providerSessions[0]!,
89 + id: ProviderSessionId.make("unrelated"),
90 + extensionStatuses: [{ key: "wrong", text: "Wrong session" }],
91 + },
92 + ],
93 + }),
94 + ).toEqual(statuses);
95 + expect(
96 + deriveProviderExtensionStatuses({
97 + ...projection,
98 + providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" }],
99 + }),
100 + ).toEqual([]);
101 + expect(
102 + deriveProviderExtensionStatuses({
103 + ...projection,
104 + providerSessions: [{ ...projection.providerSessions[0]!, status: "error" }],
105 + }),
106 + ).toEqual(statuses);
107 + expect(
108 + deriveProviderExtensionStatuses({
109 + ...projection,
110 + providerSessions: [
111 + { ...projection.providerSessions[0]!, status: "error", extensionStatuses: [] },
112 + ],
113 + }),
114 + ).toEqual([]);
115 + expect(
116 + deriveProviderExtensionStatuses({
117 + ...projection,
118 + providerSessions: [{ ...projection.providerSessions[0]!, extensionStatuses: undefined }],
119 + }),
120 + ).toEqual([]);
121 + expect(
122 + deriveProviderExtensionStatuses({
123 + ...projection,
124 + thread: {
125 + ...projection.thread,
126 + modelSelection: { instanceId: ProviderInstanceId.make("other"), model: "default" },
127 + },
128 + }),
129 + ).toEqual([]);
130 + expect(deriveProviderExtensionStatuses(null)).toEqual([]);
131 + });
132 +
133 it("derives the current root failure without inheriting errors from children or previous runs", () => {
134 const failed = { ...run("limited", 1, "failed"), rootNodeId: NodeId.make("root") };
135 const item = {
packages/client-runtime/src/state/threadExecution.ts
+40
@@ -13,6 +13,7 @@ import {
13 type OrchestrationV2NotificationSource,
14 type OrchestrationV2PendingBackgroundTask,
15 type OrchestrationV2ProviderGoal,
16 + type OrchestrationV2ProviderSession,
17 type ServerProvider,
18 type ServerProviderModel,
19 type OrchestrationV2ExecutionNode,
@@ -50,6 +51,45 @@ import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
51 const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
52 const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
53
54 +const EMPTY_EXTENSION_STATUSES: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]> =
55 + [];
56 +
57 +/** Only the selected provider's current session can supply transient extension status. */
58 +export function deriveProviderExtensionStatuses(
59 + projection:
60 + | (Pick<ThreadStructure, "thread"> & {
61 + readonly providerThreads: ReadonlyArray<
62 + Pick<
63 + ThreadStructure["providerThreads"][number],
64 + "id" | "providerSessionId" | "providerInstanceId"
65 + >
66 + >;
67 + readonly providerSessions: ReadonlyArray<
68 + Pick<
69 + OrchestrationV2ProviderSession,
70 + "id" | "providerInstanceId" | "status" | "extensionStatuses"
71 + >
72 + >;
73 + })
74 + | null,
75 +) {
76 + if (projection === null) return EMPTY_EXTENSION_STATUSES;
77 + const instanceId = projection.thread.modelSelection.instanceId;
78 + const activeThread = projection.providerThreads.find(
79 + (thread) => thread.id === projection.thread.activeProviderThreadId,
80 + );
81 + if (activeThread !== undefined && activeThread.providerInstanceId !== instanceId)
82 + return EMPTY_EXTENSION_STATUSES;
83 + const session = projection.providerSessions.findLast(
84 + (session) =>
85 + session.providerInstanceId === instanceId &&
86 + (activeThread === undefined || session.id === activeThread.providerSessionId),
87 + );
88 + return session === undefined || session.status === "stopped"
89 + ? EMPTY_EXTENSION_STATUSES
90 + : (session.extensionStatuses ?? EMPTY_EXTENSION_STATUSES);
91 +}
92 +
93 function latestMatchingRun(
94 projection: ThreadStructure,
95 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
packages/contracts/src/orchestrationV2.ts
+8
@@ -953,6 +953,14 @@ export const OrchestrationV2ProviderSession = Schema.Struct({
953 cwd: TrimmedNonEmptyString,
954 model: Schema.NullOr(TrimmedNonEmptyString),
955 capabilities: OrchestrationV2ProviderCapabilities,
956 + extensionStatuses: Schema.optional(
957 + Schema.Array(
958 + Schema.Struct({
959 + key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
960 + text: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
961 + }),
962 + ).check(Schema.isMaxLength(32)),
963 + ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
964 createdAt: Schema.DateTimeUtc,
965 updatedAt: Schema.DateTimeUtc,
966 lastError: Schema.NullOr(Schema.String),
packages/provider-pi/src/server/adapter.test.ts
+413
@@ -550,6 +550,419 @@ const startTurn = Effect.fnUntraced(function* (
550 });
551
552 describe("PiAdapterV2", () => {
553 + it.effect(
554 + "replaces keyed extension statuses while idle without producing conversation items",
555 + () =>
556 + Effect.gen(function* () {
557 + const fake = yield* makeFakePi;
558 + const { runtime, takeEvent } = yield* openRuntime(fake);
559 + const updates = [
560 + { statusKey: "watch", statusText: "\u001b[32mWatching 3 files\u001b[0m\u0007" },
561 + { statusKey: "lint", statusText: "Lint clean" },
562 + { statusKey: "watch", statusText: "Watching 4 files" },
563 + { statusKey: "watch", statusText: "Watching 4 files" },
564 + { statusKey: "watch", statusText: "\u001b[32mWatching 4 files\u001b[0m" },
565 + { statusKey: "lint", statusText: "" },
566 + { statusKey: "missing" },
567 + { statusKey: "watch" },
568 + { statusKey: "watch", statusText: "Watching 4 files" },
569 + ];
570 + for (const update of updates) {
571 + yield* fake.emit({ type: "extension_ui_request", method: "setStatus", ...update });
572 + }
573 + // The following dialog is an observable milestone after the preceding native notifications.
574 + yield* fake.emit({
575 + type: "extension_ui_request",
576 + id: "status-barrier",
577 + method: "input",
578 + title: "Continue?",
579 + });
580 + const observed: ProviderAdapter.ProviderAdapterV2Event[] = [];
581 + yield* takeEvent((event) => {
582 + observed.push(event);
583 + return event.type === "runtime_request.updated";
584 + });
585 + assert.deepInclude(runtime.providerSession, {
586 + extensionStatuses: [{ key: "watch", text: "Watching 4 files" }],
587 + });
588 + const snapshots = observed.filter((event) => event.type === "provider_session.updated");
589 + assert.lengthOf(snapshots, 6);
590 + assert.deepInclude(snapshots[0]?.providerSession, {
591 + extensionStatuses: [{ key: "watch", text: "Watching 3 files" }],
592 + });
593 + assert.deepInclude(snapshots[2]?.providerSession, {
594 + extensionStatuses: [
595 + { key: "watch", text: "Watching 4 files" },
596 + { key: "lint", text: "Lint clean" },
597 + ],
598 + });
599 + assert.isFalse(observed.some((event) => event.type === "message.updated"));
600 + assert.isFalse(
601 + observed.some(
602 + (event) =>
603 + event.type === "turn_item.updated" && event.turnItem.type !== "user_input_request",
604 + ),
605 + );
606 + assert.isFalse(
607 + fake.allRequests().some((request) => request["type"] === "extension_ui_response"),
608 + );
609 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
610 + );
611 +
612 + it.effect("bounds native extension statuses and lets cleared keys free capacity", () =>
613 + Effect.gen(function* () {
614 + const fake = yield* makeFakePi;
615 + const { runtime, takeEvent } = yield* openRuntime(fake);
616 + for (let index = 0; index < 35; index++) {
617 + yield* fake.emit({
618 + type: "extension_ui_request",
619 + method: "setStatus",
620 + statusKey: `key-${index}`,
621 + statusText: index === 1 ? "w".repeat(20000) : "Watching",
622 + });
623 + }
624 + for (const update of [
625 + { statusKey: "" },
626 + { statusKey: "x".repeat(257) },
627 + { statusKey: "malformed", statusText: null },
628 + ]) {
629 + yield* fake.emit({
630 + type: "extension_ui_request",
631 + method: "setStatus",
632 + statusText: "Invalid",
633 + ...update,
634 + });
635 + }
636 + yield* fake.emit({ type: "extension_ui_request", method: "setStatus", statusKey: "key-0" });
637 + yield* fake.emit({
638 + type: "extension_ui_request",
639 + method: "setStatus",
640 + statusKey: "replacement",
641 + statusText: "New status",
642 + });
643 + yield* fake.emit({
644 + type: "extension_ui_request",
645 + id: "status-barrier",
646 + method: "input",
647 + title: "Continue?",
648 + });
649 + yield* takeEvent((event) => event.type === "runtime_request.updated");
650 + const statuses = runtime.providerSession.extensionStatuses ?? [];
651 + assert.lengthOf(statuses, 32);
652 + assert.equal(statuses[0]?.key, "key-1");
653 + assert.equal(statuses[0]?.text.length, 4096);
654 + assert.deepEqual(statuses.at(-1), { key: "replacement", text: "New status" });
655 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
656 + );
657 +
658 + it.effect("publishes extension status while native work awaits adoption", () =>
659 + Effect.gen(function* () {
660 + const fake = yield* makeFakePi;
661 + const offers =
662 + yield* Queue.unbounded<ProviderContinuationRequests.ProviderContinuationRequest>();
663 + const { runtime, takeEvent } = yield* openRuntime(
664 + fake,
665 + "default",
666 + THREAD_ID,
667 + SESSION_ID,
668 + undefined,
669 + { offer: (offer) => Queue.offer(offers, offer).pipe(Effect.asVoid) },
670 + );
671 + yield* runtime.ensureThread({
672 + threadId: THREAD_ID,
673 + modelSelection: modelSelection("default"),
674 + runtimePolicy,
675 + });
676 + yield* fake.emit({ type: "agent_start" });
677 + yield* Queue.take(offers);
678 + yield* fake.emit({
679 + type: "extension_ui_request",
680 + method: "setStatus",
681 + statusKey: "watch",
682 + statusText: "Native wake",
683 + });
684 + yield* fake.emit({
685 + type: "extension_ui_request",
686 + id: "status-barrier",
687 + method: "input",
688 + title: "Continue?",
689 + });
690 + yield* takeEvent((event) => event.type === "runtime_request.updated");
691 + assert.deepEqual(runtime.providerSession.extensionStatuses, [
692 + { key: "watch", text: "Native wake" },
693 + ]);
694 + assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
695 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
696 + );
697 +
698 + it.effect(
699 + "keeps extension status through turn settlement and clears it on native session replacement",
700 + () =>
701 + Effect.gen(function* () {
702 + const fake = yield* makeFakePi;
703 + const { runtime, takeEvent } = yield* openRuntime(fake);
704 + const providerThread = yield* runtime.ensureThread({
705 + threadId: THREAD_ID,
706 + modelSelection: modelSelection("default"),
707 + runtimePolicy,
708 + });
709 + yield* startTurn(runtime, providerThread);
710 + yield* fake.takeRequest("prompt");
711 + yield* fake.emit({
712 + type: "extension_ui_request",
713 + method: "setStatus",
714 + statusKey: "watch",
715 + statusText: "Watching",
716 + });
717 + yield* fake.emit({ type: "agent_settled" });
718 + yield* takeEvent((event) => event.type === "turn.terminal");
719 + assert.deepInclude(runtime.providerSession, {
720 + status: "ready",
721 + extensionStatuses: [{ key: "watch", text: "Watching" }],
722 + });
723 + yield* startTurn(
724 + runtime,
725 + providerThread,
726 + "anthropic/other-model",
727 + [],
728 + "Hello again",
729 + undefined,
730 + 2,
731 + );
732 + assert.deepEqual(runtime.providerSession.extensionStatuses, [
733 + { key: "watch", text: "Watching" },
734 + ]);
735 + yield* fake.emit({ type: "agent_settled" });
736 + yield* takeEvent((event) => event.type === "turn.terminal");
737 + yield* runtime.ensureThread({
738 + threadId: THREAD_ID,
739 + modelSelection: modelSelection("default"),
740 + runtimePolicy,
741 + });
742 + assert.deepInclude(runtime.providerSession, { extensionStatuses: [] });
743 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
744 + );
745 +
746 + it.effect.each(["model error", "rejected prompt", "failed compact"] as const)(
747 + "keeps extension status through a reusable %s and the next turn",
748 + (failure) =>
749 + Effect.gen(function* () {
750 + const fake = yield* makeFakePi;
751 + const { runtime, takeEvent } = yield* openRuntime(fake);
752 + const providerThread = yield* runtime.ensureThread({
753 + threadId: THREAD_ID,
754 + modelSelection: modelSelection("default"),
755 + runtimePolicy,
756 + });
757 + yield* fake.emit({
758 + type: "extension_ui_request",
759 + method: "setStatus",
760 + statusKey: "watch",
761 + statusText: "Watching 3 files",
762 + });
763 + const command = failure === "failed compact" ? "compact" : "prompt";
764 + yield* startTurn(
765 + runtime,
766 + providerThread,
767 + "default",
768 + [],
769 + command === "compact" ? "/compact" : "Hello pi",
770 + );
771 + yield* fake.takeRequest(command);
772 + if (failure === "model error") {
773 + yield* fake.emit({
774 + type: "message_end",
775 + message: { role: "assistant", stopReason: "error", errorMessage: "Rate limited" },
776 + });
777 + yield* fake.emit({ type: "agent_settled" });
778 + } else {
779 + yield* fake.emit({
780 + type: "response",
781 + command,
782 + success: false,
783 + error: "Request rejected",
784 + });
785 + }
786 + const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
787 + assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "failed");
788 + assert.deepInclude(runtime.providerSession, {
789 + status: "error",
790 + extensionStatuses: [{ key: "watch", text: "Watching 3 files" }],
791 + });
792 +
793 + yield* fake.emit({
794 + type: "extension_ui_request",
795 + method: "setStatus",
796 + statusKey: "watch",
797 + statusText: "Watching 4 files",
798 + });
799 + yield* fake.emit({
800 + type: "extension_ui_request",
801 + id: "failed-turn-status-barrier",
802 + method: "input",
803 + title: "Continue?",
804 + });
805 + yield* takeEvent((event) => event.type === "runtime_request.updated");
806 + assert.deepInclude(runtime.providerSession, {
807 + status: "error",
808 + extensionStatuses: [{ key: "watch", text: "Watching 4 files" }],
809 + });
810 +
811 + yield* startTurn(runtime, providerThread, "default", [], "Hello again", undefined, 2);
812 + yield* fake.takeRequest("prompt");
813 + yield* fake.emit({ type: "agent_settled" });
814 + const nextTerminal = yield* takeEvent((event) => event.type === "turn.terminal");
815 + assert.isTrue(nextTerminal.type === "turn.terminal" && nextTerminal.status === "completed");
816 + assert.deepInclude(runtime.providerSession, {
817 + id: SESSION_ID,
818 + status: "ready",
819 + extensionStatuses: [{ key: "watch", text: "Watching 4 files" }],
820 + });
821 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
822 + );
823 +
824 + it.effect("preserves extension statuses when a native session switch is vetoed", () =>
825 + Effect.gen(function* () {
826 + const fake = yield* makeFakePi;
827 + const { runtime, takeEvent } = yield* openRuntime(fake);
828 + const providerThread = yield* runtime.ensureThread({
829 + threadId: THREAD_ID,
830 + modelSelection: modelSelection("default"),
831 + runtimePolicy,
832 + });
833 + yield* fake.emit({
834 + type: "extension_ui_request",
835 + method: "setStatus",
836 + statusKey: "watch",
837 + statusText: "Watching",
838 + });
839 + yield* fake.emit({
840 + type: "extension_ui_request",
841 + id: "status-barrier",
842 + method: "input",
843 + title: "Continue?",
844 + });
845 + yield* takeEvent((event) => event.type === "runtime_request.updated");
846 + fake.vetoNextSwitch();
847 + const exit = yield* runtime.resumeThread({ providerThread }).pipe(Effect.exit);
848 + assert.isTrue(Exit.isFailure(exit));
849 + assert.deepEqual(runtime.providerSession.extensionStatuses, [
850 + { key: "watch", text: "Watching" },
851 + ]);
852 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
853 + );
854 +
855 + it.effect.each(["success", "cancelled", "error"] as const)(
856 + "handles native status publications during session switch hooks, outcome=%s",
857 + (outcome) =>
858 + Effect.gen(function* () {
859 + const fake = yield* makeFakePi;
860 + const { runtime, takeEvent } = yield* openRuntime(fake);
861 + const providerThread = yield* runtime.ensureThread({
862 + threadId: THREAD_ID,
863 + modelSelection: modelSelection("default"),
864 + runtimePolicy,
865 + });
866 + for (const key of ["watch", "lint"])
867 + yield* fake.emit({
868 + type: "extension_ui_request",
869 + method: "setStatus",
870 + statusKey: key,
871 + statusText: key === "lint" ? "Lint clean" : "Watching",
872 + });
873 + fake.deferNextLifecycle("switch_session");
874 + const switching = yield* runtime
875 + .resumeThread({ providerThread })
876 + .pipe(Effect.exit, Effect.forkScoped);
877 + const request = yield* fake.takeRequest("switch_session");
878 + yield* fake.emit({ type: "extension_ui_request", method: "setStatus", statusKey: "watch" });
879 + yield* fake.emit({
880 + type: "extension_ui_request",
881 + method: "setStatus",
882 + statusKey: "startup",
883 + statusText: "Fresh status",
884 + });
885 + yield* fake.emit({
886 + type: "extension_ui_request",
887 + id: "switch-hook",
888 + method: "input",
889 + title: "Continue?",
890 + });
891 + yield* takeEvent((event) => event.type === "runtime_request.updated");
892 + yield* fake.emit({
893 + type: "response",
894 + id: request["id"],
895 + command: "switch_session",
896 + success: outcome !== "error",
897 + data: { cancelled: outcome === "cancelled" },
898 + ...(outcome === "error" ? { error: "Session replacement failed" } : {}),
899 + });
900 + const exit = yield* Fiber.join(switching);
901 + assert.equal(Exit.isFailure(exit), outcome !== "success");
902 + if (outcome === "error") {
903 + const reuse = yield* runtime.resumeThread({ providerThread }).pipe(Effect.exit);
904 + assert.isTrue(Exit.isFailure(reuse));
905 + yield* takeEvent(
906 + (event) =>
907 + event.type === "provider_session.updated" && event.providerSession.status === "error",
908 + );
909 + assert.deepEqual(runtime.providerSession.extensionStatuses, []);
910 + return;
911 + }
912 + assert.deepEqual(runtime.providerSession.extensionStatuses, [
913 + ...(outcome === "cancelled" ? [{ key: "lint", text: "Lint clean" }] : []),
914 + { key: "startup", text: "Fresh status" },
915 + ]);
916 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
917 + );
918 +
919 + it.effect.each(["stop", "transport death"] as const)(
920 + "clears extension statuses on %s",
921 + (retirement) =>
922 + Effect.gen(function* () {
923 + const fake = yield* makeFakePi;
924 + const { runtime, takeEvent } = yield* openRuntime(fake);
925 + const providerThread = yield* runtime.ensureThread({
926 + threadId: THREAD_ID,
927 + modelSelection: modelSelection("default"),
928 + runtimePolicy,
929 + });
930 + yield* startTurn(runtime, providerThread);
931 + const turnStarted = yield* takeEvent((event) => event.type === "provider_turn.updated");
932 + assert.equal(turnStarted.type, "provider_turn.updated");
933 + if (turnStarted.type !== "provider_turn.updated") return;
934 + yield* fake.emit({
935 + type: "extension_ui_request",
936 + method: "setStatus",
937 + statusKey: "watch",
938 + statusText: "Watching",
939 + });
940 + yield* fake.emit({
941 + type: "extension_ui_request",
942 + id: "status-barrier",
943 + method: "input",
944 + title: "Continue?",
945 + });
946 + yield* takeEvent((event) => event.type === "runtime_request.updated");
947 + assert.deepInclude(runtime.providerSession, {
948 + extensionStatuses: [{ key: "watch", text: "Watching" }],
949 + });
950 + if (retirement === "stop") {
951 + yield* runtime.interruptTurn({
952 + providerThread,
953 + providerTurnId: turnStarted.providerTurn.id,
954 + requestRuntimeRestart: true,
955 + });
956 + } else yield* fake.closeStdout;
957 + yield* takeEvent(
958 + (event) =>
959 + event.type === "provider_session.updated" &&
960 + event.providerSession.status === (retirement === "stop" ? "stopped" : "error"),
961 + );
962 + assert.deepInclude(runtime.providerSession, { extensionStatuses: [] });
963 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
964 + );
965 +
966 it.effect("keeps native image bytes and the saved path in the prompt", () =>
967 Effect.gen(function* () {
968 const host = yield* ProviderHost.ProviderHost;
packages/provider-pi/src/server/adapter.ts
+179 -16
@@ -1,4 +1,5 @@
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 +import * as NodeUtil from "node:util";
3 import { AgentScope } from "@t3tools/shared/AgentScope";
4 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
5 import { readToolOutputImage } from "@t3tools/shared/toolOutput";
@@ -82,6 +83,9 @@ const PI_INHERIT_MODEL_SLUG = "default";
83 const STREAM_FLUSH_MS = 50;
84 const PI_REQUEST_TIMEOUT_MS = 15_000;
85 const PI_SESSION_TIMEOUT_MS = 60_000;
86 +const MAX_EXTENSION_STATUSES = 32;
87 +const MAX_EXTENSION_STATUS_KEY_LENGTH = 256;
88 +const MAX_EXTENSION_STATUS_TEXT_LENGTH = 4096;
89 const PI_UNSOLICITED_ACTIVITY_ERROR =
90 "Pi started agent work outside an active T3 turn. The session was stopped to prevent invisible tool execution.";
91 const SETTLE_PROBE_MAX_ATTEMPTS = 3;
@@ -521,6 +525,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
525 cwd,
526 model: input.modelSelection.model,
527 capabilities: PiProviderCapabilitiesV2,
528 + extensionStatuses: [],
529 createdAt: now,
530 updatedAt: now,
531 lastError: null,
@@ -538,7 +543,14 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
543 let lastNativeThreadId: string | null = null;
544 let stopRequested = false;
545 let unsolicitedActivityDetected = false;
546 + // Turn failures can leave Pi alive; pump termination retires the runtime.
547 + let runtimeRetired = false;
548 let pendingWake: PiWake | null = null;
549 + let extensionStatusReset: {
550 + previous: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>;
551 + readonly touched: Set<string>;
552 + readonly ready: Deferred.Deferred<void, ProviderAdapter.ProviderAdapterProtocolError>;
553 + } | null = null;
554 let rollbackBarrier: Deferred.Deferred<
555 void,
556 ProviderAdapter.ProviderAdapterProtocolError
@@ -547,7 +559,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
559 yield* Effect.addFinalizer(() =>
560 Effect.gen(function* () {
561 closed = true;
562 + sessionEntity = { ...sessionEntity, extensionStatuses: [] };
563 pendingWake = null;
564 + if (extensionStatusReset !== null)
565 + yield* Deferred.fail(
566 + extensionStatusReset.ready,
567 + protocolError("Pi session closed during status reset"),
568 + );
569 if (rollbackBarrier !== null)
570 yield* Deferred.fail(
571 rollbackBarrier,
@@ -609,7 +627,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
627 lastError: string | null = sessionEntity.lastError,
628 ) {
629 const updatedAt = yield* DateTime.now;
612 - sessionEntity = { ...sessionEntity, status, lastError, updatedAt };
630 + sessionEntity = {
631 + ...sessionEntity,
632 + status,
633 + lastError,
634 + updatedAt,
635 + ...(status === "stopped" || runtimeRetired || unsolicitedActivityDetected
636 + ? { extensionStatuses: [] }
637 + : {}),
638 + };
639 yield* emit({
640 type: "provider_session.updated",
641 driver: PI_PROVIDER,
@@ -617,6 +643,63 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
643 });
644 });
645
646 + // Frequent notifications share the event pump's tracing boundary and outlive individual turns.
647 + const updateExtensionStatus = Effect.fnUntraced(function* (event: PiRpcRecord) {
648 + if (
649 + closed ||
650 + stopRequested ||
651 + runtimeRetired ||
652 + unsolicitedActivityDetected ||
653 + sessionEntity.status === "stopped"
654 + )
655 + return;
656 + const key = recordString(event, "statusKey");
657 + const rawText = recordField(event, "statusText");
658 + if (
659 + key === undefined ||
660 + key.trim().length === 0 ||
661 + key.length > MAX_EXTENSION_STATUS_KEY_LENGTH ||
662 + (rawText !== undefined && typeof rawText !== "string")
663 + )
664 + return;
665 + const text =
666 + typeof rawText === "string"
667 + ? NodeUtil.stripVTControlCharacters(
668 + rawText.slice(0, MAX_EXTENSION_STATUS_TEXT_LENGTH * 4),
669 + )
670 + .replaceAll(/\p{Cc}/gu, " ")
671 + .trim()
672 + .slice(0, MAX_EXTENSION_STATUS_TEXT_LENGTH)
673 + : "";
674 + const statuses = sessionEntity.extensionStatuses ?? [];
675 + if (extensionStatusReset?.previous.some((status) => status.key === key)) {
676 + extensionStatusReset.touched.add(key);
677 + }
678 + const index = statuses.findIndex((status) => status.key === key);
679 + if (
680 + index < 0
681 + ? text.length === 0 || statuses.length >= MAX_EXTENSION_STATUSES
682 + : statuses[index]?.text === text
683 + )
684 + return;
685 + sessionEntity = {
686 + ...sessionEntity,
687 + extensionStatuses:
688 + text.length === 0
689 + ? statuses.filter((status) => status.key !== key)
690 + : index < 0
691 + ? [...statuses, { key, text }]
692 + : statuses.map((status) => (status.key === key ? { key, text } : status)),
693 + };
694 + yield* updateProviderSession(sessionEntity.status);
695 + });
696 +
697 + const clearExtensionStatuses = Effect.fn("PiAdapter.clearExtensionStatuses")(function* () {
698 + if (sessionEntity.extensionStatuses?.length === 0) return;
699 + sessionEntity = { ...sessionEntity, extensionStatuses: [] };
700 + yield* updateProviderSession(sessionEntity.status);
701 + });
702 +
703 const updateProviderThread =
704 /* Provider events include streaming deltas; avoid a span for each update. */
705 Effect.fnUntraced(function* (
@@ -661,22 +744,81 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
744 return null;
745 };
746
664 - const lifecycleRequest = (record: PiRpcRecord) =>
665 - request(record, PI_SESSION_TIMEOUT_MS).pipe(
666 - // Timeout does not cancel Pi's lifecycle hook; retire the process before fallback can race it.
667 - Effect.tapError((error) =>
668 - Effect.logWarning("Pi session lifecycle request failed", {
669 - providerSessionId: input.providerSessionId,
670 - operation: record["type"],
671 - errorTag: error._tag,
672 - }),
747 + const lifecycleRequest = Effect.fn("PiAdapter.lifecycleRequest")(
748 + function* (record: PiRpcRecord) {
749 + if (extensionStatusReset !== null)
750 + return yield* protocolError("A Pi session lifecycle request is already pending");
751 + const reset = {
752 + previous: sessionEntity.extensionStatuses ?? [],
753 + touched: new Set<string>(),
754 + ready: yield* Deferred.make<void, ProviderAdapter.ProviderAdapterProtocolError>(),
755 + };
756 + extensionStatusReset = reset;
757 + return yield* Effect.gen(function* () {
758 + // RPC responses bypass the pump. Reset after all earlier native notifications.
759 + if (
760 + !(yield* Queue.offer(connection.events, { type: "t3.extension_status_reset", reset }))
761 + )
762 + return yield* protocolError("Pi transport closed during status reset");
763 + yield* Deferred.await(reset.ready);
764 + const result = yield* request(record, PI_SESSION_TIMEOUT_MS);
765 + if (recordField(result, "cancelled") === true) {
766 + yield* sessionEventPermit.withPermits(1)(
767 + Effect.gen(function* () {
768 + if (closed || stopRequested) return;
769 + const current = sessionEntity.extensionStatuses ?? [];
770 + // A veto keeps the old session. Preserve updates and clears from its lifecycle hooks.
771 + const restored = reset.previous.flatMap((status) => {
772 + if (!reset.touched.has(status.key)) return [status];
773 + const updated = current.find((candidate) => candidate.key === status.key);
774 + return updated === undefined ? [] : [updated];
775 + });
776 + restored.push(
777 + ...current.filter(
778 + (status) => !reset.previous.some((previous) => previous.key === status.key),
779 + ),
780 + );
781 + const statuses = restored.slice(0, MAX_EXTENSION_STATUSES);
782 + if (
783 + statuses.length === current.length &&
784 + statuses.every(
785 + (status, index) =>
786 + status.key === current[index]?.key && status.text === current[index]?.text,
787 + )
788 + )
789 + return;
790 + sessionEntity = { ...sessionEntity, extensionStatuses: statuses };
791 + yield* updateProviderSession(sessionEntity.status);
792 + }),
793 + );
794 + }
795 + return result;
796 + }).pipe(
797 + Effect.ensuring(
798 + Effect.sync(() => {
799 + if (extensionStatusReset === reset) extensionStatusReset = null;
800 + }),
801 + ),
802 + );
803 + },
804 + (effect, record) =>
805 + effect.pipe(
806 + Effect.tapError((error) =>
807 + Effect.logWarning("Pi session lifecycle request failed", {
808 + providerSessionId: input.providerSessionId,
809 + operation: record["type"],
810 + errorTag: error._tag,
811 + }),
812 + ),
813 + // A failed lifecycle RPC can leave Pi's previous native session disposed.
814 + Effect.tapError((error) =>
815 + error._tag === "PiRpcError" || error._tag === "PiRpcTimeoutError"
816 + ? connection.terminate
817 + : Effect.void,
818 + ),
819 + Effect.onInterrupt(() => connection.terminate),
820 ),
674 - Effect.catchTags({
675 - PiRpcTimeoutError: (error) =>
676 - connection.terminate.pipe(Effect.andThen(Effect.fail(error))),
677 - }),
678 - Effect.onInterrupt(() => connection.terminate),
679 - );
821 + );
822
823 const tokenUsageFromStats = (
824 stats: unknown,
@@ -1700,6 +1842,21 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1842 });
1843
1844 const handleSessionEvent = Effect.fnUntraced(function* (event: PiRpcRecord) {
1845 + if (event["type"] === "t3.extension_status_reset") {
1846 + const reset = extensionStatusReset;
1847 + if (reset !== null && event["reset"] === reset) {
1848 + reset.previous = sessionEntity.extensionStatuses ?? [];
1849 + reset.touched.clear();
1850 + yield* clearExtensionStatuses();
1851 + yield* Deferred.succeed(reset.ready, undefined);
1852 + }
1853 + return;
1854 + }
1855 + // A native wake may wait for a turn owner; status belongs to the live session immediately.
1856 + if (event["type"] === "extension_ui_request" && event["method"] === "setStatus") {
1857 + yield* updateExtensionStatus(event);
1858 + return;
1859 + }
1860 // Model hooks can show dialogs before turn ownership; keep requests session-scoped and buffer output.
1861 const interactiveUiRequest =
1862 event["type"] === "extension_ui_request" &&
@@ -2205,7 +2362,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2362 Effect.catchCause((cause) =>
2363 sessionEventPermit.withPermits(1)(
2364 Effect.gen(function* () {
2365 + runtimeRetired = true;
2366 const state = threadState;
2367 + if (extensionStatusReset !== null)
2368 + yield* Deferred.fail(
2369 + extensionStatusReset.ready,
2370 + protocolError("Pi transport closed during status reset"),
2371 + );
2372 if (rollbackBarrier !== null)
2373 yield* Deferred.fail(
2374 rollbackBarrier,