@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/app.tsx ADDED
@@ -0,0 +1,862 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ import type { ModelInfo, OpenCodeEvent, PermissionRequest, SessionInfo, SessionMessageInfo } from '@opencode/client';
3
+ import { render, useEffect, useRef, useState } from 'hono/jsx/dom';
4
+ import { ChangesPanel, GitChip, gitState, type GitState } from './changes.js';
5
+ import { CodePanel } from './code.js';
6
+ import { Composer } from './composer.js';
7
+ import { Conversations } from './conversations.js';
8
+ import { ForgeChip } from './forge.js';
9
+ import { Icon } from './icons.js';
10
+ import { contextUsage, effortFor, lastTurn, mentionAttachment, modelKey, promptFiles, skillOrigin, slashInvocation, uploadAttachment, visibleMessages, type Attachment, type SlashOption } from './logic.js';
11
+ import { allowNotifications, notificationPermission, notificationsSupported, tell } from './notify.js';
12
+ import { LogsPanel } from './logs.js';
13
+ import { ModelPicker } from './model-picker.js';
14
+ import { Prose } from './prose.js';
15
+ import { Providers } from './providers.js';
16
+ import { QueuePanel } from './queue.js';
17
+ import { client, config, directory, errorText, location_, relative, repository } from './shared.js';
18
+ import { useSplit } from './splitter.js';
19
+ import { TerminalPanel } from './terminal.js';
20
+ import { ContextMeter } from './usage.js';
21
+ import { pageUrl } from './urls.js';
22
+
23
+ interface LastException {
24
+ exception: string;
25
+ message: string;
26
+ markdown: string;
27
+ time: string;
28
+ }
29
+
30
+ type Status = 'idle' | 'busy' | 'retry';
31
+
32
+ const TABS = [
33
+ ['preview', 'Preview'],
34
+ ['changes', 'Changes'],
35
+ ['code', 'Code'],
36
+ ['terminal', 'Terminal'],
37
+ ['logs', 'Logs'],
38
+ ['queue', 'Queue'],
39
+ ] as const;
40
+ type Tab = (typeof TABS)[number][0];
41
+
42
+ /** The agents to switch between when OpenCode has not listed them yet: its two primary ones. */
43
+ const PRIMARY_AGENTS = [
44
+ { id: 'build', name: 'build' },
45
+ { id: 'plan', name: 'plan' },
46
+ ];
47
+
48
+ const remembered = {
49
+ get: (key: string) => {
50
+ try {
51
+ return localStorage.getItem(`ranting-studio:${config.directory}:${key}`) ?? undefined;
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ },
56
+ set: (key: string, value: string | undefined) => {
57
+ try {
58
+ if (value === undefined) localStorage.removeItem(`ranting-studio:${config.directory}:${key}`);
59
+ else localStorage.setItem(`ranting-studio:${config.directory}:${key}`, value);
60
+ } catch {
61
+ // Private windows keep nothing: the page works without it.
62
+ }
63
+ },
64
+ };
65
+
66
+ /** The effort last chosen for each model, by `provider/model`. */
67
+ const rememberedEfforts = (): Record<string, string> => {
68
+ try {
69
+ return JSON.parse(remembered.get('efforts') ?? '{}') as Record<string, string>;
70
+ } catch {
71
+ return {};
72
+ }
73
+ };
74
+
75
+ /** What a tool call is about, in one line: its file, command, pattern or URL. */
76
+ function toolSubject(input: unknown): string {
77
+ if (!input || typeof input !== 'object') return typeof input === 'string' ? input.slice(0, 120) : '';
78
+ const record = input as Record<string, unknown>;
79
+ for (const key of ['filePath', 'path', 'command', 'pattern', 'url', 'query', 'description']) {
80
+ if (typeof record[key] === 'string') return relative(String(record[key])).slice(0, 160);
81
+ }
82
+ return '';
83
+ }
84
+
85
+ type AssistantPart = Extract<SessionMessageInfo, { type: 'assistant' }>['content'][number];
86
+
87
+ function ToolCall({ part }: { part: Extract<AssistantPart, { type: 'tool' }> }) {
88
+ const state = part.state;
89
+ const output = 'content' in state && state.content ? state.content.map((block) => (block.type === 'text' ? block.text : `[${block.mime}] ${block.name ?? block.uri.slice(0, 40)}`)).join('\n') : '';
90
+ const failed = state.status === 'error' ? state.error.message : '';
91
+ return (
92
+ <details class={`tool tool-${state.status}`}>
93
+ <summary>
94
+ <span class="tool-dot" />
95
+ <span class="tool-name">{part.name}</span>
96
+ <span class="tool-subject">{toolSubject(state.input)}</span>
97
+ </summary>
98
+ {state.status !== 'streaming' && <pre class="code">{JSON.stringify(state.input, null, 2)}</pre>}
99
+ {failed && <p class="tool-error">{failed}</p>}
100
+ {output && <pre class="code tool-output">{output.length > 6000 ? `${output.slice(0, 6000)}\n…` : output}</pre>}
101
+ </details>
102
+ );
103
+ }
104
+
105
+ /**
106
+ * A message of the user's: a long one (a command's prompt, which OpenCode keeps whole; a pasted log) shows its first
107
+ * lines until opened.
108
+ */
109
+ function UserText({ text }: { text: string }) {
110
+ const [open, setOpen] = useState(false);
111
+ const long = text.length > 800 || text.split('\n').length > 12;
112
+ if (!long) return <Prose text={text} />;
113
+ return (
114
+ <>
115
+ {open ? <Prose text={text} /> : <div class="user-preview">{text.split('\n').slice(0, 4).join('\n').slice(0, 320)}</div>}
116
+ <button type="button" class="ghost user-toggle" onClick={() => setOpen(!open)}>
117
+ <Icon name={open ? 'chevronUp' : 'chevronDown'} size={13} />
118
+ {open ? 'Show less' : `Show all (${text.split('\n').length} lines)`}
119
+ </button>
120
+ </>
121
+ );
122
+ }
123
+
124
+ function Message({ message, streaming }: { message: SessionMessageInfo; streaming?: string }) {
125
+ switch (message.type) {
126
+ case 'user':
127
+ return (
128
+ <div class="message user">
129
+ {message.files?.length ? (
130
+ <div class="thumbs">
131
+ {message.files.map((file) =>
132
+ file.mime.startsWith('image/') && file.data ? (
133
+ <img src={`data:${file.mime};base64,${file.data}`} alt={file.name ?? ''} />
134
+ ) : (
135
+ <span class="sent-file">
136
+ <Icon name={file.mention ? 'at' : 'file'} size={13} />
137
+ {file.name ?? file.mime}
138
+ </span>
139
+ ),
140
+ )}
141
+ </div>
142
+ ) : null}
143
+ <UserText text={message.text} />
144
+ </div>
145
+ );
146
+ case 'assistant': {
147
+ const text = message.content.filter((part) => part.type === 'text').map((part) => part.text).join('');
148
+ const live = streaming && streaming.length > text.length ? streaming : undefined;
149
+ return (
150
+ <div class="message assistant">
151
+ {message.content.map((part) => {
152
+ if (part.type === 'reasoning') return part.text.trim() ? <details class="reasoning"><summary>Thinking</summary><Prose text={part.text} /></details> : null;
153
+ if (part.type === 'tool') return <ToolCall part={part} />;
154
+ return live ? null : <Prose text={part.text} />;
155
+ })}
156
+ {live && <Prose text={live} />}
157
+ {message.error && <p class="note error">{message.error.message}</p>}
158
+ </div>
159
+ );
160
+ }
161
+ case 'shell':
162
+ return <div class="note">Shell command run in the session</div>;
163
+ case 'agent-switched':
164
+ return <div class="divider">Agent: {message.agent}</div>;
165
+ case 'model-switched':
166
+ return <div class="divider">Model changed</div>;
167
+ case 'idle':
168
+ return message.error ? <p class="note error">{message.error.message}</p> : null;
169
+ case 'compaction':
170
+ return <div class="divider">Earlier messages summarized</div>;
171
+ default:
172
+ return null;
173
+ }
174
+ }
175
+
176
+ function Permission({ request, onReply }: { request: PermissionRequest; onReply: (decision: 'once' | 'always' | 'reject') => void }) {
177
+ return (
178
+ <div class="permission">
179
+ <div class="permission-head">
180
+ <strong>Allow {request.action}?</strong>
181
+ {request.message && <span>{request.message}</span>}
182
+ </div>
183
+ {request.resources.length > 0 && <pre class="code">{relative(request.resources.join('\n'))}</pre>}
184
+ <div class="permission-actions">
185
+ <button class="primary" onClick={() => onReply('once')}>Allow once</button>
186
+ <button onClick={() => onReply('always')}>Always allow</button>
187
+ <button class="danger" onClick={() => onReply('reject')}>Reject</button>
188
+ </div>
189
+ </div>
190
+ );
191
+ }
192
+
193
+ function App() {
194
+ const [sessions, setSessions] = useState<SessionInfo[]>([]);
195
+ const [sessionID, setSessionID] = useState<string | undefined>(remembered.get('session'));
196
+ const [messages, setMessages] = useState<SessionMessageInfo[]>([]);
197
+ const [streaming, setStreaming] = useState<Record<string, string>>({});
198
+ const [statuses, setStatuses] = useState<Record<string, Status>>({});
199
+ const [permissions, setPermissions] = useState<PermissionRequest[]>([]);
200
+ const [models, setModels] = useState<ModelInfo[]>([]);
201
+ const [defaultModel, setDefaultModel] = useState<ModelInfo | undefined>();
202
+ const [providerNames, setProviderNames] = useState<Record<string, string>>({});
203
+ /** The model chosen (`provider/model`), else OpenCode's default answers. */
204
+ const [modelChoice, setModelChoice] = useState<string>(remembered.get('model') ?? '');
205
+ const [efforts, setEfforts] = useState<Record<string, string>>(rememberedEfforts());
206
+ const [agents, setAgents] = useState(PRIMARY_AGENTS);
207
+ const [agent, setAgent] = useState<string>(remembered.get('agent') ?? 'build');
208
+ const [draft, setDraft] = useState('');
209
+ const [attachments, setAttachments] = useState<Attachment[]>([]);
210
+ const [slashChoices, setSlashChoices] = useState<SlashOption[]>([]);
211
+ const [dragging, setDragging] = useState(false);
212
+ const [tab, setTab] = useState<Tab>('preview');
213
+ // Panels stay once opened (a file being edited, a running shell), shown or hidden.
214
+ const [opened, setOpened] = useState<Tab[]>(['preview']);
215
+ const [filesChanged, setFilesChanged] = useState(0);
216
+ const [git, setGit] = useState<GitState | undefined>();
217
+ const [forgeChanged, setForgeChanged] = useState(0);
218
+ const [exception, setException] = useState<LastException | undefined>();
219
+ const [dismissed, setDismissed] = useState(remembered.get('dismissed') ?? '');
220
+ const [error, setError] = useState('');
221
+ const [offline, setOffline] = useState(false);
222
+ const [showProviders, setShowProviders] = useState(false);
223
+ const [path, setPath] = useState(new URLSearchParams(location.search).get('path') || '/');
224
+ const [previewKey, setPreviewKey] = useState(0);
225
+ const current = useRef<string | undefined>(sessionID);
226
+ const sending = useRef(false);
227
+ // For the events' handler, which outlives renders: the conversations' titles, and whether to notify.
228
+ const sessionsSeen = useRef<SessionInfo[]>([]);
229
+ const [notifying, setNotifying] = useState(remembered.get('notify') === 'on' && notificationPermission() === 'granted');
230
+ const notifyOn = useRef(notifying);
231
+ notifyOn.current = notifying;
232
+ const scroller = useRef<HTMLDivElement>(null);
233
+ // The chat column's width, dragged by the divider on its right edge (the stage keeps 420px at least).
234
+ const chatSplit = useSplit('chat', 300, () => window.innerWidth - 420, () => document.querySelector('aside.chat'));
235
+ current.current = sessionID;
236
+
237
+ const loadSessions = async () =>
238
+ client.session
239
+ .list({ directory: await directory, limit: 50, order: 'desc' })
240
+ .then((result) => {
241
+ setSessions(result.data);
242
+ setOffline(false);
243
+ })
244
+ .catch((failure) => {
245
+ setOffline(true);
246
+ setError(errorText(failure));
247
+ });
248
+ const loadMessages = async (id = current.current) => {
249
+ if (!id) return setMessages([]);
250
+ try {
251
+ const result = await client.message.list({ sessionID: id, limit: 200, order: 'asc' });
252
+ if (id === current.current) setMessages(result.data);
253
+ } catch (failure) {
254
+ setError(errorText(failure));
255
+ }
256
+ };
257
+ const loadPermissions = () =>
258
+ client.permission.request
259
+ .list({ location: location_ })
260
+ .then((result) => setPermissions(result.data))
261
+ .catch(() => undefined);
262
+ const loadModels = () => {
263
+ client.model
264
+ .list({ location: location_ })
265
+ // Chat models: those typed so, and those of providers that give no type (Claude Agent's).
266
+ .then((result) => setModels(result.data.filter((entry) => (entry.type ?? 'chat') === 'chat' && entry.enabled && entry.status !== 'deprecated')))
267
+ .catch(() => undefined);
268
+ client.model
269
+ .default({ location: location_ })
270
+ .then((result) => setDefaultModel(result.data ?? undefined))
271
+ .catch(() => undefined);
272
+ client.provider
273
+ .list({ location: location_ })
274
+ .then((result) => setProviderNames(Object.fromEntries(result.data.map((provider) => [provider.id, provider.name]))))
275
+ .catch(() => undefined);
276
+ };
277
+ // OpenCode answers a location it has not opened yet with no agents; asked again, it lists them.
278
+ const loadAgents = (tries = 5) =>
279
+ client.agent
280
+ .list({ location: location_ })
281
+ .then((result) => {
282
+ const primary = result.data.filter((entry) => entry.mode !== 'subagent' && !entry.hidden).map((entry) => ({ id: entry.id, name: entry.name }));
283
+ if (primary.length) setAgents(primary);
284
+ else if (tries > 1) setTimeout(() => loadAgents(tries - 1), 1500);
285
+ })
286
+ .catch(() => undefined);
287
+ const loadGit = () => void gitState().then(setGit);
288
+ const patchSession = (id: string, change: Partial<SessionInfo>) => setSessions((all) => all.map((entry) => (entry.id === id ? { ...entry, ...change } : entry)));
289
+ // What a `/` offers: OpenCode's commands, and the skills it found (the project's, those above it, the user's, its own).
290
+ const loadSlash = () =>
291
+ void Promise.all([client.command.list({ location: location_ }), client.skill.list({ location: location_ }), directory, repository])
292
+ .then(([commands, skills, root, repo]) =>
293
+ setSlashChoices([
294
+ ...commands.data.map((command): SlashOption => ({ kind: 'command', token: command.name, title: command.name, description: command.description ?? '' })),
295
+ ...skills.data.map((skill): SlashOption => ({ kind: 'skill', token: skill.id, title: skill.name, description: skill.description ?? '', origin: skillOrigin(skill.path, root, repo) })),
296
+ ]),
297
+ )
298
+ .catch(() => undefined);
299
+
300
+ useEffect(() => {
301
+ void loadSessions();
302
+ void loadPermissions();
303
+ loadModels();
304
+ void loadAgents();
305
+ loadGit();
306
+ loadSlash();
307
+ }, []);
308
+
309
+ // Another conversation: its messages, and the agent, model and effort it runs with.
310
+ useEffect(() => {
311
+ remembered.set('session', sessionID);
312
+ setStreaming({});
313
+ void loadMessages(sessionID);
314
+ }, [sessionID]);
315
+ const session = sessions.find((entry) => entry.id === sessionID);
316
+ sessionsSeen.current = sessions;
317
+ useEffect(() => {
318
+ if (!session) return;
319
+ if (session.agent) setAgent(session.agent);
320
+ if (session.model) {
321
+ const key = `${session.model.providerID}/${session.model.id}`;
322
+ setModelChoice(key);
323
+ if (session.model.variant) setEfforts((all) => ({ ...all, [key]: session.model!.variant! }));
324
+ }
325
+ }, [session?.id]);
326
+
327
+ useEffect(() => {
328
+ const element = scroller.current;
329
+ if (element) element.scrollTop = element.scrollHeight;
330
+ }, [messages, streaming, permissions]);
331
+
332
+ // The app's last exception, asked for now and then.
333
+ useEffect(() => {
334
+ const check = () =>
335
+ fetch(`${config.api}/exception`)
336
+ .then((response) => response.json() as Promise<{ data: LastException | null }>)
337
+ .then((result) => setException(result.data ?? undefined))
338
+ .catch(() => undefined);
339
+ void check();
340
+ const timer = setInterval(check, 4000);
341
+ return () => clearInterval(timer);
342
+ }, []);
343
+
344
+ // OpenCode's events: text as it is written, tool calls, permission requests, runs starting and ending.
345
+ useEffect(() => {
346
+ const stop = new AbortController();
347
+ let refresh: ReturnType<typeof setTimeout> | undefined;
348
+ const soon = (what: () => unknown) => {
349
+ clearTimeout(refresh);
350
+ refresh = setTimeout(what, 150);
351
+ };
352
+ /** Word of a run to someone looking elsewhere: the tab's title, and a notification when they are on. */
353
+ const tellAbout = (id: string, label: string, body: string) => {
354
+ const title = sessionsSeen.current.find((entry) => entry.id === id)?.title || 'Studio';
355
+ tell(label, title, body, id, notifyOn.current, () => setSessionID(id));
356
+ };
357
+ const handle = (event: OpenCodeEvent) => {
358
+ const data = (event as { data?: { sessionID?: string } }).data;
359
+ const mine = data?.sessionID !== undefined && data.sessionID === current.current;
360
+ switch (event.type) {
361
+ case 'session.text.delta':
362
+ if (mine) setStreaming((all) => ({ ...all, [event.data.assistantMessageID]: (all[event.data.assistantMessageID] ?? '') + event.data.delta }));
363
+ return;
364
+ case 'session.execution.started':
365
+ setStatuses((all) => ({ ...all, [event.data.sessionID]: 'busy' }));
366
+ return;
367
+ case 'session.retry.scheduled':
368
+ setStatuses((all) => ({ ...all, [event.data.sessionID]: 'retry' }));
369
+ return;
370
+ // The run ended: what it wrote, what it changed, and the app as it is now.
371
+ case 'session.execution.succeeded':
372
+ case 'session.execution.failed':
373
+ case 'session.execution.interrupted':
374
+ setStatuses((all) => ({ ...all, [event.data.sessionID]: 'idle' }));
375
+ if (mine) {
376
+ void loadMessages().then(() => setStreaming({}));
377
+ setPreviewKey((key) => key + 1);
378
+ }
379
+ // Stopped by you: nothing to tell.
380
+ if (event.type === 'session.execution.succeeded') tellAbout(event.data.sessionID, 'Done', 'The agent is done.');
381
+ if (event.type === 'session.execution.failed') tellAbout(event.data.sessionID, 'Failed', 'The agent stopped on an error.');
382
+ setFilesChanged((count) => count + 1);
383
+ loadGit();
384
+ void loadSessions();
385
+ return;
386
+ case 'session.agent.selected':
387
+ patchSession(event.data.sessionID, { agent: event.data.agent });
388
+ if (mine) setAgent(event.data.agent);
389
+ return;
390
+ case 'session.model.selected':
391
+ patchSession(event.data.sessionID, { model: event.data.model });
392
+ return;
393
+ case 'permission.asked': {
394
+ void loadPermissions();
395
+ tellAbout(event.data.sessionID, 'Needs you', `The agent asks to ${event.data.action}: allow it or not.`);
396
+ return;
397
+ }
398
+ case 'permission.replied':
399
+ void loadPermissions();
400
+ return;
401
+ // An undo: the turn hidden (and its files put back), shown again, or gone for good.
402
+ case 'session.revert.staged':
403
+ patchSession(event.data.sessionID, { revert: event.data.revert });
404
+ if (mine) setFilesChanged((count) => count + 1);
405
+ return;
406
+ case 'session.revert.cleared':
407
+ patchSession(event.data.sessionID, { revert: undefined });
408
+ if (mine) setFilesChanged((count) => count + 1);
409
+ return;
410
+ case 'session.revert.committed':
411
+ patchSession(event.data.sessionID, { revert: undefined });
412
+ if (mine) void loadMessages();
413
+ return;
414
+ case 'session.created':
415
+ case 'session.renamed':
416
+ case 'session.deleted':
417
+ void loadSessions();
418
+ return;
419
+ case 'agent.updated':
420
+ void loadAgents(1);
421
+ return;
422
+ case 'model.updated':
423
+ case 'provider.updated':
424
+ case 'integration.updated':
425
+ loadModels();
426
+ return;
427
+ case 'vcs.branch.updated':
428
+ loadGit();
429
+ return;
430
+ // The forge's MCP server connected, failed or wants a sign-in.
431
+ case 'mcp.status.changed':
432
+ setForgeChanged((count) => count + 1);
433
+ return;
434
+ case 'filesystem.changed':
435
+ soon(() => (setFilesChanged((count) => count + 1), loadGit()));
436
+ return;
437
+ default:
438
+ if (mine && event.type.startsWith('session.')) soon(() => loadMessages());
439
+ }
440
+ };
441
+ const listen = async () => {
442
+ while (!stop.signal.aborted) {
443
+ try {
444
+ for await (const event of client.event.subscribe({ signal: stop.signal })) {
445
+ setOffline(false);
446
+ if (event.type === 'server.connected') {
447
+ void loadSessions();
448
+ void loadMessages();
449
+ void loadPermissions();
450
+ // The runs going on now (events of their start came before this connection).
451
+ client.session
452
+ .active()
453
+ .then((active) => setStatuses(Object.fromEntries(Object.keys(active).map((id) => [id, 'busy' as Status]))))
454
+ .catch(() => undefined);
455
+ } else handle(event);
456
+ }
457
+ } catch {
458
+ if (stop.signal.aborted) return;
459
+ setOffline(true);
460
+ }
461
+ await new Promise((resolve) => setTimeout(resolve, 2000));
462
+ }
463
+ };
464
+ void listen();
465
+ return () => stop.abort();
466
+ }, []);
467
+
468
+ const status = sessionID ? (statuses[sessionID] ?? 'idle') : 'idle';
469
+ // The model that answers: the one chosen (or the conversation's), else OpenCode's default; always named.
470
+ const model = models.find((entry) => modelKey(entry) === modelChoice) ?? defaultModel;
471
+ const effort = effortFor(model, efforts);
472
+ const modelRef = model ? { id: model.modelID, providerID: model.providerID, ...(effort ? { variant: effort } : {}) } : undefined;
473
+ const sessionPermissions = permissions.filter((request) => request.sessionID === sessionID);
474
+ // An undone turn stays hidden until it is redone or a new message makes the undo final.
475
+ const undoneFrom = session?.revert?.messageID;
476
+ const shown = visibleMessages(messages, undoneFrom);
477
+ const turn = lastTurn(shown);
478
+ const canUndo = Boolean(sessionID && turn && !undoneFrom && status === 'idle');
479
+ const usage = contextUsage(shown);
480
+ const usageModel = (usage?.model && models.find((entry) => entry.providerID === usage.model!.providerID && entry.modelID === usage.model!.id)) || model;
481
+
482
+ const send = async (text = draft, files = attachments) => {
483
+ if (!text.trim() && !files.length) return;
484
+ // What the message box holds goes only when it is what is sent (not an exception handed to the agent).
485
+ const fromComposer = files === attachments && text === draft;
486
+ // One send at a time: a second Enter while the conversation is being made would make another one.
487
+ if (sending.current) return;
488
+ sending.current = true;
489
+ setError('');
490
+ if (fromComposer) {
491
+ setDraft('');
492
+ setAttachments([]);
493
+ }
494
+ try {
495
+ let id = sessionID;
496
+ if (!id) {
497
+ const created = await client.session.create({ location: location_, agent, model: modelRef ?? null });
498
+ id = created.id;
499
+ current.current = id;
500
+ setSessionID(id);
501
+ void loadSessions();
502
+ }
503
+ // A new message after an undo makes it final: the undone turn goes for good.
504
+ if (id === sessionID && session?.revert) await client.session.revert.commit({ sessionID: id });
505
+ // `/name …`: a command run with the rest as its input, or a skill the agent must use. The agent picks skills
506
+ // itself either way.
507
+ const invocation = slashInvocation(
508
+ text,
509
+ slashChoices.filter((choice) => choice.kind === 'command').map((choice) => choice.token),
510
+ slashChoices.filter((choice) => choice.kind === 'skill').map((choice) => ({ id: choice.token, name: choice.title })),
511
+ );
512
+ if (invocation?.kind === 'command') {
513
+ // Its request lasts as long as the run, which the events show.
514
+ void client.session.command({ sessionID: id, name: invocation.name, text: invocation.rest, files: promptFiles(invocation.rest, files) }).catch((failure) => setError(errorText(failure)));
515
+ } else {
516
+ await client.session.prompt({ sessionID: id, text, files: promptFiles(text, files), ...(invocation ? { skills: [invocation.skill] } : {}) });
517
+ }
518
+ void loadMessages(id);
519
+ } catch (failure) {
520
+ setError(errorText(failure));
521
+ // Not sent: back in the box, unless something new was typed meanwhile.
522
+ if (fromComposer) {
523
+ setDraft((now) => now || text);
524
+ setAttachments((now) => (now.length ? now : files));
525
+ }
526
+ } finally {
527
+ sending.current = false;
528
+ }
529
+ };
530
+ /**
531
+ * Undo: the last message of yours and all that came of it hidden, and the files it changed put back as they were.
532
+ * Your message goes back in the box (when it is empty). Redo brings both back until a new message is sent.
533
+ */
534
+ const undo = async () => {
535
+ if (!sessionID || !turn || turn.type !== 'user') return;
536
+ try {
537
+ const revert = await client.session.revert.stage({ sessionID, messageID: turn.id, files: true });
538
+ patchSession(sessionID, { revert });
539
+ setDraft((now) => now || turn.text);
540
+ setFilesChanged((count) => count + 1);
541
+ setPreviewKey((key) => key + 1);
542
+ } catch (failure) {
543
+ setError(errorText(failure));
544
+ }
545
+ };
546
+ const redo = async () => {
547
+ if (!sessionID) return;
548
+ const undone = messages.find((message) => message.id === undoneFrom);
549
+ try {
550
+ await client.session.revert.clear({ sessionID });
551
+ patchSession(sessionID, { revert: undefined });
552
+ if (undone?.type === 'user') setDraft((now) => (now === undone.text ? '' : now));
553
+ setFilesChanged((count) => count + 1);
554
+ setPreviewKey((key) => key + 1);
555
+ } catch (failure) {
556
+ setError(errorText(failure));
557
+ }
558
+ };
559
+ const compact = () => sessionID && client.session.compact({ sessionID }).then(() => loadMessages()).catch((failure) => setError(errorText(failure)));
560
+ /** The bell: notifications of the browser on (asked for once) or off. */
561
+ const toggleNotifications = async () => {
562
+ if (notifying) {
563
+ setNotifying(false);
564
+ remembered.set('notify', undefined);
565
+ return;
566
+ }
567
+ if (await allowNotifications()) {
568
+ setNotifying(true);
569
+ remembered.set('notify', 'on');
570
+ } else {
571
+ setError('The browser blocks notifications for this page: allow them in its site settings, then click the bell again.');
572
+ }
573
+ };
574
+ /** Text put in front of what the message box holds, for the user to finish (a file to ask about). */
575
+ const prefill = (text: string) => {
576
+ setDraft((current) => (current ? `${text}${current}` : text));
577
+ requestAnimationFrame(() => {
578
+ const field = document.querySelector<HTMLTextAreaElement>('.composer textarea');
579
+ if (field) (field.focus(), (field.selectionStart = field.selectionEnd = field.value.length));
580
+ });
581
+ };
582
+ const openTab = (next: Tab) => {
583
+ setTab(next);
584
+ setOpened((all) => (all.includes(next) ? all : [...all, next]));
585
+ };
586
+ const interrupt = () => sessionID && client.session.interrupt({ sessionID }).catch((failure) => setError(errorText(failure)));
587
+ const reply = (request: PermissionRequest, decision: 'once' | 'always' | 'reject') =>
588
+ client.permission
589
+ .reply({ sessionID: request.sessionID, requestID: request.id, decision })
590
+ .then(loadPermissions)
591
+ .catch((failure) => setError(errorText(failure)));
592
+ const chooseAgent = (id: string) => {
593
+ setAgent(id);
594
+ remembered.set('agent', id);
595
+ if (sessionID) void client.session.switchAgent({ sessionID, agent: id }).catch((failure) => setError(errorText(failure)));
596
+ };
597
+ const switchModel = (ref: NonNullable<typeof modelRef>) => sessionID && client.session.switchModel({ sessionID, model: ref }).catch((failure) => setError(errorText(failure)));
598
+ const chooseModel = (entry: ModelInfo) => {
599
+ const key = modelKey(entry);
600
+ setModelChoice(key);
601
+ remembered.set('model', key);
602
+ const level = effortFor(entry, efforts);
603
+ void switchModel({ id: entry.modelID, providerID: entry.providerID, ...(level ? { variant: level } : {}) });
604
+ };
605
+ const chooseEffort = (level: string) => {
606
+ if (!model) return;
607
+ const next = { ...efforts, [modelKey(model)]: level };
608
+ setEfforts(next);
609
+ remembered.set('efforts', JSON.stringify(next));
610
+ void switchModel({ id: model.modelID, providerID: model.providerID, variant: level });
611
+ };
612
+ const removeSession = async (id: string) => {
613
+ await client.session.remove({ sessionID: id }).catch((failure) => setError(errorText(failure)));
614
+ if (id === sessionID) setSessionID(undefined);
615
+ void loadSessions();
616
+ };
617
+ const addFiles = (files: File[]) => {
618
+ for (const file of files) {
619
+ uploadAttachment(file, `${file.name}:${file.size}:${file.lastModified}:${Math.random()}`)
620
+ .then((attachment) => setAttachments((all) => [...all, attachment]))
621
+ .catch((failure) => setError(errorText(failure)));
622
+ }
623
+ };
624
+ const addMention = async (path: string, folder: boolean) => {
625
+ const attachment = mentionAttachment(await directory, path, folder);
626
+ setAttachments((all) => (all.some((entry) => entry.id === attachment.id) ? all : [...all, attachment]));
627
+ };
628
+ const sendException = () => {
629
+ if (!exception) return;
630
+ void send(`Fix this exception the app just threw:\n\n${exception.markdown}`, []);
631
+ setDismissed(exception.time);
632
+ remembered.set('dismissed', exception.time);
633
+ };
634
+
635
+ const previewUrl = pageUrl(path, location.origin);
636
+ const showException = exception && exception.time !== dismissed;
637
+ const busy = Object.fromEntries(Object.entries(statuses).map(([id, state]) => [id, state !== 'idle']));
638
+ const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
639
+
640
+ return (
641
+ <div class="studio" style={chatSplit.width ? `--chat-width: ${chatSplit.width}px` : undefined}>
642
+ <aside
643
+ class={`chat${dragging ? ' dragging' : ''}`}
644
+ onDragOver={(event: DragEvent) => {
645
+ if (!hasFiles(event)) return;
646
+ event.preventDefault();
647
+ setDragging(true);
648
+ }}
649
+ onDragLeave={(event: DragEvent) => {
650
+ if (!(event.currentTarget as HTMLElement).contains(event.relatedTarget as Node)) setDragging(false);
651
+ }}
652
+ onDrop={(event: DragEvent) => {
653
+ if (!hasFiles(event)) return;
654
+ event.preventDefault();
655
+ setDragging(false);
656
+ addFiles(Array.from(event.dataTransfer?.files ?? []));
657
+ }}
658
+ >
659
+ <header class="chat-head">
660
+ <div class="brand">
661
+ <span class="mark" />
662
+ <span>Studio</span>
663
+ {config.appName && <span class="app-name">{config.appName}</span>}
664
+ </div>
665
+ <div class="chat-head-row">
666
+ <Conversations sessions={sessions} current={sessionID} busy={busy} models={models} onSelect={setSessionID} onNew={() => setSessionID(undefined)} onDelete={(id) => void removeSession(id)} />
667
+ <button type="button" class="icon-button" title="New conversation" aria-label="New conversation" onClick={() => setSessionID(undefined)}>
668
+ <Icon name="plus" />
669
+ </button>
670
+ {notificationsSupported && (
671
+ <button
672
+ type="button"
673
+ class={`icon-button${notifying ? ' on' : ''}`}
674
+ title={notifying ? 'Notifications on: the browser tells you when the agent is done or needs you while you are elsewhere. Click to turn them off.' : 'Notify me when the agent is done or needs me while I am elsewhere'}
675
+ aria-label={notifying ? 'Turn notifications off' : 'Turn notifications on'}
676
+ aria-pressed={String(notifying)}
677
+ onClick={() => void toggleNotifications()}
678
+ >
679
+ <Icon name={notifying ? 'bell' : 'bellOff'} />
680
+ </button>
681
+ )}
682
+ <button type="button" class="icon-button" title="AI providers" aria-label="AI providers" onClick={() => setShowProviders(true)}>
683
+ <Icon name="settings" />
684
+ </button>
685
+ </div>
686
+ </header>
687
+
688
+ <div class="messages" ref={scroller}>
689
+ {offline && (
690
+ <p class="note error">
691
+ No connection to OpenCode: the app is restarting, or <code>bunx ranting dev</code> is not running. Studio connects again by itself.
692
+ </p>
693
+ )}
694
+ {!sessionID && !offline && (
695
+ <div class="empty">
696
+ <h1>What should change?</h1>
697
+ <p>
698
+ The agent works in this project: it reads the code, edits files and runs commands, asking before it does anything risky. <strong>Plan</strong> talks it through first; attach screenshots or files, or type <code>@</code> to point at one.
699
+ </p>
700
+ </div>
701
+ )}
702
+ {shown.map((message) => (
703
+ <Message message={message} streaming={message.type === 'assistant' ? streaming[message.id] : undefined} />
704
+ ))}
705
+ {canUndo && (
706
+ <div class="turn-actions">
707
+ <button type="button" class="ghost" onClick={() => void undo()} title="Remove your last message and what the agent did for it, and put back the files it changed">
708
+ <Icon name="undo" size={14} />
709
+ Undo this turn
710
+ </button>
711
+ </div>
712
+ )}
713
+ {undoneFrom && session?.revert && (
714
+ <div class="undone">
715
+ <Icon name="undo" size={16} />
716
+ <div class="undone-text">
717
+ <strong>Turn undone</strong>
718
+ <span>
719
+ {session.revert.files?.length
720
+ ? `${session.revert.files.length === 1 ? '1 file' : `${session.revert.files.length} files`} put back: ${session.revert.files.map((file) => file.file.split('/').pop()).join(', ')}.`
721
+ : 'It changed no files.'}{' '}
722
+ Your message is back in the box; sending a message makes the undo final.
723
+ </span>
724
+ </div>
725
+ <button type="button" onClick={() => void redo()}>
726
+ <Icon name="redo" size={14} />
727
+ Redo
728
+ </button>
729
+ </div>
730
+ )}
731
+ {sessionPermissions.map((request) => (
732
+ <Permission request={request} onReply={(decision) => reply(request, decision)} />
733
+ ))}
734
+ {status !== 'idle' && (
735
+ <div class="working">
736
+ <span />
737
+ <span />
738
+ <span /> {status === 'retry' ? 'Retrying' : 'Working'}
739
+ </div>
740
+ )}
741
+ </div>
742
+
743
+ {showException && (
744
+ <div class="exception">
745
+ <div>
746
+ <strong>{exception.exception}</strong>
747
+ <span>{exception.message}</span>
748
+ </div>
749
+ <div class="exception-actions">
750
+ <button class="primary" onClick={sendException}>
751
+ Send to agent
752
+ </button>
753
+ <button class="ghost" onClick={() => (setDismissed(exception.time), remembered.set('dismissed', exception.time))}>
754
+ Dismiss
755
+ </button>
756
+ </div>
757
+ </div>
758
+ )}
759
+ {error && (
760
+ <p class="note error toast" onClick={() => setError('')}>
761
+ {error}
762
+ </p>
763
+ )}
764
+
765
+ <Composer
766
+ draft={draft}
767
+ setDraft={setDraft}
768
+ attachments={attachments}
769
+ onRemove={(id) => setAttachments((all) => all.filter((entry) => entry.id !== id))}
770
+ onFiles={addFiles}
771
+ onMention={(path, folder) => void addMention(path, folder)}
772
+ model={model}
773
+ agents={agents}
774
+ agent={agent}
775
+ onAgent={chooseAgent}
776
+ busy={status !== 'idle'}
777
+ onSend={() => void send()}
778
+ onStop={interrupt}
779
+ remembered={remembered}
780
+ slashChoices={slashChoices}
781
+ onSlashOpen={loadSlash}
782
+ picker={
783
+ <>
784
+ <ContextMeter usage={usage} window={usageModel?.limit.context} modelName={usageModel?.name} session={session} onCompact={() => void compact()} />
785
+ <ModelPicker models={models} providerNames={providerNames} model={model} effort={effort} onModel={chooseModel} onEffort={chooseEffort} onProviders={() => setShowProviders(true)} />
786
+ </>
787
+ }
788
+ />
789
+ {dragging && (
790
+ <div class="drop-overlay">
791
+ <Icon name="upload" size={28} />
792
+ <span>Drop to attach</span>
793
+ </div>
794
+ )}
795
+ <div {...chatSplit.divider} />
796
+ </aside>
797
+
798
+ <main class="stage">
799
+ <nav class="tabs">
800
+ {TABS.map(([id, label]) => (
801
+ <button class={tab === id ? 'on' : ''} onClick={() => openTab(id)}>
802
+ {label}
803
+ </button>
804
+ ))}
805
+ {tab === 'preview' && (
806
+ <form
807
+ class="address"
808
+ onSubmit={(event: Event) => {
809
+ event.preventDefault();
810
+ setPreviewKey((key) => key + 1);
811
+ }}
812
+ >
813
+ <input value={path} onInput={(event: Event) => setPath((event.target as HTMLInputElement).value || '/')} aria-label="Page" />
814
+ <button type="submit" class="icon-button" title="Reload" aria-label="Reload">
815
+ <Icon name="refresh" />
816
+ </button>
817
+ <a class="icon-button" href={previewUrl} target="_blank" rel="noopener" title="Open in a tab" aria-label="Open in a tab">
818
+ <Icon name="external" />
819
+ </a>
820
+ </form>
821
+ )}
822
+ <GitChip git={git} onOpen={() => openTab('changes')} />
823
+ <ForgeChip refresh={forgeChanged} onTerminal={() => openTab('terminal')} />
824
+ </nav>
825
+ {tab === 'preview' && <iframe key={previewKey} class="preview" src={previewUrl} title="Preview" />}
826
+ {opened.includes('changes') && (
827
+ <div class={`panel${tab === 'changes' ? '' : ' hidden'}`}>
828
+ <ChangesPanel
829
+ sessionID={sessionID}
830
+ refresh={filesChanged}
831
+ git={git}
832
+ model={model}
833
+ effort={effort}
834
+ busy={busy}
835
+ asking={permissions.map((request) => request.sessionID)}
836
+ onOpen={(id) => (setSessionID(id), void loadSessions())}
837
+ onGitChanged={loadGit}
838
+ {...(canUndo ? { onUndo: () => void undo() } : {})}
839
+ {...(undoneFrom ? { onRedo: () => void redo() } : {})}
840
+ />
841
+ </div>
842
+ )}
843
+ {opened.includes('code') && (
844
+ <div class={`panel${tab === 'code' ? '' : ' hidden'}`}>
845
+ <CodePanel refresh={filesChanged} onAsk={prefill} />
846
+ </div>
847
+ )}
848
+ {opened.includes('terminal') && (
849
+ <div class={`panel${tab === 'terminal' ? '' : ' hidden'}`}>
850
+ <TerminalPanel visible={tab === 'terminal'} />
851
+ </div>
852
+ )}
853
+ {tab === 'logs' && <LogsPanel visible />}
854
+ {tab === 'queue' && <QueuePanel visible onAsk={(text) => void send(text, [])} />}
855
+ </main>
856
+
857
+ {showProviders && <Providers onClose={() => setShowProviders(false)} onChanged={loadModels} />}
858
+ </div>
859
+ );
860
+ }
861
+
862
+ render(<App />, document.getElementById('studio')!);