@bridgebrew/sessions 0.0.34 → 0.0.38

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.
@@ -1,464 +0,0 @@
1
- // The open session's details panel, under the header: its tags (up to five, the workspace's offered as suggestions)
2
- // and what it changed in its git repository (`POST /sessions/changes`): its uncommitted files, checked to commit (all
3
- // at first), the other sessions sharing some of them (a commit then asks to confirm, and takes their changes too), a
4
- // message and Commit (`POST /sessions/commit`, with the session's trailer), its uncommitted diff file by file, and its
5
- // commits; the files it claimed (`peers.ts`). A tool call's change counts open it on that file (`focus`): the diff
6
- // opens, scrolled to the file, marked; a file with no uncommitted change says so.
7
- // Read again when the session's files, commits or last turn change. Outside a repository, it says so.
8
- import * as React from 'react';
9
- import { Badge, Button, Checkbox, Icon, Input, TagInput, cn } from '@bridge/ui';
10
-
11
- /** The fields of a session the panel reads. */
12
- export interface Details {
13
- id: string;
14
- tags?: string[];
15
- claims?: { path: string; note?: string }[];
16
- files?: string[];
17
- commits?: { sha: string; at: string; message: string; files: string[] }[];
18
- lastTurn?: { endedAt: string };
19
- running?: boolean;
20
- }
21
- interface Changes {
22
- repository: string;
23
- files: { path: string; pending: boolean }[];
24
- commits: { sha: string; at: string; message: string; files: string[] }[];
25
- shared: { id: string; node: string; title: string; running: boolean; files: string[] }[];
26
- diff: string;
27
- }
28
- /** A POST to the sessions API (`path` after `/sessions`): its JSON answer, or a rejection with the refusal's `code`. */
29
- export type Post = (path: string, body: object) => Promise<any>;
30
-
31
- const TAGS_MAX = 5;
32
-
33
- /** A path as git prints it: a name with a quote, a control or a non-ASCII character comes quoted, C-escaped, its
34
- * bytes in octal (`"b/caf\\303\\251.ts"`). */
35
- const unquote = (name: string | undefined) => {
36
- if (!name?.startsWith('"') || !name.endsWith('"')) return name;
37
- const escapes: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 };
38
- const bytes: number[] = [];
39
- const body = name.slice(1, -1);
40
- for (let at = 0; at < body.length; at++) {
41
- const char = body[at]!;
42
- if (char !== '\\') bytes.push(...new TextEncoder().encode(char));
43
- else if (/[0-7]{3}/.test(body.slice(at + 1, at + 4))) {
44
- bytes.push(parseInt(body.slice(at + 1, at + 4), 8));
45
- at += 3;
46
- } else {
47
- const next = body[++at] ?? '';
48
- bytes.push(escapes[next] ?? next.charCodeAt(0));
49
- }
50
- }
51
- return new TextDecoder().decode(new Uint8Array(bytes));
52
- };
53
-
54
- /** The path of a file whose diff has no `---`/`+++` lines (a binary file, a mode change): its rename's target, else its
55
- * `diff --git` line's `b/` side, quoted, or unquoted and split where both sides name the same file (a space is in it). */
56
- const gitLinePath = (lines: string[]) => {
57
- const renamed = lines.find((line) => line.startsWith('rename to '));
58
- if (renamed) return unquote(renamed.slice('rename to '.length));
59
- const rest = lines[0]!.slice('diff --git '.length);
60
- const quoted = /"(?:[^"\\]|\\.)*"$/.exec(rest)?.[0];
61
- if (quoted) return unquote(quoted)?.replace(/^b\//, '');
62
- const half = (rest.length - 1) / 2;
63
- if (Number.isInteger(half) && rest.startsWith('a/') && rest.slice(half + 1).startsWith('b/') && rest.slice(2, half) === rest.slice(half + 3))
64
- return rest.slice(half + 3);
65
- return /^a\/(.*) b\//.exec(rest)?.[1];
66
- };
67
-
68
- /** A `git diff` cut per file: its path (the new one, the old one for a deletion), its lines from its first hunk, and
69
- * its added and removed line counts. */
70
- export const diffFiles = (diff: string) =>
71
- diff
72
- .split(/^(?=diff --git )/m)
73
- .filter((chunk) => chunk.startsWith('diff --git '))
74
- .map((chunk) => {
75
- const lines = chunk.replace(/\n$/, '').split('\n');
76
- const side = (prefix: string) => {
77
- // Git ends a name holding a space with a tab, outside its quotes: dropped before reading it (#197).
78
- const name = unquote(
79
- lines
80
- .find((line) => line.startsWith(prefix))
81
- ?.slice(prefix.length)
82
- .replace(/\t$/, ''),
83
- );
84
- return name && name !== '/dev/null' ? name.replace(/^[ab]\//, '') : undefined;
85
- };
86
- const hunk = lines.findIndex((line) => line.startsWith('@@'));
87
- const body = hunk < 0 ? lines.slice(1) : lines.slice(hunk);
88
- return {
89
- path: side('+++ ') ?? side('--- ') ?? gitLinePath(lines) ?? '',
90
- lines: body,
91
- added: body.filter((line) => line[0] === '+').length,
92
- removed: body.filter((line) => line[0] === '-').length,
93
- };
94
- });
95
-
96
- /** The file of `files` (relative to `repository`) that `wanted` names, as an agent named it (absolute, or relative to
97
- * the session's folder): the same path first, else one ending the other (`src/app.ts` before `app.ts`). */
98
- const fileNamed = <T extends { path: string }>(files: T[], wanted: string, repository: string) =>
99
- files.find(
100
- ({ path }) => wanted === path || wanted === `${repository.replace(/\/$/, '')}/${path}`,
101
- ) ??
102
- files.find(({ path }) => wanted.endsWith(`/${path}`)) ??
103
- files.find(({ path }) => path.endsWith(`/${wanted}`));
104
-
105
- interface DetailsProps {
106
- session: Details;
107
- known: string[];
108
- /** The file to show (a tool call's change counts asked for it), again at each new `at`. */
109
- focus?: { path: string; at: number } | undefined;
110
- post: Post;
111
- onChanged: () => void;
112
- onOpen: (id: string) => void;
113
- }
114
-
115
- /** The nested repositories the last commit of `session` left out (plugins#145). */
116
- type LeftOut = { session: string; paths: string[] } | undefined;
117
-
118
- /** The details panel of one session: drawn afresh for each (plugins#61), so nothing of the previous one (changes,
119
- * files picked, message, a commit to confirm, a tag being typed, the diff open) shows under the next, and its late
120
- * answers land nowhere. The last commit's nested repositories outlive the switch, kept for their own session. */
121
- export function SessionDetails(props: DetailsProps) {
122
- const [left, setLeft] = React.useState<LeftOut>();
123
- return <SessionPanel key={props.session.id} {...props} left={left} setLeft={setLeft} />;
124
- }
125
-
126
- function SessionPanel({
127
- session,
128
- known,
129
- focus,
130
- post,
131
- onChanged,
132
- onOpen,
133
- left,
134
- setLeft,
135
- }: DetailsProps & { left: LeftOut; setLeft: (left: LeftOut) => void }) {
136
- const [changes, setChanges] = React.useState<Changes | null>();
137
- const [outside, setOutside] = React.useState(false);
138
- const [error, setError] = React.useState('');
139
- const [picked, setPicked] = React.useState<Set<string>>(new Set());
140
- const [message, setMessage] = React.useState('');
141
- const [committing, setCommitting] = React.useState(false);
142
- // Another session's are not shown.
143
- const leftOut = left?.session === session.id ? left.paths : [];
144
- /** Other sessions share the picked files: Commit asks again before it takes their changes. */
145
- const [confirming, setConfirming] = React.useState(false);
146
- const listId = React.useId();
147
- const [diffOpen, setDiffOpen] = React.useState(false);
148
- const files = React.useMemo(() => diffFiles(changes?.diff ?? ''), [changes?.diff]);
149
- const focused = focus && changes ? fileNamed(files, focus.path, changes.repository) : undefined;
150
- const fileRefs = React.useRef(new Map<string, HTMLElement>());
151
- // Asked for a file: the diff opens on it.
152
- React.useEffect(() => {
153
- if (focused) setDiffOpen(true);
154
- }, [focus?.at, focused?.path]);
155
- React.useEffect(() => {
156
- if (focused && diffOpen)
157
- fileRefs.current.get(focused.path)?.scrollIntoView?.({ block: 'start' });
158
- }, [focus?.at, focused?.path, diffOpen]);
159
- const key = JSON.stringify([
160
- session.id,
161
- session.files,
162
- session.commits?.length,
163
- session.lastTurn?.endedAt,
164
- ]);
165
- React.useEffect(() => {
166
- let live = true;
167
- setError('');
168
- post('/changes', { id: session.id }).then(
169
- (found: Changes) => {
170
- if (!live) return;
171
- setOutside(false);
172
- setChanges(found);
173
- setPicked(new Set(found.files.filter((each) => each.pending).map((each) => each.path)));
174
- setConfirming(false);
175
- },
176
- (cause: unknown) => {
177
- if (!live) return;
178
- const code =
179
- typeof cause === 'object' && cause !== null && 'code' in cause ? cause.code : undefined;
180
- if (code === 'not_a_repository') setOutside(true);
181
- else setError(cause instanceof Error ? cause.message : String(cause));
182
- setChanges(null);
183
- },
184
- );
185
- return () => {
186
- live = false;
187
- };
188
- }, [key]);
189
-
190
- const tag = (tags: string[]) => {
191
- setError('');
192
- post('/tags', { id: session.id, tags: tags.slice(0, TAGS_MAX) }).then(onChanged, (cause) =>
193
- setError(cause instanceof Error ? cause.message : String(cause)),
194
- );
195
- };
196
- const pending = changes?.files.filter((each) => each.pending) ?? [];
197
- const shared =
198
- changes?.shared.filter((each) => each.files.some((file) => picked.has(file))) ?? [];
199
- const commit = async (event: React.FormEvent) => {
200
- event.preventDefault();
201
- if (shared.length && !confirming) {
202
- setConfirming(true);
203
- return;
204
- }
205
- setCommitting(true);
206
- setError('');
207
- setLeft(undefined);
208
- try {
209
- const done: unknown = await post('/commit', {
210
- id: session.id,
211
- message: message.trim(),
212
- files: [...picked],
213
- ...(confirming && { force: true }),
214
- });
215
- const nested =
216
- typeof done === 'object' && done !== null && 'left' in done && Array.isArray(done.left)
217
- ? done.left.filter((path): path is string => typeof path === 'string')
218
- : [];
219
- setLeft({ session: session.id, paths: nested });
220
- setMessage('');
221
- onChanged();
222
- } catch (cause) {
223
- setError(cause instanceof Error ? cause.message : String(cause));
224
- } finally {
225
- setCommitting(false);
226
- setConfirming(false);
227
- }
228
- };
229
-
230
- return (
231
- <div
232
- aria-label="Session details"
233
- className="flex max-h-[45vh] shrink-0 flex-col gap-3 overflow-y-auto border-b border-border bg-surface px-4 py-3 text-sm"
234
- >
235
- <div className="flex items-center gap-2">
236
- <Icon name="tag" size={14} className="shrink-0 text-muted" />
237
- <TagInput
238
- aria-label="Tags"
239
- list={listId}
240
- placeholder={(session.tags?.length ?? 0) < TAGS_MAX ? 'Add a tag…' : ''}
241
- value={session.tags ?? []}
242
- onChange={tag}
243
- className="min-w-0 flex-1"
244
- />
245
- <datalist id={listId}>
246
- {known
247
- .filter((each) => !session.tags?.includes(each))
248
- .map((each) => (
249
- <option key={each} value={each} />
250
- ))}
251
- </datalist>
252
- </div>
253
- {!!session.claims?.length && (
254
- <p className="text-xs text-secondary">
255
- <span className="font-medium text-foreground">Claimed</span> (other sessions see it before
256
- they edit):{' '}
257
- <span className="font-mono">
258
- {session.claims.map(({ path, note }) => (note ? `${path} (${note})` : path)).join(', ')}
259
- </span>
260
- </p>
261
- )}
262
- {focus && changes && !focused && (
263
- <p role="status" className="text-xs text-muted">
264
- {/* A session's files are read at each turn's end: a running turn's are not there yet. */}
265
- {session.running ? 'The changes to ' : 'No uncommitted change to '}
266
- <span className="font-mono">
267
- {focus.path.split(`${changes.repository.replace(/\/$/, '')}/`).join('')}
268
- </span>
269
- {session.running ? ' show here once the turn ends.' : ': committed or undone since.'}
270
- </p>
271
- )}
272
- {outside && (
273
- <p className="text-xs text-muted">
274
- This session works outside any git repository: no changes to commit.
275
- </p>
276
- )}
277
- {changes && (
278
- <>
279
- {pending.length === 0 ? (
280
- <p className="text-xs text-muted">
281
- {changes.files.length
282
- ? 'Everything this session changed is committed.'
283
- : 'No changes from this session yet.'}
284
- </p>
285
- ) : (
286
- <form
287
- aria-label="Commit"
288
- onSubmit={(event) => {
289
- void commit(event);
290
- }}
291
- className="flex flex-col gap-2"
292
- >
293
- <ul aria-label="Uncommitted files" className="m-0 flex list-none flex-col gap-1 p-0">
294
- {pending.map(({ path }) => {
295
- const others = changes.shared.filter((each) => each.files.includes(path));
296
- return (
297
- <li key={path} className="flex items-center gap-2">
298
- <Checkbox
299
- aria-label={`Commit ${path}`}
300
- checked={picked.has(path)}
301
- onCheckedChange={(checked: boolean) =>
302
- setPicked((was) => {
303
- const next = new Set(was);
304
- if (checked) next.add(path);
305
- else next.delete(path);
306
- return next;
307
- })
308
- }
309
- />
310
- <span className="min-w-0 truncate font-mono text-xs">{path}</span>
311
- {others.length > 0 && (
312
- <span
313
- className="flex shrink-0 items-center gap-1 text-xs text-warning"
314
- title={`Also changed by ${others.map((each) => each.title).join(', ')}`}
315
- >
316
- <Icon name="triangle-alert" size={12} />
317
- shared
318
- </span>
319
- )}
320
- </li>
321
- );
322
- })}
323
- </ul>
324
- {changes.shared.length > 0 && (
325
- <div
326
- role="note"
327
- className="rounded-md border border-border px-3 py-2 text-xs text-secondary"
328
- >
329
- Other sessions changed some of these files and have not committed them:
330
- <ul className="m-0 mt-1 flex list-none flex-col gap-0.5 p-0">
331
- {changes.shared.map((each) => (
332
- <li key={each.id}>
333
- <button
334
- type="button"
335
- className="cursor-pointer border-0 bg-transparent p-0 text-xs font-medium text-foreground underline-offset-2 hover:underline"
336
- onClick={() => onOpen(each.id)}
337
- >
338
- {each.title}
339
- </button>
340
- {each.running && ' (running)'}:{' '}
341
- <span className="font-mono">{each.files.join(', ')}</span>
342
- </li>
343
- ))}
344
- </ul>
345
- </div>
346
- )}
347
- <div className="flex items-center gap-2">
348
- <Input
349
- size="sm"
350
- aria-label="Commit message"
351
- placeholder="Commit message"
352
- value={message}
353
- onChange={(event) => {
354
- setMessage(event.currentTarget.value);
355
- setConfirming(false);
356
- }}
357
- className="min-w-0 flex-1"
358
- />
359
- <Button
360
- type="submit"
361
- size="sm"
362
- variant={confirming ? 'outline' : 'primary'}
363
- disabled={committing || session.running || !picked.size || !message.trim()}
364
- >
365
- <Icon name="git-branch" size={14} />
366
- {confirming ? 'Commit their changes too' : `Commit ${picked.size}`}
367
- </Button>
368
- </div>
369
- {confirming && (
370
- <p role="status" className="text-xs text-warning">
371
- The shared files hold the other sessions' changes too: they go in this commit.
372
- Click again to confirm.
373
- </p>
374
- )}
375
- {session.running && <p className="text-xs text-muted">Commit once the turn ends.</p>}
376
- {changes.diff && (
377
- <details
378
- open={diffOpen}
379
- onToggle={(event) => setDiffOpen(event.currentTarget.open)}
380
- >
381
- <summary className="cursor-pointer text-xs text-muted">Diff</summary>
382
- <div className="mt-1 flex flex-col gap-2">
383
- {files.map((file) => (
384
- <section
385
- key={file.path}
386
- ref={(element) => {
387
- if (element) fileRefs.current.set(file.path, element);
388
- else fileRefs.current.delete(file.path);
389
- }}
390
- aria-label={file.path}
391
- data-diff-file={file.path}
392
- data-focused={file === focused || undefined}
393
- className={cn(
394
- 'scroll-mt-2 overflow-hidden rounded-md border border-border-subtle bg-background',
395
- file === focused && 'border-accent ring-1 ring-accent',
396
- )}
397
- >
398
- <div className="flex h-7 items-center gap-2 border-b border-border-subtle bg-surface px-2.5 text-xs">
399
- <span className="min-w-0 truncate font-mono text-secondary">
400
- {file.path}
401
- </span>
402
- <span className="shrink-0 font-mono">
403
- {file.added > 0 && <span className="text-success">+{file.added}</span>}
404
- {file.added > 0 && file.removed > 0 && ' '}
405
- {file.removed > 0 && (
406
- <span className="text-destructive">−{file.removed}</span>
407
- )}
408
- </span>
409
- </div>
410
- <pre className="max-h-72 overflow-auto py-1 font-mono text-[11px] leading-4">
411
- {file.lines.map((line, at) => (
412
- <div
413
- key={at}
414
- className={cn(
415
- 'px-2.5',
416
- line[0] === '+'
417
- ? 'bg-success-subtle text-success'
418
- : line[0] === '-'
419
- ? 'bg-destructive-subtle text-destructive'
420
- : line.startsWith('@@')
421
- ? 'text-accent'
422
- : 'text-muted',
423
- )}
424
- >
425
- {line || ' '}
426
- </div>
427
- ))}
428
- </pre>
429
- </section>
430
- ))}
431
- </div>
432
- </details>
433
- )}
434
- </form>
435
- )}
436
- {changes.commits.length > 0 && (
437
- <ul aria-label="Commits" className="m-0 flex list-none flex-col gap-1 p-0">
438
- {[...changes.commits].reverse().map((each) => (
439
- <li key={each.sha} className="flex items-center gap-2 text-xs text-secondary">
440
- <Badge className="shrink-0 font-mono">{each.sha.slice(0, 7)}</Badge>
441
- <span className="min-w-0 truncate">{each.message.split('\n')[0]}</span>
442
- <span className="shrink-0 text-muted">
443
- {each.files.length} file{each.files.length === 1 ? '' : 's'}
444
- </span>
445
- </li>
446
- ))}
447
- </ul>
448
- )}
449
- </>
450
- )}
451
- {leftOut.length > 0 && (
452
- <p role="status" className="text-xs text-warning">
453
- Not committed: {leftOut.join(', ')} (
454
- {leftOut.length === 1 ? 'a nested repository' : 'nested repositories'}).
455
- </p>
456
- )}
457
- {error && (
458
- <p role="alert" className="text-xs text-destructive">
459
- {error}
460
- </p>
461
- )}
462
- </div>
463
- );
464
- }