@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
@@ -0,0 +1,384 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ // The providers dialog: what is connected and how, a few popular providers to add, a search over all of them, and
3
+ // one provider at a time with its ways to connect (sign-in, the machine's login, an API key, an environment variable).
4
+ import type { IntegrationInfo } from '@opencode/client';
5
+ import { useEffect, useState } from 'hono/jsx/dom';
6
+ import { Icon } from './icons.js';
7
+ import { client, errorText, location_, waitForSignIn } from './shared.js';
8
+
9
+ /** The ones most people use, with what each gives; OpenCode lists every provider without telling. */
10
+ const POPULAR: [id: string, note: string][] = [
11
+ ['claude-agent', 'Your Claude subscription, through Claude Code’s login'],
12
+ ['anthropic', 'Claude models with an API key'],
13
+ ['openai', 'GPT models: ChatGPT sign-in or an API key'],
14
+ ['github-copilot', 'Your GitHub Copilot subscription'],
15
+ ['google', 'Gemini models with an API key'],
16
+ ['openrouter', 'Hundreds of models behind one key'],
17
+ ['xai', 'Grok models: SuperGrok or an API key'],
18
+ ['deepseek', 'DeepSeek models with an API key'],
19
+ ];
20
+
21
+ type Method = IntegrationInfo['methods'][number];
22
+ type Connection = IntegrationInfo['connections'][number];
23
+ type FormField = NonNullable<Extract<Method, { type: 'oauth' }>['form']>[number];
24
+ type Answer = Record<string, string | number | boolean | string[]>;
25
+
26
+ const connectionKind = (connection: Connection) =>
27
+ connection.type === 'env' ? 'environment variable' : connection.method === 'key' ? 'API key' : connection.method === 'oauth' ? 'sign-in' : 'login of this machine';
28
+
29
+ /** The fields of a form that apply with the answers given so far (`when` another field has a value). */
30
+ const shownFields = (form: FormField[] | undefined, answer: Answer) =>
31
+ (form ?? []).filter((field) => !('hidden' in field && field.hidden) && (!('when' in field) || !field.when || field.when.every((rule) => String(answer[rule.key]) === String(rule.value))));
32
+
33
+ /** Answers a form starts with: its defaults, the hidden fields' too. */
34
+ const defaults = (form: FormField[] | undefined): Answer =>
35
+ Object.fromEntries((form ?? []).flatMap((field) => ('default' in field && field.default !== undefined ? [[field.key, field.default as Answer[string]]] : [])));
36
+
37
+ function Fields({ form, answer, setAnswer }: { form: FormField[] | undefined; answer: Answer; setAnswer: (answer: Answer) => void }) {
38
+ return (
39
+ <>
40
+ {shownFields(form, answer).map((field) => {
41
+ if (field.type === 'external') {
42
+ return (
43
+ <a class="field-link" href={field.url} target="_blank" rel="noopener">
44
+ {field.title ?? field.url}
45
+ </a>
46
+ );
47
+ }
48
+ if (field.type === 'boolean') {
49
+ return (
50
+ <label class="field-check">
51
+ <input type="checkbox" checked={Boolean(answer[field.key])} onChange={(event: Event) => setAnswer({ ...answer, [field.key]: (event.target as HTMLInputElement).checked })} />
52
+ {field.title ?? field.key}
53
+ </label>
54
+ );
55
+ }
56
+ if (field.type === 'string' && field.options?.length) {
57
+ return (
58
+ <fieldset class="field-choice">
59
+ <legend>{field.title ?? field.key}</legend>
60
+ {field.options.map((option) => (
61
+ <label class={answer[field.key] === option.value ? 'on' : ''}>
62
+ <input type="radio" name={field.key} checked={answer[field.key] === option.value} onChange={() => setAnswer({ ...answer, [field.key]: option.value })} />
63
+ <span>{option.label ?? option.value}</span>
64
+ {option.description && <small>{option.description}</small>}
65
+ </label>
66
+ ))}
67
+ </fieldset>
68
+ );
69
+ }
70
+ return (
71
+ <label class="field-text">
72
+ <span>{field.title ?? field.key}</span>
73
+ <input
74
+ type={field.type === 'number' || field.type === 'integer' ? 'number' : 'text'}
75
+ value={String(answer[field.key] ?? '')}
76
+ placeholder={'placeholder' in field ? field.placeholder : undefined}
77
+ onInput={(event: Event) => setAnswer({ ...answer, [field.key]: (event.target as HTMLInputElement).value })}
78
+ />
79
+ </label>
80
+ );
81
+ })}
82
+ </>
83
+ );
84
+ }
85
+
86
+ /** One provider: its connections, then each way to connect it. */
87
+ function ProviderDetail({ integration, active, onBack, onChanged }: { integration: IntegrationInfo; active: Record<string, boolean>; onBack: () => void; onChanged: () => Promise<unknown> }) {
88
+ const [key, setKey] = useState('');
89
+ const [busy, setBusy] = useState(false);
90
+ const [error, setError] = useState('');
91
+ const [answers, setAnswers] = useState<Record<string, Answer>>({});
92
+ const [attempt, setAttempt] = useState<{ attemptID: string; url: string; instructions: string; paste: boolean } | undefined>();
93
+ const [code, setCode] = useState('');
94
+ const [others, setOthers] = useState(false);
95
+
96
+ const run = async (action: () => Promise<unknown>) => {
97
+ setBusy(true);
98
+ setError('');
99
+ try {
100
+ await action();
101
+ await onChanged();
102
+ } catch (failure) {
103
+ setError(errorText(failure));
104
+ }
105
+ setBusy(false);
106
+ };
107
+
108
+ // A sign-in in its own tab: done when OpenCode says so.
109
+ useEffect(() => {
110
+ if (!attempt || attempt.paste) return;
111
+ const wait = waitForSignIn(integration.id, attempt.attemptID);
112
+ void wait.done.then(async (failed) => {
113
+ if (failed) setError(failed);
114
+ setAttempt(undefined);
115
+ await onChanged();
116
+ });
117
+ return wait.stop;
118
+ }, [attempt]);
119
+
120
+ const signIn = (method: Extract<Method, { type: 'oauth' }>) =>
121
+ run(async () => {
122
+ const started = await client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, location: location_, answer: { ...defaults(method.form), ...answers[method.id] } as never });
123
+ window.open(started.data.url, '_blank', 'noopener');
124
+ setAttempt({ attemptID: started.data.attemptID, url: started.data.url, instructions: started.data.instructions, paste: started.data.mode === 'code' });
125
+ });
126
+ const remove = (connection: Extract<Connection, { type: 'credential' }>) => {
127
+ if (confirm(`Remove “${connection.label}” from OpenCode? Every project loses it.`)) void run(() => client.credential.remove({ credentialID: connection.id }));
128
+ };
129
+
130
+ const loggedIn = integration.connections.some((connection) => connection.type === 'credential' && connection.method === 'external');
131
+ const legacy = (method: Method) => 'label' in method && /legacy/i.test(method.label ?? '');
132
+ const methods = integration.methods.filter((method) => method.type !== 'env' && !legacy(method));
133
+ const older = integration.methods.filter(legacy);
134
+ const env = integration.methods.find((method): method is Extract<Method, { type: 'env' }> => method.type === 'env');
135
+
136
+ const render = (method: Method) => {
137
+ if (method.type === 'oauth') {
138
+ const answer = { ...defaults(method.form), ...answers[method.id] };
139
+ return (
140
+ <section class="method">
141
+ <h4>
142
+ <Icon name="login" /> {method.label}
143
+ </h4>
144
+ <Fields form={method.form} answer={answer} setAnswer={(next) => setAnswers({ ...answers, [method.id]: next })} />
145
+ <button class="primary" disabled={busy} onClick={() => signIn(method)}>
146
+ Sign in
147
+ </button>
148
+ <p class="hint">A sign-in page opens in a new tab.</p>
149
+ </section>
150
+ );
151
+ }
152
+ if (method.type === 'external') {
153
+ return (
154
+ <section class="method">
155
+ <h4>
156
+ <Icon name="terminal" /> {method.label}
157
+ </h4>
158
+ {loggedIn ? (
159
+ <p class="hint">
160
+ <Icon name="check" /> In use: this machine’s login is connected.
161
+ </p>
162
+ ) : (
163
+ <button class="primary" disabled={busy} onClick={() => run(() => client.integration.connect.external({ integrationID: integration.id, methodID: method.id, location: location_ }))}>
164
+ Use this login
165
+ </button>
166
+ )}
167
+ </section>
168
+ );
169
+ }
170
+ if (method.type === 'key') {
171
+ return (
172
+ <section class="method">
173
+ <h4>
174
+ <Icon name="key" /> {method.label ?? 'API key'}
175
+ </h4>
176
+ <form
177
+ class="row"
178
+ onSubmit={(event: Event) => {
179
+ event.preventDefault();
180
+ if (key.trim()) void run(() => client.integration.connect.key({ integrationID: integration.id, key: key.trim(), location: location_ }).then(() => setKey('')));
181
+ }}
182
+ >
183
+ <input type="password" autocomplete="off" value={key} placeholder={`${integration.name} API key`} onInput={(event: Event) => setKey((event.target as HTMLInputElement).value)} />
184
+ <button class="primary" type="submit" disabled={busy || !key.trim()}>
185
+ Save
186
+ </button>
187
+ </form>
188
+ </section>
189
+ );
190
+ }
191
+ if (method.type === 'command') {
192
+ return (
193
+ <section class="method">
194
+ <h4>
195
+ <Icon name="terminal" /> {method.label}
196
+ </h4>
197
+ <p class="hint">
198
+ Run <code>{method.command.join(' ')}</code> in a terminal.
199
+ </p>
200
+ </section>
201
+ );
202
+ }
203
+ return null;
204
+ };
205
+
206
+ return (
207
+ <div class="provider-detail">
208
+ <header class="dialog-head">
209
+ <button class="icon-button" onClick={onBack} aria-label="Back to providers">
210
+ <Icon name="chevronLeft" />
211
+ </button>
212
+ <h2>Connect {integration.name}</h2>
213
+ </header>
214
+ {error && <p class="note error">{error}</p>}
215
+ {integration.connections.length > 0 && (
216
+ <ul class="connections">
217
+ {integration.connections.map((connection) => (
218
+ <li>
219
+ <span class="connection-kind">{connectionKind(connection)}</span>
220
+ <span class="connection-label">{connection.type === 'env' ? <code>{connection.name}</code> : connection.label}</span>
221
+ {connection.type === 'credential' && active[connection.id] && <span class="connection-active">in use</span>}
222
+ {connection.status && <span class="connection-warning">{connection.status.message}</span>}
223
+ {connection.type === 'credential' && (
224
+ <button class="text-button danger" onClick={() => remove(connection)}>
225
+ Remove
226
+ </button>
227
+ )}
228
+ </li>
229
+ ))}
230
+ </ul>
231
+ )}
232
+ {attempt && (
233
+ <div class="attempt">
234
+ <p>{attempt.instructions || 'Finish signing in in the tab that opened.'}</p>
235
+ <a href={attempt.url} target="_blank" rel="noopener">
236
+ Open the sign-in page again <Icon name="external" size={13} />
237
+ </a>
238
+ {attempt.paste && (
239
+ <div class="row">
240
+ <input value={code} placeholder="Paste the code" onInput={(event: Event) => setCode((event.target as HTMLInputElement).value)} />
241
+ <button class="primary" disabled={!code.trim()} onClick={() => run(() => client.integration.oauth.complete({ integrationID: integration.id, attemptID: attempt.attemptID, code: code.trim(), location: location_ }).then(() => setAttempt(undefined)))}>
242
+ Connect
243
+ </button>
244
+ </div>
245
+ )}
246
+ </div>
247
+ )}
248
+ <div class="methods">{methods.map(render)}</div>
249
+ {older.length > 0 && (
250
+ <details class="other-methods" open={others} onToggle={(event: Event) => setOthers((event.target as HTMLDetailsElement).open)}>
251
+ <summary>Other ways</summary>
252
+ {older.map(render)}
253
+ </details>
254
+ )}
255
+ {env && (
256
+ <p class="hint env-hint">
257
+ Or set {env.names.map((name, index) => [index ? ' or ' : '', <code>{name}</code>])} in the app’s <code>.env</code> and restart <code>bunx ranting dev</code>.
258
+ </p>
259
+ )}
260
+ </div>
261
+ );
262
+ }
263
+
264
+ /** The dialog: connected providers, popular ones, a search over all; one provider at a time to connect it. */
265
+ export function Providers({ onClose, onChanged }: { onClose: () => void; onChanged: () => void }) {
266
+ const [integrations, setIntegrations] = useState<IntegrationInfo[]>([]);
267
+ const [active, setActive] = useState<Record<string, boolean>>({});
268
+ const [query, setQuery] = useState('');
269
+ const [chosen, setChosen] = useState<string | undefined>();
270
+ const [error, setError] = useState('');
271
+ const [loading, setLoading] = useState(true);
272
+
273
+ const load = () =>
274
+ Promise.all([
275
+ client.integration.list({ location: location_ }).then((result) => setIntegrations(result.data)),
276
+ client.credential.list().then((entries) => setActive(Object.fromEntries(entries.map((entry) => [entry.id, entry.active])))),
277
+ ])
278
+ .catch((failure) => setError(errorText(failure)))
279
+ .finally(() => setLoading(false));
280
+
281
+ // Logins of this machine taken more than once hold no secret, only the same login: all but the one in use go.
282
+ // API keys and sign-ins are never removed here.
283
+ const dropDuplicateLogins = async () => {
284
+ const [list, entries] = await Promise.all([client.integration.list({ location: location_ }), client.credential.list()]);
285
+ const inUse = new Set(entries.filter((entry) => entry.active).map((entry) => entry.id));
286
+ for (const integration of list.data) {
287
+ const logins = integration.connections.flatMap((connection) => (connection.type === 'credential' && connection.method === 'external' ? [connection.id] : []));
288
+ const keep = logins.find((id) => inUse.has(id)) ?? logins[0];
289
+ for (const id of logins) if (id !== keep) await client.credential.remove({ credentialID: id }).catch(() => undefined);
290
+ }
291
+ };
292
+ useEffect(() => {
293
+ void dropDuplicateLogins()
294
+ .catch(() => undefined)
295
+ .then(load);
296
+ }, []);
297
+ useEffect(() => {
298
+ const escape = (event: KeyboardEvent) => event.key === 'Escape' && (chosen ? setChosen(undefined) : onClose());
299
+ document.addEventListener('keydown', escape);
300
+ return () => document.removeEventListener('keydown', escape);
301
+ }, [chosen]);
302
+
303
+ const changed = async () => {
304
+ await load();
305
+ onChanged();
306
+ };
307
+ const byId = new Map(integrations.map((integration) => [integration.id, integration]));
308
+ const connected = integrations.filter((integration) => integration.connections.length > 0);
309
+ const popular = POPULAR.flatMap(([id, note]) => (byId.has(id) ? [{ integration: byId.get(id)!, note }] : []));
310
+ const term = query.trim().toLowerCase();
311
+ const found = term ? integrations.filter((integration) => integration.name.toLowerCase().includes(term) || integration.id.includes(term)) : [];
312
+ const selected = chosen ? byId.get(chosen) : undefined;
313
+
314
+ return (
315
+ <div class="overlay" onMouseDown={(event: Event) => event.target === event.currentTarget && onClose()}>
316
+ <div class="dialog providers-dialog" role="dialog" aria-label="AI providers">
317
+ {selected ? (
318
+ <ProviderDetail integration={selected} active={active} onBack={() => setChosen(undefined)} onChanged={changed} />
319
+ ) : (
320
+ <>
321
+ <header class="dialog-head">
322
+ <h2>AI providers</h2>
323
+ <button class="icon-button" onClick={onClose} aria-label="Close">
324
+ <Icon name="x" />
325
+ </button>
326
+ </header>
327
+ {error && <p class="note error">{error}</p>}
328
+ {loading && <p class="hint">Loading providers…</p>}
329
+ {connected.length > 0 && (
330
+ <section>
331
+ <h3 class="section-title">Connected</h3>
332
+ <ul class="provider-rows">
333
+ {connected.map((integration) => (
334
+ <li>
335
+ <button class="provider-row" onClick={() => setChosen(integration.id)}>
336
+ <span class="provider-row-name">{integration.name}</span>
337
+ <span class="provider-row-how">{[...new Set(integration.connections.map(connectionKind))].join(', ')}</span>
338
+ <Icon name="chevronRight" />
339
+ </button>
340
+ </li>
341
+ ))}
342
+ </ul>
343
+ </section>
344
+ )}
345
+ <section>
346
+ <h3 class="section-title">Add a provider</h3>
347
+ <div class="provider-tiles">
348
+ {popular.map(({ integration, note }) => (
349
+ <button class="provider-tile" onClick={() => setChosen(integration.id)}>
350
+ <span class="provider-tile-name">
351
+ {integration.name}
352
+ {integration.connections.length > 0 && <Icon name="check" size={14} class="tile-check" label="Connected" />}
353
+ </span>
354
+ <span class="provider-tile-note">{note}</span>
355
+ </button>
356
+ ))}
357
+ </div>
358
+ <label class="search-field">
359
+ <Icon name="search" />
360
+ <input value={query} placeholder={`Search all ${integrations.length || ''} providers`} onInput={(event: Event) => setQuery((event.target as HTMLInputElement).value)} />
361
+ </label>
362
+ {term && (
363
+ <ul class="provider-rows found">
364
+ {found.slice(0, 40).map((integration) => (
365
+ <li>
366
+ <button class="provider-row" onClick={() => setChosen(integration.id)}>
367
+ <span class="provider-row-name">{integration.name}</span>
368
+ {integration.connections.length > 0 && <span class="provider-row-how">connected</span>}
369
+ <Icon name="chevronRight" />
370
+ </button>
371
+ </li>
372
+ ))}
373
+ {!found.length && <li class="hint">No provider by that name.</li>}
374
+ {found.length > 40 && <li class="hint">Showing 40 of {found.length}: type more to narrow them.</li>}
375
+ </ul>
376
+ )}
377
+ </section>
378
+ <p class="hint dialog-foot">OpenCode keeps these in your user profile, for every project. Its free models need none.</p>
379
+ </>
380
+ )}
381
+ </div>
382
+ </div>
383
+ );
384
+ }
package/ui/queue.tsx ADDED
@@ -0,0 +1,89 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ import { useEffect, useState } from 'hono/jsx/dom';
3
+ import { errorText, studioApi } from './shared.js';
4
+
5
+ interface FailedJob {
6
+ id: string;
7
+ uuid: string;
8
+ name: string;
9
+ connection: string;
10
+ queue: string;
11
+ failedAt: string;
12
+ exception: string;
13
+ }
14
+
15
+ interface QueueState {
16
+ connection?: string;
17
+ size: number | null;
18
+ failed: FailedJob[];
19
+ }
20
+
21
+ /** The queue: how many jobs wait, and the failed ones, retried, forgotten or handed to the agent. */
22
+ export function QueuePanel({ visible, onAsk }: { visible: boolean; onAsk: (text: string) => void }) {
23
+ const [state, setState] = useState<QueueState | undefined>();
24
+ const [error, setError] = useState('');
25
+
26
+ const load = () =>
27
+ studioApi<QueueState>('queue')
28
+ .then((data) => {
29
+ setState(data);
30
+ setError('');
31
+ })
32
+ .catch((failure) => setError(errorText(failure)));
33
+ useEffect(() => {
34
+ if (!visible) return;
35
+ void load();
36
+ const timer = setInterval(load, 5000);
37
+ return () => clearInterval(timer);
38
+ }, [visible]);
39
+
40
+ const act = (path: string, method: string) =>
41
+ studioApi(path, { method })
42
+ .then(load)
43
+ .catch((failure) => setError(errorText(failure)));
44
+
45
+ const sync = state?.connection === 'sync';
46
+ return (
47
+ <div class="queue">
48
+ {error && <p class="note error">{error}</p>}
49
+ {state && (
50
+ <>
51
+ <div class="queue-summary">
52
+ <div>
53
+ <span class="queue-number">{state.size ?? '–'}</span>
54
+ <span>waiting on {state.connection ?? 'the default connection'}</span>
55
+ </div>
56
+ <div>
57
+ <span class="queue-number">{state.failed.length}</span>
58
+ <span>failed</span>
59
+ </div>
60
+ </div>
61
+ {sync && <p class="hint">With <code>QUEUE_CONNECTION=sync</code> jobs run at once, in the request: none wait.</p>}
62
+ {state.failed.length === 0 ? (
63
+ <p class="hint">No failed jobs.</p>
64
+ ) : (
65
+ state.failed.map((job) => (
66
+ <details class="failed-job">
67
+ <summary>
68
+ <span class="job-name">{job.name}</span>
69
+ <span class="job-where">
70
+ {job.connection}:{job.queue} · {new Date(job.failedAt).toLocaleString()}
71
+ </span>
72
+ <span class="job-error">{job.exception.split('\n')[0]}</span>
73
+ </summary>
74
+ <pre class="code">{job.exception}</pre>
75
+ <div class="job-actions">
76
+ <button class="primary" onClick={() => onAsk(`Fix why this queued job failed: ${job.name} on ${job.connection}:${job.queue}.\n\n\`\`\`\n${job.exception.slice(0, 8000)}\n\`\`\``)}>
77
+ Send to agent
78
+ </button>
79
+ <button onClick={() => act(`queue/failed/${encodeURIComponent(job.id)}/retry`, 'POST')}>Retry</button>
80
+ <button class="danger" onClick={() => act(`queue/failed/${encodeURIComponent(job.id)}`, 'DELETE')}>Forget</button>
81
+ </div>
82
+ </details>
83
+ ))
84
+ )}
85
+ </>
86
+ )}
87
+ </div>
88
+ );
89
+ }
package/ui/shared.ts ADDED
@@ -0,0 +1,74 @@
1
+ // What every panel of the page shares: the config the app put in it, the OpenCode client (through the app's proxy)
2
+ // and small helpers.
3
+ import { OpenCode } from '@opencode/client';
4
+
5
+ export interface Config {
6
+ appName?: string;
7
+ appUrl?: string;
8
+ base: string;
9
+ api: string;
10
+ opencode: string;
11
+ directory: string;
12
+ }
13
+
14
+ export const config = (window as unknown as { Studio: Config }).Studio;
15
+
16
+ /**
17
+ * fetch, waiting for the app to come back: it restarts when a source file changes (`bun --watch`), the agent's edits and
18
+ * the editor's saves included, and its proxy drops what it was answering. A read sent meanwhile is sent again, every
19
+ * half second for ten seconds; a write is not (it may have been done), its caller checks.
20
+ */
21
+ export async function patientFetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
22
+ const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
23
+ for (let attempt = 0; ; attempt++) {
24
+ try {
25
+ return await fetch(input, init);
26
+ } catch (error) {
27
+ if ((method !== 'GET' && method !== 'HEAD') || attempt >= 20 || init?.signal?.aborted) throw error;
28
+ await new Promise((resolve) => setTimeout(resolve, 500));
29
+ }
30
+ }
31
+ }
32
+
33
+ export const client = OpenCode.make({ baseUrl: location.origin + config.opencode, fetch: patientFetch as typeof fetch });
34
+ export const location_ = { directory: config.directory };
35
+
36
+ /** Where OpenCode works: the project's directory and the repository it is in. */
37
+ const located = client.location.get({ location: location_ }).catch(() => undefined);
38
+
39
+ /** The project's directory as OpenCode writes it (on Windows with a lower-case drive), which its filters compare exactly. */
40
+ export const directory = located.then((info) => info?.directory ?? config.directory);
41
+
42
+ /** The repository's root folder (git gives paths from it), or the project's own when it is not in one. */
43
+ export const repository = located.then((info) => info?.project.directory ?? config.directory);
44
+
45
+ const projectPath = new RegExp(config.directory.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
46
+ /** A path or text with the project's directory as `.`. */
47
+ export const relative = (text: string) => text.replace(projectPath, '.');
48
+
49
+ export const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));
50
+
51
+ /**
52
+ * A sign-in of OpenCode's in its own tab, waited for: done when OpenCode says so (every 2 s). Resolves with why it did
53
+ * not succeed, or nothing; `stop()` ends the wait.
54
+ */
55
+ export function waitForSignIn(integrationID: string, attemptID: string): { done: Promise<string | undefined>; stop: () => void } {
56
+ let timer: ReturnType<typeof setInterval> | undefined;
57
+ const done = new Promise<string | undefined>((resolve) => {
58
+ timer = setInterval(async () => {
59
+ const status = await client.integration.oauth.status({ integrationID, attemptID, location: location_ }).catch(() => undefined);
60
+ if (!status || status.data.status === 'pending') return;
61
+ clearInterval(timer);
62
+ resolve(status.data.status === 'failed' ? status.data.message : status.data.status === 'expired' ? 'The sign-in expired: start it again.' : undefined);
63
+ }, 2000);
64
+ });
65
+ return { done, stop: () => clearInterval(timer) };
66
+ }
67
+
68
+ /** Studio's own API (`/ranting-studio/api/...`): JSON in, its `data` out, its `message` thrown. */
69
+ export async function studioApi<T>(path: string, init?: RequestInit): Promise<T> {
70
+ const response = await patientFetch(`${config.api}/${path}`, { ...init, headers: { accept: 'application/json', ...init?.headers } });
71
+ const body = (await response.json().catch(() => ({}))) as { data?: T; message?: string };
72
+ if (!response.ok) throw new Error(body.message ?? `${response.status} ${response.statusText}`);
73
+ return body.data as T;
74
+ }
@@ -0,0 +1,70 @@
1
+ // A divider dragged to resize the pane before it; double-click puts it back. The width is kept per divider.
2
+ import { useState } from 'hono/jsx/dom';
3
+ import { config } from './shared.js';
4
+
5
+ const key = (name: string) => `ranting-studio:${config.directory}:width:${name}`;
6
+
7
+ function stored(name: string): number | undefined {
8
+ try {
9
+ return Number(localStorage.getItem(key(name))) || undefined;
10
+ } catch {
11
+ return undefined;
12
+ }
13
+ }
14
+
15
+ function store(name: string, width: number | undefined) {
16
+ try {
17
+ if (width === undefined) localStorage.removeItem(key(name));
18
+ else localStorage.setItem(key(name), String(Math.round(width)));
19
+ } catch {
20
+ // Private windows keep nothing: the pane keeps its width until the page reloads.
21
+ }
22
+ }
23
+
24
+ /**
25
+ * The width of a pane `name` (undefined: its CSS width) and the props of the divider after it, which drags it between
26
+ * `min` and `max` pixels (`max` may depend on the window). `pane` finds the pane's element when a drag starts.
27
+ */
28
+ export function useSplit(name: string, min: number, max: number | (() => number), pane: () => Element | null | undefined) {
29
+ const [width, setWidth] = useState<number | undefined>(stored(name));
30
+ const limit = (value: number) => Math.round(Math.max(min, Math.min(typeof max === 'function' ? max() : max, value)));
31
+
32
+ const divider = {
33
+ class: 'splitter',
34
+ role: 'separator',
35
+ 'aria-orientation': 'vertical',
36
+ title: 'Drag to resize · double-click to reset',
37
+ onDblClick: () => {
38
+ setWidth(undefined);
39
+ store(name, undefined);
40
+ },
41
+ onPointerDown: (event: PointerEvent) => {
42
+ const element = pane();
43
+ if (!element || event.button !== 0) return;
44
+ event.preventDefault();
45
+ const handle = event.currentTarget as HTMLElement;
46
+ handle.setPointerCapture(event.pointerId);
47
+ const startX = event.clientX;
48
+ const start = element.getBoundingClientRect().width;
49
+ // Frames (the preview) would take the pointer while it crosses them.
50
+ document.body.classList.add('resizing');
51
+ let last = start;
52
+ const move = (moved: PointerEvent) => {
53
+ last = limit(start + moved.clientX - startX);
54
+ setWidth(last);
55
+ };
56
+ const up = () => {
57
+ handle.removeEventListener('pointermove', move);
58
+ handle.removeEventListener('pointerup', up);
59
+ handle.removeEventListener('pointercancel', up);
60
+ document.body.classList.remove('resizing');
61
+ store(name, last);
62
+ };
63
+ handle.addEventListener('pointermove', move);
64
+ handle.addEventListener('pointerup', up);
65
+ handle.addEventListener('pointercancel', up);
66
+ },
67
+ };
68
+
69
+ return { width, divider };
70
+ }