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

main
ts 199 lines 7.74 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import { assert, it } from "@effect/vitest";
5 import * as Console from "effect/Console";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Path from "effect/Path";
10 import * as TestClock from "effect/testing/TestClock";
11
12 import * as BootService from "../cloud/bootService.ts";
13 import { runDoctor } from "./doctor.ts";
14 import { DatabaseMaintenance } from "../persistence/DatabaseMaintenance.ts";
15 import * as ProcessRunner from "../processRunner.ts";
16 import { acquireServerOwnership } from "../serverOwnership.ts";
17 import { makePersistedServerRuntimeState } from "../serverRuntimeState.ts";
18
19 // An empty home, so no boot service unit installed on this machine is read.
20 const layerHost = Layer.mergeAll(
21 ProcessRunner.layer,
22 Layer.effect(
23 HostProcess.HomeDirectory,
24 Effect.gen(function* () {
25 return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
26 }),
27 ),
28 Layer.succeed(HostProcess.Environment, {}),
29 ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
30
31 it.effect(
32 "--fix locks the home while the service is paused, names a server that holds it, keeps the V1 database, and --dry-run changes nothing",
33 () =>
34 Effect.gen(function* () {
35 const fs = yield* FileSystem.FileSystem;
36 const path = yield* Path.Path;
37 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-" });
38 const serverRuntimeStatePath = path.join(stateDir, "server-runtime.json");
39 const calls: string[] = [];
40 const services =
41 yield* Effect.context<Effect.Services<ReturnType<typeof acquireServerOwnership>>>();
42 // Stands in for a server launched for the same home, for example over SSH.
43 const startServer = Effect.scoped(acquireServerOwnership(serverRuntimeStatePath)).pipe(
44 Effect.result,
45 Effect.map((result) =>
46 calls.push(result._tag === "Success" ? "server started" : result.failure._tag),
47 ),
48 Effect.provide(services),
49 );
50 const doctor = (dryRun: boolean) =>
51 runDoctor(
52 { dbPath: path.join(stateDir, "statev2.sqlite"), serverRuntimeStatePath },
53 { fix: true, dryRun, interactive: false },
54 ).pipe(
55 Effect.provide(
56 Layer.mergeAll(
57 Layer.mock(BootService.BootService)({
58 withStopped: (operation) =>
59 Effect.sync(() => calls.push("pause")).pipe(
60 Effect.andThen(operation),
61 Effect.ensuring(Effect.sync(() => calls.push("resume"))),
62 ),
63 }),
64 Layer.succeed(DatabaseMaintenance, {
65 inspect: () =>
66 Effect.succeed({
67 databaseBytes: 2000,
68 reclaimableBytes: 1000,
69 incrementalVacuumEnabled: false,
70 legacyDatabaseBytes: 4000,
71 legacyOnlyRecords: { projects: 0, threads: 0 },
72 }),
73 compact: () =>
74 startServer.pipe(
75 Effect.map(() => {
76 calls.push("compact");
77 return {
78 beforeBytes: 2000,
79 afterBytes: 1000,
80 deletedEventCount: 1,
81 deletedReceiptCount: 0,
82 };
83 }),
84 ),
85 removeLegacyDatabase: () => Effect.sync(() => calls.push("remove legacy")),
86 }),
87 ),
88 ),
89 );
90 yield* doctor(true);
91 assert.deepEqual(calls, []);
92 yield* doctor(false);
93 yield* startServer;
94 assert.deepEqual(calls, [
95 "pause",
96 "ServerAlreadyRunningError",
97 "compact",
98 "resume",
99 "server started",
100 ]);
101
102 calls.length = 0;
103 const state = yield* makePersistedServerRuntimeState({
104 config: { host: undefined, devUrl: undefined },
105 port: 3773,
106 });
107 const refused = yield* Effect.scoped(
108 acquireServerOwnership(serverRuntimeStatePath).pipe(
109 Effect.tap((owner) => owner.publish(state)),
110 Effect.andThen(doctor(false)),
111 ),
112 ).pipe(Effect.flip);
113 assert.equal(
114 refused.message,
115 `Stop T3 Code server process ${state.pid}, which the background service did not start, before repairing the database.`,
116 );
117 assert.deepEqual(calls, ["pause", "resume"]);
118 }).pipe(Effect.provide(layerHost)),
119 );
120
121 it.effect("warns how long reclaiming can take and reports each step with its elapsed time", () =>
122 Effect.gen(function* () {
123 const output: string[] = [];
124 const steps = [
125 ["prune-events", "65 seconds"],
126 ["vacuum", "701 seconds"],
127 ["rebuild-search", "1 second"],
128 ["checkpoint", "1 second"],
129 ] as const;
130 const stateDir = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
131 const path = yield* Path.Path;
132 yield* runDoctor(
133 {
134 dbPath: path.join(stateDir, "statev2.sqlite"),
135 serverRuntimeStatePath: path.join(stateDir, "server-runtime.json"),
136 },
137 { fix: true, dryRun: false, interactive: false },
138 ).pipe(
139 Effect.provide(
140 Layer.mergeAll(
141 Layer.mock(BootService.BootService)({
142 withStopped: (operation) =>
143 Effect.sync(() => output.push("<pause>")).pipe(
144 Effect.andThen(operation),
145 Effect.ensuring(Effect.sync(() => output.push("<resume>"))),
146 ),
147 }),
148 Layer.succeed(DatabaseMaintenance, {
149 inspect: () =>
150 Effect.succeed({
151 databaseBytes: 12.8 * 1024 ** 3,
152 reclaimableBytes: 0,
153 incrementalVacuumEnabled: false,
154 legacyDatabaseBytes: null,
155 legacyOnlyRecords: null,
156 }),
157 compact: (_databasePath, onStep) =>
158 Effect.gen(function* () {
159 for (const [step, duration] of steps) {
160 if (onStep) yield* onStep(step);
161 yield* TestClock.adjust(duration);
162 }
163 return {
164 beforeBytes: 12.8 * 1024 ** 3,
165 afterBytes: 12.8 * 1024 ** 3,
166 deletedEventCount: 0,
167 deletedReceiptCount: 0,
168 };
169 }),
170 removeLegacyDatabase: () => Effect.void,
171 }),
172 ),
173 ),
174 Effect.provideService(Console.Console, {
175 ...globalThis.console,
176 log: (...args: ReadonlyArray<unknown>) => {
177 output.push(...args.join(" ").split("\n"));
178 },
179 }),
180 );
181
182 const paused = output.indexOf("<pause>");
183 const resumed = output.indexOf("<resume>");
184 assert.isAbove(paused, -1, "the repair must run with the service paused");
185 const beforePause = output.slice(0, paused).join("\n");
186 const description = beforePause.slice(beforePause.indexOf("Reclaim database space"));
187 assert.include(description, "12.80 GiB", "the repair must state the database size up front");
188 assert.match(description, /hour/, "the repair must warn it can take over an hour");
189 const progress = output
190 .slice(paused + 1, resumed)
191 .filter((line) => line.trim() !== "" && !line.trim().startsWith("Done"))
192 .map((line) => /\[(\d+:\d{2})\]/.exec(line)?.[1] ?? `unprefixed: ${line}`);
193 assert.deepEqual(
194 progress,
195 ["0:00", "1:05", "12:46", "12:47"],
196 "each compaction step must print one line with the elapsed time as it starts",
197 );
198 }).pipe(Effect.provide(layerHost)),
199 );