@rantingjs/studio 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +145 -2
  2. package/dist/badge.d.ts +2 -0
  3. package/dist/badge.js +17 -0
  4. package/dist/badge.js.map +1 -0
  5. package/dist/commands.d.ts +8 -0
  6. package/dist/commands.js +49 -0
  7. package/dist/commands.js.map +1 -0
  8. package/dist/config.d.ts +24 -0
  9. package/dist/config.js +26 -0
  10. package/dist/config.js.map +1 -0
  11. package/dist/forge.d.ts +67 -0
  12. package/dist/forge.js +138 -0
  13. package/dist/forge.js.map +1 -0
  14. package/dist/http.d.ts +25 -0
  15. package/dist/http.js +248 -0
  16. package/dist/http.js.map +1 -0
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.js +4 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/opencode.d.ts +30 -0
  21. package/dist/opencode.js +113 -0
  22. package/dist/opencode.js.map +1 -0
  23. package/dist/page.d.ts +11 -0
  24. package/dist/page.js +31 -0
  25. package/dist/page.js.map +1 -0
  26. package/dist/studio.module.d.ts +21 -0
  27. package/dist/studio.module.js +129 -0
  28. package/dist/studio.module.js.map +1 -0
  29. package/package.json +99 -4
  30. package/src/config.ts +26 -0
  31. package/ui/app.tsx +862 -0
  32. package/ui/changes.tsx +420 -0
  33. package/ui/code.tsx +194 -0
  34. package/ui/composer.tsx +362 -0
  35. package/ui/conversations.tsx +103 -0
  36. package/ui/editor.ts +144 -0
  37. package/ui/forge.tsx +236 -0
  38. package/ui/icons.tsx +59 -0
  39. package/ui/logic.ts +304 -0
  40. package/ui/logs.tsx +87 -0
  41. package/ui/model-picker.tsx +121 -0
  42. package/ui/notify.ts +45 -0
  43. package/ui/page.ts +27 -0
  44. package/ui/popover.tsx +66 -0
  45. package/ui/prose.tsx +50 -0
  46. package/ui/providers.tsx +384 -0
  47. package/ui/queue.tsx +89 -0
  48. package/ui/shared.ts +74 -0
  49. package/ui/splitter.tsx +70 -0
  50. package/ui/styles.css +2632 -0
  51. package/ui/terminal.tsx +108 -0
  52. package/ui/tsconfig.json +13 -0
  53. package/ui/urls.ts +9 -0
  54. package/ui/usage.tsx +86 -0
