@bridgebrew/sessions 0.0.38 → 0.0.43

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/branch-name.ts CHANGED
@@ -1,13 +1,24 @@
1
1
  // A session's branch name (research-083): from a model's answer (`type/topic`), else from the words of the message
2
2
  // that asked for the work.
3
+ /** The letters NFKD leaves whole (no base letter and mark to split them into), spelled in plain Latin (plugins#217). */
4
+ const LETTERS: Record<string, string> = { ß: 'ss', æ: 'ae', œ: 'oe', ø: 'o', ł: 'l', đ: 'd', ð: 'd', þ: 'th', ı: 'i' };
5
+ /** `text` lowercase in plain Latin letters where it has them: those letters spelled out, then accents dropped
6
+ * (`Straße Łódź` → `strasse lodz`). */
7
+ export const foldLetters = (text: string) =>
8
+ text
9
+ // ʼn first: NFKD splits it into an apostrophe and `n`, which would split the word.
10
+ .replace(/ʼn/g, 'n')
11
+ // NFKD before the rest: it reveals letters (`Ǽ` → `Æ` + accent, `𝐒` → `S`) the table and the lowercase then see.
12
+ .normalize('NFKD')
13
+ .toLowerCase()
14
+ .replace(/[ßæœøłđðþı]/g, (letter) => LETTERS[letter] ?? letter)
15
+ .replace(/[\u0300-\u036f]/g, '');
16
+
3
17
  /** A branch name from a message (research-083): its first words, lowercase, joined by `-`; empty when it has none.
4
18
  * A URL gives none of them (plugins#73). The fallback of a model's name (`typedBranch`). */
5
19
  export const branchSlug = (text: string) =>
