@rantingjs/studio 0.0.0-stage → 0.1.1

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 +146 -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 +386 -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/logs.tsx ADDED
@@ -0,0 +1,87 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ import { useEffect, useRef, useState } from 'hono/jsx/dom';
3
+ import { errorText, studioApi } from './shared.js';
4
+
5
+ interface LogChunk {
6
+ file: string;
7
+ text: string;
8
+ offset: number;
9
+ reset: boolean;
10
+ }
11
+
12
+ /** The most of the log kept on the page. */
13
+ const KEEP = 400_000;
14
+ const LEVEL = /\.(EMERGENCY|ALERT|CRITICAL|ERROR|WARNING|NOTICE|INFO|DEBUG): /;
15
+ const levelClass = (level: string) => (['EMERGENCY', 'ALERT', 'CRITICAL', 'ERROR'].includes(level) ? 'error' : level === 'WARNING' ? 'warning' : level === 'DEBUG' ? 'debug' : 'info');
16
+
17
+ /** The app's log file as it is written (every process of `ranting dev` writes to it), filtered by a word. */
18
+ export function LogsPanel({ visible }: { visible: boolean }) {
19
+ const [text, setText] = useState('');
20
+ const [file, setFile] = useState<string | null | undefined>();
21
+ const [filter, setFilter] = useState('');
22
+ const [error, setError] = useState('');
23
+ const offset = useRef<number | undefined>(undefined);
24
+ const view = useRef<HTMLPreElement>(null);
25
+
26
+ useEffect(() => {
27
+ if (!visible) return;
28
+ let stopped = false;
29
+ const poll = async () => {
30
+ try {
31
+ const chunk = await studioApi<LogChunk | null>(`logs${offset.current === undefined ? '' : `?from=${offset.current}`}`);
32
+ if (stopped) return;
33
+ setError('');
34
+ setFile(chunk?.file ?? null);
35
+ if (!chunk) return;
36
+ offset.current = chunk.offset;
37
+ if (chunk.reset || chunk.text) {
38
+ const element = view.current;
39
+ const atBottom = !element || element.scrollHeight - element.scrollTop - element.clientHeight < 40;
40
+ setText((all) => (chunk.reset ? chunk.text : (all + chunk.text).slice(-KEEP)));
41
+ if (atBottom) requestAnimationFrame(() => view.current && (view.current.scrollTop = view.current.scrollHeight));
42
+ }
43
+ } catch (failure) {
44
+ setError(errorText(failure));
45
+ }
46
+ };
47
+ void poll();
48
+ const timer = setInterval(poll, 1500);
49
+ return () => {
50
+ stopped = true;
51
+ clearInterval(timer);
52
+ };
53
+ }, [visible]);
54
+
55
+ // A line without a level (a stack trace) belongs to the entry above it.
56
+ let level = 'info';
57
+ const lines = text.split('\n').filter((line, index, all) => line || index < all.length - 1);
58
+ const shown = lines
59
+ .map((line) => {
60
+ const match = LEVEL.exec(line);
61
+ if (match) level = levelClass(match[1]!);
62
+ return { line, level: match ? level : `${level} more` };
63
+ })
64
+ .filter(({ line }) => !filter || line.toLowerCase().includes(filter.toLowerCase()));
65
+
66
+ return (
67
+ <div class="logs">
68
+ <header class="logs-head">
69
+ <span class="logs-file">{file ?? (file === null ? 'No log file' : '…')}</span>
70
+ <input class="logs-filter" value={filter} placeholder="Filter" onInput={(event: Event) => setFilter((event.target as HTMLInputElement).value)} />
71
+ <button class="ghost" onClick={() => setText('')}>Clear view</button>
72
+ </header>
73
+ {error && <p class="note error">{error}</p>}
74
+ {file === null ? (
75
+ <p class="hint logs-empty">
76
+ The app logs to no file. Set <code>LOG_CHANNEL=single</code> (or <code>daily</code>, or a stack with one) to follow its log here.
77
+ </p>
78
+ ) : (
79
+ <pre class="logs-view" ref={view}>
80
+ {shown.map(({ line, level }) => (
81
+ <span class={`log-line ${level}`}>{line}{'\n'}</span>
82
+ ))}
83
+ </pre>
84
+ )}
85
+ </div>
86
+ );
87
+ }
@@ -0,0 +1,121 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ // The model and its effort, in one picker: the button says what answers ("Sonnet 5.5 · High"), the popover lists the
3
+ // models by provider with a search, and the effort levels of the one chosen.
4
+ import type { ModelInfo } from '@opencode/client';
5
+ import { useState } from 'hono/jsx/dom';
6
+ import { Icon } from './icons.js';
7
+ import { contextLabel, effortLabel, modelKey } from './logic.js';
8
+ import { Popover, useListKeys } from './popover.js';
9
+
10
+ /** A model whose every price is zero: OpenCode's free ones. A subscription's (no prices at all) is not "free". */
11
+ const free = (model: ModelInfo) => model.cost.length > 0 && model.cost.every((cost) => !cost.input && !cost.output);
12
+
13
+ /** What a provider's group says under its name. */
14
+ const providerNote = (models: ModelInfo[]) => (models.every(free) ? 'free' : '');
15
+
16
+ export function ModelPicker({
17
+ models,
18
+ providerNames,
19
+ model,
20
+ effort,
21
+ onModel,
22
+ onEffort,
23
+ onProviders,
24
+ }: {
25
+ models: ModelInfo[];
26
+ providerNames: Record<string, string>;
27
+ model: ModelInfo | undefined;
28
+ effort: string | undefined;
29
+ onModel: (model: ModelInfo) => void;
30
+ onEffort: (level: string) => void;
31
+ onProviders: () => void;
32
+ }) {
33
+ const [open, setOpen] = useState(false);
34
+ const [query, setQuery] = useState('');
35
+ const term = query.trim().toLowerCase();
36
+ const shown = models.filter((entry) => !term || `${entry.name} ${entry.modelID} ${providerNames[entry.providerID] ?? entry.providerID}`.toLowerCase().includes(term));
37
+ // By name, the free ones last.
38
+ const order = (providerID: string) => (shown.filter((entry) => entry.providerID === providerID).every(free) ? 1 : 0);
39
+ const groups = [...new Set(shown.map((entry) => entry.providerID))].sort((a, b) => order(a) - order(b) || a.localeCompare(b));
40
+ const flat = groups.flatMap((providerID) => shown.filter((entry) => entry.providerID === providerID));
41
+ const pick = (entry: ModelInfo) => {
42
+ onModel(entry);
43
+ setQuery('');
44
+ };
45
+ const keys = useListKeys(flat.length, (index) => flat[index] && pick(flat[index]));
46
+ const levels = model?.variants.map((variant) => variant.id) ?? [];
47
+
48
+ return (
49
+ <div class="anchor model-anchor">
50
+ <button type="button" class={`chip model-chip${open ? ' open' : ''}`} onClick={() => setOpen(!open)} title="Model and effort">
51
+ <Icon name="sparkle" size={14} />
52
+ <span class="chip-text">{model ? model.name : 'Choose a model'}</span>
53
+ {effort && <span class="chip-effort">{effortLabel(effort)}</span>}
54
+ <Icon name="chevronDown" size={14} />
55
+ </button>
56
+ <Popover open={open} onClose={() => setOpen(false)} placement="above-end" class="model-popover">
57
+ <label class="search-field">
58
+ <Icon name="search" />
59
+ <input value={query} placeholder="Search models" onInput={(event: Event) => setQuery((event.target as HTMLInputElement).value)} onKeyDown={keys.onKeyDown} />
60
+ </label>
61
+ <div class="popover-list">
62
+ {groups.map((providerID) => (
63
+ <div class="list-group">
64
+ <div class="list-group-title">
65
+ {providerNames[providerID] ?? providerID}
66
+ {providerNote(models.filter((entry) => entry.providerID === providerID)) && <span> · {providerNote(models.filter((entry) => entry.providerID === providerID))}</span>}
67
+ </div>
68
+ {shown
69
+ .filter((entry) => entry.providerID === providerID)
70
+ .map((entry) => {
71
+ const index = flat.indexOf(entry);
72
+ const selected = model && modelKey(model) === modelKey(entry);
73
+ return (
74
+ <button type="button" class={`list-row${selected ? ' selected' : ''}`} data-active={String(index === keys.active)} onMouseEnter={() => keys.setActive(index)} onClick={() => pick(entry)}>
75
+ <span class="row-check">{selected && <Icon name="check" size={14} />}</span>
76
+ <span class="row-main">{entry.name}</span>
77
+ <span class="row-meta">
78
+ {entry.capabilities.input.includes('image') && <Icon name="image" size={13} label="Reads images" />}
79
+ {entry.capabilities.input.includes('pdf') && <Icon name="file" size={13} label="Reads PDFs" />}
80
+ {entry.limit.context > 0 && <span title="Context window">{contextLabel(entry.limit.context)}</span>}
81
+ {free(entry) && <span class="badge">Free</span>}
82
+ </span>
83
+ </button>
84
+ );
85
+ })}
86
+ </div>
87
+ ))}
88
+ {!flat.length && <p class="hint popover-empty">No model by that name.</p>}
89
+ </div>
90
+ <div class="popover-foot">
91
+ <div class="effort-row">
92
+ <span class="effort-title" title="How much the model thinks before it answers">
93
+ Effort
94
+ </span>
95
+ {levels.length ? (
96
+ <div class="segmented small" role="radiogroup" aria-label="Effort">
97
+ {levels.map((level) => (
98
+ <button type="button" role="radio" aria-checked={String(level === effort)} class={level === effort ? 'on' : ''} onClick={() => onEffort(level)}>
99
+ {effortLabel(level)}
100
+ </button>
101
+ ))}
102
+ </div>
103
+ ) : (
104
+ <span class="hint">{model ? `${model.name} has no effort levels.` : 'Choose a model first.'}</span>
105
+ )}
106
+ </div>
107
+ <button
108
+ type="button"
109
+ class="text-button"
110
+ onClick={() => {
111
+ setOpen(false);
112
+ onProviders();
113
+ }}
114
+ >
115
+ <Icon name="settings" size={14} /> Manage providers
116
+ </button>
117
+ </div>
118
+ </Popover>
119
+ </div>
120
+ );
121
+ }
package/ui/notify.ts ADDED
@@ -0,0 +1,45 @@
1
+ // Word that the agent is done or needs an answer, for when Studio is not what you are looking at: the tab's title
2
+ // always, a notification of the browser when you have turned them on.
3
+
4
+ const title = document.title;
5
+
6
+ /** Studio is not what you look at: its tab hidden, or the focus in another window. */
7
+ const away = () => document.hidden || !document.hasFocus();
8
+
9
+ const back = () => {
10
+ if (!away()) document.title = title;
11
+ };
12
+ document.addEventListener('visibilitychange', back);
13
+ window.addEventListener('focus', back);
14
+
15
+ export const notificationsSupported = typeof Notification !== 'undefined';
16
+
17
+ /** The browser's answer so far: `granted`, `denied`, or `default` (not asked yet). */
18
+ export const notificationPermission = () => (notificationsSupported ? Notification.permission : 'denied');
19
+
20
+ /** Asks the browser (it shows its prompt once); true when notifications may be shown. */
21
+ export async function allowNotifications(): Promise<boolean> {
22
+ if (!notificationsSupported) return false;
23
+ return (await Notification.requestPermission()) === 'granted';
24
+ }
25
+
26
+ /**
27
+ * Says what happened while you were away: `(Done) …` in the tab's title until you come back, and a notification
28
+ * (one per conversation, replaced by the next) when they are on. A click on it brings Studio back on that conversation.
29
+ */
30
+ export function tell(label: string, heading: string, body: string, conversation: string, notify: boolean, open: () => void) {
31
+ if (!away()) return;
32
+ document.title = `(${label}) ${title}`;
33
+ if (!notify || notificationPermission() !== 'granted') return;
34
+ // A browser that cannot show one (some only from a service worker) keeps the title's word; the events go on.
35
+ try {
36
+ const note = new Notification(heading, { body, tag: conversation });
37
+ note.onclick = () => {
38
+ window.focus();
39
+ open();
40
+ note.close();
41
+ };
42
+ } catch {
43
+ // The title says it.
44
+ }
45
+ }
package/ui/page.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { join } from 'node:path';
2
+
3
+ const here = import.meta.dir;
4
+
5
+ async function build() {
6
+ const result = await Bun.build({ entrypoints: [join(here, 'app.tsx')], target: 'browser', minify: true, format: 'esm' });
7
+ if (!result.success) throw new AggregateError(result.logs, 'Building Studio failed');
8
+ const entry = result.outputs.find((output) => output.kind === 'entry-point') ?? result.outputs[0]!;
9
+ // The terminal's own styles, then Studio's.
10
+ const xterm = await Bun.file(Bun.resolveSync('@xterm/xterm/css/xterm.css', here)).text();
11
+ return { js: await entry.text(), css: xterm + (await Bun.file(join(here, 'styles.css')).text()) };
12
+ }
13
+
14
+ let cached: Promise<{ js: string; css: string }> | undefined;
15
+
16
+ /** Bundles the page once per process (a failed build is retried on the next call). */
17
+ export function buildUi() {
18
+ return (cached ??= build().catch((error) => {
19
+ cached = undefined;
20
+ throw error;
21
+ }));
22
+ }
23
+
24
+ /** The `compile` hook of the package's manifest: the page built at `ranting build --compile`. */
25
+ export default function compile() {
26
+ return buildUi();
27
+ }
package/ui/popover.tsx ADDED
@@ -0,0 +1,66 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ // The page's popovers: a panel beside its trigger, closed by a click elsewhere or Esc, with a list driven by the
3
+ // keyboard (↑ ↓ Enter).
4
+ import type { Child } from 'hono/jsx';
5
+ import { useEffect, useRef, useState } from 'hono/jsx/dom';
6
+
7
+ export type Placement = 'below-start' | 'below-end' | 'above-start' | 'above-end';
8
+
9
+ /**
10
+ * A panel for the trigger in the same `.anchor` element. Clicks outside that element and Esc close it.
11
+ */
12
+ export function Popover({ open, onClose, placement = 'below-start', class: className, children }: { open: boolean; onClose: () => void; placement?: Placement; class?: string; children: Child }) {
13
+ const panel = useRef<HTMLDivElement>(null);
14
+ useEffect(() => {
15
+ if (!open) return;
16
+ // Its search field takes the keys at once.
17
+ requestAnimationFrame(() => panel.current?.querySelector<HTMLInputElement>('input')?.focus());
18
+ const anchor = panel.current?.closest('.anchor');
19
+ const outside = (event: MouseEvent) => {
20
+ if (anchor && !anchor.contains(event.target as Node)) onClose();
21
+ };
22
+ const escape = (event: KeyboardEvent) => {
23
+ if (event.key === 'Escape') {
24
+ event.stopPropagation();
25
+ onClose();
26
+ }
27
+ };
28
+ document.addEventListener('mousedown', outside);
29
+ document.addEventListener('keydown', escape);
30
+ return () => {
31
+ document.removeEventListener('mousedown', outside);
32
+ document.removeEventListener('keydown', escape);
33
+ };
34
+ }, [open]);
35
+ if (!open) return null;
36
+ return (
37
+ <div ref={panel} class={`popover ${placement}${className ? ` ${className}` : ''}`} role="dialog">
38
+ {children}
39
+ </div>
40
+ );
41
+ }
42
+
43
+ /**
44
+ * A list picked with the keyboard: ↑ ↓ move, Enter picks, the active row stays in view. `count` is how many rows
45
+ * there are; the active one resets when they change.
46
+ */
47
+ export function useListKeys(count: number, pick: (index: number) => void) {
48
+ const [active, setActive] = useState(0);
49
+ useEffect(() => setActive(0), [count]);
50
+ useEffect(() => {
51
+ document.querySelector('.popover [data-active="true"]')?.scrollIntoView({ block: 'nearest' });
52
+ }, [active]);
53
+ const onKeyDown = (event: KeyboardEvent) => {
54
+ if (event.key === 'ArrowDown') {
55
+ event.preventDefault();
56
+ setActive((at) => Math.min(count - 1, at + 1));
57
+ } else if (event.key === 'ArrowUp') {
58
+ event.preventDefault();
59
+ setActive((at) => Math.max(0, at - 1));
60
+ } else if (event.key === 'Enter' && count > 0) {
61
+ event.preventDefault();
62
+ pick(active);
63
+ }
64
+ };
65
+ return { active, setActive, onKeyDown };
66
+ }
package/ui/prose.tsx ADDED
@@ -0,0 +1,50 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ // The agent's text as the page shows it: in the chat, and a review's summary above a commit.
3
+ import type { Child } from 'hono/jsx';
4
+
5
+ /** Text with ``` fences as code blocks, the rest as paragraphs (line breaks kept). */
6
+ export function Prose({ text }: { text: string }) {
7
+ const parts = text.split(/```[^\n]*\n?/);
8
+ return (
9
+ <div class="prose">
10
+ {parts.map((part, index) =>
11
+ index % 2 ? (
12
+ <pre class="code">{part.replace(/\n$/, '')}</pre>
13
+ ) : (
14
+ part
15
+ .split(/\n{2,}/)
16
+ .filter((paragraph) => paragraph.trim())
17
+ .map(block)
18
+ ),
19
+ )}
20
+ </div>
21
+ );
22
+ }
23
+
24
+ /** A paragraph: a `#` heading line first, a list of `-`/`*`/`1.` items, or text (line breaks kept). */
25
+ function block(paragraph: string): Child {
26
+ const lines = paragraph.replace(/^\n+|\n+$/g, '').split('\n');
27
+ const heading = /^#{1,6}\s+(.*)$/.exec(lines[0]!);
28
+ if (heading) return [<h4>{inline(heading[1]!)}</h4>, ...(lines.length > 1 ? [block(lines.slice(1).join('\n'))] : [])];
29
+ const item = /^\s*(?:[-*]|(\d+)\.)\s+(.*)$/;
30
+ const first = item.exec(lines[0]!);
31
+ if (!first) return <p>{inline(paragraph)}</p>;
32
+ // Items, each with the lines under it that start no item of their own.
33
+ const items: string[] = [];
34
+ for (const line of lines) {
35
+ const match = item.exec(line);
36
+ if (match) items.push(match[2]!);
37
+ else items[items.length - 1] += `\n${line.trim()}`;
38
+ }
39
+ const content = items.map((text) => <li>{inline(text)}</li>);
40
+ return first[1] !== undefined ? <ol start={Number(first[1])}>{content}</ol> : <ul>{content}</ul>;
41
+ }
42
+
43
+ /** `code` and **bold** inside a paragraph. */
44
+ function inline(text: string) {
45
+ return text.split(/(`[^`\n]+`|\*\*[^*\n]+\*\*)/).map((piece) => {
46
+ if (piece.startsWith('`') && piece.endsWith('`') && piece.length > 2) return <code>{piece.slice(1, -1)}</code>;
47
+ if (piece.startsWith('**') && piece.endsWith('**') && piece.length > 4) return <strong>{piece.slice(2, -2)}</strong>;
48
+ return piece;
49
+ });
50
+ }