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

main
ts 257 lines 9.37 KB
Raw
1 import {
2 EnvironmentId,
3 ProjectId,
4 ThreadId,
5 type OrchestrationSearchThreadsResult,
6 type OrchestrationV2SearchThreadsInput,
7 type OrchestrationV2ThreadShell,
8 } from "@t3tools/contracts";
9 import * as Cause from "effect/Cause";
10 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11 import { expect, it } from "vite-plus/test";
12
13 import {
14 claimThreadOpen,
15 nextShownOrder,
16 createThreadSearchResultsAtomFamily,
17 makeThreadSearchKey,
18 threadSearchMatchKey,
19 threadSearchSubject,
20 visibleThreadSearch,
21 } from "./threadSearch.ts";
22
23 const envA = EnvironmentId.make("env-a");
24 const envB = EnvironmentId.make("env-b");
25
26 it("creates keys without array methods unavailable in Hermes", () => {
27 const descriptor = Object.getOwnPropertyDescriptor(Array.prototype, "toSorted");
28 Reflect.deleteProperty(Array.prototype, "toSorted");
29
30 try {
31 expect(makeThreadSearchKey([envB, envA], "needle")).toBe('[["env-a","env-b"],"needle"]');
32 } finally {
33 if (descriptor !== undefined) {
34 Reflect.defineProperty(Array.prototype, "toSorted", descriptor);
35 }
36 }
37 });
38
39 it("encodes scoped thread keys without delimiter collisions", () => {
40 const first = threadSearchMatchKey({
41 environmentId: EnvironmentId.make("env\u0000thread"),
42 threadId: ThreadId.make("id"),
43 });
44 const second = threadSearchMatchKey({
45 environmentId: EnvironmentId.make("env"),
46 threadId: ThreadId.make("thread\u0000id"),
47 });
48
49 expect(first).not.toBe(second);
50 });
51
52 it("ignores invalid search keys", () => {
53 let searchCount = 0;
54 const searchAtom = createThreadSearchResultsAtomFamily<Error>({
55 getSearchAtom: () => {
56 searchCount += 1;
57 return Atom.make(AsyncResult.success({ matches: [] }));
58 },
59 labelPrefix: "test:thread-search",
60 }).results;
61 const registry = AtomRegistry.make();
62
63 try {
64 const state = registry.get(searchAtom(makeThreadSearchKey([envA], "a".repeat(201))));
65 const malformedState = registry.get(searchAtom("not json{{"));
66
67 expect(state).toEqual({ matches: [], isLoading: false, failed: false, rows: [] });
68 expect(malformedState).toEqual({ matches: [], isLoading: false, failed: false, rows: [] });
69 expect(searchCount).toBe(0);
70 } finally {
71 registry.dispose();
72 }
73 });
74
75 it("merges successful environments, and reports a failure only when none answered", () => {
76 const result: OrchestrationSearchThreadsResult = {
77 matches: [
78 {
79 threadId: ThreadId.make("thread-a"),
80 projectId: ProjectId.make("project-a"),
81 source: "user",
82 snippet: "needle",
83 messageCreatedAt: "2026-07-30T00:00:00.000Z",
84 },
85 ],
86 };
87 const searchAtom = createThreadSearchResultsAtomFamily<Error>({
88 getSearchAtom: (environmentId) =>
89 environmentId === envA
90 ? Atom.make(AsyncResult.success(result))
91 : Atom.make(
92 AsyncResult.failure<OrchestrationSearchThreadsResult, Error>(
93 Cause.fail(new Error("unsupported rpc")),
94 ),
95 ),
96 labelPrefix: "test:thread-search",
97 }).results;
98 const registry = AtomRegistry.make();
99
100 const state = registry.get(searchAtom(makeThreadSearchKey([envB, envA], "needle")));
101 expect(state).toEqual({
102 matches: [{ ...result.matches[0], environmentId: envA }],
103 isLoading: false,
104 failed: false,
105 rows: [],
106 });
107 expect(threadSearchMatchKey(state.matches[0]!)).toBe('["env-a","thread-a"]');
108 // With no environment answering, an empty result must not read as "no matches".
109 expect(registry.get(searchAtom(makeThreadSearchKey([envB], "needle")))).toEqual({
110 matches: [],
111 isLoading: false,
112 failed: true,
113 rows: [],
114 });
115
116 registry.dispose();
117 });
118
119 it("asks environments that omit older settled threads for their rows, with the caller's scope", () => {
120 const inputs: Array<readonly [EnvironmentId, OrchestrationV2SearchThreadsInput]> = [];
121 const row = { id: ThreadId.make("thread-old") } as OrchestrationV2ThreadShell;
122 const search = createThreadSearchResultsAtomFamily<Error>({
123 getSearchAtom: (environmentId, input) => {
124 inputs.push([environmentId, input]);
125 return Atom.make(AsyncResult.success({ matches: [], snapshotSequence: 9, threads: [row] }));
126 },
127 olderSettledBefore: (environmentId) =>
128 Atom.make(environmentId === envA ? "2026-10-01T00:00:00.000Z" : null),
129 labelPrefix: "test:thread-search",
130 });
131 const registry = AtomRegistry.make();
132 const scope = {
133 projectIds: [ProjectId.make("project-a")],
134 environmentLabels: { [envA]: "Laptop" },
135 };
136
137 // Too short to match messages: only the environment with older rows is asked, for titles.
138 const key = makeThreadSearchKey([envA, envB], "ui", scope);
139 expect(registry.get(search.results(key)).rows).toEqual([
140 { environmentId: envA, read: { snapshotSequence: 9, threads: [row] } },
141 ]);
142 expect(registry.get(search.rows(key, envA))).toEqual([{ snapshotSequence: 9, threads: [row] }]);
143 expect(inputs).toEqual([
144 [
145 envA,
146 {
147 query: "ui",
148 olderSettledBefore: "2026-10-01T00:00:00.000Z",
149 projectIds: scope.projectIds,
150 environmentLabel: "Laptop",
151 titlesOnly: true,
152 },
153 ],
154 ]);
155 inputs.length = 0;
156 registry.get(search.results(makeThreadSearchKey([envB], "needle")));
157 expect(inputs).toEqual([[envB, { query: "needle" }]]);
158
159 registry.dispose();
160 });
161
162 it("keeps the previous results visible only while a refined or widened query is pending", () => {
163 const previous = {
164 query: "websock",
165 matches: [
166 {
167 environmentId: envA,
168 threadId: ThreadId.make("thread-a"),
169 projectId: ProjectId.make("project-a"),
170 source: "user" as const,
171 snippet: "websocket reconnect",
172 messageCreatedAt: null,
173 },
174 ],
175 };
176 expect(visibleThreadSearch("websocke", null, previous)).toBe(previous);
177 expect(visibleThreadSearch("webso", null, previous)).toBe(previous);
178 expect(visibleThreadSearch("billing", null, previous)).toEqual({ query: "", matches: [] });
179 const ready = { query: "websocke", matches: [] };
180 expect(visibleThreadSearch("websocke", ready, previous)).toBe(ready);
181 });
182
183 it("ranks recent threads by this client's own latest open", () => {
184 const thread = {
185 environmentId: envA,
186 id: ThreadId.make("thread-local"),
187 title: "Local",
188 branch: null,
189 createdAt: "2026-10-01T00:00:00.000Z",
190 updatedAt: "2026-10-01T00:00:00.000Z",
191 latestUserMessageAt: null,
192 opens: { openedAt: 1_000, score: 1, picks: [] },
193 };
194 claimThreadOpen(envA, "thread-local", 5_000);
195 expect(threadSearchSubject(thread, null).opens?.openedAt).toBe(5_000);
196 // Also when the server has no record of opens, as an older server would not.
197 claimThreadOpen(envA, "thread-unrecorded", 6_000);
198 expect(
199 threadSearchSubject({ ...thread, id: ThreadId.make("thread-unrecorded"), opens: null }, null)
200 .opens,
201 ).toEqual({ openedAt: 6_000, score: 1, picks: [] });
202 // A subject built before the open does not hide it.
203 claimThreadOpen(envA, "thread-local", 7_000);
204 expect(threadSearchSubject(thread, null).opens?.openedAt).toBe(7_000);
205 expect(threadSearchSubject(thread, "Project").projectTitle).toBe("Project");
206 });
207
208 it("counts recency from what the user wrote, else from when the thread began", () => {
209 const thread = {
210 environmentId: envA,
211 id: ThreadId.make("thread-agent"),
212 title: "Launched by an agent",
213 branch: null,
214 createdAt: "2026-10-01T00:00:00.000Z",
215 updatedAt: "2026-10-20T00:00:00.000Z",
216 latestUserMessageAt: "2026-10-20T00:00:00.000Z",
217 opens: null,
218 };
219 expect(
220 threadSearchSubject({ ...thread, latestUserAuthoredMessageAt: null }, null).activityAt,
221 ).toBe(Date.parse("2026-10-01T00:00:00.000Z"));
222 expect(
223 threadSearchSubject(
224 { ...thread, latestUserAuthoredMessageAt: "2026-10-05T00:00:00.000Z" },
225 null,
226 ).activityAt,
227 ).toBe(Date.parse("2026-10-05T00:00:00.000Z"));
228 // An older server omits the field.
229 expect(threadSearchSubject(thread, null).activityAt).toBe(Date.parse("2026-10-20T00:00:00.000Z"));
230 });
231
232 it("keeps shown message rows in place and leaves room for a slower environment", () => {
233 // The fast environment answers first and fills the limit.
234 const fast = Array.from({ length: 12 }, (_, index) => `a${index}`);
235 const first = nextShownOrder(null, "rust", fast, 10);
236 expect(first.keys.slice(0, first.shown)).toEqual(fast.slice(0, 10));
237 // The slow one's matches rank first: shown rows hold, and its best few come next.
238 const slow = ["b0", "b1", "b2", "b3"];
239 const second = nextShownOrder(first, "rust", [...slow, ...fast], 10);
240 expect(second.keys.slice(0, second.shown)).toEqual([...fast.slice(0, 10), "b0", "b1", "b2"]);
241 // Nothing new: nothing moves and nothing grows.
242 expect(nextShownOrder(second, "rust", [...slow, ...fast], 10)).toBe(second);
243 // A third environment gets no more room past the limit.
244 const third = nextShownOrder(second, "rust", ["c0", ...slow, ...fast], 10);
245 expect(third.shown).toBe(13);
246 expect(third.keys.slice(0, 13)).toEqual(second.keys.slice(0, 13));
247 // A new query starts from its own ranking.
248 expect(nextShownOrder(second, "rusty", ["b0"], 10).keys).toEqual(["b0"]);
249 });
250
251 it("sends one open per thread every ten minutes by this client's clock", () => {
252 const minute = 60_000;
253 expect(claimThreadOpen(envA, "thread-open", 0)).toBe(true);
254 expect(claimThreadOpen(envA, "thread-open", 9 * minute)).toBe(false);
255 expect(claimThreadOpen(envB, "thread-open", 9 * minute)).toBe(true);
256 expect(claimThreadOpen(envA, "thread-open", 10 * minute)).toBe(true);
257 });