package/ui/changes.tsx ADDED
@@ -0,0 +1,420 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ // Changes: everything not committed yet (git's working tree, the agent's edits and yours), or what the agent changed
3
+ // in its last turn. Files on the left, the diff of the one picked on the right. A commit starts with the agent's
4
+ // review of what goes in it; a project without git gets the review of what the agent changed.
5
+ import type { FileDiffInfo, ModelInfo } from '@opencode/client';
6
+ import { useEffect, useState } from 'hono/jsx/dom';
7
+ import { Icon } from './icons.js';
8
+ import { cleanCommitMessage, commitMessagePrompt, effortLabel, mentionAttachment, projectPath, promptFiles, REVIEW_SCOPE, reviewOutcome, reviewPrompt, subpathOf } from './logic.js';
9
+ import { Prose } from './prose.js';
10
+ import { client, directory, errorText, location_, repository, studioApi } from './shared.js';
11
+ import { useSplit } from './splitter.js';
12
+
13
+ /** The project's folder inside its repository, once known. */
14
+ export const projectSubpath = Promise.all([directory, repository]).then(([dir, repo]) => subpathOf(dir, repo));
15
+
16
+ /** The branch and how many files are not committed: the chip above the stage. */
17
+ export interface GitState {
18
+ branch?: string;
19
+ changed: number;
20
+ repository: boolean;
21
+ }
22
+
23
+ export async function gitState(): Promise<GitState> {
24
+ try {
25
+ const [info, status] = await Promise.all([client.vcs.get({ location: location_ }), client.vcs.status({ location: location_ })]);
26
+ return { branch: info.data.branch.current, changed: status.data.length, repository: Boolean(info.data.provider) };
27
+ } catch {
28
+ return { changed: 0, repository: false };
29
+ }
30
+ }
31
+
32
+ export function GitChip({ git, onOpen }: { git: GitState | undefined; onOpen: () => void }) {
33
+ if (!git?.repository) return null;
34
+ return (
35
+ <button type="button" class="chip git-chip" onClick={onOpen} title="Uncommitted changes">
36
+ <Icon name="branch" size={14} />
37
+ <span class="chip-text">{git.branch ?? 'detached'}</span>
38
+ {git.changed > 0 && <span class="chip-count">{git.changed} changed</span>}
39
+ </button>
40
+ );
41
+ }
42
+
43
+ const STATUS_LETTER = { added: 'A', deleted: 'D', modified: 'M' } as const;
44
+
45
+ function Patch({ diff }: { diff: FileDiffInfo }) {
46
+ const lines = diff.patch.split('\n').filter((line) => !/^(---|\+\+\+|diff |index |new file|deleted file|similarity|rename )/.test(line));
47
+ return (
48
+ <pre class="diff-body">
49
+ {lines.map((line) => (
50
+ <span class={line.startsWith('@@') ? 'hunk' : line.startsWith('+') ? 'add' : line.startsWith('-') ? 'del' : ''}>
51
+ {line}
52
+ {'\n'}
53
+ </span>
54
+ ))}
55
+ {diff.more && <span class="hunk">… the patch is cut here</span>}
56
+ </pre>
57
+ );
58
+ }
59
+
60
+ /** What the chat gives the Changes panel: the model that answers, the runs going on, and how to show a conversation. */
61
+ export interface ChangesProps {
62
+ sessionID: string | undefined;
63
+ refresh: number;
64
+ git: GitState | undefined;
65
+ model: ModelInfo | undefined;
66
+ effort: string | undefined;
67
+ /** Conversations running now, and those whose agent waits for an answer (a permission). */
68
+ busy: Record<string, boolean>;
69
+ asking: string[];
70
+ onOpen: (sessionID: string) => void;
71
+ onGitChanged: () => void;
72
+ /** The open conversation's last turn undone (and its files put back), or that undo taken back. */
73
+ onUndo?: () => void;
74
+ onRedo?: () => void;
75
+ }
76
+
77
+ /** Where a commit is: not started, its review running, or reviewed (or the review skipped) and waiting for its message. */
78
+ type Step = { name: 'idle' } | { name: 'reviewing'; sessionID: string } | { name: 'reviewed'; sessionID?: string; summary: string; failed?: string };
79
+
80
+ export function ChangesPanel({ sessionID, refresh, git, model, effort, busy, asking, onOpen, onGitChanged, onUndo, onRedo }: ChangesProps) {
81
+ const noGit = git !== undefined && !git.repository;
82
+ const [chosenView, setView] = useState<'working' | 'turn'>('working');
83
+ // Without git there is no working tree to compare: only what the agent changed.
84
+ const view = noGit ? 'turn' : chosenView;
85
+ const [diffs, setDiffs] = useState<FileDiffInfo[]>([]);
86
+ const [subpath, setSubpath] = useState('');
87
+ const [picked, setPicked] = useState<string | undefined>();
88
+ const [error, setError] = useState('');
89
+ const [loading, setLoading] = useState(true);
90
+ const [reloads, setReloads] = useState(0);
91
+ const [step, setStep] = useState<Step>({ name: 'idle' });
92
+ const [message, setMessage] = useState('');
93
+ const [working, setWorking] = useState<'' | 'starting' | 'suggesting' | 'committing'>('');
94
+ const [committed, setCommitted] = useState('');
95
+ const listSplit = useSplit('changes-list', 180, () => window.innerWidth * 0.5, () => document.querySelector('.changes-list'));
96
+ const modelRef = model ? { id: model.modelID, providerID: model.providerID, ...(effort ? { variant: effort } : {}) } : undefined;
97
+ const modelName = model ? `${model.name}${effort ? ` · ${effortLabel(effort)}` : ''}` : '';
98
+
99
+ useEffect(() => void projectSubpath.then(setSubpath), []);
100
+ useEffect(() => {
101
+ setLoading(true);
102
+ const load =
103
+ view === 'working'
104
+ ? client.vcs.diff({ location: location_, mode: 'working', context: 3, untracked: 'files' }).then((result) => result.data)
105
+ : sessionID
106
+ ? client.session.diff({ sessionID, context: 3 })
107
+ : Promise.resolve([] as FileDiffInfo[]);
108
+ void load
109
+ .then((result) => {
110
+ setDiffs(result);
111
+ setError('');
112
+ })
113
+ .catch((failure) => setError(errorText(failure)))
114
+ .finally(() => setLoading(false));
115
+ }, [view, sessionID, refresh, reloads]);
116
+
117
+ // The review is done when its run has ended: its last answer becomes the summary above the commit message.
118
+ const reviewing = step.name === 'reviewing' ? step.sessionID : undefined;
119
+ const reviewBusy = reviewing ? Boolean(busy[reviewing]) : false;
120
+ useEffect(() => {
121
+ if (!reviewing || reviewBusy) return;
122
+ void client.message
123
+ .list({ sessionID: reviewing, limit: 30, order: 'desc' })
124
+ .then((result) => {
125
+ const outcome = reviewOutcome([...result.data].reverse());
126
+ if (!outcome.done) return;
127
+ setStep((now) => (now.name === 'reviewing' && now.sessionID === reviewing ? { name: 'reviewed', sessionID: reviewing, summary: outcome.text, ...(outcome.failed ? { failed: outcome.failed } : {}) } : now));
128
+ })
129
+ .catch(() => undefined);
130
+ }, [reviewing, reviewBusy, refresh]);
131
+
132
+ const fail = (failure: unknown) => setError(errorText(failure));
133
+ /** "Commit…": a conversation of the plan agent (it changes nothing) running `/review` on what is not committed. */
134
+ const startReview = async () => {
135
+ setError('');
136
+ setCommitted('');
137
+ setWorking('starting');
138
+ try {
139
+ const created = await client.session.create({ location: location_, agent: 'plan', title: `Review before commit${git?.branch ? ` · ${git.branch}` : ''}`, ...(modelRef ? { model: modelRef } : {}) });
140
+ setStep({ name: 'reviewing', sessionID: created.id });
141
+ // Its request lasts as long as the run: the run's end is seen in its messages, a failure to start here.
142
+ void client.session.command({ sessionID: created.id, name: 'review', text: REVIEW_SCOPE }).catch((failure) =>
143
+ setStep((now) => {
144
+ if (now.name !== 'reviewing' || now.sessionID !== created.id) return now;
145
+ fail(failure);
146
+ return { name: 'idle' };
147
+ }),
148
+ );
149
+ } catch (failure) {
150
+ fail(failure);
151
+ setStep({ name: 'idle' });
152
+ } finally {
153
+ setWorking('');
154
+ }
155
+ };
156
+ const stopReview = () => {
157
+ if (step.name === 'reviewing') void client.session.interrupt({ sessionID: step.sessionID }).catch(() => undefined);
158
+ };
159
+ const skipReview = () => {
160
+ stopReview();
161
+ setStep({ name: 'reviewed', summary: '' });
162
+ };
163
+ const cancel = () => {
164
+ stopReview();
165
+ setStep({ name: 'idle' });
166
+ setError('');
167
+ };
168
+ const suggest = async () => {
169
+ setWorking('suggesting');
170
+ try {
171
+ const changes = await client.vcs.diff({ location: location_, mode: 'working', context: 3, untracked: 'files' });
172
+ // A provider that does not answer (it happens) leaves the message to be written by hand.
173
+ const answer = await client.experimental.generate.text({ prompt: commitMessagePrompt(changes.data.map((diff) => diff.patch)), ...(modelRef ? { model: modelRef } : {}) }, { signal: AbortSignal.timeout(45_000) });
174
+ setMessage(cleanCommitMessage(answer.text));
175
+ } catch (failure) {
176
+ fail((failure as Error | undefined)?.name === 'TimeoutError' || /timed? ?out/i.test(errorText(failure)) ?new Error(`${model?.name ?? 'The model'} did not answer within 45 seconds: write the message, or ask again.`) : failure);
177
+ } finally {
178
+ setWorking('');
179
+ }
180
+ };
181
+ const commit = async () => {
182
+ if (!message.trim() || working) return;
183
+ setError('');
184
+ setWorking('committing');
185
+ try {
186
+ const done = await studioApi<{ hash: string; subject: string }>('git/commit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ message }) });
187
+ setCommitted(`${done.hash} · ${done.subject}`);
188
+ setMessage('');
189
+ setStep({ name: 'idle' });
190
+ setReloads((count) => count + 1);
191
+ onGitChanged();
192
+ } catch (failure) {
193
+ fail(failure);
194
+ } finally {
195
+ setWorking('');
196
+ }
197
+ };
198
+ /** The review found problems: the same conversation, now the build agent, fixes them. The commit waits for a new review. */
199
+ const fix = async () => {
200
+ if (step.name !== 'reviewed' || !step.sessionID) return;
201
+ const id = step.sessionID;
202
+ try {
203
+ await client.session.switchAgent({ sessionID: id, agent: 'build' });
204
+ await client.session.prompt({ sessionID: id, text: 'Fix the problems this review found.' });
205
+ setStep({ name: 'idle' });
206
+ onOpen(id);
207
+ } catch (failure) {
208
+ fail(failure);
209
+ }
210
+ };
211
+ /** Without git: the plan agent reviews the files the open conversation changed, read in place. */
212
+ const reviewTurn = async () => {
213
+ setError('');
214
+ setWorking('starting');
215
+ try {
216
+ const { text, mentions } = reviewPrompt(diffs.map((diff) => ({ path: projectPath(diff.file, subpath), status: diff.status })));
217
+ const root = await directory;
218
+ const created = await client.session.create({ location: location_, agent: 'plan', title: 'Review of the agent’s changes', ...(modelRef ? { model: modelRef } : {}) });
219
+ await client.session.prompt({ sessionID: created.id, text, files: promptFiles(text, mentions.map((path) => mentionAttachment(root, path, false))) });
220
+ onOpen(created.id);
221
+ } catch (failure) {
222
+ fail(failure);
223
+ } finally {
224
+ setWorking('');
225
+ }
226
+ };
227
+ const initGit = async () => {
228
+ setError('');
229
+ try {
230
+ await client.vcs.init({ location: location_ });
231
+ onGitChanged();
232
+ } catch (failure) {
233
+ fail(failure);
234
+ }
235
+ };
236
+
237
+ const shown = diffs.find((diff) => diff.file === picked) ?? diffs[0];
238
+ const added = diffs.reduce((sum, diff) => sum + diff.additions, 0);
239
+ const removed = diffs.reduce((sum, diff) => sum + diff.deletions, 0);
240
+ const canCommit = !noGit && view === 'working' && diffs.length > 0 && step.name === 'idle';
241
+ const fileCount = `${diffs.length} ${diffs.length === 1 ? 'file' : 'files'}`;
242
+ return (
243
+ <div class="changes">
244
+ <header class="changes-head">
245
+ {noGit ? (
246
+ <span class="changes-title">Agent’s last turn</span>
247
+ ) : (
248
+ <div class="segmented small" role="radiogroup" aria-label="Which changes">
249
+ <button type="button" class={view === 'working' ? 'on' : ''} onClick={() => setView('working')}>
250
+ Uncommitted
251
+ </button>
252
+ <button type="button" class={view === 'turn' ? 'on' : ''} onClick={() => setView('turn')}>
253
+ Agent’s last turn
254
+ </button>
255
+ </div>
256
+ )}
257
+ {diffs.length > 0 && (
258
+ <span class="changes-total">
259
+ {fileCount} <span class="add">+{added}</span> <span class="del">−{removed}</span>
260
+ </span>
261
+ )}
262
+ {view === 'turn' && onRedo && (
263
+ <button type="button" class="commit-start" onClick={onRedo} title="Bring back the turn you undid, and its changes">
264
+ <Icon name="redo" size={14} />
265
+ Redo the turn
266
+ </button>
267
+ )}
268
+ {view === 'turn' && onUndo && diffs.length > 0 && (
269
+ <button type="button" class="commit-start" onClick={onUndo} title="Remove your last message and what the agent did for it, and put these files back as they were">
270
+ <Icon name="undo" size={14} />
271
+ Undo this turn
272
+ </button>
273
+ )}
274
+ {canCommit && (
275
+ <button type="button" class="primary commit-start" onClick={() => void startReview()} disabled={working === 'starting'} title="The agent reviews the changes, then you commit them">
276
+ <Icon name="check" size={14} />
277
+ {working === 'starting' ? 'Starting review…' : 'Commit…'}
278
+ </button>
279
+ )}
280
+ </header>
281
+
282
+ {noGit && (
283
+ <section class="commit">
284
+ <div class="commit-row">
285
+ <Icon name="warning" size={16} />
286
+ <span class="commit-text">
287
+ <strong>Not a git repository</strong>
288
+ <span class="muted">Nothing to commit: have the agent review what it changed, or start a repository.</span>
289
+ </span>
290
+ </div>
291
+ <div class="commit-actions">
292
+ <button type="button" onClick={() => void initGit()}>
293
+ <Icon name="branch" size={14} />
294
+ Initialize git
295
+ </button>
296
+ <button type="button" class="primary" onClick={() => void reviewTurn()} disabled={!diffs.length || working === 'starting'} title={diffs.length ? 'A conversation of the plan agent reviews these files' : 'The open conversation changed no files'}>
297
+ <Icon name="sparkle" size={14} />
298
+ {working === 'starting' ? 'Starting review…' : 'Review the agent’s changes'}
299
+ </button>
300
+ </div>
301
+ </section>
302
+ )}
303
+
304
+ {step.name === 'reviewing' && (
305
+ <section class="commit">
306
+ <div class="commit-row">
307
+ <span class="spinner" />
308
+ <span class="commit-text">
309
+ <strong>Reviewing before the commit</strong>
310
+ <span class="muted">
311
+ {fileCount}
312
+ {modelName && ` · ${modelName}`}
313
+ </span>
314
+ </span>
315
+ {asking.includes(step.sessionID) && <span class="commit-badge">The agent asks you something</span>}
316
+ <button type="button" class="ghost" onClick={() => onOpen(step.sessionID)}>
317
+ Open in chat
318
+ </button>
319
+ <button type="button" class="ghost" onClick={skipReview} title="Commit without a review">
320
+ Skip review
321
+ </button>
322
+ </div>
323
+ </section>
324
+ )}
325
+
326
+ {step.name === 'reviewed' && (
327
+ <section class="commit">
328
+ <div class="commit-row">
329
+ <Icon name={step.sessionID ? 'sparkle' : 'warning'} size={16} />
330
+ <span class="commit-text">
331
+ <strong>{step.sessionID ? 'Review' : 'Not reviewed'}</strong>
332
+ {!step.sessionID && <span class="muted">The review was skipped.</span>}
333
+ </span>
334
+ {step.sessionID && (
335
+ <button type="button" class="ghost" onClick={() => onOpen(step.sessionID!)}>
336
+ Open in chat
337
+ </button>
338
+ )}
339
+ </div>
340
+ {step.failed && <p class="note error">{step.failed}</p>}
341
+ {step.summary && (
342
+ <div class="review-summary">
343
+ <Prose text={step.summary} />
344
+ </div>
345
+ )}
346
+ <div class="commit-label">
347
+ <label for="commit-message">Commit message</label>
348
+ <button type="button" class="ghost" onClick={() => void suggest()} disabled={working !== ''} title={modelName ? `Written by ${modelName} from the diff` : 'Written from the diff'}>
349
+ <Icon name="sparkle" size={13} />
350
+ {working === 'suggesting' ? 'Writing…' : 'Suggest'}
351
+ </button>
352
+ </div>
353
+ <textarea
354
+ id="commit-message"
355
+ class="commit-message"
356
+ rows={2}
357
+ value={message}
358
+ placeholder="What these changes do, in one line"
359
+ onInput={(event: Event) => setMessage((event.target as HTMLTextAreaElement).value)}
360
+ onKeyDown={(event: KeyboardEvent) => {
361
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) void commit();
362
+ }}
363
+ />
364
+ <div class="commit-actions">
365
+ {step.sessionID && (
366
+ <button type="button" onClick={() => void fix()} title="The agent fixes what the review found; commit again after it">
367
+ Fix with agent
368
+ </button>
369
+ )}
370
+ <button type="button" class="ghost" onClick={cancel}>
371
+ Cancel
372
+ </button>
373
+ <button type="button" class="primary" onClick={() => void commit()} disabled={!message.trim() || working !== ''} title="Ctrl+Enter">
374
+ {working === 'committing' ? 'Committing…' : 'Commit'}
375
+ </button>
376
+ </div>
377
+ </section>
378
+ )}
379
+
380
+ {committed && (
381
+ <p class="note good" onClick={() => setCommitted('')}>
382
+ <Icon name="check" size={14} />
383
+ Committed {committed}
384
+ </p>
385
+ )}
386
+ {error && <p class="note error">{error}</p>}
387
+ {!loading && !diffs.length && !error && (
388
+ <p class="hint changes-empty">{view === 'working' ? 'Nothing uncommitted: the working tree is clean.' : sessionID ? 'The agent’s last turn changed no files.' : 'Open a conversation to see what its last turn changed.'}</p>
389
+ )}
390
+ {diffs.length > 0 && (
391
+ <div class="changes-body" style={listSplit.width ? `--list-width: ${listSplit.width}px` : undefined}>
392
+ <div class="changes-list">
393
+ <ul class="changed-files">
394
+ {diffs.map((diff) => (
395
+ <li>
396
+ <button type="button" class={`changed-file${shown?.file === diff.file ? ' on' : ''}`} onClick={() => setPicked(diff.file)} title={diff.file}>
397
+ <span class={`status-letter ${diff.status}`}>{STATUS_LETTER[diff.status]}</span>
398
+ <span class="changed-name">{projectPath(diff.file, subpath)}</span>
399
+ <span class="changed-count">
400
+ <span class="add">+{diff.additions}</span> <span class="del">−{diff.deletions}</span>
401
+ </span>
402
+ </button>
403
+ </li>
404
+ ))}
405
+ </ul>
406
+ <div {...listSplit.divider} />
407
+ </div>
408
+ <section class="diff-pane">
409
+ {shown && (
410
+ <>
411
+ <div class="diff-pane-head">{projectPath(shown.file, subpath)}</div>
412
+ <Patch diff={shown} />
413
+ </>
414
+ )}
415
+ </section>
416
+ </div>
417
+ )}
418
+ </div>
419
+ );
420
+ }
package/ui/code.tsx ADDED
@@ -0,0 +1,194 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ import type { FileSystemEntry } from '@opencode/client';
3
+ import { useEffect, useRef, useState } from 'hono/jsx/dom';
4
+ import { createEditor, type CodeEditor } from './editor.js';
5
+ import { Icon } from './icons.js';
6
+ import { client, errorText, location_ } from './shared.js';
7
+ import { useSplit } from './splitter.js';
8
+
9
+ /** `src\views\` as `src/views`: OpenCode answers with the platform's separators and a slash after a folder. */
10
+ const clean = (path: string) => path.replace(/\\/g, '/').replace(/\/$/, '');
11
+ const name = (path: string) => path.slice(path.lastIndexOf('/') + 1);
12
+ /** Folders first, then by name. */
13
+ const ordered = (entries: FileSystemEntry[]) => [...entries].sort((a, b) => (a.type === b.type ? clean(a.path).localeCompare(clean(b.path)) : a.type === 'directory' ? -1 : 1));
14
+
15
+ /** Files bigger than this open read-only: a textarea is no place for them. */
16
+ const EDITABLE = 1_000_000;
17
+
18
+ interface OpenFile {
19
+ path: string;
20
+ text: string;
21
+ saved: string;
22
+ readOnly?: string;
23
+ }
24
+
25
+ /**
26
+ * The project's files: a tree read folder by folder, a search by name, and an editor that saves through OpenCode.
27
+ * `refresh` changes when files changed on disk (the agent's edits): the tree and an unedited open file are read again.
28
+ */
29
+ export function CodePanel({ refresh, onAsk }: { refresh: number; onAsk: (text: string) => void }) {
30
+ const [folders, setFolders] = useState<Record<string, FileSystemEntry[]>>({});
31
+ const [expanded, setExpanded] = useState<string[]>(['']);
32
+ const [open, setOpen] = useState<OpenFile | undefined>();
33
+ const [query, setQuery] = useState('');
34
+ const [found, setFound] = useState<FileSystemEntry[] | undefined>();
35
+ const [error, setError] = useState('');
36
+ const [saving, setSaving] = useState(false);
37
+ const host = useRef<HTMLDivElement>(null);
38
+ const treeSplit = useSplit('code-tree', 160, () => window.innerWidth * 0.5, () => host.current?.closest('.code')?.querySelector('.files'));
39
+ const editor = useRef<CodeEditor | undefined>(undefined);
40
+ const shown = useRef<{ path: string; readOnly: boolean } | undefined>(undefined);
41
+
42
+ const list = async (folder: string) => {
43
+ try {
44
+ const result = await client.file.list({ location: location_, ...(folder ? { path: folder } : {}) });
45
+ setFolders((all) => ({ ...all, [folder]: ordered(result.data) }));
46
+ } catch (failure) {
47
+ setError(errorText(failure));
48
+ }
49
+ };
50
+ const read = async (path: string): Promise<OpenFile> => {
51
+ const bytes = await client.file.read({ location: location_, path });
52
+ if (bytes.subarray(0, 8000).includes(0)) return { path, text: '', saved: '', readOnly: 'A binary file: it is not shown here.' };
53
+ const text = new TextDecoder().decode(bytes);
54
+ return { path, text, saved: text, readOnly: bytes.length > EDITABLE ? 'Too big to edit here: it is shown read-only.' : undefined };
55
+ };
56
+ const show = async (path: string) => {
57
+ if (open && open.text !== open.saved && !confirm(`Leave ${open.path} without saving?`)) return;
58
+ setError('');
59
+ try {
60
+ setOpen(await read(path));
61
+ } catch (failure) {
62
+ setError(errorText(failure));
63
+ }
64
+ };
65
+ const save = async () => {
66
+ if (!open || open.readOnly || open.text === open.saved) return;
67
+ setSaving(true);
68
+ const { path, text } = open;
69
+ // What was written is what is saved; typing on meanwhile stays unsaved (and in the editor).
70
+ const saved = () => {
71
+ setOpen((current) => (current?.path === path ? { ...current, saved: text } : current));
72
+ setError('');
73
+ };
74
+ try {
75
+ await client.file.write({ location: location_, path, payload: new TextEncoder().encode(text) });
76
+ saved();
77
+ } catch (failure) {
78
+ // Saving a source file restarts the app, whose proxy may drop the answer: the file says whether it was saved.
79
+ const stored = await read(path).catch(() => undefined);
80
+ if (stored?.text === text) saved();
81
+ else setError(errorText(failure));
82
+ }
83
+ setSaving(false);
84
+ };
85
+
86
+ // Ctrl+S in the editor runs the save of the latest render (it knows the text as it is now).
87
+ const latestSave = useRef(save);
88
+ latestSave.current = save;
89
+ useEffect(() => {
90
+ if (!host.current) return;
91
+ editor.current = createEditor(
92
+ host.current,
93
+ (text) => setOpen((current) => current && { ...current, text }),
94
+ () => void latestSave.current(),
95
+ );
96
+ return () => editor.current?.destroy();
97
+ }, []);
98
+
99
+ // Another file opens anew (its own language and undo history); the same one read again from disk is replaced. Only
100
+ // then: edits made in the editor reach the state after it, so comparing on every keystroke would put an older text
101
+ // back under the cursor.
102
+ useEffect(() => {
103
+ const view = editor.current;
104
+ if (!view || !open) return;
105
+ const readOnly = Boolean(open.readOnly);
106
+ if (shown.current?.path !== open.path || shown.current.readOnly !== readOnly) {
107
+ shown.current = { path: open.path, readOnly };
108
+ view.open(open.path, open.text, readOnly);
109
+ } else if (open.text === open.saved && view.text() !== open.saved) view.replace(open.saved);
110
+ }, [open?.path, open?.saved, open?.readOnly]);
111
+
112
+ useEffect(() => {
113
+ for (const folder of expanded) void list(folder);
114
+ // A file the agent changed is read again, unless it has edits of yours.
115
+ if (open && open.text === open.saved) void read(open.path).then(setOpen, () => undefined);
116
+ }, [refresh]);
117
+
118
+ // A search by name, a moment after typing stops.
119
+ useEffect(() => {
120
+ if (!query.trim()) return setFound(undefined);
121
+ const timer = setTimeout(() => {
122
+ client.file
123
+ .find({ location: location_, query: query.trim(), type: 'file', limit: 50 })
124
+ .then((result) => setFound(result.data))
125
+ .catch((failure) => setError(errorText(failure)));
126
+ }, 250);
127
+ return () => clearTimeout(timer);
128
+ }, [query]);
129
+
130
+ const toggle = (folder: string) => {
131
+ if (expanded.includes(folder)) return setExpanded(expanded.filter((entry) => entry !== folder));
132
+ setExpanded([...expanded, folder]);
133
+ if (!folders[folder]) void list(folder);
134
+ };
135
+ const tree = (folder: string, depth: number): unknown =>
136
+ (folders[folder] ?? []).map((entry) => {
137
+ const path = clean(entry.path);
138
+ const isOpen = expanded.includes(path);
139
+ return entry.type === 'directory' ? (
140
+ <>
141
+ <button class="tree-item folder" style={`padding-left:${8 + depth * 14}px`} onClick={() => toggle(path)}>
142
+ <Icon name={isOpen ? 'chevronDown' : 'chevronRight'} size={13} class="caret" />
143
+ {name(path)}
144
+ </button>
145
+ {isOpen && tree(path, depth + 1)}
146
+ </>
147
+ ) : (
148
+ <button class={`tree-item${open?.path === path ? ' on' : ''}`} style={`padding-left:${22 + depth * 14}px`} onClick={() => show(path)}>
149
+ {name(path)}
150
+ </button>
151
+ );
152
+ });
153
+
154
+ const dirty = open ? open.text !== open.saved : false;
155
+ return (
156
+ <div class="code" style={treeSplit.width ? `--tree-width: ${treeSplit.width}px` : undefined}>
157
+ <aside class="files">
158
+ <input class="file-search" value={query} placeholder="Find a file" onInput={(event: Event) => setQuery((event.target as HTMLInputElement).value)} />
159
+ <div class="tree">
160
+ {found
161
+ ? found.length
162
+ ? found.map((entry) => (
163
+ <button class={`tree-item${open?.path === clean(entry.path) ? ' on' : ''}`} onClick={() => show(clean(entry.path))}>
164
+ {clean(entry.path)}
165
+ </button>
166
+ ))
167
+ : <p class="hint">No file by that name.</p>
168
+ : tree('', 0)}
169
+ </div>
170
+ <div {...treeSplit.divider} />
171
+ </aside>
172
+ <section class="editor">
173
+ {open ? (
174
+ <>
175
+ <header class="editor-head">
176
+ <span class="editor-path">
177
+ {open.path}
178
+ {dirty && <span class="dirty" title="Not saved" />}
179
+ </span>
180
+ <button class="ghost" title="Ask the agent about this file" onClick={() => onAsk(`In \`${open.path}\`: `)}>Ask agent</button>
181
+ <button class="primary" disabled={!dirty || saving || Boolean(open.readOnly)} onClick={save}>{saving ? 'Saving…' : 'Save'}</button>
182
+ </header>
183
+ {error && <p class="note error">{error}</p>}
184
+ {open.readOnly && <p class="note">{open.readOnly}</p>}
185
+ </>
186
+ ) : (
187
+ <p class="hint editor-empty">{error || 'Pick a file to read or edit it. Ctrl+S saves, Ctrl+F searches.'}</p>
188
+ )}
189
+ {/* The editor stays, hidden until a file opens: CodeMirror keeps its state in its own element. */}
190
+ <div class={`editor-host${open ? '' : ' hidden'}`} ref={host} />
191
+ </section>
192
+ </div>
193
+ );
194
+ }