The best way to control Claude Code, Codex and more from any computer or phone
perf(web): saving the thread list cache no longer re-encodes every thread (#19915)
Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Aaron Queen committed
Oct 15, 2026 at 21:04 UTC
e2b929f10a4c7436b9f0a5a517aec61ae94394f1
6 files changed
+388
-268
apps/mobile/src/connection/environment-cache-store.test.ts
-261
@@ -1,7 +1,6 @@
1
import {
2
ORCHESTRATION_CACHE_SCHEMA_VERSION,
3
ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
4
- StoredOrchestrationShellSnapshot,
4
} from "@t3tools/client-runtime/platform";
5
import {
6
CommandId,
@@ -17,16 +16,11 @@ import {
16
import { describe, expect, it } from "@effect/vitest";
17
import * as DateTime from "effect/DateTime";
18
import * as Effect from "effect/Effect";
20
-import * as Fiber from "effect/Fiber";
19
import * as Logger from "effect/Logger";
22
-import * as Schema from "effect/Schema";
23
-import { vi } from "vite-plus/test";
24
-import * as Deferred from "effect/Deferred";
20
import * as Option from "effect/Option";
21
22
import * as MobileDatabase from "../persistence/mobile-database";
23
import { make } from "./environment-cache-store";
29
-import { makeStoredShellSnapshotEncoder } from "./shell-cache-encoding";
24
25
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
26
const PROJECT_ID = ProjectId.make("project-1");
@@ -408,258 +402,3 @@ describe("mobile SQLite environment cache store", () => {
402
}),
403
);
404
});
411
-
412
-describe("cooperative shell cache encoding", () => {
413
- // A fresh encoder per call keeps these cases cold; the cache has its own cases below.
414
- const encodeStoredShellSnapshot = (stored: typeof StoredOrchestrationShellSnapshot.Type) =>
415
- makeStoredShellSnapshotEncoder()(stored);
416
- const encodeOriginal = Schema.encodeEffect(
417
- Schema.fromJsonString(StoredOrchestrationShellSnapshot),
418
- );
419
- const stored = {
420
- schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
421
- environmentId: ENVIRONMENT_ID,
422
- snapshot: {
423
- ...SHELL_SNAPSHOT,
424
- projects: SHELL_SNAPSHOT.projects.map((project) => ({
425
- ...project,
426
- title: " Project ",
427
- unexpected: "drop this field",
428
- })),
429
- threads: Array.from({ length: 64 }, (_, index) => ({
430
- ...SHELL_SNAPSHOT.threads[0]!,
431
- id: ThreadId.make(`thread-${index}`),
432
- branch: " main ",
433
- activityRunStartedAt: index % 2 === 0 ? NOW : null,
434
- unsettledAt: index % 2 === 0 ? NOW : null,
435
- modelSelection: {
436
- instanceId: PROVIDER_INSTANCE_ID,
437
- model: " gpt-5.4 ",
438
- unexpected: "drop this field",
439
- },
440
- unexpected: "drop this field",
441
- })),
442
- archivedThreads: [{ ...SHELL_SNAPSHOT.threads[0]!, archivedAt: NOW }],
443
- unexpected: "drop this field",
444
- },
445
- unexpected: "drop this field",
446
- };
447
-
448
- it.effect("preserves exact JSON, transforms, nulls, dates, and unknown-field stripping", () =>
449
- Effect.gen(function* () {
450
- const expected = yield* encodeOriginal(stored);
451
- const actual = yield* encodeStoredShellSnapshot(stored);
452
- expect(actual).toBe(expected);
453
- const parsed = JSON.parse(actual);
454
- expect(parsed).not.toHaveProperty("unexpected");
455
- expect(parsed.snapshot).not.toHaveProperty("unexpected");
456
- expect(parsed.snapshot.projects[0]).not.toHaveProperty("unexpected");
457
- expect(parsed.snapshot.projects[0].title).toBe("Project");
458
- expect(parsed.snapshot.threads[0]).not.toHaveProperty("unexpected");
459
- expect(parsed.snapshot.threads[0].branch).toBe("main");
460
- expect(parsed.snapshot.threads[0].modelSelection).toEqual({
461
- instanceId: "codex",
462
- model: "gpt-5.4",
463
- });
464
- expect(parsed.snapshot.threads[0].activityRunStartedAt).toBe(DateTime.formatIso(NOW));
465
- expect(parsed.snapshot.threads[1].activityRunStartedAt).toBeNull();
466
- expect(parsed.snapshot.archivedThreads[0].archivedAt).toBe(DateTime.formatIso(NOW));
467
- }),
468
- );
469
-
470
- it.effect("preserves optional fields and dates across chunk boundaries and archived rows", () =>
471
- Effect.gen(function* () {
472
- const base = SHELL_SNAPSHOT.threads[0]!;
473
- const { titleRegeneration: _, unsettledAt: __, ...withoutOptional } = base;
474
- const row = (index: number) =>
475
- index % 3 === 0
476
- ? { ...withoutOptional, id: ThreadId.make(`row-${index}`) }
477
- : {
478
- ...base,
479
- id: ThreadId.make(`row-${index}`),
480
- snoozedUntil: DateTime.add(NOW, { minutes: index }),
481
- pinnedAt: index % 2 === 0 ? null : NOW,
482
- };
483
- const mixed = {
484
- ...stored,
485
- snapshot: {
486
- ...stored.snapshot,
487
- threads: Array.from({ length: 65 }, (_, index) => row(index)),
488
- archivedThreads: Array.from({ length: 33 }, (_, index) => ({
489
- ...row(index + 100),
490
- archivedAt: DateTime.add(NOW, { hours: index }),
491
- })),
492
- },
493
- };
494
- const actual = yield* encodeStoredShellSnapshot(mixed);
495
- expect(actual).toBe(yield* encodeOriginal(mixed));
496
- const parsed = JSON.parse(actual);
497
- expect(parsed.snapshot.threads).toHaveLength(65);
498
- expect(parsed.snapshot.threads[63]).not.toHaveProperty("titleRegeneration");
499
- expect(parsed.snapshot.threads[63]).not.toHaveProperty("unsettledAt");
500
- expect(parsed.snapshot.threads[64].snoozedUntil).toBe(
501
- DateTime.formatIso(DateTime.add(NOW, { minutes: 64 })),
502
- );
503
- expect(parsed.snapshot.archivedThreads).toHaveLength(33);
504
- expect(parsed.snapshot.archivedThreads[32].archivedAt).toBe(
505
- DateTime.formatIso(DateTime.add(NOW, { hours: 32 })),
506
- );
507
- }),
508
- );
509
-
510
- it.effect("yields to a host timer between every 32-row chunk", () =>
511
- Effect.gen(function* () {
512
- const setTimer = vi.spyOn(globalThis, "setTimeout");
513
- try {
514
- yield* encodeStoredShellSnapshot({
515
- ...stored,
516
- snapshot: {
517
- ...stored.snapshot,
518
- threads: Array.from({ length: 65 }, () => ({ ...stored.snapshot.threads[0]! })),
519
- archivedThreads: Array.from({ length: 33 }, () => ({
520
- ...stored.snapshot.archivedThreads[0]!,
521
- })),
522
- },
523
- });
524
- // Five row chunks (3 active + 2 archived): four yields between them, one before the envelope.
525
- expect(setTimer).toHaveBeenCalledTimes(5);
526
- } finally {
527
- vi.restoreAllMocks();
528
- }
529
- }),
530
- );
531
-
532
- it.effect("still rejects invalid active and archived rows after an encoding chunk yields", () =>
533
- Effect.gen(function* () {
534
- const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
535
- const invalidActive = {
536
- ...stored,
537
- snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
538
- };
539
- const invalidArchived = {
540
- ...stored,
541
- snapshot: { ...stored.snapshot, archivedThreads: [invalidRow] },
542
- };
543
- const invalidEnvelope = { ...stored, snapshot: { ...stored.snapshot, snapshotSequence: -1 } };
544
- expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidActive))).toBe(true);
545
- expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidArchived))).toBe(true);
546
- expect(yield* Effect.isFailure(encodeOriginal(invalidEnvelope))).toBe(true);
547
- expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidEnvelope))).toBe(true);
548
- }),
549
- );
550
-
551
- it.effect("keeps concurrent saves independent", () =>
552
- Effect.gen(function* () {
553
- const other = {
554
- ...stored,
555
- environmentId: EnvironmentId.make("environment-2"),
556
- snapshot: {
557
- ...stored.snapshot,
558
- threads: stored.snapshot.threads.slice(0, 40).map((thread) => ({
559
- ...thread,
560
- title: `Other ${thread.id}`,
561
- })),
562
- archivedThreads: [],
563
- },
564
- };
565
- const [first, second] = yield* Effect.all(
566
- [encodeStoredShellSnapshot(stored), encodeStoredShellSnapshot(other)],
567
- { concurrency: "unbounded" },
568
- );
569
- expect(first).toBe(yield* encodeOriginal(stored));
570
- expect(second).toBe(yield* encodeOriginal(other));
571
- }),
572
- );
573
-
574
- it.effect("cancels the pending host timer when encoding is interrupted", () =>
575
- Effect.gen(function* () {
576
- vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
577
- const fakeSetTimeout = globalThis.setTimeout;
578
- const scheduled = yield* Deferred.make<ReturnType<typeof setTimeout>>();
579
- vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
580
- const timer = fakeSetTimeout(...args);
581
- Deferred.doneUnsafe(scheduled, Effect.succeed(timer));
582
- return timer;
583
- });
584
- const clearTimer = vi.spyOn(globalThis, "clearTimeout");
585
- const fiber = yield* Effect.forkScoped(
586
- Effect.suspend(() => encodeStoredShellSnapshot(stored)),
587
- );
588
- try {
589
- const pendingTimer = yield* Deferred.await(scheduled);
590
- expect(vi.getTimerCount()).toBe(1);
591
- yield* Fiber.interrupt(fiber);
592
- expect(clearTimer).toHaveBeenCalledWith(pendingTimer);
593
- expect(vi.getTimerCount()).toBe(0);
594
- } finally {
595
- yield* Fiber.interrupt(fiber);
596
- vi.restoreAllMocks();
597
- vi.useRealTimers();
598
- }
599
- }),
600
- );
601
-
602
- it.effect("reuses encoded rows across saves without changing the payload", () =>
603
- Effect.gen(function* () {
604
- const encode = makeStoredShellSnapshotEncoder();
605
- expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
606
-
607
- const setTimer = vi.spyOn(globalThis, "setTimeout");
608
- try {
609
- // Same row references, new envelope: no row work, so no host yields.
610
- const resaved = {
611
- ...stored,
612
- snapshot: { ...stored.snapshot, snapshotSequence: 4 },
613
- };
614
- expect(yield* encode(resaved)).toBe(yield* encodeOriginal(resaved));
615
- expect(setTimer).not.toHaveBeenCalled();
616
- } finally {
617
- vi.restoreAllMocks();
618
- }
619
- }),
620
- );
621
-
622
- it.effect("encodes replaced, added, and moved-to-archive rows on a warm encoder", () =>
623
- Effect.gen(function* () {
624
- const encode = makeStoredShellSnapshotEncoder();
625
- yield* encode(stored);
626
- const [first, second, ...rest] = stored.snapshot.threads;
627
- const next = {
628
- ...stored,
629
- snapshot: {
630
- ...stored.snapshot,
631
- threads: [
632
- { ...first!, title: "Renamed", itemCount: 9 },
633
- ...rest,
634
- { ...first!, id: ThreadId.make("thread-new"), branch: " feature " },
635
- ],
636
- archivedThreads: [
637
- ...stored.snapshot.archivedThreads,
638
- { ...second!, archivedAt: DateTime.add(NOW, { hours: 1 }) },
639
- ],
640
- },
641
- };
642
- const actual = yield* encode(next);
643
- expect(actual).toBe(yield* encodeOriginal(next));
644
- const parsed = JSON.parse(actual);
645
- expect(parsed.snapshot.threads[0].title).toBe("Renamed");
646
- expect(parsed.snapshot.threads.at(-1).branch).toBe("feature");
647
- expect(parsed.snapshot.archivedThreads).toHaveLength(2);
648
- }),
649
- );
650
-
651
- it.effect("does not cache rows from a failed encode", () =>
652
- Effect.gen(function* () {
653
- const encode = makeStoredShellSnapshotEncoder();
654
- const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
655
- const invalid = {
656
- ...stored,
657
- snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
658
- };
659
- expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
660
- expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
661
- // Valid rows from the failed save still encode correctly afterwards.
662
- expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
663
- }),
664
- );
665
-});
apps/mobile/src/connection/environment-cache-store.ts
+1
-1
@@ -3,6 +3,7 @@ import {
3
ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
4
StoredOrchestrationThreadSnapshot,
5
Persistence,
6
+ makeStoredShellSnapshotEncoder,
7
} from "@t3tools/client-runtime/platform";
8
import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
9
import * as Effect from "effect/Effect";
@@ -11,7 +12,6 @@ import * as Option from "effect/Option";
12
import * as Schema from "effect/Schema";
13
14
import * as MobileDatabase from "../persistence/mobile-database";
14
-import { makeStoredShellSnapshotEncoder } from "./shell-cache-encoding";
15
import {
16
attachProjectFaviconDatabase,
17
projectFaviconDatabaseCache,
apps/web/src/connection/storage.ts
+24
-1
@@ -15,6 +15,7 @@ import {
15
setRoutesInCatalog,
16
replaceCatalogValue,
17
Persistence,
18
+ makeStoredShellSnapshotEncoder,
19
} from "@t3tools/client-runtime/platform";
20
import { TokenStore } from "@t3tools/client-runtime/authorization";
21
import {
@@ -68,7 +69,6 @@ const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDoc
69
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
70
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
71
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshotJson);
71
-const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshotJson);
72
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshotJson);
73
const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson);
74
const decodeStoredServerConfig = Schema.decodeUnknownEffect(StoredServerConfigJson);
@@ -601,6 +601,25 @@ export function makeBrowserGitHubRoutingPermissions(
601
});
602
}
603
604
+// A posted message resumes in a fresh task, so input and rendering get a turn between
605
+// encoding chunks. A zero-delay timer would not do: browsers clamp nested timers to
606
+// 4 ms and throttle them to once a second or less in a background tab.
607
+const yieldToBrowserTask = Effect.callback<void>((resume) => {
608
+ const { port1, port2 } = new MessageChannel();
609
+ port1.addEventListener(
610
+ "message",
611
+ () => {
612
+ port1.close();
613
+ resume(Effect.void);
614
+ },
615
+ { once: true },
616
+ );
617
+ port1.start();
618
+ port2.postMessage(null);
619
+ // A closed port delivers nothing, so interruption needs no listener bookkeeping.
620
+ return Effect.sync(() => port1.close());
621
+});
622
+
623
export const layer = Layer.effectContext(
624
Effect.gen(function* () {
625
const { handle: database } = yield* Effect.acquireRelease(
@@ -609,6 +628,10 @@ export const layer = Layer.effectContext(
628
);
629
const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
630
const githubRoutingPermissions = makeBrowserGitHubRoutingPermissions();
631
+ // Remembers each thread row's encoding, so a save only encodes rows that changed.
632
+ const encodeStoredShellSnapshot = makeStoredShellSnapshotEncoder({
633
+ yieldToHost: yieldToBrowserTask,
634
+ });
635
636
const targetStore = Persistence.ConnectionTargetStore.of({
637
list: catalog.read.pipe(
packages/client-runtime/src/platform/index.ts
+1
@@ -3,5 +3,6 @@ export * as Persistence from "./persistence.ts";
3
// Flat so consumers' inferred types can name it.
4
export { ConnectionPersistenceError } from "./persistence.ts";
5
export * from "./orchestrationCache.ts";
6
+export * from "./shellCacheEncoding.ts";
7
export * as PlatformConnectionSource from "./source.ts";
8
export * from "./storageDocument.ts";
packages/client-runtime/src/platform/shellCacheEncoding.test.ts
new
+348
@@ -0,0 +1,348 @@
1
+import {
2
+ CommandId,
3
+ EnvironmentId,
4
+ ProjectId,
5
+ ProviderInstanceId,
6
+ ThreadId,
7
+ type OrchestrationV2ShellSnapshot,
8
+} from "@t3tools/contracts";
9
+import { describe, expect, it } from "@effect/vitest";
10
+import * as DateTime from "effect/DateTime";
11
+import * as Effect from "effect/Effect";
12
+import * as Fiber from "effect/Fiber";
13
+import * as Schema from "effect/Schema";
14
+import { vi } from "vite-plus/test";
15
+import * as Deferred from "effect/Deferred";
16
+
17
+import {
18
+ ORCHESTRATION_CACHE_SCHEMA_VERSION,
19
+ StoredOrchestrationShellSnapshot,
20
+} from "./orchestrationCache.ts";
21
+import { makeStoredShellSnapshotEncoder } from "./shellCacheEncoding.ts";
22
+
23
+const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
24
+const PROJECT_ID = ProjectId.make("project-1");
25
+const THREAD_ID = ThreadId.make("thread-1");
26
+const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
27
+const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
28
+const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
29
+ schemaVersion: 1,
30
+ snapshotSequence: 3,
31
+ projects: [
32
+ {
33
+ id: PROJECT_ID,
34
+ title: "Project",
35
+ workspaceRoot: "/repo",
36
+ repositoryIdentity: null,
37
+ defaultModelSelection: null,
38
+ scripts: [],
39
+ createdAt: "2026-07-29T12:00:00.000Z",
40
+ updatedAt: "2026-07-29T12:00:00.000Z",
41
+ },
42
+ ],
43
+ threads: [
44
+ {
45
+ id: THREAD_ID,
46
+ projectId: PROJECT_ID,
47
+ title: "Thread",
48
+ providerInstanceId: PROVIDER_INSTANCE_ID,
49
+ modelSelection: {
50
+ instanceId: PROVIDER_INSTANCE_ID,
51
+ model: "gpt-5.4",
52
+ },
53
+ runtimeMode: "full-access",
54
+ interactionMode: "default",
55
+ branch: null,
56
+ worktreePath: null,
57
+ activeProviderThreadId: null,
58
+ lineage: {
59
+ rootThreadId: THREAD_ID,
60
+ parentThreadId: null,
61
+ relationshipToParent: null,
62
+ },
63
+ forkedFrom: null,
64
+ createdBy: "user",
65
+ creationSource: "mobile",
66
+ latestRunId: null,
67
+ activeRunId: null,
68
+ status: "idle",
69
+ pendingRuntimeRequest: null,
70
+ latestVisibleMessage: null,
71
+ latestUserMessageAt: NOW,
72
+ activityRunStartedAt: NOW,
73
+ activityRunStatus: "running",
74
+ hasActionableProposedPlan: false,
75
+ itemCount: 0,
76
+ visibleItemCount: 0,
77
+ createdAt: NOW,
78
+ updatedAt: NOW,
79
+ archivedAt: null,
80
+ settledOverride: null,
81
+ settledAt: NOW,
82
+ unsettledAt: NOW,
83
+ lastVisitedAt: null,
84
+ titleRegeneration: {
85
+ requestId: CommandId.make("title-regeneration-1"),
86
+ startedAt: NOW,
87
+ },
88
+ deletedAt: null,
89
+ },
90
+ ],
91
+ archivedThreads: [],
92
+};
93
+
94
+describe("cooperative shell cache encoding", () => {
95
+ // A fresh encoder per call keeps these cases cold; the cache has its own cases below.
96
+ const encodeStoredShellSnapshot = (stored: typeof StoredOrchestrationShellSnapshot.Type) =>
97
+ makeStoredShellSnapshotEncoder()(stored);
98
+ const encodeOriginal = Schema.encodeEffect(
99
+ Schema.fromJsonString(StoredOrchestrationShellSnapshot),
100
+ );
101
+ const stored = {
102
+ schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
103
+ environmentId: ENVIRONMENT_ID,
104
+ snapshot: {
105
+ ...SHELL_SNAPSHOT,
106
+ projects: SHELL_SNAPSHOT.projects.map((project) => ({
107
+ ...project,
108
+ title: " Project ",
109
+ unexpected: "drop this field",
110
+ })),
111
+ threads: Array.from({ length: 64 }, (_, index) => ({
112
+ ...SHELL_SNAPSHOT.threads[0]!,
113
+ id: ThreadId.make(`thread-${index}`),
114
+ branch: " main ",
115
+ activityRunStartedAt: index % 2 === 0 ? NOW : null,
116
+ unsettledAt: index % 2 === 0 ? NOW : null,
117
+ modelSelection: {
118
+ instanceId: PROVIDER_INSTANCE_ID,
119
+ model: " gpt-5.4 ",
120
+ unexpected: "drop this field",
121
+ },
122
+ unexpected: "drop this field",
123
+ })),
124
+ archivedThreads: [{ ...SHELL_SNAPSHOT.threads[0]!, archivedAt: NOW }],
125
+ unexpected: "drop this field",
126
+ },
127
+ unexpected: "drop this field",
128
+ };
129
+
130
+ it.effect("preserves exact JSON, transforms, nulls, dates, and unknown-field stripping", () =>
131
+ Effect.gen(function* () {
132
+ const expected = yield* encodeOriginal(stored);
133
+ const actual = yield* encodeStoredShellSnapshot(stored);
134
+ expect(actual).toBe(expected);
135
+ const parsed = JSON.parse(actual);
136
+ expect(parsed).not.toHaveProperty("unexpected");
137
+ expect(parsed.snapshot).not.toHaveProperty("unexpected");
138
+ expect(parsed.snapshot.projects[0]).not.toHaveProperty("unexpected");
139
+ expect(parsed.snapshot.projects[0].title).toBe("Project");
140
+ expect(parsed.snapshot.threads[0]).not.toHaveProperty("unexpected");
141
+ expect(parsed.snapshot.threads[0].branch).toBe("main");
142
+ expect(parsed.snapshot.threads[0].modelSelection).toEqual({
143
+ instanceId: "codex",
144
+ model: "gpt-5.4",
145
+ });
146
+ expect(parsed.snapshot.threads[0].activityRunStartedAt).toBe(DateTime.formatIso(NOW));
147
+ expect(parsed.snapshot.threads[1].activityRunStartedAt).toBeNull();
148
+ expect(parsed.snapshot.archivedThreads[0].archivedAt).toBe(DateTime.formatIso(NOW));
149
+ }),
150
+ );
151
+
152
+ it.effect("preserves optional fields and dates across chunk boundaries and archived rows", () =>
153
+ Effect.gen(function* () {
154
+ const base = SHELL_SNAPSHOT.threads[0]!;
155
+ const { titleRegeneration: _, unsettledAt: __, ...withoutOptional } = base;
156
+ const row = (index: number) =>
157
+ index % 3 === 0
158
+ ? { ...withoutOptional, id: ThreadId.make(`row-${index}`) }
159
+ : {
160
+ ...base,
161
+ id: ThreadId.make(`row-${index}`),
162
+ snoozedUntil: DateTime.add(NOW, { minutes: index }),
163
+ pinnedAt: index % 2 === 0 ? null : NOW,
164
+ };
165
+ const mixed = {
166
+ ...stored,
167
+ snapshot: {
168
+ ...stored.snapshot,
169
+ threads: Array.from({ length: 65 }, (_, index) => row(index)),
170
+ archivedThreads: Array.from({ length: 33 }, (_, index) => ({
171
+ ...row(index + 100),
172
+ archivedAt: DateTime.add(NOW, { hours: index }),
173
+ })),
174
+ },
175
+ };
176
+ const actual = yield* encodeStoredShellSnapshot(mixed);
177
+ expect(actual).toBe(yield* encodeOriginal(mixed));
178
+ const parsed = JSON.parse(actual);
179
+ expect(parsed.snapshot.threads).toHaveLength(65);
180
+ expect(parsed.snapshot.threads[63]).not.toHaveProperty("titleRegeneration");
181
+ expect(parsed.snapshot.threads[63]).not.toHaveProperty("unsettledAt");
182
+ expect(parsed.snapshot.threads[64].snoozedUntil).toBe(
183
+ DateTime.formatIso(DateTime.add(NOW, { minutes: 64 })),
184
+ );
185
+ expect(parsed.snapshot.archivedThreads).toHaveLength(33);
186
+ expect(parsed.snapshot.archivedThreads[32].archivedAt).toBe(
187
+ DateTime.formatIso(DateTime.add(NOW, { hours: 32 })),
188
+ );
189
+ }),
190
+ );
191
+
192
+ it.effect("yields to a host timer between every 32-row chunk", () =>
193
+ Effect.gen(function* () {
194
+ const setTimer = vi.spyOn(globalThis, "setTimeout");
195
+ try {
196
+ yield* encodeStoredShellSnapshot({
197
+ ...stored,
198
+ snapshot: {
199
+ ...stored.snapshot,
200
+ threads: Array.from({ length: 65 }, () => ({ ...stored.snapshot.threads[0]! })),
201
+ archivedThreads: Array.from({ length: 33 }, () => ({
202
+ ...stored.snapshot.archivedThreads[0]!,
203
+ })),
204
+ },
205
+ });
206
+ // Five row chunks (3 active + 2 archived): four yields between them, one before the envelope.
207
+ expect(setTimer).toHaveBeenCalledTimes(5);
208
+ } finally {
209
+ vi.restoreAllMocks();
210
+ }
211
+ }),
212
+ );
213
+
214
+ it.effect("still rejects invalid active and archived rows after an encoding chunk yields", () =>
215
+ Effect.gen(function* () {
216
+ const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
217
+ const invalidActive = {
218
+ ...stored,
219
+ snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
220
+ };
221
+ const invalidArchived = {
222
+ ...stored,
223
+ snapshot: { ...stored.snapshot, archivedThreads: [invalidRow] },
224
+ };
225
+ const invalidEnvelope = { ...stored, snapshot: { ...stored.snapshot, snapshotSequence: -1 } };
226
+ expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidActive))).toBe(true);
227
+ expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidArchived))).toBe(true);
228
+ expect(yield* Effect.isFailure(encodeOriginal(invalidEnvelope))).toBe(true);
229
+ expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidEnvelope))).toBe(true);
230
+ }),
231
+ );
232
+
233
+ it.effect("keeps concurrent saves independent", () =>
234
+ Effect.gen(function* () {
235
+ const other = {
236
+ ...stored,
237
+ environmentId: EnvironmentId.make("environment-2"),
238
+ snapshot: {
239
+ ...stored.snapshot,
240
+ threads: stored.snapshot.threads.slice(0, 40).map((thread) => ({
241
+ ...thread,
242
+ title: `Other ${thread.id}`,
243
+ })),
244
+ archivedThreads: [],
245
+ },
246
+ };
247
+ const [first, second] = yield* Effect.all(
248
+ [encodeStoredShellSnapshot(stored), encodeStoredShellSnapshot(other)],
249
+ { concurrency: "unbounded" },
250
+ );
251
+ expect(first).toBe(yield* encodeOriginal(stored));
252
+ expect(second).toBe(yield* encodeOriginal(other));
253
+ }),
254
+ );
255
+
256
+ it.effect("cancels the pending host timer when encoding is interrupted", () =>
257
+ Effect.gen(function* () {
258
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
259
+ const fakeSetTimeout = globalThis.setTimeout;
260
+ const scheduled = yield* Deferred.make<ReturnType<typeof setTimeout>>();
261
+ vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
262
+ // @effect-diagnostics-next-line globalTimers:off - Observes the encoder's own host timer.
263
+ const timer = fakeSetTimeout(...args);
264
+ Deferred.doneUnsafe(scheduled, Effect.succeed(timer));
265
+ return timer;
266
+ });
267
+ const clearTimer = vi.spyOn(globalThis, "clearTimeout");
268
+ const fiber = yield* Effect.forkScoped(
269
+ Effect.suspend(() => encodeStoredShellSnapshot(stored)),
270
+ );
271
+ try {
272
+ const pendingTimer = yield* Deferred.await(scheduled);
273
+ expect(vi.getTimerCount()).toBe(1);
274
+ yield* Fiber.interrupt(fiber);
275
+ expect(clearTimer).toHaveBeenCalledWith(pendingTimer);
276
+ expect(vi.getTimerCount()).toBe(0);
277
+ } finally {
278
+ yield* Fiber.interrupt(fiber);
279
+ vi.restoreAllMocks();
280
+ vi.useRealTimers();
281
+ }
282
+ }),
283
+ );
284
+
285
+ it.effect("reuses encoded rows across saves without changing the payload", () =>
286
+ Effect.gen(function* () {
287
+ const encode = makeStoredShellSnapshotEncoder();
288
+ expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
289
+
290
+ const setTimer = vi.spyOn(globalThis, "setTimeout");
291
+ try {
292
+ // Same row references, new envelope: no row work, so no host yields.
293
+ const resaved = {
294
+ ...stored,
295
+ snapshot: { ...stored.snapshot, snapshotSequence: 4 },
296
+ };
297
+ expect(yield* encode(resaved)).toBe(yield* encodeOriginal(resaved));
298
+ expect(setTimer).not.toHaveBeenCalled();
299
+ } finally {
300
+ vi.restoreAllMocks();
301
+ }
302
+ }),
303
+ );
304
+
305
+ it.effect("encodes replaced, added, and moved-to-archive rows on a warm encoder", () =>
306
+ Effect.gen(function* () {
307
+ const encode = makeStoredShellSnapshotEncoder();
308
+ yield* encode(stored);
309
+ const [first, second, ...rest] = stored.snapshot.threads;
310
+ const next = {
311
+ ...stored,
312
+ snapshot: {
313
+ ...stored.snapshot,
314
+ threads: [
315
+ { ...first!, title: "Renamed", itemCount: 9 },
316
+ ...rest,
317
+ { ...first!, id: ThreadId.make("thread-new"), branch: " feature " },
318
+ ],
319
+ archivedThreads: [
320
+ ...stored.snapshot.archivedThreads,
321
+ { ...second!, archivedAt: DateTime.add(NOW, { hours: 1 }) },
322
+ ],
323
+ },
324
+ };
325
+ const actual = yield* encode(next);
326
+ expect(actual).toBe(yield* encodeOriginal(next));
327
+ const parsed = JSON.parse(actual);
328
+ expect(parsed.snapshot.threads[0].title).toBe("Renamed");
329
+ expect(parsed.snapshot.threads.at(-1).branch).toBe("feature");
330
+ expect(parsed.snapshot.archivedThreads).toHaveLength(2);
331
+ }),
332
+ );
333
+
334
+ it.effect("does not cache rows from a failed encode", () =>
335
+ Effect.gen(function* () {
336
+ const encode = makeStoredShellSnapshotEncoder();
337
+ const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
338
+ const invalid = {
339
+ ...stored,
340
+ snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
341
+ };
342
+ expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
343
+ expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
344
+ // Valid rows from the failed save still encode correctly afterwards.
345
+ expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
346
+ }),
347
+ );
348
+});
packages/client-runtime/src/platform/shellCacheEncoding.ts
renamed
+14
-5
@@ -1,13 +1,17 @@
1
-import { StoredOrchestrationShellSnapshot } from "@t3tools/client-runtime/platform";
1
import { OrchestrationV2ThreadShellJson } from "@t3tools/contracts";
2
import * as Effect from "effect/Effect";
3
import * as Schema from "effect/Schema";
4
5
+import { StoredOrchestrationShellSnapshot } from "./orchestrationCache.ts";
6
+
7
const ROWS_PER_CHUNK = 32;
8
8
-// Effect's cooperative yield resumes through microtasks on React Native. A host
9
-// timer lets input and rendering run between chunks of shell rows instead.
10
-const yieldToHost = Effect.callback<void>((resume) => {
9
+// Effect's own yield resumes through `setImmediate` where the host defines it and a
10
+// zero-delay timer otherwise. React Native's `setImmediate` is a microtask shim, so
11
+// nothing from the host runs before the fiber resumes. A timer yields on every host;
12
+// a browser can pass a yield that its timer clamping and throttling do not slow.
13
+const yieldToHostTimer = Effect.callback<void>((resume) => {
14
+ // @effect-diagnostics-next-line globalTimersInEffect:off - A host timer, not Effect.sleep, is the point.
15
const timer = setTimeout(() => resume(Effect.void), 0);
16
return Effect.sync(() => clearTimeout(timer));
17
});
@@ -38,8 +42,13 @@ const encodeEnvelope = Schema.encodeEffect(
42
* Shell rows are immutable and the shell reducer keeps unchanged rows by
43
* reference, so each encoder remembers the canonical encoding of rows it has
44
* already encoded successfully and only runs the row codec for new rows.
45
+ *
46
+ * `yieldToHost` defaults to a zero-delay timer.
47
*/
42
-export function makeStoredShellSnapshotEncoder() {
48
+export function makeStoredShellSnapshotEncoder(
49
+ options: { readonly yieldToHost?: Effect.Effect<void> } = {},
50
+) {
51
+ const yieldToHost = options.yieldToHost ?? yieldToHostTimer;
52
const encodedRows = new WeakMap<OrchestrationV2ThreadShellJson, unknown>();
53
54
return Effect.fnUntraced(function* (stored: typeof StoredOrchestrationShellSnapshot.Type) {