@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.
- package/README.md +145 -2
- package/dist/badge.d.ts +2 -0
- package/dist/badge.js +17 -0
- package/dist/badge.js.map +1 -0
- package/dist/commands.d.ts +8 -0
- package/dist/commands.js +49 -0
- package/dist/commands.js.map +1 -0
- package/dist/config.d.ts +24 -0
- package/dist/config.js +26 -0
- package/dist/config.js.map +1 -0
- package/dist/forge.d.ts +67 -0
- package/dist/forge.js +138 -0
- package/dist/forge.js.map +1 -0
- package/dist/http.d.ts +25 -0
- package/dist/http.js +248 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/opencode.d.ts +30 -0
- package/dist/opencode.js +113 -0
- package/dist/opencode.js.map +1 -0
- package/dist/page.d.ts +11 -0
- package/dist/page.js +31 -0
- package/dist/page.js.map +1 -0
- package/dist/studio.module.d.ts +21 -0
- package/dist/studio.module.js +129 -0
- package/dist/studio.module.js.map +1 -0
- package/package.json +99 -4
- package/src/config.ts +26 -0
- package/ui/app.tsx +862 -0
- package/ui/changes.tsx +420 -0
- package/ui/code.tsx +194 -0
- package/ui/composer.tsx +362 -0
- package/ui/conversations.tsx +103 -0
- package/ui/editor.ts +144 -0
- package/ui/forge.tsx +236 -0
- package/ui/icons.tsx +59 -0
- package/ui/logic.ts +304 -0
- package/ui/logs.tsx +87 -0
- package/ui/model-picker.tsx +121 -0
- package/ui/notify.ts +45 -0
- package/ui/page.ts +27 -0
- package/ui/popover.tsx +66 -0
- package/ui/prose.tsx +50 -0
- package/ui/providers.tsx +384 -0
- package/ui/queue.tsx +89 -0
- package/ui/shared.ts +74 -0
- package/ui/splitter.tsx +70 -0
- package/ui/styles.css +2632 -0
- package/ui/terminal.tsx +108 -0
- package/ui/tsconfig.json +13 -0
- package/ui/urls.ts +9 -0
- package/ui/usage.tsx +86 -0
package/ui/forge.tsx
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/** @jsxImportSource hono/jsx/dom */
|
|
2
|
+
// The repository's forge (GitHub, GitLab, one's own GitLab), found from `origin`: a chip beside the branch, and what
|
|
3
|
+
// the agent can do there once its MCP server is connected: a GitLab sign-in, or GitHub's token from the GitHub CLI.
|
|
4
|
+
import type { McpServer } from '@opencode/client';
|
|
5
|
+
import { useEffect, useState } from 'hono/jsx/dom';
|
|
6
|
+
import { Icon } from './icons.js';
|
|
7
|
+
import { Popover } from './popover.js';
|
|
8
|
+
import { client, errorText, location_, studioApi, waitForSignIn } from './shared.js';
|
|
9
|
+
|
|
10
|
+
/** What the server says of the forge (api/forge): never a token, only where one comes from. */
|
|
11
|
+
export interface ForgeInfo {
|
|
12
|
+
type: 'github' | 'gitlab';
|
|
13
|
+
host: string;
|
|
14
|
+
web: string;
|
|
15
|
+
project: string;
|
|
16
|
+
origin: string | null;
|
|
17
|
+
/** The MCP server's name in OpenCode. */
|
|
18
|
+
server: string;
|
|
19
|
+
mcp?: string;
|
|
20
|
+
enterprise?: boolean;
|
|
21
|
+
token: 'env' | 'gh' | null;
|
|
22
|
+
ready: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const NAME = { github: 'GitHub', gitlab: 'GitLab' } as const;
|
|
26
|
+
|
|
27
|
+
type State = 'connected' | 'sign-in' | 'connecting' | 'token' | 'failed' | 'enterprise' | 'missing';
|
|
28
|
+
|
|
29
|
+
/** Where the forge's connection is, from what the server found and OpenCode's MCP server. */
|
|
30
|
+
function stateOf(forge: ForgeInfo, server: McpServer | undefined): State {
|
|
31
|
+
if (forge.enterprise || !forge.mcp) return 'enterprise';
|
|
32
|
+
if (forge.type === 'github' && !forge.token) return 'token';
|
|
33
|
+
if (!server) return 'missing';
|
|
34
|
+
switch (server.status.status) {
|
|
35
|
+
case 'connected':
|
|
36
|
+
return 'connected';
|
|
37
|
+
case 'needs_auth':
|
|
38
|
+
return 'sign-in';
|
|
39
|
+
case 'pending':
|
|
40
|
+
return 'connecting';
|
|
41
|
+
default:
|
|
42
|
+
return 'failed';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A failure of the forge's MCP server as something to do about it. */
|
|
47
|
+
function advice(forge: ForgeInfo, error: string): string {
|
|
48
|
+
if (/instance_setting_disabled|403|forbidden/i.test(error) && forge.type === 'gitlab')
|
|
49
|
+
return `The MCP server is turned off on ${forge.host}. An administrator turns it on: Admin area → Settings → Visibility and access controls → "Allow access to the MCP server". Or set GITLAB_TOKEN (a fine-grained token with the MCP permission)${forge.host === 'gitlab.com' ? '' : ` and GITLAB_TOKEN_HOST=${forge.host}`} in .env, then check again.`;
|
|
50
|
+
if (/dynamic client registration/i.test(error))
|
|
51
|
+
return `${forge.host} does not let apps sign in by themselves. Set GITLAB_TOKEN (a fine-grained token with the MCP permission)${forge.host === 'gitlab.com' ? '' : ` and GITLAB_TOKEN_HOST=${forge.host}`} in .env, then check again.`;
|
|
52
|
+
if (/401|unauthorized|bad credentials|badly formatted/i.test(error))
|
|
53
|
+
return forge.type === 'github' ? 'GitHub refused the token: run gh auth login again (or set a new GITHUB_TOKEN in .env), then check again.' : 'The sign-in expired or was revoked: sign in again.';
|
|
54
|
+
return error;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function ForgeChip({ refresh, onTerminal }: { refresh: number; onTerminal: () => void }) {
|
|
58
|
+
const [forge, setForge] = useState<ForgeInfo | null>(null);
|
|
59
|
+
const [server, setServer] = useState<McpServer | undefined>();
|
|
60
|
+
const [open, setOpen] = useState(false);
|
|
61
|
+
const [busy, setBusy] = useState('');
|
|
62
|
+
const [error, setError] = useState('');
|
|
63
|
+
|
|
64
|
+
const loadServer = (name: string) =>
|
|
65
|
+
client.mcp
|
|
66
|
+
.list({ location: location_ })
|
|
67
|
+
.then((result) => setServer(result.data.find((entry) => entry.name === name)))
|
|
68
|
+
.catch(() => undefined);
|
|
69
|
+
useEffect(() => {
|
|
70
|
+
void studioApi<ForgeInfo | null>('forge')
|
|
71
|
+
.then((found) => {
|
|
72
|
+
setForge(found);
|
|
73
|
+
if (found) void loadServer(found.server);
|
|
74
|
+
})
|
|
75
|
+
.catch(() => undefined);
|
|
76
|
+
}, [refresh]);
|
|
77
|
+
|
|
78
|
+
if (!forge) return null;
|
|
79
|
+
const state = stateOf(forge, server);
|
|
80
|
+
const name = forge.enterprise ? 'GitHub Enterprise' : NAME[forge.type];
|
|
81
|
+
const failure = server?.status.status === 'failed' || server?.status.status === 'needs_auth' ? server.status.error : '';
|
|
82
|
+
|
|
83
|
+
const act = async (label: string, action: () => Promise<unknown>) => {
|
|
84
|
+
setBusy(label);
|
|
85
|
+
setError('');
|
|
86
|
+
try {
|
|
87
|
+
await action();
|
|
88
|
+
} catch (failed) {
|
|
89
|
+
setError(errorText(failed));
|
|
90
|
+
}
|
|
91
|
+
setBusy('');
|
|
92
|
+
};
|
|
93
|
+
/** The server again: what it finds now (a token set, a login, an administrator's change), given to OpenCode. */
|
|
94
|
+
const checkAgain = () =>
|
|
95
|
+
act('check', async () => {
|
|
96
|
+
const found = await studioApi<ForgeInfo | null>('forge/refresh', { method: 'POST' });
|
|
97
|
+
setForge(found);
|
|
98
|
+
if (found) {
|
|
99
|
+
// OpenCode connects it in a moment.
|
|
100
|
+
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
101
|
+
await loadServer(found.server);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
/** GitLab's sign-in, in its own tab; OpenCode keeps the token. */
|
|
105
|
+
const signIn = () =>
|
|
106
|
+
act('sign-in', async () => {
|
|
107
|
+
const integrationID = server?.integrationID;
|
|
108
|
+
if (!integrationID) throw new Error('OpenCode has no sign-in for this server yet: check again.');
|
|
109
|
+
const started = await client.integration.oauth.connect({ integrationID, methodID: integrationID, location: location_ });
|
|
110
|
+
window.open(started.data.url, '_blank', 'noopener');
|
|
111
|
+
const failed = await waitForSignIn(integrationID, started.data.attemptID).done;
|
|
112
|
+
if (failed) throw new Error(failed);
|
|
113
|
+
await client.experimental.mcp.connect({ server: forge.server, location: location_ }).catch(() => undefined);
|
|
114
|
+
await loadServer(forge.server);
|
|
115
|
+
});
|
|
116
|
+
/** Signed out: the MCP server let go and its token removed from OpenCode. */
|
|
117
|
+
const signOut = () =>
|
|
118
|
+
act('sign-out', async () => {
|
|
119
|
+
if (!confirm(`Sign out of ${forge.host}? The agent loses ${name} until you sign in again.`)) return;
|
|
120
|
+
const integrationID = server?.integrationID;
|
|
121
|
+
if (integrationID) {
|
|
122
|
+
const integration = await client.integration.get({ integrationID, location: location_ });
|
|
123
|
+
for (const connection of integration.data.connections) if (connection.type === 'credential') await client.credential.remove({ credentialID: connection.id });
|
|
124
|
+
}
|
|
125
|
+
await client.experimental.mcp.disconnect({ server: forge.server, location: location_ }).catch(() => undefined);
|
|
126
|
+
await loadServer(forge.server);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const dot = state === 'connected' ? 'good' : state === 'failed' || state === 'enterprise' ? 'bad' : state === 'connecting' ? 'busy' : 'idle';
|
|
130
|
+
const action = state === 'sign-in' ? 'Sign in' : state === 'token' ? 'Needs a token' : state === 'failed' ? 'Not working' : state === 'missing' ? 'Check' : '';
|
|
131
|
+
return (
|
|
132
|
+
<div class="anchor forge-anchor">
|
|
133
|
+
<button type="button" class={`chip forge-chip${open ? ' open' : ''}${action ? ' attention' : ''}`} onClick={() => setOpen(!open)} title={`${name} at ${forge.web}: ${forge.project}${action ? ` · ${action}` : ''}`}>
|
|
134
|
+
<span class={`forge-dot ${dot}`} />
|
|
135
|
+
<span class="chip-text">{name}</span>
|
|
136
|
+
{action && <span class="chip-count forge-action">{action}</span>}
|
|
137
|
+
</button>
|
|
138
|
+
<Popover open={open} onClose={() => setOpen(false)} placement="below-end" class="forge-popover">
|
|
139
|
+
<div class="forge-body">
|
|
140
|
+
<div class="forge-head">
|
|
141
|
+
<strong>{name}</strong>
|
|
142
|
+
<a href={`${forge.web}/${forge.project}`} target="_blank" rel="noopener" class="forge-link">
|
|
143
|
+
{forge.host}/{forge.project}
|
|
144
|
+
<Icon name="external" size={12} />
|
|
145
|
+
</a>
|
|
146
|
+
</div>
|
|
147
|
+
{forge.origin && <code class="forge-origin">origin {forge.origin}</code>}
|
|
148
|
+
|
|
149
|
+
{state === 'connected' && (
|
|
150
|
+
<>
|
|
151
|
+
<p class="forge-status good">
|
|
152
|
+
<span class="forge-dot good" /> Connected{forge.token === 'gh' ? ' with the GitHub CLI’s login' : forge.token === 'env' ? ` with ${forge.type === 'github' ? 'GITHUB_TOKEN' : 'GITLAB_TOKEN'}` : ''}
|
|
153
|
+
</p>
|
|
154
|
+
<p class="hint">
|
|
155
|
+
The agent can read and open {forge.type === 'gitlab' ? 'merge requests, issues and pipelines' : 'pull requests, issues and workflow runs'} of {forge.project}, as you. Try: “{forge.type === 'gitlab' ? 'open a merge request for this branch' : 'open a pull request for this branch'}”.
|
|
156
|
+
</p>
|
|
157
|
+
{forge.type === 'gitlab' && !forge.token && (
|
|
158
|
+
<div class="forge-actions">
|
|
159
|
+
<button type="button" onClick={() => void signOut()} disabled={busy !== ''}>
|
|
160
|
+
Sign out
|
|
161
|
+
</button>
|
|
162
|
+
</div>
|
|
163
|
+
)}
|
|
164
|
+
</>
|
|
165
|
+
)}
|
|
166
|
+
|
|
167
|
+
{state === 'sign-in' && (
|
|
168
|
+
<>
|
|
169
|
+
<p class="forge-status">
|
|
170
|
+
<span class="forge-dot idle" /> Not signed in
|
|
171
|
+
</p>
|
|
172
|
+
<p class="hint">Sign in and the agent can read and open merge requests, issues and pipelines of {forge.project}, as you.</p>
|
|
173
|
+
<div class="forge-actions">
|
|
174
|
+
<button type="button" class="primary" onClick={() => void signIn()} disabled={busy !== ''}>
|
|
175
|
+
<Icon name="login" size={14} />
|
|
176
|
+
{busy === 'sign-in' ? 'Waiting for the sign-in…' : `Sign in to ${name}`}
|
|
177
|
+
</button>
|
|
178
|
+
</div>
|
|
179
|
+
<p class="hint small">The sign-in opens {forge.host} in a tab; OpenCode keeps the token in your profile, for every project.</p>
|
|
180
|
+
</>
|
|
181
|
+
)}
|
|
182
|
+
|
|
183
|
+
{state === 'token' && (
|
|
184
|
+
<>
|
|
185
|
+
<p class="forge-status">
|
|
186
|
+
<span class="forge-dot idle" /> Needs a token
|
|
187
|
+
</p>
|
|
188
|
+
<p class="hint">GitHub’s MCP server has no sign-in for agents: it takes a token. Either</p>
|
|
189
|
+
<ol class="forge-steps">
|
|
190
|
+
<li>
|
|
191
|
+
sign in with the GitHub CLI: <code>gh auth login</code> in the{' '}
|
|
192
|
+
<button type="button" class="text-button" onClick={onTerminal}>
|
|
193
|
+
Terminal
|
|
194
|
+
</button>{' '}
|
|
195
|
+
tab; Studio uses its login;
|
|
196
|
+
</li>
|
|
197
|
+
<li>
|
|
198
|
+
or set <code>GITHUB_TOKEN</code> in <code>.env</code> (a fine-grained token for this repository).
|
|
199
|
+
</li>
|
|
200
|
+
</ol>
|
|
201
|
+
</>
|
|
202
|
+
)}
|
|
203
|
+
|
|
204
|
+
{state === 'failed' && (
|
|
205
|
+
<>
|
|
206
|
+
<p class="forge-status bad">
|
|
207
|
+
<Icon name="warning" size={14} /> Not working
|
|
208
|
+
</p>
|
|
209
|
+
<p class="hint">{advice(forge, failure)}</p>
|
|
210
|
+
</>
|
|
211
|
+
)}
|
|
212
|
+
|
|
213
|
+
{state === 'connecting' && <p class="forge-status"><span class="forge-dot busy" /> Connecting…</p>}
|
|
214
|
+
|
|
215
|
+
{state === 'missing' && <p class="hint">OpenCode does not have {name}’s MCP server yet: check again to give it.</p>}
|
|
216
|
+
|
|
217
|
+
{state === 'enterprise' && (
|
|
218
|
+
<p class="hint">
|
|
219
|
+
{forge.host} is a GitHub Enterprise Server: it has no MCP server to connect from here. The agent can still use <code>gh</code> in the terminal.
|
|
220
|
+
</p>
|
|
221
|
+
)}
|
|
222
|
+
|
|
223
|
+
{error && <p class="note error">{error}</p>}
|
|
224
|
+
{(state === 'token' || state === 'failed' || state === 'missing') && (
|
|
225
|
+
<div class="forge-actions">
|
|
226
|
+
<button type="button" class={state === 'missing' ? 'primary' : ''} onClick={() => void checkAgain()} disabled={busy !== ''}>
|
|
227
|
+
<Icon name="refresh" size={14} />
|
|
228
|
+
{busy === 'check' ? 'Checking…' : 'Check again'}
|
|
229
|
+
</button>
|
|
230
|
+
</div>
|
|
231
|
+
)}
|
|
232
|
+
</div>
|
|
233
|
+
</Popover>
|
|
234
|
+
</div>
|
|
235
|
+
);
|
|
236
|
+
}
|
package/ui/icons.tsx
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** @jsxImportSource hono/jsx/dom */
|
|
2
|
+
// Studio's icons: line drawings in the page's text color, the same on every system (no emoji or font glyphs).
|
|
3
|
+
|
|
4
|
+
const PATHS = {
|
|
5
|
+
plus: 'M12 5v14M5 12h14',
|
|
6
|
+
x: 'M18 6 6 18M6 6l12 12',
|
|
7
|
+
check: 'M20 6 9 17l-5-5',
|
|
8
|
+
chevronDown: 'm6 9 6 6 6-6',
|
|
9
|
+
chevronUp: 'm18 15-6-6-6 6',
|
|
10
|
+
chevronRight: 'm9 18 6-6-6-6',
|
|
11
|
+
chevronLeft: 'm15 18-6-6 6-6',
|
|
12
|
+
search: 'M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16zM21 21l-4.3-4.3',
|
|
13
|
+
settings: 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z',
|
|
14
|
+
trash: 'M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6M10 11v6M14 11v6',
|
|
15
|
+
paperclip: 'm21.4 11.1-9.2 9.2a6 6 0 0 1-8.5-8.5l9.2-9.2a4 4 0 0 1 5.7 5.7l-9.2 9.2a2 2 0 0 1-2.8-2.8l8.5-8.5',
|
|
16
|
+
at: 'M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8',
|
|
17
|
+
upload: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12',
|
|
18
|
+
file: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6',
|
|
19
|
+
folder: 'M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9l-.8-1.2A2 2 0 0 0 7.9 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2z',
|
|
20
|
+
image: 'M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zM9 11a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM21 15l-3.1-3.1a2 2 0 0 0-2.8 0L6 21',
|
|
21
|
+
arrowUp: 'M12 19V5M5 12l7-7 7 7',
|
|
22
|
+
stop: 'M7 7h10v10H7z',
|
|
23
|
+
refresh: 'M21 12a9 9 0 0 1-15.5 6.2L3 16M3 21v-5h5M3 12a9 9 0 0 1 15.5-6.2L21 8M21 3v5h-5',
|
|
24
|
+
external: 'M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6',
|
|
25
|
+
branch: 'M6 3v12M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM18 9a9 9 0 0 1-9 9',
|
|
26
|
+
history: 'M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5M12 7v5l4 2',
|
|
27
|
+
sparkle: 'M12 3l1.9 5.8L20 11l-6.1 2.2L12 19l-1.9-5.8L4 11l6.1-2.2z',
|
|
28
|
+
warning: 'M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0zM12 9v4M12 17h.01',
|
|
29
|
+
key: 'M21 2l-2 2m-7.6 7.6a5.5 5.5 0 1 1-7.8 7.8 5.5 5.5 0 0 1 7.8-7.8zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4',
|
|
30
|
+
login: 'M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4M10 17l5-5-5-5M15 12H3',
|
|
31
|
+
terminal: 'm4 17 6-6-6-6M12 19h8',
|
|
32
|
+
dot: 'M12 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2z',
|
|
33
|
+
undo: 'M9 14 4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11',
|
|
34
|
+
redo: 'm15 14 5-5-5-5M20 9H9.5a5.5 5.5 0 0 0 0 11H13',
|
|
35
|
+
bell: 'M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.94 1.94 0 0 0 3.4 0',
|
|
36
|
+
bellOff: 'M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7M10.3 21a1.94 1.94 0 0 0 3.4 0M2 2l20 20',
|
|
37
|
+
} as const;
|
|
38
|
+
|
|
39
|
+
export type IconName = keyof typeof PATHS;
|
|
40
|
+
|
|
41
|
+
/** An icon at `size` pixels; decorative unless it has a `label` (then read aloud). */
|
|
42
|
+
export function Icon({ name, size = 16, label, class: className }: { name: IconName; size?: number; label?: string; class?: string }) {
|
|
43
|
+
return (
|
|
44
|
+
<svg
|
|
45
|
+
class={`icon${className ? ` ${className}` : ''}`}
|
|
46
|
+
width={size}
|
|
47
|
+
height={size}
|
|
48
|
+
viewBox="0 0 24 24"
|
|
49
|
+
fill="none"
|
|
50
|
+
stroke="currentColor"
|
|
51
|
+
stroke-width="2"
|
|
52
|
+
stroke-linecap="round"
|
|
53
|
+
stroke-linejoin="round"
|
|
54
|
+
{...(label ? { role: 'img', 'aria-label': label } : { 'aria-hidden': 'true' })}
|
|
55
|
+
>
|
|
56
|
+
<path d={PATHS[name]} />
|
|
57
|
+
</svg>
|
|
58
|
+
);
|
|
59
|
+
}
|
package/ui/logic.ts
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// What the page decides without the page: effort levels, attachments and @-mentions, git paths. Kept free of the
|
|
2
|
+
// DOM so it is tested on its own.
|
|
3
|
+
|
|
4
|
+
/** The parts of a model the page reasons about. */
|
|
5
|
+
export interface ModelLike {
|
|
6
|
+
providerID: string;
|
|
7
|
+
modelID: string;
|
|
8
|
+
variants: { id: string }[];
|
|
9
|
+
capabilities: { input: string[] };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const modelKey = (model: Pick<ModelLike, 'providerID' | 'modelID'>) => `${model.providerID}/${model.modelID}`;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The effort a model runs at: none for a model without levels, else the level last chosen for it, else `high`, else
|
|
16
|
+
* the middle one. Always a level the model has: the picker never shows an unknown "default".
|
|
17
|
+
*/
|
|
18
|
+
export function effortFor(model: ModelLike | undefined, chosen: Record<string, string>): string | undefined {
|
|
19
|
+
const levels = model?.variants.map((variant) => variant.id) ?? [];
|
|
20
|
+
if (!model || !levels.length) return undefined;
|
|
21
|
+
const last = chosen[modelKey(model)];
|
|
22
|
+
if (last && levels.includes(last)) return last;
|
|
23
|
+
return levels.includes('high') ? 'high' : levels[Math.floor((levels.length - 1) / 2)];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A level as the picker shows it: `xhigh` as `XHigh`. */
|
|
27
|
+
export const effortLabel = (level: string) => (level === 'xhigh' ? 'XHigh' : level.charAt(0).toUpperCase() + level.slice(1));
|
|
28
|
+
|
|
29
|
+
/** The largest file OpenCode takes in a prompt. */
|
|
30
|
+
export const MAX_ATTACHMENT = 20 * 1024 * 1024;
|
|
31
|
+
|
|
32
|
+
export type AttachmentKind = 'image' | 'pdf' | 'text' | 'folder' | 'file';
|
|
33
|
+
|
|
34
|
+
/** A file going with the next message: uploaded (a `data:` URL) or a file of the project @-mentioned (`file:`). */
|
|
35
|
+
export interface Attachment {
|
|
36
|
+
id: string;
|
|
37
|
+
name: string;
|
|
38
|
+
kind: AttachmentKind;
|
|
39
|
+
uri: string;
|
|
40
|
+
size?: number;
|
|
41
|
+
/** For a mentioned file: the `@path` it was mentioned as. */
|
|
42
|
+
mention?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const TEXT_TYPES = /^(text\/|application\/(json|xml|javascript|x-javascript|typescript|x-yaml|yaml|toml|x-sh|sql|graphql))/;
|
|
46
|
+
const TEXT_EXTENSIONS = /\.(ts|tsx|js|jsx|mjs|cjs|json|jsonc|md|txt|log|css|scss|html|htm|vue|svelte|yml|yaml|toml|env|ini|sql|sh|ps1|py|php|rb|go|rs|java|kt|c|h|cpp|cs|xml|csv|svg)$/i;
|
|
47
|
+
|
|
48
|
+
/** What a file is, for the model and the chip: by its type, else its name. */
|
|
49
|
+
export function attachmentKind(name: string, mime: string): AttachmentKind {
|
|
50
|
+
if (mime.startsWith('image/') && mime !== 'image/svg+xml') return 'image';
|
|
51
|
+
if (mime === 'application/pdf' || /\.pdf$/i.test(name)) return 'pdf';
|
|
52
|
+
if (TEXT_TYPES.test(mime) || TEXT_EXTENSIONS.test(name)) return 'text';
|
|
53
|
+
return 'file';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Bytes as base64, in chunks (a large file would overflow the call stack in one go). */
|
|
57
|
+
function base64(bytes: Uint8Array) {
|
|
58
|
+
let binary = '';
|
|
59
|
+
for (let at = 0; at < bytes.length; at += 0x8000) binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));
|
|
60
|
+
return btoa(binary);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A file of the computer as an attachment: its bytes in a `data:` URL. Bigger than OpenCode takes: an error. */
|
|
64
|
+
export async function uploadAttachment(file: Blob & { name?: string }, id: string): Promise<Attachment> {
|
|
65
|
+
const name = file.name || 'pasted';
|
|
66
|
+
if (file.size > MAX_ATTACHMENT) throw new Error(`${name} is ${Math.round(file.size / 1024 / 1024)} MB: attachments go up to 20 MB.`);
|
|
67
|
+
const kind = attachmentKind(name, file.type);
|
|
68
|
+
const mime = file.type || (kind === 'text' ? 'text/plain' : 'application/octet-stream');
|
|
69
|
+
return { id, name, kind, size: file.size, uri: `data:${mime};base64,${base64(new Uint8Array(await file.arrayBuffer()))}` };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A `file:` URL of a path of the project, as OpenCode reads it on the server (`E:\app` + `src/a.ts`). */
|
|
73
|
+
export function fileUri(directory: string, path: string): string {
|
|
74
|
+
const root = directory.replace(/\\/g, '/').replace(/\/$/, '');
|
|
75
|
+
const full = `${root}/${path.replace(/\\/g, '/').replace(/^\.?\//, '').replace(/\/$/, '')}`;
|
|
76
|
+
return `file://${full.startsWith('/') ? '' : '/'}${encodeURI(full)}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A project file @-mentioned: read by OpenCode in place, nothing uploaded. */
|
|
80
|
+
export function mentionAttachment(directory: string, path: string, folder: boolean): Attachment {
|
|
81
|
+
const clean = path.replace(/\\/g, '/').replace(/\/$/, '');
|
|
82
|
+
return { id: `@${clean}`, name: clean, kind: folder ? 'folder' : attachmentKind(clean, ''), uri: fileUri(directory, clean), mention: `@${clean}` };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The @-mention being typed at the caret: where its `@` is and what follows it. None outside one. */
|
|
86
|
+
export function mentionAt(text: string, caret: number): { start: number; query: string } | undefined {
|
|
87
|
+
const before = text.slice(0, caret);
|
|
88
|
+
const match = /(^|\s)@([^\s@]*)$/.exec(before);
|
|
89
|
+
return match ? { start: caret - match[2]!.length - 1, query: match[2]! } : undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The text with the mention typed at `start`..`caret` replaced by `@path ` and where the caret goes after it. */
|
|
93
|
+
export function insertMention(text: string, start: number, caret: number, path: string): { text: string; caret: number } {
|
|
94
|
+
const inserted = `@${path.replace(/\\/g, '/').replace(/\/$/, '')} `;
|
|
95
|
+
return { text: text.slice(0, start) + inserted + text.slice(caret), caret: start + inserted.length };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** A file of a prompt, as OpenCode takes it. */
|
|
99
|
+
export interface PromptFile {
|
|
100
|
+
uri: string;
|
|
101
|
+
name: string;
|
|
102
|
+
source?: { type: 'inline' };
|
|
103
|
+
mention?: { start: number; end: number; text: string };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The files a message carries, as OpenCode's prompt takes them: a mention still in the text keeps its place in it. */
|
|
107
|
+
export function promptFiles(text: string, attachments: Attachment[]): PromptFile[] {
|
|
108
|
+
return attachments.flatMap((attachment): PromptFile[] => {
|
|
109
|
+
if (!attachment.mention) return [{ uri: attachment.uri, name: attachment.name, source: { type: 'inline' as const } }];
|
|
110
|
+
const start = text.indexOf(attachment.mention);
|
|
111
|
+
// Mentioned, then deleted from the text: not sent.
|
|
112
|
+
if (start === -1) return [];
|
|
113
|
+
return [{ uri: attachment.uri, name: attachment.name, mention: { start, end: start + attachment.mention.length, text: attachment.mention } }];
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Attachments a model cannot read (an image for a model of text only). */
|
|
118
|
+
export function unreadable(model: Pick<ModelLike, 'capabilities'> | undefined, attachment: Attachment): boolean {
|
|
119
|
+
if (!model) return false;
|
|
120
|
+
const input = model.capabilities.input;
|
|
121
|
+
if (attachment.kind === 'image') return !input.includes('image');
|
|
122
|
+
if (attachment.kind === 'pdf') return !input.includes('pdf');
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** A path git gives (from the repository's root) as the project sees it: `examples/shop/src/a.ts` as `src/a.ts`. */
|
|
127
|
+
export function projectPath(file: string, subpath: string): string {
|
|
128
|
+
const path = file.replace(/\\/g, '/');
|
|
129
|
+
const prefix = subpath.replace(/\\/g, '/').replace(/^\/|\/$/g, '');
|
|
130
|
+
return prefix && path.toLowerCase().startsWith(`${prefix.toLowerCase()}/`) ? path.slice(prefix.length + 1) : path;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The project's folder inside its repository (`examples/shop`), empty at its root. */
|
|
134
|
+
export function subpathOf(directory: string, repository: string): string {
|
|
135
|
+
const dir = directory.replace(/\\/g, '/').replace(/\/$/, '');
|
|
136
|
+
const root = repository.replace(/\\/g, '/').replace(/\/$/, '');
|
|
137
|
+
return dir.toLowerCase().startsWith(`${root.toLowerCase()}/`) ? dir.slice(root.length + 1) : '';
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** `3 min ago`, `yesterday`, a date further back. */
|
|
141
|
+
export function ago(time: number, now = Date.now()): string {
|
|
142
|
+
const seconds = Math.max(0, Math.round((now - time) / 1000));
|
|
143
|
+
if (seconds < 60) return 'just now';
|
|
144
|
+
if (seconds < 3600) return `${Math.floor(seconds / 60)} min ago`;
|
|
145
|
+
if (seconds < 86_400) return `${Math.floor(seconds / 3600)} h ago`;
|
|
146
|
+
if (seconds < 172_800) return 'yesterday';
|
|
147
|
+
return new Date(time).toLocaleDateString();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A context window as people say it: 1M, 200K. */
|
|
151
|
+
export const contextLabel = (tokens: number) => (tokens >= 1_000_000 ? `${Math.round(tokens / 100_000) / 10}M` : tokens >= 1000 ? `${Math.round(tokens / 1000)}K` : String(tokens));
|
|
152
|
+
|
|
153
|
+
/** What `/review` is given: the uncommitted changes of the project's folder (the app may live in a bigger repository). */
|
|
154
|
+
export const REVIEW_SCOPE = 'the uncommitted changes in this folder only: `git status --short -- .`, `git diff -- .` and `git diff --cached -- .`';
|
|
155
|
+
|
|
156
|
+
/** A message of a conversation, as far as a review's outcome needs it. */
|
|
157
|
+
export interface MessageLike {
|
|
158
|
+
type: string;
|
|
159
|
+
content?: readonly { type: string; text?: string }[];
|
|
160
|
+
outcome?: string;
|
|
161
|
+
error?: { message: string };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A review run: done once its last message is the run's end; what the agent answered last; why it failed, if it did. */
|
|
165
|
+
export function reviewOutcome(messages: readonly MessageLike[]): { done: boolean; text: string; failed?: string } {
|
|
166
|
+
const last = messages.at(-1);
|
|
167
|
+
const answer = messages.findLast((message) => message.type === 'assistant');
|
|
168
|
+
const text = (answer?.content ?? []).filter((part) => part.type === 'text').map((part) => part.text ?? '').join('').trim();
|
|
169
|
+
const done = last?.type === 'idle';
|
|
170
|
+
const failed = done ? (last.error?.message ?? (last.outcome && last.outcome !== 'succeeded' ? `The review ${last.outcome === 'interrupted' ? 'was stopped' : 'failed'}.` : undefined)) : undefined;
|
|
171
|
+
return { done, text, ...(failed ? { failed } : {}) };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A review of what the agent changed, for a project without git (no `/review`): the files @-mentioned, the deleted ones named. */
|
|
175
|
+
export function reviewPrompt(files: readonly { path: string; status: string }[]): { text: string; mentions: string[] } {
|
|
176
|
+
const kept = files.filter((file) => file.status !== 'deleted').map((file) => file.path);
|
|
177
|
+
const deleted = files.filter((file) => file.status === 'deleted').map((file) => file.path);
|
|
178
|
+
const text = [
|
|
179
|
+
'Review these changes for bugs, security problems and what goes against the conventions of this project. Read each file whole. Do not edit any file.',
|
|
180
|
+
'List the problems by file and line, the worst first, with how to fix each; or say there are none.',
|
|
181
|
+
'',
|
|
182
|
+
...(kept.length ? [`Changed: ${kept.map((path) => `@${path}`).join(' ')}`] : []),
|
|
183
|
+
...(deleted.length ? [`Deleted: ${deleted.join(', ')}`] : []),
|
|
184
|
+
].join('\n');
|
|
185
|
+
return { text, mentions: kept };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** What a model is asked for a commit message: the patches, cut to a size a small model reads quickly. */
|
|
189
|
+
export function commitMessagePrompt(patches: readonly string[], limit = 24_000): string {
|
|
190
|
+
const diff = patches.join('\n');
|
|
191
|
+
return [
|
|
192
|
+
'Write the git commit message for this diff: a subject line of at most 72 characters in the imperative mood, then (only if the change needs it) a blank line and a short body.',
|
|
193
|
+
'Answer with the message only: no quotes, no code fence, no preamble.',
|
|
194
|
+
'',
|
|
195
|
+
diff.length > limit ? `${diff.slice(0, limit)}\n… (cut)` : diff,
|
|
196
|
+
].join('\n');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** A model's commit message without what models wrap it in: a code fence, quotes, a "Commit message:" label. */
|
|
200
|
+
export function cleanCommitMessage(text: string): string {
|
|
201
|
+
return text
|
|
202
|
+
.trim()
|
|
203
|
+
.replace(/^```[^\n]*\n([\s\S]*?)\n?```$/, '$1')
|
|
204
|
+
.replace(/^(commit message|message)\s*:\s*/i, '')
|
|
205
|
+
.replace(/^(["'`])([\s\S]*)\1$/, '$2')
|
|
206
|
+
.trim();
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A command or skill being typed as the message's first word (`/rev`): what follows the `/`. None elsewhere. */
|
|
210
|
+
export function slashAt(text: string, caret: number): string | undefined {
|
|
211
|
+
return /^\/([^\s/]*)$/.exec(text.slice(0, caret))?.[1];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The text with its first word replaced by `/token ` (the rest kept), and where the caret goes after it. */
|
|
215
|
+
export function insertSlash(text: string, token: string): { text: string; caret: number } {
|
|
216
|
+
const inserted = `/${token} `;
|
|
217
|
+
return { text: inserted + text.replace(/^\/\S*\s*/, ''), caret: inserted.length };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Where a skill comes from: OpenCode itself, the project, a folder above it (its repository), or the user's profile. */
|
|
221
|
+
export type SkillOrigin = 'built-in' | 'project' | 'repo' | 'user';
|
|
222
|
+
|
|
223
|
+
export function skillOrigin(path: string, directory: string, repository: string): SkillOrigin {
|
|
224
|
+
if (path.startsWith('skill://')) return 'built-in';
|
|
225
|
+
const norm = (value: string) => `${value.replace(/\\/g, '/').replace(/\/$/, '').toLowerCase()}/`;
|
|
226
|
+
const file = norm(path);
|
|
227
|
+
if (file.startsWith(norm(directory))) return 'project';
|
|
228
|
+
return file.startsWith(norm(repository)) ? 'repo' : 'user';
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** A choice of the `/` picker. */
|
|
232
|
+
export interface SlashOption {
|
|
233
|
+
kind: 'command' | 'skill';
|
|
234
|
+
/** What is typed after the `/`: a command's name, a skill's id. */
|
|
235
|
+
token: string;
|
|
236
|
+
title: string;
|
|
237
|
+
description: string;
|
|
238
|
+
origin?: SkillOrigin;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** The choices for what follows the `/`: those whose token starts with it first, then those that mention it; commands before skills. */
|
|
242
|
+
export function slashOptions(query: string, options: readonly SlashOption[]): SlashOption[] {
|
|
243
|
+
const term = query.toLowerCase();
|
|
244
|
+
const rank = (option: SlashOption) => {
|
|
245
|
+
if (!term) return 0;
|
|
246
|
+
if (option.token.toLowerCase().startsWith(term) || option.title.toLowerCase().startsWith(term)) return 0;
|
|
247
|
+
return `${option.token} ${option.title} ${option.description}`.toLowerCase().includes(term) ? 1 : -1;
|
|
248
|
+
};
|
|
249
|
+
return options
|
|
250
|
+
.map((option, index) => ({ option, index, rank: rank(option) }))
|
|
251
|
+
.filter((entry) => entry.rank >= 0)
|
|
252
|
+
.sort((a, b) => a.rank - b.rank || (a.option.kind === b.option.kind ? a.index - b.index : a.option.kind === 'command' ? -1 : 1))
|
|
253
|
+
.map((entry) => entry.option);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* What a message that starts with `/token` asks: a command run with the rest of the text as its input, or a skill the
|
|
258
|
+
* agent must use (the token stays in the text, marked where it is). Anything else is an ordinary message.
|
|
259
|
+
*/
|
|
260
|
+
export function slashInvocation(
|
|
261
|
+
text: string,
|
|
262
|
+
commands: readonly string[],
|
|
263
|
+
skills: readonly { id: string; name: string }[],
|
|
264
|
+
): { kind: 'command'; name: string; rest: string } | { kind: 'skill'; skill: { id: string; name: string; mention: { start: number; end: number; text: string } } } | undefined {
|
|
265
|
+
const match = /^\/(\S+)/.exec(text);
|
|
266
|
+
if (!match) return undefined;
|
|
267
|
+
const token = match[1]!;
|
|
268
|
+
if (commands.includes(token)) return { kind: 'command', name: token, rest: text.slice(match[0].length).trim() };
|
|
269
|
+
const skill = skills.find((entry) => entry.id === token);
|
|
270
|
+
return skill ? { kind: 'skill', skill: { id: skill.id, name: skill.name, mention: { start: 0, end: match[0].length, text: match[0] } } } : undefined;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** A message as the turn and usage logic needs it. */
|
|
274
|
+
export interface TurnMessage {
|
|
275
|
+
id: string;
|
|
276
|
+
type: string;
|
|
277
|
+
model?: { id: string; providerID: string };
|
|
278
|
+
tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** The messages to show: those before an undone turn's first one (OpenCode keeps them until the undo is final). */
|
|
282
|
+
export function visibleMessages<T extends { id: string }>(messages: readonly T[], undoneFrom: string | undefined): T[] {
|
|
283
|
+
const at = undoneFrom ? messages.findIndex((message) => message.id === undoneFrom) : -1;
|
|
284
|
+
return at === -1 ? [...messages] : messages.slice(0, at);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The last turn: the last message of the user's, which an undo goes back to. None before the first. */
|
|
288
|
+
export function lastTurn<T extends { type: string }>(messages: readonly T[]): T | undefined {
|
|
289
|
+
return messages.findLast((message) => message.type === 'user');
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* How much of the model's context the conversation fills: what its last request sent (new input and what came from or
|
|
294
|
+
* went to the cache), with what it wrote. From the last answer that counted its tokens.
|
|
295
|
+
*/
|
|
296
|
+
export function contextUsage(messages: readonly TurnMessage[]): { tokens: number; model?: { id: string; providerID: string }; last: NonNullable<TurnMessage['tokens']> } | undefined {
|
|
297
|
+
const answer = messages.findLast((message) => message.type === 'assistant' && message.tokens);
|
|
298
|
+
if (!answer?.tokens) return undefined;
|
|
299
|
+
const { input, output, cache } = answer.tokens;
|
|
300
|
+
return { tokens: input + cache.read + cache.write + output, ...(answer.model ? { model: answer.model } : {}), last: answer.tokens };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** A share of a context window, as a whole percent that is never 0 for a conversation that has begun. */
|
|
304
|
+
export const contextShare = (tokens: number, window: number) => (window > 0 ? Math.min(100, Math.max(tokens > 0 ? 1 : 0, Math.round((tokens / window) * 100))) : 0);
|