@devries-cameron20 / t3code-1 / commits / 242d00cd34
Fork 0

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

fix(clients): threads no longer flash in the inbox before they settle (#24760)

With the Working shelf on, a thread that stops working stays there for 2s. A server auto-settle in that window sends it straight to Settled, so threads no longer flash in the inbox and vanish. "Thread completed" waits the same 2s and fires once. The server now settles fast enough to land inside the window: it reads a pull request when a shell merge or close command ends, sweeps a thread when its background work ends, and runs per-thread settle checks in parallel, one per thread at a time. Takes over #22458. Co-authored-by: Omar <76748259+omar9848492@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 24, 2026 at 23:57 UTC 242d00cd34534e7a93cb6f6b02cf4652bdd1210e
14 files changed +1137 -187
apps/mobile/src/features/threads/threadListV2.test.ts
+30 -1
@@ -1,4 +1,5 @@
1 import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
2 +import { createInboxReturnTracker } from "@t3tools/client-runtime/state/thread-inbox";
3 import { presentThreadShell } from "@t3tools/client-runtime/state/models";
4 import * as DateTime from "effect/DateTime";
5 import * as Schema from "effect/Schema";
@@ -24,7 +25,7 @@ import {
25 RunId,
26 ThreadId,
27 } from "@t3tools/contracts";
27 -import { describe, expect, it } from "vite-plus/test";
28 +import { describe, expect, it, vi } from "vite-plus/test";
29
30 import type { PendingNewTask } from "../../state/use-pending-new-tasks";
31 import { makeRawThreadShell, makeThreadShellFixture } from "../../test-fixtures";
@@ -1562,6 +1563,34 @@ describe("Working section beta", () => {
1563 expect(off.workingCount).toBe(0);
1564 });
1565
1566 + it("keeps an inactive row in Working during the shared grace and returns it on expiry", () => {
1567 + vi.useFakeTimers();
1568 + vi.setSystemTime(new Date(NOW));
1569 + const tracker = createInboxReturnTracker();
1570 + const working = makeThread({ id: ThreadId.make("grace"), title: "grace", runtime: running });
1571 + const inactive = { ...working, runtime: null };
1572 + const render = () =>
1573 + build({
1574 + threads: [inactive],
1575 + workingShelfExpanded: true,
1576 + isWorking: tracker.isWorking,
1577 + inboxReturnAt: tracker.returnedAt,
1578 + });
1579 + try {
1580 + tracker.observe([working]);
1581 + tracker.observe([inactive]);
1582 + expect(render().workingCount).toBe(1);
1583 + expect(render().items[0]?.thread.runtime).toBeNull();
1584 + vi.advanceTimersByTime(2_000);
1585 + expect(render().workingCount).toBe(0);
1586 + expect(ids(render())).toEqual(["grace"]);
1587 + expect(tracker.returnedAt(inactive)).toBe(Date.parse(NOW) + 2_000);
1588 + } finally {
1589 + tracker.observe(null);
1590 + vi.useRealTimers();
1591 + }
1592 + });
1593 +
1594 it("orders the inbox by the latest return this device observed", () => {
1595 const layout = build({
1596 inboxReturnAt: (thread) =>
apps/mobile/src/features/threads/threadListV2.ts
+2 -1
@@ -577,6 +577,7 @@ export function buildThreadListV2Items(input: {
577 readonly now: string;
578 readonly workingShelfEnabled?: boolean;
579 readonly workingShelfExpanded?: boolean;
580 + readonly isWorking?: (thread: EnvironmentThreadShell) => boolean;
581 readonly inboxReturnAt?: (thread: EnvironmentThreadShell) => number | undefined;
582 readonly snoozedShelfExpanded?: boolean;
583 readonly settledShelfExpanded?: boolean;
@@ -659,7 +660,7 @@ export function buildThreadListV2Items(input: {
660 settled.push(thread);
661 } else if (thread.pinnedAt != null) {
662 pinned.push(thread);
662 - } else if (workingShelfEnabled && isThreadWorking(thread)) {
663 + } else if (workingShelfEnabled && (input.isWorking ?? isThreadWorking)(thread)) {
664 working.push(thread);
665 } else {
666 active.push(thread);
apps/mobile/src/features/threads/useThreadListV2.ts
+11 -5
@@ -1,5 +1,5 @@
1 import type { EnvironmentId } from "@t3tools/contracts";
2 -import { useMemo } from "react";
2 +import { useMemo, useSyncExternalStore } from "react";
3
4 import { scopedProjectKey } from "../../lib/scopedEntities";
5 import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -54,10 +54,15 @@ export function useThreadListV2(input: {
54 readonly selectedThreadKey: string | null;
55 }) {
56 const { threads, workingShelfEnabled } = input;
57 - // Observed once per change to the threads: that is when a thread can stop working.
58 - const inboxReturnAt = useMemo(
57 + // A thread can stop working when the threads change, or when its exit grace expires.
58 + const inboxVersion = useSyncExternalStore(
59 + threadListInboxReturns.subscribe,
60 + threadListInboxReturns.getSnapshot,
61 + );
62 + const inbox = useMemo(
63 () => threadListInboxReturns.observe(workingShelfEnabled ? threads : null),
60 - [threads, workingShelfEnabled],
64 + // oxlint-disable-next-line react/memo-dependencies -- the version signals an expired grace
65 + [threads, workingShelfEnabled, inboxVersion],
66 );
67 // Up/down menu availability for every card, computed once per section per
68 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
@@ -97,7 +102,8 @@ export function useThreadListV2(input: {
102 now: input.now,
103 workingShelfEnabled,
104 workingShelfExpanded: input.workingShelfExpanded,
100 - inboxReturnAt,
105 + inboxReturnAt: inbox.returnedAt,
106 + isWorking: inbox.isWorking,
107 snoozedShelfExpanded: input.snoozedShelfExpanded,
108 settledShelfExpanded: input.settledShelfExpanded,
109 selectedThreadKey: input.selectedThreadKey,
apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
+89 -1
@@ -1340,7 +1340,7 @@ describe("PullRequestSyncReactor", () => {
1340 "gh pr merge 7 --squash 2>&1 | tail -3",
1341 "cafe pr merge 7 --squash",
1342 "az repos pr update --id 7 --status completed",
1343 - ])("reads open links fresh only when a run that ran `%s` ends", (mergeCommand) =>
1343 + ])("reads open links fresh only for a thread that ran `%s`", (mergeCommand) =>
1344 Effect.scoped(
1345 Effect.gen(function* () {
1346 yield* TestClock.setTime(Date.parse(NOW));
@@ -1392,4 +1392,92 @@ describe("PullRequestSyncReactor", () => {
1392 }),
1393 ),
1394 );
1395 +
1396 + it.effect("reads open links again when the run ends, after `merge --auto` left them open", () =>
1397 + Effect.scoped(
1398 + Effect.gen(function* () {
1399 + yield* TestClock.setTime(Date.parse(NOW));
1400 + const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1401 + const fixture = yield* makeHarness({
1402 + snapshot: makeSnapshot([
1403 + makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1404 + ]),
1405 + summary: (input) =>
1406 + Ref.get(state).pipe(
1407 + Effect.map((current) =>
1408 + makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1409 + ),
1410 + ),
1411 + });
1412 +
1413 + yield* Effect.gen(function* () {
1414 + const reactor = yield* startAndSweep(fixture);
1415 + yield* Queue.offer(
1416 + fixture.domainEvents,
1417 + commandRan(ThreadId.make("agent"), "gh pr merge 7 --auto"),
1418 + );
1419 + yield* Queue.take(fixture.snapshotReads);
1420 + yield* Queue.take(fixture.snapshotReads);
1421 + yield* reactor.drain;
1422 + yield* Ref.set(state, "merged");
1423 + yield* Ref.set(fixture.syncCommands, []);
1424 +
1425 + yield* Queue.offer(fixture.domainEvents, runUpdated(ThreadId.make("agent"), "completed"));
1426 + yield* Queue.take(fixture.snapshotReads);
1427 + yield* Queue.take(fixture.snapshotReads);
1428 + yield* reactor.drain;
1429 +
1430 + assert.deepStrictEqual(
1431 + (yield* Ref.get(fixture.syncCommands)).map((command) => [
1432 + command.number,
1433 + command.snapshot.state,
1434 + ]),
1435 + [[7, "merged"]],
1436 + );
1437 + }).pipe(Effect.provide(fixture.layer));
1438 + }),
1439 + ),
1440 + );
1441 +
1442 + it.effect("reads open links fresh as soon as a merge command ends, before its run ends", () =>
1443 + Effect.scoped(
1444 + Effect.gen(function* () {
1445 + yield* TestClock.setTime(Date.parse(NOW));
1446 + const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1447 + const fixture = yield* makeHarness({
1448 + snapshot: makeSnapshot([
1449 + makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1450 + ]),
1451 + summary: (input) =>
1452 + Ref.get(state).pipe(
1453 + Effect.map((current) =>
1454 + makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1455 + ),
1456 + ),
1457 + });
1458 +
1459 + yield* Effect.gen(function* () {
1460 + const reactor = yield* startAndSweep(fixture);
1461 + yield* Ref.set(state, "merged");
1462 + yield* Ref.set(fixture.summaryCalls, []);
1463 +
1464 + yield* Queue.offer(
1465 + fixture.domainEvents,
1466 + commandRan(ThreadId.make("agent"), "gh pr merge 7"),
1467 + );
1468 + yield* Queue.take(fixture.snapshotReads);
1469 + yield* Queue.take(fixture.snapshotReads);
1470 + yield* reactor.drain;
1471 +
1472 + assert.deepStrictEqual(
1473 + (yield* Ref.get(fixture.syncCommands)).map((command) => [
1474 + command.number,
1475 + command.snapshot.state,
1476 + ]),
1477 + [[7, "merged"]],
1478 + );
1479 + }).pipe(Effect.provide(fixture.layer));
1480 + }),
1481 + ),
1482 + );
1483 });
apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
+17 -13
@@ -1,5 +1,6 @@
1 import {
2 CommandId,
3 + isOrchestrationV2WorkActive,
4 type PullRequestSummary,
5 type ThreadId,
6 type ThreadPullRequestKey,
@@ -481,7 +482,8 @@ export const make = Effect.gen(function* () {
482 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
483 );
484
484 - const closeCommandThreads = new Set<ThreadId>();
485 + // Threads that ran a close command this run, with the commands already read for.
486 + const closeCommands = new Map<ThreadId, Set<string>>();
487 const refreshOpenLinks = (threadId: ThreadId) =>
488 projections.getThreadsWithPullRequests(threadId).pipe(
489 Effect.flatMap((threads) =>
@@ -525,20 +527,22 @@ export const make = Effect.gen(function* () {
527 { discard: true },
528 );
529 // An agent can merge or close its pull request from a shell with its host's CLI, which
528 - // sends no merge notification. When a run that ran such a command ends, read the
529 - // thread's open links fresh, so settlement does not wait for the next sweep and the
530 - // cached summary. Other runs add no host reads.
531 - case "turn-item.updated":
532 - if (
533 - event.payload.type === "command_execution" &&
534 - isChangeRequestCloseCommand(event.payload.input)
535 - ) {
536 - closeCommandThreads.add(event.threadId);
530 + // sends no merge notification. Read the thread's open links fresh once that command
531 + // ends, while the agent usually still replies, so settlement can land before the run
532 + // ends. Read again when the run ends, since `merge --auto` returns before it merges.
533 + case "turn-item.updated": {
534 + const item = event.payload;
535 + if (item.type !== "command_execution" || !isChangeRequestCloseCommand(item.input)) {
536 + return Effect.void;
537 }
538 - return Effect.void;
538 + const ended = closeCommands.get(event.threadId) ?? new Set<string>();
539 + closeCommands.set(event.threadId, ended);
540 + if (isOrchestrationV2WorkActive(item.status) || ended.has(item.id)) return Effect.void;
541 + ended.add(item.id);
542 + return refreshOpenLinks(event.threadId);
543 + }
544 case "run.updated":
540 - return isTerminalRunStatus(event.payload.status) &&
541 - closeCommandThreads.delete(event.threadId)
545 + return isTerminalRunStatus(event.payload.status) && closeCommands.delete(event.threadId)
546 ? refreshOpenLinks(event.threadId)
547 : Effect.void;
548 default:
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+159
@@ -6,6 +6,7 @@ import {
6 ProjectId,
7 EventId,
8 ProviderInstanceId,
9 + RunId,
10 ThreadId,
11 type OrchestrationProjectShell,
12 type OrchestrationV2AppThread,
@@ -892,6 +893,164 @@ describe("ThreadSettlementServiceV2 worker", () => {
893 ),
894 );
895
896 + it.effect("settles a merged thread when its background work ends, during a slow full sweep", () =>
897 + Effect.scoped(
898 + Effect.gen(function* () {
899 + yield* TestClock.setTime(Date.parse(NOW));
900 + const periodicLookupStarted = yield* Deferred.make<void>();
901 + const releasePeriodicLookup = yield* Deferred.make<void>();
902 + const settled = yield* Deferred.make<void>();
903 + const branchLookupCount = yield* Ref.make(0);
904 + const mergedLink: NonNullable<SettlementShell["pullRequests"]>[number] = {
905 + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")),
906 + snapshot: {
907 + state: "merged",
908 + title: "Pull request",
909 + headBranch: "feature",
910 + baseBranch: "main",
911 + isDraft: false,
912 + updatedAt: NOW,
913 + syncedAt: NOW,
914 + mergedAt: NOW,
915 + },
916 + };
917 + const waiting = makeThread("waiting-on-subagent", {
918 + pullRequests: [mergedLink],
919 + pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
920 + });
921 + const slow = makeThread("slow-periodic-lookup", {
922 + branch: "another-feature",
923 + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
924 + });
925 + const fixture = yield* makeHarness({
926 + snapshot: makeSnapshot([waiting, slow]),
927 + branchPullRequest: () =>
928 + Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
929 + Effect.flatMap((count) =>
930 + count === 1
931 + ? Effect.succeed(makeBranchPullRequest("open"))
932 + : Deferred.succeed(periodicLookupStarted, undefined).pipe(
933 + Effect.andThen(Deferred.await(releasePeriodicLookup)),
934 + Effect.as(makeBranchPullRequest("open")),
935 + ),
936 + ),
937 + ),
938 + onDispatch: () => Deferred.succeed(settled, undefined),
939 + });
940 +
941 + yield* Effect.gen(function* () {
942 + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
943 + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
944 + assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
945 + yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
946 + yield* Deferred.await(periodicLookupStarted);
947 +
948 + yield* Ref.set(
949 + fixture.snapshots,
950 + makeSnapshot([{ ...waiting, pendingBackgroundTasks: [] }, slow]),
951 + );
952 + yield* fixture.publishEvent({
953 + type: "run.background-work-cancelled",
954 + id: EventId.make("event:background-ended"),
955 + threadId: waiting.id,
956 + occurredAt: DateTime.makeUnsafe(NOW),
957 + payload: { runId: RunId.make("run:waiting"), restartCancelledBackgroundWork: [] },
958 + });
959 + yield* Deferred.await(settled);
960 +
961 + assert.deepStrictEqual(
962 + (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
963 + [waiting.id],
964 + );
965 + yield* Deferred.succeed(releasePeriodicLookup, undefined);
966 + yield* reactor.drain;
967 + }).pipe(Effect.provide(fixture.layer));
968 + }),
969 + ),
970 + );
971 +
972 + it.effect("settles a stopped thread while another thread's lookup is slow", () =>
973 + Effect.scoped(
974 + Effect.gen(function* () {
975 + yield* TestClock.setTime(Date.parse(NOW));
976 + const slowLookupStarted = yield* Deferred.make<void>();
977 + const releaseSlowLookup = yield* Deferred.make<void>();
978 + const settled = yield* Deferred.make<void>();
979 + const branchLookupCount = yield* Ref.make(0);
980 + const recent = DateTime.makeUnsafe("2026-08-27T00:00:00.000Z");
981 + const slow = makeThread("slow-lookup", { branch: "feature", latestUserMessageAt: recent });
982 + const merged = makeThread("merged", {
983 + latestUserMessageAt: recent,
984 + pullRequests: [
985 + {
986 + ...persistedLink("open", recent),
987 + snapshot: {
988 + state: "merged",
989 + title: "Pull request",
990 + headBranch: "feature",
991 + baseBranch: "main",
992 + isDraft: false,
993 + updatedAt: NOW,
994 + syncedAt: NOW,
995 + mergedAt: NOW,
996 + },
997 + },
998 + ],
999 + pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1000 + });
1001 + const fixture = yield* makeHarness({
1002 + snapshot: makeSnapshot([slow, merged]),
1003 + branchPullRequest: () =>
1004 + Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1005 + Effect.flatMap((count) =>
1006 + count === 1
1007 + ? Effect.succeed(makeBranchPullRequest("open"))
1008 + : Deferred.succeed(slowLookupStarted, undefined).pipe(
1009 + Effect.andThen(Deferred.await(releaseSlowLookup)),
1010 + Effect.as(makeBranchPullRequest("open")),
1011 + ),
1012 + ),
1013 + ),
1014 + onDispatch: () => Deferred.succeed(settled, undefined),
1015 + });
1016 + const backgroundEnded = (threadId: ThreadId): OrchestrationV2DomainEvent => ({
1017 + type: "run.background-work-cancelled",
1018 + id: EventId.make(`event:background-ended:${threadId}`),
1019 + threadId,
1020 + occurredAt: DateTime.makeUnsafe(NOW),
1021 + payload: { runId: RunId.make(`run:${threadId}`), restartCancelledBackgroundWork: [] },
1022 + });
1023 +
1024 + yield* Effect.gen(function* () {
1025 + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1026 + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1027 + yield* fixture.publishEvent(backgroundEnded(slow.id));
1028 + yield* Deferred.await(slowLookupStarted);
1029 + // More events for the slow thread coalesce into one more pass, not more sweeps.
1030 + for (let index = 0; index < 9; index++) {
1031 + yield* fixture.publishEvent(backgroundEnded(slow.id));
1032 + }
1033 +
1034 + yield* Ref.set(
1035 + fixture.snapshots,
1036 + makeSnapshot([slow, { ...merged, pendingBackgroundTasks: [] }]),
1037 + );
1038 + yield* fixture.publishEvent(backgroundEnded(merged.id));
1039 + yield* Deferred.await(settled);
1040 +
1041 + assert.deepStrictEqual(
1042 + (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1043 + [merged.id],
1044 + );
1045 + yield* Deferred.succeed(releaseSlowLookup, undefined);
1046 + yield* reactor.drain;
1047 + // The startup sweep, the first per-thread sweep, and one coalesced rerun.
1048 + assert.strictEqual(yield* Ref.get(branchLookupCount), 3);
1049 + }).pipe(Effect.provide(fixture.layer));
1050 + }),
1051 + ),
1052 + );
1053 +
1054 it.effect(
1055 "settles branch threads on a pull request merge without waiting for the next sweep",
1056 () =>
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+60 -11
@@ -1,8 +1,12 @@
1 -import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
1 +import {
2 + backgroundWorkHoldsCompletion,
3 + turnItemUpdateCanEndBackgroundWork,
4 +} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
5 import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
6 import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
7 import {
8 CommandId,
9 + isOrchestrationV2WorkActive,
10 type ThreadId,
11 type OrchestrationV2DomainEvent,
12 type OrchestrationV2ThreadShell,
@@ -13,9 +17,11 @@ import * as Context from "effect/Context";
17 import * as Crypto from "effect/Crypto";
18 import * as DateTime from "effect/DateTime";
19 import * as Effect from "effect/Effect";
20 +import * as FiberSet from "effect/FiberSet";
21 import * as FileSystem from "effect/FileSystem";
22 import * as Layer from "effect/Layer";
23 import * as Schedule from "effect/Schedule";
24 +import * as Semaphore from "effect/Semaphore";
25 import type * as Scope from "effect/Scope";
26 import * as Stream from "effect/Stream";
27
@@ -523,9 +529,35 @@ export const make = Effect.gen(function* () {
529 }),
530 ),
531 );
526 - const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
527 - runSweep(null, threadId),
528 - );
532 + // A thread that just stopped must not wait behind a full sweep or another thread's host
533 + // reads: clients hold it in Working only briefly, so a late settle makes it appear and then vanish.
534 + const fullSweeps = yield* makeDrainableWorker(() => runSweep(null));
535 + const threadSweeps = yield* FiberSet.make<void>();
536 + const threadSweepSlots = yield* Semaphore.make(8);
537 + // One sweep per thread at a time; events during a running sweep coalesce into one more pass.
538 + const threadSweepStates = new Map<ThreadId, "queued" | "running" | "rerun">();
539 + const sweepThread = (
540 + threadId: ThreadId,
541 + ): Effect.Effect<void, Effect.Error<ReturnType<typeof runSweep>>> =>
542 + Effect.sync(() => threadSweepStates.set(threadId, "running")).pipe(
543 + Effect.andThen(runSweep(null, threadId)),
544 + threadSweepSlots.withPermits(1),
545 + Effect.andThen(
546 + Effect.suspend(() => {
547 + if (threadSweepStates.get(threadId) === "rerun") return sweepThread(threadId);
548 + threadSweepStates.delete(threadId);
549 + return Effect.void;
550 + }),
551 + ),
552 + );
553 + const enqueueThread = (threadId: ThreadId) =>
554 + Effect.suspend(() => {
555 + const state = threadSweepStates.get(threadId);
556 + if (state === "running") threadSweepStates.set(threadId, "rerun");
557 + if (state !== undefined) return Effect.void;
558 + threadSweepStates.set(threadId, "queued");
559 + return sweepThread(threadId).pipe(FiberSet.run(threadSweeps), Effect.asVoid);
560 + });
561
562 // Skip settle scripts in shared checkouts where other threads may still work.
563 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
@@ -572,16 +604,30 @@ export const make = Effect.gen(function* () {
604 case "thread.pull-request-link-updated":
605 case "thread.pull-request-synced":
606 case "provider-session.detached":
575 - return worker.enqueue(event.threadId);
607 + case "run.background-work-cancelled":
608 + return enqueueThread(event.threadId);
609 + // Sweep only when the work can have ended: progress updates cannot settle anything.
610 + case "subagent.updated":
611 + return isOrchestrationV2WorkActive(event.payload.status)
612 + ? Effect.void
613 + : enqueueThread(event.threadId);
614 + case "provider-thread.updated":
615 + return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])
616 + ? Effect.void
617 + : enqueueThread(event.threadId);
618 + case "turn-item.updated":
619 + return turnItemUpdateCanEndBackgroundWork(event.payload)
620 + ? enqueueThread(event.threadId)
621 + : Effect.void;
622 case "provider-session.updated":
623 return event.payload.status !== "starting" && event.payload.status !== "running"
578 - ? worker.enqueue(event.threadId)
624 + ? enqueueThread(event.threadId)
625 : Effect.void;
626 case "run.updated":
627 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
628 event.payload.status,
629 )
584 - ? worker.enqueue(event.threadId)
630 + ? enqueueThread(event.threadId)
631 : Effect.void;
632 default:
633 return Effect.void;
@@ -598,8 +644,8 @@ export const make = Effect.gen(function* () {
644 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
645 yield* forkParked(
646 Effect.gen(function* () {
601 - yield* worker.enqueue(undefined);
602 - yield* worker.drain;
647 + yield* fullSweeps.enqueue(undefined);
648 + yield* fullSweeps.drain;
649 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
650 );
651 yield* forkParked(
@@ -609,7 +655,7 @@ export const make = Effect.gen(function* () {
655 return Effect.void;
656 }
657 lastSettlementSettings = key;
612 - return worker.enqueue(undefined);
658 + return fullSweeps.enqueue(undefined);
659 }),
660 );
661 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
@@ -622,7 +668,10 @@ export const make = Effect.gen(function* () {
668 );
669 });
670
625 - return { start, drain: worker.drain } satisfies ThreadSettlementServiceV2["Service"];
671 + return {
672 + start,
673 + drain: Effect.andThen(fullSweeps.drain, FiberSet.awaitEmpty(threadSweeps)),
674 + } satisfies ThreadSettlementServiceV2["Service"];
675 });
676
677 export const layer = Layer.effect(ThreadSettlementServiceV2, make);
apps/web/src/components/Sidebar.tsx
+21 -8
@@ -28,7 +28,10 @@ import {
28 effectiveSnoozed,
29 threadWokeAt,
30 } from "@t3tools/client-runtime/state/thread-settled";
31 -import { createInboxReturnTracker } from "@t3tools/client-runtime/state/thread-inbox";
31 +import {
32 + createInboxReturnTracker,
33 + isThreadWorking,
34 +} from "@t3tools/client-runtime/state/thread-inbox";
35 import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
36 import {
37 nextShownOrder,
@@ -61,6 +64,7 @@ import {
64 useReducer,
65 useRef,
66 useState,
67 + useSyncExternalStore,
68 type KeyboardEvent as ReactKeyboardEvent,
69 type MouseEvent as ReactMouseEvent,
70 type ReactNode,
@@ -154,7 +158,6 @@ import {
158 filterSidebarProjectScopeItems,
159 firstValidTimestampMs,
160 isSidebarNestedLinkClick,
157 - isSidebarThreadWorking,
161 isTrailingDoubleClick,
162 orderItemsByPreferredIds,
163 planSidebarThreadDrop,
@@ -302,6 +305,9 @@ interface SidebarThreadPartitionInput {
305 readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
306 readonly optimisticDrop: SidebarOptimisticDrop | null;
307 readonly workingShelfEnabled: boolean;
308 + // Snooze wakes, the queued-turn grace and the Working shelf's exit grace depend
309 + // on the clock, so the minute tick, the precise snooze-wake tick and the inbox
310 + // tracker's expiry version are inputs: a new key repartitions.
311 readonly clockKey: string;
312 }
313
@@ -375,6 +381,10 @@ function useSidebarThreads(input: {
381 ),
382 );
383 const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled);
384 + const inboxReturnsVersion = useSyncExternalStore(
385 + inboxReturns.subscribe,
386 + inboxReturns.getSnapshot,
387 + );
388 const nowMinute = useNowMinute();
389 // Minute-quantized clocks would delay second-precise snooze wakes by up to a minute.
390 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
@@ -414,7 +424,7 @@ function useSidebarThreads(input: {
424 serverConfigs,
425 optimisticDrop,
426 workingShelfEnabled,
417 - clockKey: `${nowMinute}:${snoozeWakeTick}`,
427 + clockKey: `${nowMinute}:${snoozeWakeTick}:${inboxReturnsVersion}`,
428 });
429 const partitionNextWakeAt = partition.snoozedThreads[0]?.snoozedUntil ?? null;
430 if (partitionNextWakeAt !== nextSnoozeWakeAt) setNextSnoozeWakeAt(partitionNextWakeAt);
@@ -506,12 +516,15 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
516 const { threads, scopedProjectKeys, serverConfigs, optimisticDrop, workingShelfEnabled } = input;
517 const preciseNow = new Date().toISOString();
518 const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys);
509 - inboxReturns.observe(workingShelfEnabled ? threads : null);
519 + const inboxObservation = inboxReturns.observe(workingShelfEnabled ? threads : null);
520 const pinned: EnvironmentThreadShell[] = [];
521 const active: EnvironmentThreadShell[] = [];
522 const working: EnvironmentThreadShell[] = [];
513 - const inbox = (thread: EnvironmentThreadShell) =>
514 - workingShelfEnabled && isSidebarThreadWorking(thread) ? working : active;
523 + const inbox = (thread: EnvironmentThreadShell, manuallyMoved = false) =>
524 + workingShelfEnabled &&
525 + (manuallyMoved ? isThreadWorking(thread) : inboxObservation.isWorking(thread))
526 + ? working
527 + : active;
528 const snoozed: EnvironmentThreadShell[] = [];
529 const settled: EnvironmentThreadShell[] = [];
530 const draggable = new Set<string>();
@@ -536,7 +549,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
549 ? pinned
550 : optimisticDrop.section === "settled"
551 ? settled
539 - : inbox(projected)
552 + : inbox(projected, true)
553 ).push(
554 optimisticDrop.clearsSnooze
555 ? projected
@@ -561,7 +574,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
574 // Capability gates dragging only; mixed server versions must preserve the same pinned order across clients.
575 const sortedPinned = sortPinnedThreadsForSidebar(pinned);
576 const sortedActive = workingShelfEnabled
564 - ? sortInboxThreadsByReturn(active, inboxReturns.returnedAt)
577 + ? sortInboxThreadsByReturn(active, inboxObservation.returnedAt)
578 : sortThreadsForSidebar(active);
579 return {
580 pinnedThreads:
apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx
+27 -1
@@ -1,11 +1,12 @@
1 import { RegistryContext } from "@effect/atom-react";
2 +import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
3 import { EnvironmentId } from "@t3tools/contracts";
4 import * as DateTime from "effect/DateTime";
5 import * as Option from "effect/Option";
6 import { Atom, AtomRegistry } from "effect/reactivity";
7 import { expect, it, vi } from "vite-plus/test";
8
8 -import { render, stubGlobal, type Screen } from "../../test/render";
9 +import { fakeTimers, render, stubGlobal, type Screen } from "../../test/render";
10
11 const state = vi.hoisted(() => ({
12 mode: "notifications",
@@ -235,6 +236,31 @@ it.each([
236 latestTurn: { turnId: "turn", state: status, completedAt: "2026-09-13T07:01:00.000Z" },
237 }),
238 );
239 + using _timers = fakeTimers();
240 await screen.rerender(app.ui());
241 + await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
242 expect(TestNotification.sent.map((notification) => notification.title)).toEqual(titles);
243 });
244 +
245 +it("holds a completion through a continuation gap and notifies once it settles", async () => {
246 + await using app = setup();
247 + await app.render();
248 + using _timers = fakeTimers();
249 + const finished = (turnId: string, completedAt: string) => ({
250 + latestTurn: { turnId, state: "completed", completedAt },
251 + });
252 + state.shells.set("one", shell(finished("turn-1", "2026-09-13T07:00:01.000Z")));
253 + await app.render();
254 + state.shells.set(
255 + "one",
256 + shell({ latestTurn: { turnId: "turn-2", state: "running", completedAt: null } }),
257 + );
258 + await app.render();
259 + state.shells.set("one", shell(finished("turn-2", "2026-09-13T07:00:02.000Z")));
260 + await app.render();
261 + expect(TestNotification.sent).toEqual([]);
262 + await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS - 1);
263 + expect(TestNotification.sent).toEqual([]);
264 + await vi.advanceTimersByTimeAsync(1);
265 + expect(TestNotification.sent.map((sent) => sent.title)).toEqual(["Thread completed"]);
266 +});
apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts new
+193
@@ -0,0 +1,193 @@
1 +import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
2 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +
4 +import {
5 + createThreadNotificationGate,
6 + type ThreadNotificationObservation,
7 +} from "./ThreadNotificationCoordinator.logic";
8 +
9 +const working: ThreadNotificationObservation = {
10 + attention: null,
11 + settled: false,
12 + completedAt: null,
13 +};
14 +const completed = (at: number): ThreadNotificationObservation => ({
15 + attention: null,
16 + settled: true,
17 + completedAt: at,
18 +});
19 +const visible = { archived: false, quiet: false };
20 +
21 +function harness() {
22 + const notify = vi.fn();
23 + const gate = createThreadNotificationGate<string>(notify);
24 + let prior: ThreadNotificationObservation | undefined;
25 + const observe = (next: ThreadNotificationObservation, options = visible) => {
26 + gate.observe("thread", prior, next, options);
27 + prior = next;
28 + };
29 + return { gate, notify, observe };
30 +}
31 +
32 +describe("createThreadNotificationGate", () => {
33 + beforeEach(() => {
34 + vi.useFakeTimers();
35 + });
36 + afterEach(() => {
37 + vi.useRealTimers();
38 + });
39 +
40 + it("drops a completion when the thread resumes within the grace", () => {
41 + const { notify, observe } = harness();
42 + observe(working);
43 + observe(completed(1));
44 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS - 1);
45 + observe(working);
46 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
47 + expect(notify).not.toHaveBeenCalled();
48 + });
49 +
50 + it("notifies a real completion once after the grace", () => {
51 + const { notify, observe } = harness();
52 + observe(working);
53 + observe(completed(1));
54 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS - 1);
55 + expect(notify).not.toHaveBeenCalled();
56 + vi.advanceTimersByTime(1);
57 + expect(notify.mock.calls).toEqual([["thread", "completion"]]);
58 + observe({ ...completed(1) });
59 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
60 + expect(notify).toHaveBeenCalledTimes(1);
61 + });
62 +
63 + it("notifies attention at once and replaces a pending completion", () => {
64 + const { notify, observe } = harness();
65 + observe(working);
66 + observe(completed(1));
67 + vi.advanceTimersByTime(500);
68 + observe({ attention: "run-1:approval", settled: false, completedAt: null });
69 + expect(notify.mock.calls).toEqual([["thread", "input"]]);
70 + vi.advanceTimersByTime(60_000);
71 + // The request resolves and the same run reads as completed again.
72 + observe(completed(1));
73 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
74 + expect(notify.mock.calls).toEqual([["thread", "input"]]);
75 + });
76 +
77 + it("notifies one completion across continuation gaps", () => {
78 + const { notify, observe } = harness();
79 + observe(working);
80 + observe(completed(1));
81 + vi.advanceTimersByTime(300);
82 + observe(working);
83 + vi.advanceTimersByTime(5_000);
84 + observe(completed(2));
85 + vi.advanceTimersByTime(300);
86 + observe(working);
87 + vi.advanceTimersByTime(5_000);
88 + observe(completed(3));
89 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
90 + expect(notify.mock.calls).toEqual([["thread", "completion"]]);
91 + });
92 +
93 + it("keeps a completion interrupted by attention after a working gap from firing", () => {
94 + const { notify, observe } = harness();
95 + observe(working);
96 + observe(completed(1));
97 + vi.advanceTimersByTime(500);
98 + observe(working);
99 + observe({ attention: "run-1:approval", settled: false, completedAt: null });
100 + vi.advanceTimersByTime(60_000);
101 + observe(completed(1));
102 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
103 + expect(notify.mock.calls).toEqual([["thread", "input"]]);
104 + });
105 +
106 + it("adds nothing when attention follows a completion that already fired", () => {
107 + const { notify, observe } = harness();
108 + observe(working);
109 + observe(completed(1));
110 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
111 + observe({ attention: "run-1:limited", settled: false, completedAt: null });
112 + observe(completed(1));
113 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
114 + expect(notify.mock.calls).toEqual([
115 + ["thread", "completion"],
116 + ["thread", "input"],
117 + ]);
118 + });
119 +
120 + it("still notifies a newer completion after attention", () => {
121 + const { notify, observe } = harness();
122 + observe(working);
123 + observe(completed(1));
124 + vi.advanceTimersByTime(500);
125 + observe({ attention: "run-2:approval", settled: false, completedAt: null });
126 + observe(working);
127 + observe(completed(2));
128 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
129 + expect(notify.mock.calls).toEqual([
130 + ["thread", "input"],
131 + ["thread", "completion"],
132 + ]);
133 + });
134 +
135 + it("ignores unrelated updates while a completion waits", () => {
136 + const { notify, observe } = harness();
137 + observe(working);
138 + observe(completed(1));
139 + vi.advanceTimersByTime(1_500);
140 + observe({ ...completed(1) });
141 + vi.advanceTimersByTime(500);
142 + expect(notify).toHaveBeenCalledTimes(1);
143 + });
144 +
145 + it("notifies a run that settles again after a brief runtime blip", () => {
146 + const { notify, observe } = harness();
147 + observe(working);
148 + observe(completed(1));
149 + vi.advanceTimersByTime(500);
150 + observe(working);
151 + observe(completed(1));
152 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
153 + expect(notify.mock.calls).toEqual([["thread", "completion"]]);
154 + });
155 +
156 + it("restarts the grace when a newer completion replaces a pending one", () => {
157 + const { notify, observe } = harness();
158 + observe(working);
159 + observe(completed(1));
160 + vi.advanceTimersByTime(1_500);
161 + observe(completed(2));
162 + vi.advanceTimersByTime(1_500);
163 + expect(notify).not.toHaveBeenCalled();
164 + vi.advanceTimersByTime(500);
165 + expect(notify).toHaveBeenCalledTimes(1);
166 + });
167 +
168 + it("drops a pending completion on archive, stop request, removal or clear", () => {
169 + for (const end of [
170 + (h: ReturnType<typeof harness>) => h.observe(completed(1), { ...visible, archived: true }),
171 + (h: ReturnType<typeof harness>) =>
172 + h.observe({ ...completed(1) }, { ...visible, quiet: true }),
173 + (h: ReturnType<typeof harness>) => h.gate.retain(new Set()),
174 + (h: ReturnType<typeof harness>) => h.gate.clear(),
175 + ]) {
176 + const h = harness();
177 + h.observe(working);
178 + h.observe(completed(1));
179 + end(h);
180 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
181 + expect(h.notify).not.toHaveBeenCalled();
182 + }
183 + });
184 +
185 + it("never notifies a stopped run or the first observation", () => {
186 + const { notify, observe } = harness();
187 + observe(completed(1));
188 + observe(working);
189 + observe(completed(2), { ...visible, quiet: true });
190 + vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
191 + expect(notify).not.toHaveBeenCalled();
192 + });
193 +});
apps/web/src/components/ThreadNotificationCoordinator.logic.ts new
+78
@@ -0,0 +1,78 @@
1 +import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
2 +
3 +export type ThreadNotificationKind = "input" | "completion";
4 +
5 +export interface ThreadNotificationObservation {
6 + /** Run and status key while the thread needs attention, otherwise null. */
7 + readonly attention: string | null;
8 + /** The thread is idle and its latest run completed. */
9 + readonly settled: boolean;
10 + /** When the latest run completed, if it did. */
11 + readonly completedAt: number | null;
12 +}
13 +
14 +/**
15 + * Attention notifies at once. Completion waits out the Working shelf's exit grace,
16 + * because an orchestrator run can end moments before its continuation starts. Any
17 + * observation that is not settled during the wait cancels it.
18 + */
19 +export function createThreadNotificationGate<Key>(
20 + notify: (key: Key, kind: ThreadNotificationKind) => void,
21 +) {
22 + const pending = new Map<Key, { at: number; timer: ReturnType<typeof setTimeout> }>();
23 + // The newest completion already notified, or deliberately skipped.
24 + const handled = new Map<Key, number>();
25 + // The newest completion seen settled, kept while the thread works or waits.
26 + const lastSettled = new Map<Key, number>();
27 + const cancel = (key: Key) => {
28 + clearTimeout(pending.get(key)?.timer);
29 + pending.delete(key);
30 + };
31 + const skip = (key: Key, at: number | null) => {
32 + if (at !== null && at > (handled.get(key) ?? -Infinity)) handled.set(key, at);
33 + };
34 + return {
35 + observe(
36 + key: Key,
37 + prior: ThreadNotificationObservation | undefined,
38 + next: ThreadNotificationObservation,
39 + options: { readonly archived: boolean; readonly quiet: boolean },
40 + ): void {
41 + if (next.settled && next.completedAt !== null) lastSettled.set(key, next.completedAt);
42 + if (!next.settled || options.archived || options.quiet) cancel(key);
43 + // The first sighting, archived threads, and stopped or silent runs never notify completion.
44 + if (!prior || options.archived || options.quiet) skip(key, next.completedAt);
45 + if (!prior || options.archived) return;
46 + if (next.attention && next.attention !== prior.attention) {
47 + // Attention replaces the completion before it, so that run must not notify later.
48 + skip(key, lastSettled.get(key) ?? null);
49 + cancel(key);
50 + notify(key, "input");
51 + return;
52 + }
53 + const at = next.completedAt;
54 + if (!next.settled || at === null || at <= (handled.get(key) ?? -Infinity)) return;
55 + if (pending.get(key)?.at === at) return;
56 + cancel(key);
57 + pending.set(key, {
58 + at,
59 + timer: setTimeout(() => {
60 + pending.delete(key);
61 + handled.set(key, at);
62 + notify(key, "completion");
63 + }, WORKING_EXIT_GRACE_MS),
64 + });
65 + },
66 + /** Forgets threads that left the snapshot. */
67 + retain(keys: ReadonlySet<Key>): void {
68 + for (const key of pending.keys()) if (!keys.has(key)) cancel(key);
69 + for (const key of handled.keys()) if (!keys.has(key)) handled.delete(key);
70 + for (const key of lastSettled.keys()) if (!keys.has(key)) lastSettled.delete(key);
71 + },
72 + clear(): void {
73 + for (const key of pending.keys()) cancel(key);
74 + handled.clear();
75 + lastSettled.clear();
76 + },
77 + };
78 +}
apps/web/src/components/ThreadNotificationCoordinator.tsx
+134 -112
@@ -1,4 +1,5 @@
1 import {
2 + type EnvironmentThreadShell,
3 type PendingSubagentRequest,
4 presentThreadShell,
5 } from "@t3tools/client-runtime/state/models";
@@ -13,7 +14,7 @@ import {
14 MessageCircleQuestionIcon,
15 ShieldQuestionIcon,
16 } from "lucide-react";
16 -import { useEffect, useRef } from "react";
17 +import { useEffect, useEffectEvent, useRef } from "react";
18
19 import { getClientSettings, useClientSettings } from "../hooks/useSettings";
20 import { useEnvironmentIds } from "../state/environments";
@@ -26,7 +27,12 @@ import {
27 threadNotificationTag,
28 unlockNotificationAudio,
29 } from "../threadNotifications";
29 -import { resolveSidebarThreadStatus } from "./Sidebar.logic";
30 +import { resolveSidebarThreadStatus, type SidebarThreadStatus } from "./Sidebar.logic";
31 +import {
32 + createThreadNotificationGate,
33 + type ThreadNotificationKind,
34 + type ThreadNotificationObservation,
35 +} from "./ThreadNotificationCoordinator.logic";
36 import { toastManager } from "./ui/toast";
37
38 export function ThreadNotificationCoordinator() {
@@ -93,11 +99,11 @@ export function ThreadNotificationCoordinator() {
99 ));
100 }
101
96 -interface NotificationState {
102 +interface NotificationState extends ThreadNotificationObservation {
103 readonly raw: OrchestrationV2ThreadShell;
104 readonly subagentRequest: PendingSubagentRequest | null;
99 - readonly attention: string | null;
100 - readonly completion: number | null;
105 + readonly thread: EnvironmentThreadShell;
106 + readonly status: SidebarThreadStatus;
107 }
108
109 function EnvironmentNotifications({
@@ -120,13 +126,116 @@ function EnvironmentNotifications({
126 });
127 const previous = useRef(new Map<ThreadId, NotificationState>());
128
129 + // Completions fire from a timer, so read settings, focus and route when presenting.
130 + const present = useEffectEvent((threadId: ThreadId, kind: ThreadNotificationKind) => {
131 + const entry = previous.current.get(threadId);
132 + if (!entry) return;
133 + const { thread, status } = entry;
134 + const title =
135 + kind === "completion"
136 + ? "Thread completed"
137 + : status === "approval"
138 + ? "Approval needed"
139 + : status === "limited"
140 + ? "Usage limit reached"
141 + : status === "failed"
142 + ? "Thread failed"
143 + : status === "request"
144 + ? "Guest request"
145 + : "Input needed";
146 + if (hasNotificationSound(mode)) {
147 + void playNotificationSound(kind, () =>
148 + hasNotificationSound(getClientSettings().notificationMode),
149 + );
150 + }
151 + if (
152 + inAppNotificationsEnabled &&
153 + document.visibilityState === "visible" &&
154 + document.hasFocus() &&
155 + (activeEnvironmentId !== environmentId || activeThreadId !== thread.id)
156 + ) {
157 + const toastId = toastManager.add({
158 + type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
159 + title,
160 + description: thread.title,
161 + data: {
162 + hideCopyButton: true,
163 + leadingIcon:
164 + kind === "completion" ? (
165 + <CircleCheckIcon aria-hidden className="size-4 text-success-foreground" />
166 + ) : status === "approval" ? (
167 + <ShieldQuestionIcon aria-hidden className="size-4 text-warning-foreground" />
168 + ) : status === "failed" ? (
169 + <CircleAlertIcon aria-hidden className="size-4 text-destructive-foreground" />
170 + ) : (
171 + <MessageCircleQuestionIcon aria-hidden className="size-4 text-info-foreground" />
172 + ),
173 + },
174 + actionProps: {
175 + children: "Open thread",
176 + onClick: () => {
177 + toastManager.close(toastId);
178 + void navigate({
179 + to: "/$environmentId/$threadId",
180 + params: { environmentId, threadId: thread.id },
181 + });
182 + },
183 + },
184 + });
185 + return;
186 + }
187 + if (
188 + !hasDesktopNotifications(mode) ||
189 + (document.visibilityState === "visible" && document.hasFocus()) ||
190 + typeof Notification === "undefined" ||
191 + Notification.permission !== "granted"
192 + )
193 + return;
194 + try {
195 + const notification = new Notification(title, {
196 + body: thread.title,
197 + tag: threadNotificationTag(environmentId, thread.id),
198 + silent: true,
199 + });
200 + onNotification(environmentId, notification);
201 + notification.addEventListener("click", () => {
202 + notification.close();
203 + window.focus();
204 + void window.desktopBridge?.revealWindow?.().catch(() => undefined);
205 + void navigate({
206 + to: "/$environmentId/$threadId",
207 + params: { environmentId, threadId: thread.id },
208 + });
209 + });
210 + } catch {
211 + // Some browsers expose Notification but reject desktop presentation.
212 + }
213 + });
214 + const gate = useRef<ReturnType<typeof createThreadNotificationGate<ThreadId>>>(null);
215 useEffect(() => {
216 + const created = createThreadNotificationGate<ThreadId>((threadId, kind) =>
217 + present(threadId, kind),
218 + );
219 + gate.current = created;
220 + return () => {
221 + created.clear();
222 + gate.current = null;
223 + // A new gate has no pending completions, so forget the states they compared against.
224 + previous.current.clear();
225 + };
226 + }, []);
227 +
228 + useEffect(() => {
229 + const pendingCompletions = gate.current;
230 + if (!pendingCompletions) return;
231 if (threads === null) {
232 + pendingCompletions.clear();
233 previous.current.clear();
234 return;
235 }
236 const next = new Map<ThreadId, NotificationState>();
237 const subagentRequests = pendingSubagentRequestsByThread(threads);
238 + const changed: Array<[NotificationState | undefined, NotificationState]> = [];
239 for (const rawThread of threads) {
240 if (rawThread.lineage.relationshipToParent === "subagent") continue;
241 const prior = previous.current.get(rawThread.id);
@@ -147,115 +256,28 @@ function EnvironmentNotifications({
256 ? `${thread.latestRun?.runId ?? ""}:${status}`
257 : null;
258 const completedAt = Date.parse(thread.latestRun?.completedAt ?? "");
150 - const completion =
151 - status === "ready" &&
152 - thread.latestRun?.status === "completed" &&
153 - Number.isFinite(completedAt)
154 - ? completedAt
155 - : (prior?.completion ?? null);
156 - next.set(thread.id, { raw: rawThread, subagentRequest, attention, completion });
157 - if (!prior || thread.archivedAt !== null) continue;
158 - const kind =
159 - attention && attention !== prior.attention
160 - ? "input"
161 - : !rawThread.latestRunStopRequested &&
162 - !rawThread.latestRunSilent &&
163 - completion !== null &&
164 - (prior.completion === null || completion > prior.completion)
165 - ? "completion"
166 - : null;
167 - if (!kind) continue;
168 - const title =
169 - kind === "completion"
170 - ? "Thread completed"
171 - : status === "approval"
172 - ? "Approval needed"
173 - : status === "limited"
174 - ? "Usage limit reached"
175 - : status === "failed"
176 - ? "Thread failed"
177 - : status === "request"
178 - ? "Guest request"
179 - : "Input needed";
180 - if (hasNotificationSound(mode)) {
181 - void playNotificationSound(kind, () =>
182 - hasNotificationSound(getClientSettings().notificationMode),
183 - );
184 - }
185 - if (
186 - inAppNotificationsEnabled &&
187 - document.visibilityState === "visible" &&
188 - document.hasFocus() &&
189 - (activeEnvironmentId !== environmentId || activeThreadId !== thread.id)
190 - ) {
191 - const toastId = toastManager.add({
192 - type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
193 - title,
194 - description: thread.title,
195 - data: {
196 - hideCopyButton: true,
197 - leadingIcon:
198 - kind === "completion" ? (
199 - <CircleCheckIcon aria-hidden className="size-4 text-success-foreground" />
200 - ) : status === "approval" ? (
201 - <ShieldQuestionIcon aria-hidden className="size-4 text-warning-foreground" />
202 - ) : status === "failed" ? (
203 - <CircleAlertIcon aria-hidden className="size-4 text-destructive-foreground" />
204 - ) : (
205 - <MessageCircleQuestionIcon aria-hidden className="size-4 text-info-foreground" />
206 - ),
207 - },
208 - actionProps: {
209 - children: "Open thread",
210 - onClick: () => {
211 - toastManager.close(toastId);
212 - void navigate({
213 - to: "/$environmentId/$threadId",
214 - params: { environmentId, threadId: thread.id },
215 - });
216 - },
217 - },
218 - });
219 - continue;
220 - }
221 - if (
222 - !hasDesktopNotifications(mode) ||
223 - (document.visibilityState === "visible" && document.hasFocus()) ||
224 - typeof Notification === "undefined" ||
225 - Notification.permission !== "granted"
226 - )
227 - continue;
228 - try {
229 - const notification = new Notification(title, {
230 - body: thread.title,
231 - tag: threadNotificationTag(environmentId, thread.id),
232 - silent: true,
233 - });
234 - onNotification(environmentId, notification);
235 - notification.addEventListener("click", () => {
236 - notification.close();
237 - window.focus();
238 - void window.desktopBridge?.revealWindow?.().catch(() => undefined);
239 - void navigate({
240 - to: "/$environmentId/$threadId",
241 - params: { environmentId, threadId: thread.id },
242 - });
243 - });
244 - } catch {
245 - // Some browsers expose Notification but reject desktop presentation.
246 - }
259 + const settled = status === "ready" && thread.latestRun?.status === "completed";
260 + const state = {
261 + raw: rawThread,
262 + subagentRequest,
263 + thread,
264 + status,
265 + attention,
266 + settled,
267 + completedAt: settled && Number.isFinite(completedAt) ? completedAt : null,
268 + };
269 + next.set(thread.id, state);
270 + changed.push([prior, state]);
271 }
272 previous.current = next;
249 - }, [
250 - activeEnvironmentId,
251 - activeThreadId,
252 - environmentId,
253 - inAppNotificationsEnabled,
254 - mode,
255 - navigate,
256 - onNotification,
257 - threads,
258 - ]);
273 + pendingCompletions.retain(new Set(next.keys()));
274 + for (const [prior, state] of changed) {
275 + pendingCompletions.observe(state.thread.id, prior, state, {
276 + archived: state.thread.archivedAt !== null,
277 + quiet: state.raw.latestRunStopRequested === true || state.raw.latestRunSilent === true,
278 + });
279 + }
280 + }, [environmentId, threads]);
281
282 return null;
283 }
packages/client-runtime/src/state/threadInbox.test.ts
+180 -8
@@ -1,7 +1,12 @@
1 import { EnvironmentId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";
2 -import { describe, expect, it } from "vite-plus/test";
2 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3
4 -import { createInboxReturnTracker, sortWorkingThreadsBySend } from "./threadInbox.ts";
4 +import {
5 + createInboxReturnTracker,
6 + isThreadWorking,
7 + sortInboxThreadsByReturn,
8 + sortWorkingThreadsBySend,
9 +} from "./threadInbox.ts";
10
11 const environmentId = EnvironmentId.make("environment-1");
12
@@ -30,18 +35,185 @@ function thread(id: string, working: boolean) {
35 }
36
37 describe("createInboxReturnTracker", () => {
38 + beforeEach(() => {
39 + vi.useFakeTimers();
40 + vi.setSystemTime(10_000);
41 + });
42 + afterEach(() => {
43 + vi.clearAllTimers();
44 + vi.useRealTimers();
45 + });
46 it("stamps a thread when it stops working, but never on the first observation", () => {
47 const tracker = createInboxReturnTracker();
48 const first = tracker.observe([thread("a", true), thread("b", false)]);
36 - expect(first(thread("a", true))).toBeUndefined();
37 - expect(first(thread("b", false))).toBeUndefined();
49 + expect(first.returnedAt(thread("a", true))).toBeUndefined();
50 + expect(first.returnedAt(thread("b", false))).toBeUndefined();
51
52 + const held = tracker.observe([thread("a", false), thread("b", false)]);
53 + vi.advanceTimersByTime(2_000);
54 const second = tracker.observe([thread("a", false), thread("b", false)]);
40 - expect(second(thread("a", false))).toBeDefined();
41 - expect(second(thread("b", false))).toBeUndefined();
42 - expect(tracker.returnedAt(thread("a", false))).toBe(second(thread("a", false)));
55 + expect(second.returnedAt(thread("a", false))).toBeDefined();
56 + expect(second.returnedAt(thread("b", false))).toBeUndefined();
57 + expect(tracker.returnedAt(thread("a", false))).toBe(second.returnedAt(thread("a", false)));
58 // An earlier observation keeps its answer, so lists built from it stay valid.
44 - expect(first(thread("a", false))).toBeUndefined();
59 + expect(held.isWorking(thread("a", false))).toBe(true);
60 + expect(held.returnedAt(thread("a", false))).toBeUndefined();
61 + });
62 +
63 + it("holds only placement, then expires and notifies without another shell event", () => {
64 + const tracker = createInboxReturnTracker();
65 + const notify = vi.fn();
66 + const unsubscribe = tracker.subscribe(notify);
67 + tracker.observe([thread("a", true)]);
68 + tracker.observe([thread("a", false)]);
69 + expect(isThreadWorking(thread("a", false))).toBe(false);
70 + expect(tracker.isWorking(thread("a", false))).toBe(true);
71 + vi.advanceTimersByTime(1_999);
72 + tracker.observe([thread("a", false)]);
73 + expect(tracker.isWorking(thread("a", false))).toBe(true);
74 + expect(tracker.returnedAt(thread("a", false))).toBeUndefined();
75 + vi.advanceTimersByTime(1);
76 + expect(tracker.isWorking(thread("a", false))).toBe(false);
77 + expect(tracker.returnedAt(thread("a", false))).toBe(12_000);
78 + expect(notify).toHaveBeenCalledTimes(1);
79 + unsubscribe();
80 + });
81 +
82 + it("cancels a transient return on resume and grants a fresh grace after the next finish", () => {
83 + const tracker = createInboxReturnTracker();
84 + tracker.observe([thread("a", false)]);
85 + expect(tracker.isWorking(thread("a", false))).toBe(false);
86 + tracker.observe([thread("a", true)]);
87 + expect(tracker.isWorking(thread("a", true))).toBe(true);
88 + tracker.observe([thread("a", false)]);
89 + vi.advanceTimersByTime(1_500);
90 + tracker.observe([thread("a", true)]);
91 + vi.advanceTimersByTime(1_000);
92 + expect(tracker.returnedAt(thread("a", true))).toBeUndefined();
93 + tracker.observe([thread("a", false)]);
94 + vi.advanceTimersByTime(1_999);
95 + expect(tracker.isWorking(thread("a", false))).toBe(true);
96 + vi.advanceTimersByTime(1);
97 + expect(tracker.returnedAt(thread("a", false))).toBe(14_500);
98 + });
99 +
100 + it.each([
101 + { hasPendingApprovals: true },
102 + { hasPendingUserInput: true },
103 + { pendingSubagentRequest: "approval" as const },
104 + { pendingSubagentRequest: "user_input" as const },
105 + { pendingGuestMessageCount: 1 },
106 + { interactionMode: "plan" as const, hasActionableProposedPlan: true },
107 + { runtime: { ...thread("a", true).runtime!, status: "failed" as const, lastError: "failed" } },
108 + { pinnedAt: "2026-06-01T00:00:01Z" },
109 + { settledOverride: "settled" as const },
110 + { snoozedUntil: "2026-06-02T00:00:00Z" },
111 + { activeOrderKey: "manual-order" },
112 + ])("ends a grace immediately for attention or manual placement: %j", (change) => {
113 + const tracker = createInboxReturnTracker();
114 + tracker.observe([thread("a", true)]);
115 + tracker.observe([thread("a", false)]);
116 + tracker.observe([{ ...thread("a", false), ...change }]);
117 + expect(tracker.isWorking(thread("a", false))).toBe(false);
118 + expect(tracker.returnedAt(thread("a", false))).toBe(10_000);
119 + expect(vi.getTimerCount()).toBe(0);
120 + });
121 +
122 + it.each(["interrupted", "cancelled", "rolled_back"] as const)(
123 + "holds a %s run, because the server can still settle it",
124 + (status) => {
125 + const tracker = createInboxReturnTracker();
126 + const stopped = {
127 + ...thread("a", false),
128 + latestRun: {
129 + runId: RunId.make("stopped"),
130 + status,
131 + requestedAt: null,
132 + startedAt: null,
133 + completedAt: null,
134 + assistantMessageId: null,
135 + },
136 + };
137 + tracker.observe([thread("a", true)]);
138 + tracker.observe([stopped]);
139 + expect(tracker.isWorking(stopped)).toBe(true);
140 + tracker.observe([{ ...stopped, settledOverride: "settled" as const }]);
141 + expect(tracker.isWorking(stopped)).toBe(false);
142 + },
143 + );
144 +
145 + it("grants grace after a retained expired snooze", () => {
146 + const tracker = createInboxReturnTracker();
147 + const retained = {
148 + snoozedAt: "1970-01-01T00:00:01.000Z",
149 + snoozedUntil: "1970-01-01T00:00:05.000Z",
150 + latestRun: {
151 + runId: RunId.make("completed-wake"),
152 + status: "completed" as const,
153 + requestedAt: "1970-01-01T00:00:02.000Z",
154 + startedAt: "1970-01-01T00:00:02.000Z",
155 + completedAt: "1970-01-01T00:00:09.000Z",
156 + assistantMessageId: null,
157 + },
158 + };
159 + const active = { ...thread("a", true), ...retained };
160 + const finished = { ...thread("a", false), ...retained };
161 + tracker.observe([active]);
162 + tracker.observe([finished]);
163 + expect(tracker.isWorking(finished)).toBe(true);
164 + expect(tracker.returnedAt(finished)).toBeUndefined();
165 + vi.advanceTimersByTime(1_999);
166 + expect(tracker.isWorking(finished)).toBe(true);
167 + vi.advanceTimersByTime(1);
168 + expect(tracker.isWorking(finished)).toBe(false);
169 + expect(tracker.returnedAt(finished)).toBe(12_000);
170 + });
171 +
172 + it("does not grant grace to a future snooze after background completion", () => {
173 + const tracker = createInboxReturnTracker();
174 + const retained = {
175 + snoozedAt: "1970-01-01T00:00:01.000Z",
176 + snoozedUntil: "1970-01-01T00:00:30.000Z",
177 + };
178 + tracker.observe([{ ...thread("a", true), ...retained }]);
179 + const finished = { ...thread("a", false), ...retained };
180 + tracker.observe([finished]);
181 + expect(tracker.isWorking(finished)).toBe(false);
182 + expect(vi.getTimerCount()).toBe(0);
183 + });
184 +
185 + it("stamps only stable returns and sorts them in their actual return order", () => {
186 + const tracker = createInboxReturnTracker();
187 + const a = { ...thread("a", false), createdAt: "1970-01-01T00:00:00Z" };
188 + const b = { ...thread("b", false), createdAt: "1970-01-01T00:00:00Z" };
189 + tracker.observe([thread("a", true), thread("b", true)]);
190 + tracker.observe([a, thread("b", true)]);
191 + vi.advanceTimersByTime(500);
192 + tracker.observe([a, b]);
193 + vi.advanceTimersByTime(1_500);
194 + expect(tracker.returnedAt(a)).toBe(12_000);
195 + expect(tracker.returnedAt(b)).toBeUndefined();
196 + vi.advanceTimersByTime(500);
197 + expect(sortInboxThreadsByReturn([a, b], tracker.returnedAt).map((entry) => entry.id)).toEqual([
198 + "b",
199 + "a",
200 + ]);
201 + });
202 +
203 + it("cancels pending timers for removed threads and disabled shelves", () => {
204 + const tracker = createInboxReturnTracker();
205 + const notify = vi.fn();
206 + tracker.subscribe(notify);
207 + tracker.observe([thread("a", true)]);
208 + tracker.observe([thread("a", false)]);
209 + tracker.observe([]);
210 + expect(vi.getTimerCount()).toBe(0);
211 + tracker.observe([thread("a", true)]);
212 + tracker.observe([thread("a", false)]);
213 + tracker.observe(null);
214 + vi.advanceTimersByTime(2_000);
215 + expect(notify).not.toHaveBeenCalled();
216 + expect(tracker.returnedAt(thread("a", false))).toBeUndefined();
217 });
218 });
219
packages/client-runtime/src/state/threadInbox.ts
+136 -26
@@ -1,5 +1,7 @@
1 +// @effect-diagnostics globalTimers:off - Shelf placement timers run in web and native clients, outside an Effect runtime.
2 import { threadRuntimeIsActive, type EnvironmentThreadShell } from "./models.ts";
3 import { toSortableTimestamp } from "./threadSort.ts";
4 +import { effectiveSnoozed } from "./threadSettled.ts";
5
6 type WorkingThreadInput = Pick<
7 EnvironmentThreadShell,
@@ -86,46 +88,154 @@ function sortNewestFirst<T extends Pick<EnvironmentThreadShell, "id" | "environm
88 );
89 }
90
91 +type TrackedInboxThread = WorkingThreadInput &
92 + InboxThreadInput &
93 + Partial<
94 + Pick<
95 + EnvironmentThreadShell,
96 + | "archivedAt"
97 + | "deletedAt"
98 + | "pinnedAt"
99 + | "settledOverride"
100 + | "settledAt"
101 + | "snoozedAt"
102 + | "snoozedUntil"
103 + | "activeOrderKey"
104 + | "pendingGuestMessageCount"
105 + >
106 + >;
107 +
108 +type ThreadKeyInput = Pick<EnvironmentThreadShell, "environmentId" | "id">;
109 +
110 +/**
111 + * How long a thread that stopped working keeps reading as working. An orchestrator
112 + * run can end moments before its continuation starts, so clients wait this long
113 + * before treating the thread as done.
114 + */
115 +export const WORKING_EXIT_GRACE_MS = 2_000;
116 +
117 /**
90 - * Keep one at module scope so the inbox order survives routes that unmount the
91 - * list. Call `observe` with every thread shell whenever the shells change, or
92 - * with null to reset while the beta is off. It returns the return times as of
93 - * that observation, which stay fixed so a list built from them can be cached.
118 + * Keep one at module scope so placement survives routes that unmount the list. Call
119 + * `observe` when the shells or the snapshot version change, or with null while the beta
120 + * is off. Its result stays fixed, so a list built from it can be cached.
121 */
122 export function createInboxReturnTracker() {
96 - const keyOf = (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
97 - `${thread.environmentId}:${thread.id}`;
98 - let lastWorkingKeys: ReadonlySet<string> | null = null;
123 + const keyOf = (thread: ThreadKeyInput) => `${thread.environmentId}:${thread.id}`;
124 + const states = new Map<
125 + string,
126 + { working: boolean; deadline: number | null; placement: string }
127 + >();
128 const returns = new Map<string, number>();
129 + const listeners = new Set<() => void>();
130 + let timer: ReturnType<typeof setTimeout> | undefined;
131 + let version = 0;
132 + const now = () => {
133 + // @effect-diagnostics-next-line globalDate:off - The grace deadline is wall-clock time shared by web and native clients.
134 + return Date.now();
135 + };
136 + const schedule = () => {
137 + clearTimeout(timer);
138 + timer = undefined;
139 + let next = Infinity;
140 + for (const state of states.values()) {
141 + if (state.deadline !== null) next = Math.min(next, state.deadline);
142 + }
143 + if (next === Infinity) return;
144 + timer = setTimeout(
145 + () => {
146 + const at = now();
147 + for (const [key, state] of states) {
148 + if (state.deadline !== null && state.deadline <= at) {
149 + state.working = false;
150 + state.deadline = null;
151 + returns.set(key, at);
152 + }
153 + }
154 + schedule();
155 + version++;
156 + for (const listener of listeners) listener();
157 + },
158 + Math.max(0, next - now()),
159 + );
160 + };
161 return {
101 - observe(
102 - threads: ReadonlyArray<WorkingThreadInput & InboxThreadInput> | null,
103 - ): (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) => number | undefined {
162 + subscribe(listener: () => void) {
163 + listeners.add(listener);
164 + return () => {
165 + listeners.delete(listener);
166 + };
167 + },
168 + getSnapshot: () => version,
169 + observe(threads: readonly TrackedInboxThread[] | null): {
170 + readonly isWorking: (thread: WorkingThreadInput & ThreadKeyInput) => boolean;
171 + readonly returnedAt: (thread: ThreadKeyInput) => number | undefined;
172 + } {
173 if (threads === null) {
105 - lastWorkingKeys = null;
174 + clearTimeout(timer);
175 + timer = undefined;
176 + states.clear();
177 returns.clear();
107 - return () => undefined;
178 + return { isWorking: isThreadWorking, returnedAt: () => undefined };
179 }
109 - const working = new Set<string>();
180 const present = new Set<string>();
181 + const at = now();
182 + // @effect-diagnostics-next-line globalDate:off - Snooze checks compare wall-clock ISO times.
183 + const observedAt = new Date(at).toISOString();
184 for (const thread of threads) {
185 const key = keyOf(thread);
186 present.add(key);
114 - if (isThreadWorking(thread)) working.add(key);
115 - }
116 - for (const key of returns.keys()) {
117 - if (!present.has(key)) returns.delete(key);
187 + const placement = JSON.stringify([
188 + thread.archivedAt,
189 + thread.deletedAt,
190 + thread.pinnedAt,
191 + thread.settledOverride,
192 + thread.settledAt,
193 + thread.snoozedAt,
194 + thread.snoozedUntil,
195 + thread.activeOrderKey,
196 + ]);
197 + const previous = states.get(key);
198 + const actionable =
199 + thread.hasPendingApprovals ||
200 + thread.hasPendingUserInput ||
201 + thread.pendingSubagentRequest != null ||
202 + (thread.pendingGuestMessageCount ?? 0) > 0 ||
203 + (thread.interactionMode === "plan" && thread.hasActionableProposedPlan) ||
204 + thread.runtime?.lastError != null ||
205 + thread.latestRun?.status === "failed";
206 + const moved = previous !== undefined && previous.placement !== placement;
207 + const excluded =
208 + thread.archivedAt != null ||
209 + thread.deletedAt != null ||
210 + thread.pinnedAt != null ||
211 + thread.settledOverride === "settled" ||
212 + effectiveSnoozed(thread, { now: observedAt });
213 + const actual = isThreadWorking(thread);
214 + // Only shelf placement is held: execution state and attention requests stay authoritative.
215 + const deadline =
216 + !actual && previous?.working && !actionable && !moved && !excluded
217 + ? (previous.deadline ?? at + WORKING_EXIT_GRACE_MS)
218 + : null;
219 + const working = actual || (deadline !== null && deadline > at);
220 + if (previous?.working && !working) returns.set(key, at);
221 + states.set(key, { working, deadline: working ? deadline : null, placement });
222 }
119 - // @effect-diagnostics-next-line globalDate:off
120 - const at = Date.now();
121 - for (const key of lastWorkingKeys ?? []) {
122 - if (present.has(key) && !working.has(key)) returns.set(key, at);
223 + for (const key of states.keys()) {
224 + if (!present.has(key)) {
225 + states.delete(key);
226 + returns.delete(key);
227 + }
228 }
124 - lastWorkingKeys = working;
125 - const observed = new Map(returns);
126 - return (thread) => observed.get(keyOf(thread));
229 + schedule();
230 + const observedWorking = new Map([...states].map(([key, state]) => [key, state.working]));
231 + const observedReturns = new Map(returns);
232 + return {
233 + isWorking: (thread) => observedWorking.get(keyOf(thread)) ?? isThreadWorking(thread),
234 + returnedAt: (thread) => observedReturns.get(keyOf(thread)),
235 + };
236 },
128 - returnedAt: (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
129 - returns.get(keyOf(thread)),
237 + isWorking: (thread: WorkingThreadInput & ThreadKeyInput) =>
238 + states.get(keyOf(thread))?.working ?? isThreadWorking(thread),
239 + returnedAt: (thread: ThreadKeyInput) => returns.get(keyOf(thread)),
240 };
241 }