6
- text
7
- .replace(/\b[a-z][a-z0-9+.-]*:\/\/\S*/gi, ' ')
8
- .toLowerCase()
9
- .normalize('NFKD')
10
- .replace(/[\u0300-\u036f'’]/g, '')
20
+ foldLetters(text.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S*/gi, ' '))
21
+ .replace(/['’]/g, '')
11
22
  .split(/[^a-z0-9]+/)
12
23
  .filter(Boolean)
13
24
  .slice(0, 6)
@@ -325,6 +325,42 @@ function CodeBlock({ children }: { children?: React.ReactNode }) {
325
325
  );
326
326
  }
327
327
 
328
+ /** Open in editor from the conversation (bridge-plugins#253): an agent's link to a file of the session's folder opens it
329
+ * in the code editor (`label`: `Open in VS Code on mac-mini`), at its line; none on a phone, nor without an editor. */
330
+ export interface FileOpener {
331
+ folder: string;
332
+ label: string;
333
+ open: (target: FileTarget) => void;
334
+ /** About to be used (a link pointed at, focused): the editor read again. */
335
+ refresh?: () => void;
336
+ /** Not available from this page (another computer): the link says so (`label`), and `open` only explains. */
337
+ unavailable?: boolean;
338
+ }
339
+ export interface FileTarget {
340
+ path: string;
341
+ line?: number;
342
+ column?: number;
343
+ }
344
+ const FileLinks = React.createContext<FileOpener | null>(null);
345
+ /** The file a link names inside `folder`: an absolute path, its position after it (`a.ts:12`, `a.ts:12:3`) or in its
346
+ * fragment (`a.ts#L12`, `#L12C3`), a Windows one too (`C:\\w\\a.ts:12`); none for any other link (a page of this Bridge,
347
+ * a file elsewhere). */
348
+ export const fileTarget = (href: string, folder: string): FileTarget | undefined => {
349
+ const [raw = '', fragment = ''] = href.split('#', 2);
350
+ let path: string;
351
+ try {
352
+ // A Windows path (`C:\\w\\a.ts`) read with `/`, as its folder: Windows takes either.
353
+ path = decodeURI(raw).replaceAll('\\', '/');
354
+ } catch {
355
+ return undefined;
356
+ }
357
+ const base = folder.replaceAll('\\', '/').replace(/\/$/, '');
358
+ const at = /:(\d+)(?::(\d+))?$/.exec(path) ?? /^L(\d+)(?:C(\d+))?$/.exec(fragment);
359
+ if (at?.index !== undefined && at.input === path) path = path.slice(0, at.index);
360
+ if (!path.startsWith(`${base}/`) || path.split('/').includes('..')) return undefined;
361
+ return { path, ...(at && { line: Number(at[1]) }), ...(at?.[2] && { column: Number(at[2]) }) };
362
+ };
363
+
328
364
  /** Markdown in the chat's type, GitHub's flavour (tables, bare URLs as links): no raw HTML (react-markdown escapes it),
329
365
  * external links in a new tab, local images and videos shown (`media.tsx`). */
330
366
  const markdown: Components = {
@@ -339,7 +375,25 @@ const markdown: Components = {
339
375
  ),
340
376
  // A link of this Bridge stays an anchor without a target, which the shell's link rule follows (research-048: a plain
341
377
  // click here, ⌘ or a middle click beside, ⌥ on a new desk); another opens in a new tab, which gets no `opener`.
342
- a: ({ node: _node, ...props }) => {
378
+ a: function Link({ node: _node, ...props }) {
379
+ const opener = React.useContext(FileLinks);
380
+ const file = opener && props.href ? fileTarget(props.href, opener.folder) : undefined;
381
+ if (opener && file)
382
+ return (
383
+ <a
384
+ {...props}
385
+ className="text-accent underline-offset-2 hover:underline"
386
+ title={opener.label}
387
+ aria-disabled={opener.unavailable || undefined}
388
+ data-open-in-editor
389
+ onPointerEnter={opener.refresh}
390
+ onFocus={opener.refresh}
391
+ onClick={(event) => {
392
+ event.preventDefault();
393
+ opener.open(file);
394
+ }}
395
+ />
396
+ );
343
397
  let internal = false;
344
398
  if (typeof location !== 'undefined' && props.href) {
345
399
  try {
@@ -381,7 +435,10 @@ const markdown: Components = {
381
435
  ),
382
436
  };
383
437
  const remarkPlugins = [remarkGfm];
384
- const urlTransform = (url: string, key: string) => mediaUrl(url, key, defaultUrlTransform);
438
+ // A link to a Windows path (`C:\\w\\a.ts`) is kept: react-markdown's filter reads `C:` as a scheme and drops it, and
439
+ // Open in editor reads it (`fileTarget`); a link to no file of the session stays inert (`c:` opens nothing).
440
+ const urlTransform = (url: string, key: string) =>
441
+ key === 'href' && /^[a-z]:[\\/]/i.test(url) ? url : mediaUrl(url, key, defaultUrlTransform);
385
442
  /** The blinking caret after a streaming reply's last block (a pseudo-element: no text). */
386
443
  const caret =
387
444
  "[&>:last-child]:after:ml-0.5 [&>:last-child]:after:inline-block [&>:last-child]:after:h-[1em] [&>:last-child]:after:w-[0.45em] [&>:last-child]:after:translate-y-[0.15em] [&>:last-child]:after:animate-pulse [&>:last-child]:after:rounded-[1px] [&>:last-child]:after:bg-foreground [&>:last-child]:after:content-['']";
@@ -940,6 +997,8 @@ export interface ConversationProps {
940
997
  onOpenChange?: ((path: string) => void) | undefined;
941
998
  /** The session's lineage (./children.tsx): its children's cards, its parent; without it, none drawn. */
942
999
  lineage?: Lineage | undefined;
1000
+ /** Its links to files of its folder open in the code editor (none: plain links). */
1001
+ openFile?: FileOpener | undefined;
943
1002
  }
944
1003
 
945
1004
  /** No child delegated in a turn: the same array each render. */
@@ -997,6 +1056,7 @@ export function Conversation({
997
1056
  onDecisionShown,
998
1057
  onOpenChange,
999
1058
  lineage,
1059
+ openFile,
1000
1060
  }: ConversationProps) {
1001
1061
  /** Turns opened or folded by the user, by key: otherwise a completed turn is folded. */
1002
1062
  const [unfolded, setUnfolded] = React.useState<Record<number, boolean>>({});
@@ -1050,6 +1110,22 @@ export function Conversation({
1050
1110
  };
1051
1111
  }, [events, cut]);
1052
1112
  const subagents = React.useMemo(() => subagentsByTurn(turns, events), [turns, events]);
1113
+ // The same opener while its folder and label stay: a new one would redraw every link at each streamed delta.
1114
+ const openNow = React.useRef(openFile);
1115
+ openNow.current = openFile;
1116
+ const opener = React.useMemo(
1117
+ () =>
1118
+ openFile?.folder && openFile.label
1119
+ ? {
1120
+ folder: openFile.folder,
1121
+ label: openFile.label,
1122
+ open: (target: FileTarget) => openNow.current?.open(target),
1123
+ refresh: () => openNow.current?.refresh?.(),
1124
+ ...(openFile.unavailable && { unavailable: true }),
1125
+ }
1126
+ : null,
1127
+ [openFile?.folder, openFile?.label, openFile?.unavailable],
1128
+ );
1053
1129
  const shownLive = React.useMemo(() => ownLive(live), [live]);
1054
1130
  const last = turns.findLast((turn) => turn.start || turn.partial);
1055
1131
  // Each turn's children (bridge#212): the delegations its calls made, else those made while it was the last started.
@@ -1060,6 +1136,7 @@ export function Conversation({
1060
1136
  );
1061
1137
  return (
1062
1138
  <LineageContext.Provider value={lineage ?? null}>
1139
+ <FileLinks.Provider value={opener}>
1063
1140
  <MediaWorkspace.Provider value={workspace}>
1064
1141
  <MediaOrigins.Provider value={origins}>
1065
1142
  <ol
@@ -1085,6 +1162,7 @@ export function Conversation({
1085
1162
  </ol>
1086
1163
  </MediaOrigins.Provider>
1087
1164
  </MediaWorkspace.Provider>
1165
+ </FileLinks.Provider>
1088
1166
  </LineageContext.Provider>
1089
1167
  );
1090
1168
  }
package/browser/index.tsx CHANGED
@@ -182,6 +182,8 @@ export const shownWorktree = (workspace: { slug: string }) => {
182
182
  return shown !== '' && shown !== workspace.slug ? shown : undefined;
183
183
  };
184
184
  /** `url` asking for worktree `worktree`'s sessions only, when there is one. */
185
+ /** Open in editor from another computer (the host's `local`, bridge-plugins#253): its links say so instead of opening. */
186
+ const notLocal = 'Open in editor is not available yet from another computer';
185
187
  const forWorktree = (url: string, worktree: string | undefined) =>
186
188
  worktree === undefined
187
189
  ? url
@@ -468,7 +470,16 @@ export const afterLive = (live: Live | null, event: LiveEvent): Live | null => {
468
470
  if (event.type === 'text') return { ...live, text: live.text + (event.text ?? '') };
469
471
  if (event.type === 'thought') return { ...live, thought: live.thought + (event.text ?? '') };
470
472
  if (event.type === 'plan') return { ...live, plan: event.entries ?? [] };
471
- if (event.type === 'usage') return { ...live, usage: { used: event.used, size: event.size } };
473
+ // Given in parts (Claude: `used` per message, `size` alone on its result): a part keeps the other.
474
+ if (event.type === 'usage')
475
+ return {
476
+ ...live,
477
+ usage: {
478
+ ...live.usage,
479
+ ...(event.used !== undefined && { used: event.used }),
480
+ ...(event.size !== undefined && { size: event.size }),
481
+ },
482
+ };
472
483
  if (event.type === 'decision') return { ...live, decisions: [...live.decisions, event] };
473
484
  if (event.type === 'view/draft')
474
485
  return {
@@ -1471,6 +1482,41 @@ function Sessions({
1471
1482
  .then(readJson),
1472
1483
  [workspace, api, node],
1473
1484
  );
1485
+ /** Open in editor (bridge-plugins#253): the git plugin's editor and this Bridge's computer; the conversation's links to
1486
+ * the session's files open in it. Read at first, when the page comes back to the front, and when a link is pointed
1487
+ * at: a setting changed meanwhile never shows the editor it no longer picks. */
1488
+ const [editor, setEditor] = React.useState<{ label: string; machine: string; local: boolean }>();
1489
+ const readEditor = React.useRef<() => void>(() => {});
1490
+ React.useEffect(() => {
1491
+ let live = true;
1492
+ readEditor.current = () =>
1493
+ void workspace
1494
+ .fetch(`/${encodeURIComponent(workspace.slug)}/api/git/editors`)
1495
+ .then(readJson)
1496
+ .then((body) => {
1497
+ if (!live) return;
1498
+ const chosen = isRecord(body) && isRecord(body.chosen) ? body.chosen : undefined;
1499
+ const machine = isRecord(body) ? body.machine : undefined;
1500
+ const local = isRecord(body) && body.local === true;
1501
+ if (typeof chosen?.label === 'string' && typeof machine === 'string') {
1502
+ const label = chosen.label;
1503
+ setEditor((was) =>
1504
+ was?.label === label && was.machine === machine && was.local === local
1505
+ ? was
1506
+ : { label, machine, local },
1507
+ );
1508
+ } else setEditor(undefined);
1509
+ })
1510
+ .catch(() => {});
1511
+ readEditor.current();
1512
+ const again = () => readEditor.current();
1513
+ window.addEventListener('focus', again);
1514
+ return () => {
1515
+ live = false;
1516
+ readEditor.current = () => {};
1517
+ window.removeEventListener('focus', again);
1518
+ };
1519
+ }, [workspace]);
1474
1520
  /** The listing again, for every copy (the store's, which also polls while a session no copy shows runs, and wakes
1475
1521
  * the snoozed); a workspace restarting (`starting`) is tried again, not reported. */
1476
1522
  const load = (): Promise<boolean> => {
@@ -2623,7 +2669,7 @@ function Sessions({
2623
2669
  const sessionFolder =
2624
2670
  session && session.node !== node
2625
2671
  ? undefined
2626
- : (session?.branch?.folder ?? listing.project?.path ?? listing.workspace?.folder);
2672
+ : (session?.branch?.folder ?? session?.worktree?.folder ?? listing.project?.path ?? listing.workspace?.folder);
2627
2673
  const relative = (value: string) =>
2628
2674
  sessionFolder ? value.split(`${sessionFolder.replace(/[\\/]$/, '')}/`).join('') : value;
2629
2675
  // A decision whose row is in view is answered there; the dock takes the first other one.
@@ -3234,6 +3280,37 @@ function Sessions({
3234
3280
  showPanel();
3235
3281
  }}
3236
3282
  lineage={lineageOf}
3283
+ openFile={
3284
+ editor && sessionFolder && current
3285
+ ? {
3286
+ folder: sessionFolder,
3287
+ // From another computer (the host's `local`), a link says it is not
3288
+ // available yet instead of opening.
3289
+ label: editor.local
3290
+ ? `Open in ${editor.label} on ${editor.machine}`
3291
+ : notLocal,
3292
+ refresh: () => readEditor.current(),
3293
+ unavailable: !editor.local,
3294
+ open: ({ path, line, column }) =>
3295
+ void (
3296
+ editor.local
3297
+ ? post('/open-in-editor', {
3298
+ id: current,
3299
+ path,
3300
+ ...(line && { line }),
3301
+ ...(column && { column }),
3302
+ })
3303
+ : Promise.reject(new Error(notLocal))
3304
+ ).catch((cause: unknown) =>
3305
+ toast({
3306
+ variant: 'error',
3307
+ title: `${path} not opened`,
3308
+ description: cause instanceof Error ? cause.message : String(cause),
3309
+ }),
3310
+ ),
3311
+ }
3312
+ : undefined
3313
+ }
3237
3314
  />
3238
3315
  </div>
3239
3316
  </GalleryPins.Provider>
package/delegations.ts CHANGED
@@ -115,6 +115,7 @@
115
115
  // running delegation that was neither continued nor is running nor holds a queue, and delivers what is done.
116
116
  import { createHash, randomUUID } from 'node:crypto';
117
117
  import { cutText } from './text.ts';
118
+ import { foldLetters } from './branch-name.ts';
118
119
  import { z } from 'zod';
119
120
  import { actsAs } from './peers.ts';
120
121
  import { checkAnswer, isQuestion, type Answer, type Answers, type Question } from './answers.ts';
@@ -699,10 +700,7 @@ ${input.prompt}`;
699
700
  /** The git branch of a child's worktree given none: `child-`, its title in kebab case (40 characters at most), then the
700
701
  * delegation id's first 8 hex digits. */
701
702
  export const branchOf = (title: string, id: string) => {
702
- const words = title
703
- .normalize('NFKD')
704
- .replace(/[\u0300-\u036f]/g, '')
705
- .toLowerCase()
703
+ const words = foldLetters(title)
706
704
  .replace(/[^a-z0-9]+/g, '-')
707
705
  .slice(0, 40)
708
706
  .replace(/^-+|-+$/g, '');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/sessions",
3
- "version": "0.0.38",
3
+ "version": "0.0.43",
4
4
  "license": "MIT",
5
5
  "description": "Conversations with agents, in the workspace or in a project, through the Profile.",
6
6
  "keywords": [
@@ -17,6 +17,9 @@
17
17
  "!**/*.test.tsx",
18
18
  "!vitest.config.ts"
19
19
  ],
20
+ "engines": {
21
+ "bridge": ">=0.0.1-nightly.20261123.1"
22
+ },
20
23
  "bridge": {
21
24
  "kind": "application",
22
25
  "title": "Sessions",
@@ -48,7 +51,7 @@
48
51
  "version": "1.0"
49
52
  },
50
53
  "harness": {
51
- "version": "1.0"
54
+ "version": "1.1"
52
55
  },
53
56
  "project": {
54
57
  "version": "1.0",
@@ -61,6 +64,10 @@
61
64
  "github": {
62
65
  "version": "1.0",
63
66
  "optional": true
67
+ },
68
+ "git": {
69
+ "version": "1.1",
70
+ "optional": true
64
71
  }
65
72
  }
66
73
  },
@@ -1063,8 +1070,5 @@
1063
1070
  "cordis": "4.0.0-rc.11",
1064
1071
  "react": "19.3.0"
1065
1072
  },
1066
- "releaseStage": "dev",
1067
- "engines": {
1068
- "bridge": ">=0.0.1-nightly.20261120.1"
1069
- }
1073
+ "releaseStage": "dev"
1070
1074
  }
package/server.ts CHANGED
@@ -159,7 +159,7 @@
159
159
  import { basename, dirname, extname, isAbsolute, join, relative, sep } from 'node:path';
160
160
  import type { Context } from 'cordis';
161
161
  import { z } from 'zod';
162
- import { cutText, isRecord, oneLine } from './text.ts';
162
+ import { cutText, isRecord, oneLine, tailText } from './text.ts';
163
163
  import type { SessionsService, SessionView, Shown } from './contract.ts';
164
164
  import {
165
165
  apply as applyView,
@@ -869,6 +869,12 @@ const viewActivateBody = z.strictObject({
869
869
  });
870
870
  const tagsBody = z.strictObject({ id: z.string().min(1), tags: z.array(z.string()).max(TAGS_MAX) });
871
871
  const changesBody = z.strictObject({ id: z.string().min(1), path: z.string().min(1).optional() });
872
+ const openBody = z.strictObject({
873
+ id: z.string().min(1),
874
+ path: z.string().min(1).optional(),
875
+ line: z.number().int().min(1).optional(),
876
+ column: z.number().int().min(1).optional(),
877
+ });
872
878
  const linesBody = z.strictObject({
873
879
  id: z.string().min(1),
874
880
  path: z.string().min(1),
@@ -1219,6 +1225,8 @@ const GIT_STATUS: Record<string, number> = {
1219
1225
  stale_snapshot: 409,
1220
1226
  busy: 409,
1221
1227
  timeout: 504,
1228
+ // No code editor on this computer (Open in editor, bridge-plugins#253).
1229
+ no_editor: 409,
1222
1230
  // git itself refused (a hook, a signer): its words reach the person.
1223
1231
  failed: 409,
1224
1232
  };
@@ -2844,7 +2852,7 @@ export async function apply(ctx: Context, config?: unknown) {
2844
2852
  else if (line.type === 'assistant/message') talk.push(`Agent: ${line.text}`);
2845
2853
  }
2846
2854
  // The conversation's newest part when it is long.
2847
- const conversation = talk.join('\n\n').slice(-40_000);
2855
+ const conversation = tailText(talk.join('\n\n'), 40_000);
2848
2856
  return writeOnce({
2849
2857
  ...options,
2850
2858
  ...(harness !== undefined && { harness }),
@@ -3037,6 +3045,29 @@ export async function apply(ctx: Context, config?: unknown) {
3037
3045
  },
3038
3046
  });
3039
3047
 
3048
+ /** Session `id` follows the mode its open harness session `agent` runs when the agent took it itself (it left Plan
3049
+ * once its plan was approved): the record takes it, so the mode picker and the next open do, it is logged, and the
3050
+ * token is granted for it. The agent's change wins over the user's last pick. Read when it runs, on the queue lock
3051
+ * (a turn's start waits for it), so changes apply in order and the last one wins; nothing for a harness session no
3052
+ * longer open, or a mode its agent does not list (the next open would refuse it). */
3053
+ const followMode = (id: string, agent: HarnessSession) =>
3054
+ serial(id, async () => {
3055
+ const mode = agent.mode;
3056
+ const found = await sessions.get(id);
3057
+ if (mode === undefined || !found || found.value.mode === mode || open.get(id) !== agent)
3058
+ return;
3059
+ const path = await sessionFolder(found.node, found.value);
3060
+ if (path === undefined) return;
3061
+ const modes = await listOf('modes', found.value.harness, found.node, path);
3062
+ const known = modes.find((each) => each.id === mode);
3063
+ if (modes.length && !known) return;
3064
+ if (agent.mode !== mode || open.get(id) !== agent) return; // changed again: its own call follows
3065
+ const token = tokens.get(id);
3066
+ if (token !== undefined) await grant(id, token, found.value.harness, found.node, path, mode);
3067
+ await change(id, ({ options: _old, ...now }) => ({ ...now, mode }));
3068
+ append(id, 'mode/changed', { mode, name: known?.name ?? mode });
3069
+ });
3070
+
3040
3071
  ctx.router.route(ctx, {
3041
3072
  method: 'POST',
3042
3073
  path: '/sessions/mode',
@@ -3108,6 +3139,9 @@ export async function apply(ctx: Context, config?: unknown) {
3108
3139
  name: known?.name ?? mode,
3109
3140
  ...(kept && { options: kept }),
3110
3141
  });
3142
+ // The agent took another mode right after this one: its event may have been followed before this write.
3143
+ if (harness && !harness.closed && harness.mode !== mode)
3144
+ finalize(id, followMode(id, harness).catch(log(`session ${id}: agent's mode not stored`)));
3111
3145
  return { ok: true };
3112
3146
  },
3113
3147
  });
@@ -4261,6 +4295,16 @@ export async function apply(ctx: Context, config?: unknown) {
4261
4295
  ),
4262
4296
  );
4263
4297
  }
4298
+ // The agent changed its mode itself: the record follows it (`followMode`).
4299
+ if (received.type === 'mode') {
4300
+ const emitter = agent;
4301
+ if (emitter)
4302
+ finalize(
4303
+ id,
4304
+ followMode(id, emitter).catch(log(`session ${id}: mode ${received.mode} not stored`)),
4305
+ );
4306
+ return;
4307
+ }
4264
4308
  // A `show_view` call's input as the agent writes it goes live as `view/draft` (the program so far), never stored;
4265
4309
  // another tool's draft goes nowhere (research-036 streaming).
4266
4310
  if (received.type === 'draft') {
@@ -4308,7 +4352,13 @@ export async function apply(ctx: Context, config?: unknown) {
4308
4352
  } else if (event.type === 'text') acc.text += event.text;
4309
4353
  else if (event.type === 'thought') acc.thought += event.text;
4310
4354
  else if (event.type === 'plan') acc.plan = event.entries;
4311
- else if (event.type === 'usage') acc.usage = { used: event.used, size: event.size };
4355
+ // A driver may give its usage in parts (Claude: `used` per message, `size` alone on its result): each keeps the other.
4356
+ else if (event.type === 'usage')
4357
+ acc.usage = {
4358
+ ...acc.usage,
4359
+ ...(event.used !== undefined && { used: event.used }),
4360
+ ...(event.size !== undefined && { size: event.size }),
4361
+ };
4312
4362
  else if (event.type === 'decision-withdrawn') {
4313
4363
  // Closed as an expiry is: stored, and a later answer refused (409). The stored line tells the pages.
4314
4364
  expire(event.id);
@@ -6123,6 +6173,36 @@ export async function apply(ctx: Context, config?: unknown) {
6123
6173
  },
6124
6174
  });
6125
6175
 
6176
+ // Open in editor (bridge-plugins#253): the session's folder, or a file in it or in its repository (a path relative to
6177
+ // the repository's top as the changes list it, or absolute as the conversation writes it), at a line; in the code
6178
+ // editor of the `git` plugin's setting, on this Bridge's computer. A person's action, never an agent's.
6179
+ ctx.router.route(ctx, {
6180
+ method: 'POST',
6181
+ path: '/sessions/open-in-editor',
6182
+ agent: false,
6183
+ handle: async ({ body, local }) => {
6184
+ // The host says whether the page runs on Bridge's own computer (from its connection): an editor opened from
6185
+ // another one would open here, out of its person's sight.
6186
+ if (local !== true)
6187
+ throw refused('not_local', 'Open in editor is not available yet from another computer', 403);
6188
+ const { id, path, line, column } = parse(openBody, body, 'POST /sessions/open-in-editor takes { id, path?, line?, column? }');
6189
+ const { node, value } = await find(new URLSearchParams({ id }));
6190
+ const service = git();
6191
+ if (typeof service?.openInEditor !== 'function')
6192
+ throw refused('no_editor', 'Open in editor needs the git plugin 0.0.3 or later: install or update Git', 409);
6193
+ const folder = await sessionFolder(node, value);
6194
+ if (folder === undefined) throw refused('not_found', `session ${id} works in no folder`, 404);
6195
+ const root = (await repositoryOf(folder))?.top ?? folder;
6196
+ const target = path === undefined ? folder : isAbsolute(path) ? path : join(root, path);
6197
+ return {
6198
+ id,
6199
+ ...(await service
6200
+ .openInEditor(root, target, { ...(line && { line }), ...(column && { column }) })
6201
+ .catch((error: unknown) => Promise.reject(fromGit(error)))),
6202
+ };
6203
+ },
6204
+ });
6205
+
6126
6206
  ctx.router.route(ctx, {
6127
6207
  method: 'POST',
6128
6208
  path: '/sessions/commit',
package/text.ts CHANGED
@@ -8,6 +8,15 @@ export const cutText = (text: string, max: number) => {
8
8
  return text.slice(0, code >= 0xd800 && code <= 0xdbff ? max - 1 : max);
9
9
  };
10
10
 
11
+ /** The end of `text`, at most `max` UTF-16 units, never starting on the second half of a surrogate pair (bridge#319). */
12
+ export const tailText = (text: string, max: number) => {
13
+ if (text.length <= max) return text;
14
+ if (max <= 0) return '';
15
+ const start = text.length - max;
16
+ const code = text.charCodeAt(start);
17
+ return text.slice(code >= 0xdc00 && code <= 0xdfff ? start + 1 : start);
18
+ };
19
+
11
20
  /** `text` on one line, within `max` characters (an ellipsis when cut). */
12
21
  export const oneLine = (text: string, max: number) => {
13
22
  const line = text.replace(/\s+/g, ' ').trim();