Merge origin/main into t3code/effect-tracing-observability

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-04-02 16:35:03 -07:00
commit 0ac582fabf
10 files changed
+264 -26

No files matched your search

+35
View File
@@ -1202,6 +1202,41 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("closes thread terminals after a successful archive command", () =>
Effect.gen(function* () {
const threadId = ThreadId.makeUnsafe("thread-archive");
const closeInputs: Array<Parameters<TerminalManagerShape["close"]>[0]> = [];
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
closeInputs.push(input);
}),
},
orchestrationEngine: {
dispatch: () => Effect.succeed({ sequence: 8 }),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.archive",
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 8);
assert.deepEqual(closeInputs, [{ threadId }]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience",
() =>
+14 -1
View File
@@ -118,7 +118,20 @@ const WsRpcLayer = WsRpcGroup.toLayer(
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
return yield* startup.enqueueCommand(orchestrationEngine.dispatch(normalizedCommand));
const result = yield* startup.enqueueCommand(
orchestrationEngine.dispatch(normalizedCommand),
);
if (normalizedCommand.type === "thread.archive") {
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close thread terminals after archive", {
threadId: normalizedCommand.threadId,
error: error.message,
}),
),
);
}
return result;
}).pipe(
Effect.mapError((cause) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
+17 -12
View File
@@ -52,6 +52,7 @@ import {
deriveWorkLogEntries,
hasActionableProposedPlan,
hasToolActivityForTurn,
isSessionActivelyRunningTurn,
isLatestTurnSettled,
formatElapsed,
} from "../session-logic";
@@ -1120,7 +1121,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
activePendingUserInput: activePendingUserInput?.requestId ?? null,
threadError: activeThread?.error,
});
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const isTurnRunning = isSessionActivelyRunningTurn(
activeLatestTurn,
activeThread?.session ?? null,
);
const isWorking = isTurnRunning || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
@@ -1137,7 +1142,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (activePendingProgress) {
return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`;
}
if (phase === "running") {
if (isTurnRunning) {
return "running";
}
if (showPlanFollowUpPrompt) {
@@ -1151,7 +1156,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
isConnecting,
isPreparingWorktree,
isSendBusy,
phase,
isTurnRunning,
prompt,
showPlanFollowUpPrompt,
]);
@@ -2161,13 +2166,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
} else if (shouldAutoScrollRef.current && !isNearBottom) {
@@ -2311,10 +2316,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
scheduleStickToBottom();
}, [messageCount, scheduleStickToBottom]);
useEffect(() => {
if (phase !== "running") return;
if (!isTurnRunning) return;
if (!shouldAutoScrollRef.current) return;
scheduleStickToBottom();
}, [phase, scheduleStickToBottom, timelineEntries]);
}, [isTurnRunning, scheduleStickToBottom, timelineEntries]);
useEffect(() => {
setExpandedWorkGroups({});
@@ -2533,14 +2538,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
: "local";
useEffect(() => {
if (phase !== "running") return;
if (!isTurnRunning) return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 1000);
return () => {
window.clearInterval(timer);
};
}, [phase]);
}, [isTurnRunning]);
useEffect(() => {
if (!activeThreadId) return;
@@ -2760,7 +2765,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSendBusy || isConnecting) {
if (isTurnRunning || isSendBusy || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
}
@@ -2793,7 +2798,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
setIsRevertingCheckpoint(false);
},
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, isTurnRunning, setThreadError],
);
const onSend = async (e?: { preventDefault: () => void }) => {
@@ -4382,7 +4387,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
: null
}
isRunning={phase === "running"}
isRunning={isTurnRunning}
showPlanFollowUpPrompt={
pendingUserInputs.length === 0 && showPlanFollowUpPrompt
}
+31 -5
View File
@@ -9,8 +9,8 @@ describe("collectActiveTerminalThreadIds", () => {
it("retains non-deleted server threads", () => {
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: [
{ id: threadId("server-1"), deletedAt: null },
{ id: threadId("server-2"), deletedAt: null },
{ id: threadId("server-1"), deletedAt: null, archivedAt: null },
{ id: threadId("server-2"), deletedAt: null, archivedAt: null },
],
draftThreadIds: [],
});
@@ -18,15 +18,41 @@ describe("collectActiveTerminalThreadIds", () => {
expect(activeThreadIds).toEqual(new Set([threadId("server-1"), threadId("server-2")]));
});
it("ignores deleted server threads and keeps local draft threads", () => {
it("ignores deleted and archived server threads and keeps local draft threads", () => {
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: [
{ id: threadId("server-active"), deletedAt: null },
{ id: threadId("server-deleted"), deletedAt: "2026-03-05T08:00:00.000Z" },
{ id: threadId("server-active"), deletedAt: null, archivedAt: null },
{
id: threadId("server-deleted"),
deletedAt: "2026-03-05T08:00:00.000Z",
archivedAt: null,
},
{
id: threadId("server-archived"),
deletedAt: null,
archivedAt: "2026-03-05T09:00:00.000Z",
},
],
draftThreadIds: [threadId("local-draft")],
});
expect(activeThreadIds).toEqual(new Set([threadId("server-active"), threadId("local-draft")]));
});
it("does not keep draft-linked terminal state for archived server threads", () => {
const archivedThreadId = threadId("server-archived");
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: [
{
id: archivedThreadId,
deletedAt: null,
archivedAt: "2026-03-05T09:00:00.000Z",
},
],
draftThreadIds: [archivedThreadId, threadId("local-draft")],
});
expect(activeThreadIds).toEqual(new Set([threadId("local-draft")]));
});
});
+10
View File
@@ -3,6 +3,7 @@ import type { ThreadId } from "@t3tools/contracts";
interface TerminalRetentionThread {
id: ThreadId;
deletedAt: string | null;
archivedAt: string | null;
}
interface CollectActiveTerminalThreadIdsInput {
@@ -14,11 +15,20 @@ export function collectActiveTerminalThreadIds(
input: CollectActiveTerminalThreadIdsInput,
): Set<ThreadId> {
const activeThreadIds = new Set<ThreadId>();
const snapshotThreadById = new Map(input.snapshotThreads.map((thread) => [thread.id, thread]));
for (const thread of input.snapshotThreads) {
if (thread.deletedAt !== null) continue;
if (thread.archivedAt !== null) continue;
activeThreadIds.add(thread.id);
}
for (const draftThreadId of input.draftThreadIds) {
const snapshotThread = snapshotThreadById.get(draftThreadId);
if (
snapshotThread &&
(snapshotThread.deletedAt !== null || snapshotThread.archivedAt !== null)
) {
continue;
}
activeThreadIds.add(draftThreadId);
}
return activeThreadIds;
+27 -1
View File
@@ -42,6 +42,7 @@ describe("deriveOrchestrationBatchEffects", () => {
it("targets draft promotion and terminal cleanup from thread lifecycle events", () => {
const createdThreadId = ThreadId.makeUnsafe("thread-created");
const deletedThreadId = ThreadId.makeUnsafe("thread-deleted");
const archivedThreadId = ThreadId.makeUnsafe("thread-archived");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.created", {
@@ -60,11 +61,16 @@ describe("deriveOrchestrationBatchEffects", () => {
threadId: deletedThreadId,
deletedAt: "2026-02-27T00:00:01.000Z",
}),
makeEvent("thread.archived", {
threadId: archivedThreadId,
archivedAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([createdThreadId]);
expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]);
expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId]);
expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId, archivedThreadId]);
expect(effects.needsProviderInvalidation).toBe(false);
});
@@ -105,4 +111,24 @@ describe("deriveOrchestrationBatchEffects", () => {
expect(effects.removeTerminalStateThreadIds).toEqual([]);
expect(effects.needsProviderInvalidation).toBe(true);
});
it("does not retain archive cleanup when a thread is unarchived later in the same batch", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.archived", {
threadId,
archivedAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
makeEvent("thread.unarchived", {
threadId,
updatedAt: "2026-02-27T00:00:02.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([]);
expect(effects.clearDeletedThreadIds).toEqual([]);
expect(effects.removeTerminalStateThreadIds).toEqual([]);
});
});
+18
View File
@@ -46,6 +46,24 @@ export function deriveOrchestrationBatchEffects(
break;
}
case "thread.archived": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: false,
clearDeletedThread: false,
removeTerminalState: true,
});
break;
}
case "thread.unarchived": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: false,
clearDeletedThread: false,
removeTerminalState: false,
});
break;
}
default: {
break;
}
+9 -1
View File
@@ -328,7 +328,11 @@ function EventRouter() {
useComposerDraftStore.getState().draftThreadsByThreadId,
) as ThreadId[];
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })),
snapshotThreads: threads.map((thread) => ({
id: thread.id,
deletedAt: null,
archivedAt: thread.archivedAt,
})),
draftThreadIds,
});
removeOrphanedTerminalStates(activeThreadIds);
@@ -497,6 +501,10 @@ function EventRouter() {
}
});
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const thread = useStore.getState().threads.find((entry) => entry.id === event.threadId);
if (thread && thread.archivedAt !== null) {
return;
}
useTerminalStateStore.getState().recordTerminalEvent(event);
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
if (hasRunningSubprocess === null) {
+85 -3
View File
@@ -20,6 +20,7 @@ import {
findSidebarProposedPlan,
hasActionableProposedPlan,
hasToolActivityForTurn,
isSessionActivelyRunningTurn,
isLatestTurnSettled,
} from "./session-logic";
@@ -1072,15 +1073,30 @@ describe("isLatestTurnSettled", () => {
} as const;
it("returns false while the same turn is still active in a running session", () => {
expect(
isLatestTurnSettled(
{
...latestTurn,
completedAt: null,
},
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
},
),
).toBe(false);
});
it("returns true when the turn completed but the session status stayed stale-running", () => {
expect(
isLatestTurnSettled(latestTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
}),
).toBe(false);
).toBe(true);
});
it("returns false while any turn is running to avoid stale latest-turn banners", () => {
it("returns false while a different turn is still running", () => {
expect(
isLatestTurnSettled(latestTurn, {
orchestrationStatus: "running",
@@ -1112,6 +1128,56 @@ describe("isLatestTurnSettled", () => {
});
});
describe("isSessionActivelyRunningTurn", () => {
const completedTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
startedAt: "2026-02-27T21:10:00.000Z",
completedAt: "2026-02-27T21:10:06.000Z",
} as const;
it("returns true when the current turn has not completed yet", () => {
expect(
isSessionActivelyRunningTurn(
{
...completedTurn,
completedAt: null,
},
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
},
),
).toBe(true);
});
it("returns false when the same turn already completed and only the session is stale", () => {
expect(
isSessionActivelyRunningTurn(completedTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
}),
).toBe(false);
});
it("returns true when a different turn is still active", () => {
expect(
isSessionActivelyRunningTurn(completedTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-2"),
}),
).toBe(true);
});
it("returns false when the session is not running", () => {
expect(
isSessionActivelyRunningTurn(completedTurn, {
orchestrationStatus: "ready",
activeTurnId: undefined,
}),
).toBe(false);
});
});
describe("deriveActiveWorkStartedAt", () => {
const latestTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
@@ -1122,7 +1188,10 @@ describe("deriveActiveWorkStartedAt", () => {
it("prefers the in-flight turn start when the latest turn is not settled", () => {
expect(
deriveActiveWorkStartedAt(
latestTurn,
{
...latestTurn,
completedAt: null,
},
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
@@ -1132,6 +1201,19 @@ describe("deriveActiveWorkStartedAt", () => {
).toBe("2026-02-27T21:10:00.000Z");
});
it("falls back to sendStartedAt when only the session status is stale-running", () => {
expect(
deriveActiveWorkStartedAt(
latestTurn,
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
},
"2026-02-27T21:11:00.000Z",
),
).toBe("2026-02-27T21:11:00.000Z");
});
it("falls back to sendStartedAt once the latest turn is settled", () => {
expect(
deriveActiveWorkStartedAt(
+18 -3
View File
@@ -128,15 +128,30 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
export function isSessionActivelyRunningTurn(
latestTurn: LatestTurnTiming | null,
session: SessionActivityState | null,
): boolean {
if (!session || session.orchestrationStatus !== "running") return false;
if (!latestTurn) return true;
const activeTurnId = session.activeTurnId;
if (activeTurnId === undefined) {
return latestTurn.completedAt === null;
}
if (latestTurn.turnId !== activeTurnId) {
return true;
}
return latestTurn.completedAt === null;
}
export function isLatestTurnSettled(
latestTurn: LatestTurnTiming | null,
session: SessionActivityState | null,
): boolean {
if (!latestTurn?.startedAt) return false;
if (!latestTurn.completedAt) return false;
if (!session) return true;
if (session.orchestrationStatus === "running") return false;
return true;
return !isSessionActivelyRunningTurn(latestTurn, session);
}
export function deriveActiveWorkStartedAt(