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

main
ts 118 lines 4.64 KB
Raw
1 import * as Context from "effect/Context";
2 import * as SecureRandom from "effect/crypto/SecureRandom";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Path from "effect/Path";
6 import * as Semaphore from "effect/Semaphore";
7
8 import { readFileRevision } from "./MediaFile.ts";
9
10 const MAX_TRACKED_DOCUMENTS = 64;
11 export const MAX_TRACKED_FILES_PER_DOCUMENT = 256;
12 const REVISION_READ_CONCURRENCY = 8;
13
14 /** One opened HTML page: the canonical workspace root and the page's path below it. */
15 export interface PreviewDocument {
16 readonly workspaceRoot: string;
17 readonly entryRelativePath: string;
18 }
19
20 interface DocumentState {
21 version: number;
22 /** The page loads more files than are tracked, so no revision can speak for it. */
23 overflowed: boolean;
24 /** What each file the page asked for looked like when last compared; null while it is missing. */
25 readonly files: Map<string, string | null>;
26 /** Reads are recorded one batch at a time, so an older read never overwrites a newer one. */
27 readonly comparing: Semaphore.Semaphore;
28 }
29
30 /**
31 * Tells an unchanged HTML preview from an edited one. A page's revision covers the page and the
32 * files it has requested, and no other file: an edit elsewhere, even next to it, leaves it alone.
33 */
34 export class WorkspacePreviewRevisions extends Context.Service<
35 WorkspacePreviewRevisions,
36 {
37 /** Undefined when the page cannot be tracked; the client then reloads on workspace changes. */
38 readonly revision: (document: PreviewDocument) => Effect.Effect<string | undefined>;
39 /** Records a file the page requested, found or not, as part of the page. */
40 readonly observe: (document: PreviewDocument, relativePath: string) => Effect.Effect<void>;
41 }
42 >()("t3/assets/WorkspacePreviewRevisions") {}
43
44 const make = Effect.gen(function* () {
45 const path = yield* Path.Path;
46 // Tracked files are forgotten on restart, so revisions from an earlier process must not match.
47 const processId = yield* (yield* SecureRandom.SecureRandom).uuidV4();
48 // Insertion order is recency: the least recently minted document is dropped first.
49 const documents = new Map<string, DocumentState>();
50 // One counter for all documents, so a document tracked again never repeats a revision.
51 let versions = 0;
52
53 const documentKey = (document: PreviewDocument) =>
54 JSON.stringify([document.workspaceRoot, document.entryRelativePath]);
55
56 const record = (state: DocumentState, relativePath: string, revision: string | null) => {
57 if (!state.files.has(relativePath)) {
58 if (state.files.size >= MAX_TRACKED_FILES_PER_DOCUMENT) state.overflowed = true;
59 else state.files.set(relativePath, revision);
60 return;
61 }
62 if (state.files.get(relativePath) === revision) return;
63 state.files.set(relativePath, revision);
64 state.version = ++versions;
65 };
66
67 const revision = Effect.fn("WorkspacePreviewRevisions.revision")(function* (
68 document: PreviewDocument,
69 ) {
70 const key = documentKey(document);
71 const state = documents.get(key) ?? {
72 version: ++versions,
73 overflowed: false,
74 files: new Map<string, string | null>(),
75 comparing: Semaphore.makeUnsafe(1),
76 };
77 documents.delete(key);
78 documents.set(key, state);
79 if (documents.size > MAX_TRACKED_DOCUMENTS) {
80 for (const oldest of documents.keys()) {
81 documents.delete(oldest);
82 break;
83 }
84 }
85 return yield* state.comparing.withPermits(1)(
86 Effect.gen(function* () {
87 const relativePaths = [...new Set([document.entryRelativePath, ...state.files.keys()])];
88 const revisions = yield* Effect.forEach(
89 relativePaths,
90 (relativePath) => readFileRevision(path.join(document.workspaceRoot, relativePath)),
91 { concurrency: REVISION_READ_CONCURRENCY },
92 );
93 for (const [index, relativePath] of relativePaths.entries()) {
94 record(state, relativePath, revisions[index] ?? null);
95 }
96 return state.overflowed ? undefined : `${processId}:${state.version}`;
97 }),
98 );
99 });
100
101 const observe = Effect.fn("WorkspacePreviewRevisions.observe")(function* (
102 document: PreviewDocument,
103 relativePath: string,
104 ) {
105 // A document nobody minted here gets a new revision on its next mint, which reloads it.
106 const state = documents.get(documentKey(document));
107 if (state === undefined) return;
108 yield* state.comparing.withPermits(1)(
109 Effect.map(readFileRevision(path.join(document.workspaceRoot, relativePath)), (revision) =>
110 record(state, relativePath, revision),
111 ),
112 );
113 });
114
115 return WorkspacePreviewRevisions.of({ revision, observe });
116 });
117
118 export const layer = Layer.effect(WorkspacePreviewRevisions, make);