@bridgebrew/sessions 0.0.9 → 0.0.20

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.
@@ -67,6 +67,8 @@ export interface Lineage {
67
67
  parent?: string | undefined;
68
68
  /** Where a link to session `id` goes. */
69
69
  to: (id: string) => FollowTarget;
70
+ /** Whether session `id` can be opened (an archived one cannot: the list shows none); without it, every one can. */
71
+ opens?: ((id: string) => boolean) | undefined;
70
72
  /** Stops child session `id` (its session Stop); without it, no Stop. */
71
73
  stop?: ((id: string) => void) | undefined;
72
74
  /** Where a link to the shown session's sub-agent `id` goes (bridge#212 S8, ./subagents.tsx); without it, none. */
@@ -587,11 +589,22 @@ export function BackgroundWork() {
587
589
  );
588
590
  }
589
591
 
590
- /** A child session's parent, beside its title: a link to it. */
592
+ /** A child session's parent, beside its title: a link to it; an archived one, its name only. */
591
593
  export function ParentLink({ parent }: { parent: string }) {
592
594
  const lineage = React.useContext(LineageContext);
593
595
  if (!lineage) return null;
594
596
  const title = lineage.sessions.get(parent)?.title;
597
+ if (lineage.opens?.(parent) === false)
598
+ return (
599
+ <span
600
+ data-who="parent"
601
+ className="inline-flex min-w-0 max-w-56 shrink items-center gap-1 text-xs text-muted"
602
+ >
603
+ <Icon name="arrow-up" size={13} className="shrink-0" />
604
+ <span className="shrink-0">Parent (archived)</span>
605
+ {title && <span className="truncate text-secondary">{title}</span>}
606
+ </span>
607
+ );
595
608
  return (
596
609
  <ScreenLink
597
610
  to={lineage.to(parent)}
@@ -637,7 +650,7 @@ export function TaskFrom({
637
650
  <p data-who="task-from" className="mb-1 flex min-w-0 items-center gap-1.5 text-xs text-muted">
638
651
  <Icon name={kind === 'delegation' ? 'users' : 'mail'} size={12} className="shrink-0" />
639
652
  <span className="shrink-0">{kind === 'delegation' ? 'Task from' : 'Message from'}</span>
640
- {from && lineage ? (
653
+ {from && lineage && lineage.opens?.(from) !== false ? (
641
654
  <ScreenLink to={lineage.to(from)} className="min-w-0 truncate text-secondary">
642
655
  {title}
643
656
  </ScreenLink>
@@ -1703,7 +1703,7 @@ const PendingDecision = React.memo(function PendingDecision({
1703
1703
  const deny = event.options?.find((option) => option.kind === 'deny');
1704
1704
  const allow = event.options?.find((option) => option.kind === 'allow');
1705
1705
  const label = decisionLabel(event);
1706
- // A question is read whole (its options mean nothing without it); a permission's title is its tool call's, one line.
1706
+ // A question is read whole (its options mean nothing without it); a permission's title says what the agent wants, two lines at most.
1707
1707
  const question = label === 'Answer needed';
1708
1708
  // Its questions (an agent's question tool), each drawn with its own words: no title above them.
1709
1709
  const questions = questionsAsked(event);
@@ -1732,7 +1732,7 @@ const PendingDecision = React.memo(function PendingDecision({
1732
1732
  <span
1733
1733
  data-title
1734
1734
  className={cn(
1735
- 'min-w-0 truncate text-secondary',
1735
+ 'line-clamp-2 min-w-0 break-words text-secondary',
1736
1736
  title !== undefined && asked === title && 'sr-only',
1737
1737
  )}
1738
1738
  >
@@ -1764,6 +1764,7 @@ const PendingDecision = React.memo(function PendingDecision({
1764
1764
  busy={busy}
1765
1765
  onAnswer={answer}
1766
1766
  primary={primary}
1767
+ draft={event.id}
1767
1768
  />
1768
1769
  </div>
1769
1770
  )}
@@ -2130,6 +2131,7 @@ export function DecisionDock({
2130
2131
  busy={busy}
2131
2132
  onAnswer={onAnswer}
2132
2133
  primary={primary}
2134
+ draft={event.id}
2133
2135
  />
2134
2136
  </section>
2135
2137
  );
@@ -6,11 +6,21 @@ import * as React from 'react';
6
6
  import { Button, Checkbox, Icon, Textarea, cn, isComposing } from '@bridge/ui';
7
7
  import { checkAnswer, type Answers, type Question } from '../answers.ts';
8
8
 
9
+ /** What was chosen and typed in a decision's card, not sent yet. */
10
+ export interface Draft {
11
+ chosen: Record<string, string[]>;
12
+ texts: Record<string, string>;
13
+ }
14
+ /** The shown session's drafts by decision id (#111): a card's answers belong to its decision, not to the card, so they
15
+ * follow it from the dock to its row and never show on another decision. */
16
+ export const DecisionDrafts = React.createContext<Map<string, Draft> | undefined>(undefined);
17
+
9
18
  export function DecisionQuestions({
10
19
  questions,
11
20
  busy,
12
21
  onAnswer,
13
22
  primary,
23
+ draft,
14
24
  }: {
15
25
  questions: Question[];
16
26
  busy: boolean;
@@ -18,9 +28,18 @@ export function DecisionQuestions({
18
28
  onAnswer: (answer: Answers | null) => void;
19
29
  /** Its first control, focused when nothing else is. */
20
30
  primary?: React.Ref<HTMLButtonElement> | undefined;
31
+ /** The decision's id: its draft is kept in `DecisionDrafts` under it. */
32
+ draft?: string | undefined;
21
33
  }) {
22
- const [chosen, setChosen] = React.useState<Record<string, string[]>>({});
23
- const [texts, setTexts] = React.useState<Record<string, string>>({});
34
+ const drafts = React.useContext(DecisionDrafts);
35
+ const kept = draft === undefined ? undefined : drafts?.get(draft);
36
+ const [chosen, setChosen] = React.useState<Record<string, string[]>>(kept?.chosen ?? {});
37
+ const [texts, setTexts] = React.useState<Record<string, string>>(kept?.texts ?? {});
38
+ // Kept even once sent: a submission that fails leaves the decision open with its answer, still edited. A closed
39
+ // decision draws no card again, and the map goes with the session shown.
40
+ React.useEffect(() => {
41
+ if (draft !== undefined) drafts?.set(draft, { chosen, texts });
42
+ }, [drafts, draft, chosen, texts]);
24
43
  const answers: Answers = {
25
44
  answers: questions.flatMap((question) => {
26
45
  const options = chosen[question.id] ?? [];
package/browser/index.tsx CHANGED
@@ -164,6 +164,7 @@ import { Elapsed } from './elapsed.tsx';
164
164
  import { showLink } from './open-link.tsx';
165
165
  import { viewerActivity } from '../viewer-activity.ts';
166
166
  import { answerBody, type Answer } from '../answers.ts';
167
+ import { DecisionDrafts, type Draft } from './decision-questions.tsx';
167
168
 
168
169
  export const name = 'sessions';
169
170
  export const inject = ['slots', 'workspace', 'nodes', 'sidebar', 'shell', 'screen'];
@@ -1168,6 +1169,9 @@ function Sessions({
1168
1169
  const { session: asked, subagent: shownSub } = itemParts(
1169
1170
  override && override.over === item ? override.id : (item ?? fallback),
1170
1171
  );
1172
+ /** The session asked here now, read by an action that answers after the person may have opened another. */
1173
+ const shown = React.useRef(asked);
1174
+ shown.current = asked;
1171
1175
  // A session that is gone (archived, another node's) shows a new chat.
1172
1176
  const current =
1173
1177
  asked && listing && !listing.sessions.some((each) => each.id === asked) ? undefined : asked;
@@ -1762,13 +1766,25 @@ function Sessions({
1762
1766
  kin.has(id)
1763
1767
  ? { item: id }
1764
1768
  : { node: 'root', screen: { plugin: name, id: screen }, item: id },
1769
+ // The workspace's whole list holds every session not archived; a project's or a worktree's holds its own.
1770
+ opens: (id) => kin.has(id) || node !== 'root' || worktree !== undefined,
1765
1771
  stop: (id) => stopChild.current(id),
1766
1772
  // Its sub-agents' views are this window's items too (bridge#212 S8).
1767
1773
  subagentTo: (sub) => ({ item: subagentItem(session.id, sub) }),
1768
1774
  stopSubagent: (sub) => stopSub.current(sub),
1769
1775
  }
1770
1776
  : undefined,
1771
- [kin, session?.id, session?.delegations, session?.parent, session?.subagents, shownSub, screen],
1777
+ [
1778
+ kin,
1779
+ session?.id,
1780
+ session?.delegations,
1781
+ session?.parent,
1782
+ session?.subagents,
1783
+ shownSub,
1784
+ screen,
1785
+ node,
1786
+ worktree,
1787
+ ],
1772
1788
  );
1773
1789
  // Its tabs beside the chat (./tabs.tsx: `sessions.tab`, an agent's browser).
1774
1790
  const tabs = useSessionTabs(current);
@@ -1842,6 +1858,8 @@ function Sessions({
1842
1858
  ),
1843
1859
  [renderSlot, node, sessionNode, current, post],
1844
1860
  );
1861
+ /** What was typed in the shown session's question cards, by decision (#111): a new map on a switch of session. */
1862
+ const drafts = React.useMemo(() => new Map<string, Draft>(), [current]);
1845
1863
  const galleryPins = React.useMemo(
1846
1864
  () =>
1847
1865
  current && session
@@ -1913,9 +1931,10 @@ function Sessions({
1913
1931
  choose(undefined);
1914
1932
  promptHandle.current?.focus();
1915
1933
  };
1916
- const answer = async (seq: number, decision: string, option: Answer) => {
1934
+ const answer = async (decision: string, option: Answer) => {
1917
1935
  if (!current) return;
1918
- const key = `${current}:${seq}`;
1936
+ // By the decision, not its seq: a docked one's (-1) is the next one's once it is answered (#111).
1937
+ const key = `${current}:${decision}`;
1919
1938
  setError('');
1920
1939
  setAnswering((was) => ({ ...was, [key]: true }));
1921
1940
  try {
@@ -2059,13 +2078,15 @@ function Sessions({
2059
2078
  failed(`Could not ${action === 'unread' ? 'mark it unread' : action} the session`)(cause);
2060
2079
  return;
2061
2080
  }
2062
- if (leaving) choose(next);
2081
+ // Another session opened while the request ran stays shown: only the one acted on gives way to the next.
2082
+ const moved = leaving && shown.current === each.id;
2083
+ if (moved) choose(next);
2063
2084
  /** Undoing a settle or an archive that left the open session opens it again, and snoozes it again when that ended
2064
2085
  * its snooze (and its time is still ahead). */
2065
2086
  const back = async () => {
2066
2087
  if (each.snoozedUntil && Date.parse(each.snoozedUntil) > Date.now())
2067
2088
  await triage(each.id, 'snooze', { until: each.snoozedUntil });
2068
- if (leaving) choose(each.id);
2089
+ if (moved) choose(each.id);
2069
2090
  };
2070
2091
  if (action === 'settle') {
2071
2092
  offerUndo('Session settled', each.title, async () => {
@@ -2115,12 +2136,13 @@ function Sessions({
2115
2136
  failed('Could not snooze the session')(cause);
2116
2137
  return;
2117
2138
  }
2118
- if (leaving) choose(next);
2139
+ const moved = leaving && shown.current === each.id;
2140
+ if (moved) choose(next);
2119
2141
  offerUndo('Session snoozed', `${each.title}, until ${when(until)}`, async () => {
2120
2142
  await triage(each.id, 'wake');
2121
2143
  if (each.settledAt && !each.pinnedAt) await triage(each.id, 'settle');
2122
2144
  if (unpin && each.pinnedAt) await triage(each.id, 'pin', { order: each.pinOrder });
2123
- if (leaving) choose(each.id);
2145
+ if (moved) choose(each.id);
2124
2146
  });
2125
2147
  await load();
2126
2148
  };
@@ -2550,13 +2572,13 @@ function Sessions({
2550
2572
  )}
2551
2573
  {docked && (
2552
2574
  <DecisionDock
2553
- key={docked.seq}
2575
+ key={`${current}:${docked.id}`}
2554
2576
  event={docked}
2555
2577
  relative={relative}
2556
- busy={!!answering[`${current}:${docked.seq}`]}
2578
+ busy={!!answering[`${current}:${docked.id}`]}
2557
2579
  more={waiting.length - 1}
2558
2580
  onRow={onRows[docked.seq] === false}
2559
- onAnswer={(option) => void answer(docked.seq, docked.id!, option)}
2581
+ onAnswer={(option) => void answer(docked.id!, option)}
2560
2582
  />
2561
2583
  )}
2562
2584
  </>
@@ -2697,7 +2719,7 @@ function Sessions({
2697
2719
  </Tooltip>
2698
2720
  );
2699
2721
 
2700
- return (
2722
+ const page = (
2701
2723
  <section
2702
2724
  aria-label="Screen"
2703
2725
  className={cn('flex min-h-0 flex-1 overflow-hidden', reset)}
@@ -3140,7 +3162,7 @@ function Sessions({
3140
3162
  onReview={() => {
3141
3163
  if (!details) toggleDetails();
3142
3164
  }}
3143
- onAnswer={(event, option) => answer(event.seq, event.id!, option)}
3165
+ onAnswer={(event, option) => answer(event.id!, option)}
3144
3166
  onDecisionShown={onDecisionShown}
3145
3167
  onOpenChange={(path) => {
3146
3168
  setChangeAsked({ session: current, path, at: Date.now() });
@@ -3268,6 +3290,8 @@ function Sessions({
3268
3290
  </Dialog>
3269
3291
  </section>
3270
3292
  );
3293
+ // The conversation's cards and the dock above the prompt share the drafts.
3294
+ return <DecisionDrafts.Provider value={drafts}>{page}</DecisionDrafts.Provider>;
3271
3295
  }
3272
3296
 
3273
3297
  /** The keys Sessions handles itself (its `onKey`), declared to the shell for the help and for clashes while a Sessions
package/git.ts CHANGED
@@ -32,6 +32,51 @@ export const runner =
32
32
  return { code, stdout, stderr };
33
33
  };
34
34
 
35
+ /** How long `ssh -G` may take to name an alias's host before the remote is read as written. */
36
+ export const SSH_RESOLVE_MS = 5000;
37
+
38
+ /** The host name ssh connects to for `alias` (`ssh -G`, which reads `~/.ssh/config` and connects nowhere), run in
39
+ * `cwd` through the host's processes; `undefined` when ssh fails or has not answered within `timeoutMs`. */
40
+ export const sshHostname = async (owner: Context, cwd: string, alias: string, timeoutMs = SSH_RESOLVE_MS) => {
41
+ try {
42
+ const child = await owner.processes.spawn(owner, { command: 'ssh', args: ['-G', alias], cwd });
43
+ let stdout = '';
44
+ child.onOutput((stream, chunk) => {
45
+ if (stream === 'stdout') stdout += chunk;
46
+ });
47
+ let timer: ReturnType<typeof setTimeout> | undefined;
48
+ const late = new Promise<'late'>((done) => {
49
+ timer = setTimeout(() => done('late'), timeoutMs);
50
+ });
51
+ const end = await Promise.race([child.exited, late]);
52
+ clearTimeout(timer);
53
+ if (end === 'late') {
54
+ void child.kill();
55
+ return undefined;
56
+ }
57
+ return end.code === 0 ? /^hostname (\S+)$/m.exec(stdout)?.[1] : undefined;
58
+ } catch {
59
+ return undefined;
60
+ }
61
+ };
62
+
63
+ /** `remote` with its ssh host alias replaced by the host `hostOf` resolves it to (`sshHostname`): a remote
64
+ * `git@github-work:o/r.git` whose `~/.ssh/config` says `HostName github.com` reads as GitHub's (plugins#114). Any other
65
+ * form (https, a path) and GitHub's own hosts come back as they are. */
66
+ export const resolveRemote = async (
67
+ remote: string,
68
+ hostOf: (alias: string) => Promise<string | undefined>,
69
+ ) => {
70
+ const found =
71
+ /^(ssh:\/\/(?:[^@/]+@)?)([^/:@]+)(?::\d+)?\//i.exec(remote) ?? /^((?:[^@/:]+@)?)([^/:@]+):(?!\/)/.exec(remote);
72
+ const alias = found?.[2];
73
+ // A name only, never an option for ssh (`-…`).
74
+ if (!found || !alias || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(alias) || /^(?:ssh\.)?github\.com$/i.test(alias))
75
+ return remote;
76
+ const host = await hostOf(alias);
77
+ return host ? `${found[1]}${host}${remote.slice(found[1]!.length + alias.length)}` : remote;
78
+ };
79
+
35
80
  /** The branches of the repository at `folder` that have a folder, as git lists them (`git worktree list`): its own
36
81
  * checkout first, then each worktree under its `.worktrees/` (research-083). A folder's name is never read as a branch's
37
82
  * name (`feat/x` and `feat-x` share one). */
@@ -67,12 +112,17 @@ export const branchSlug = (text: string) =>
67
112
  '',
68
113
  );
69
114
 
70
- /** A model's answer as a `type/topic` branch name (`fix/e2e-shards`), `undefined` when it is not one. */
115
+ /** The example of the prompt that asks a model for a branch name: never taken as its answer (plugins#110). */
116
+ export const BRANCH_EXAMPLE = 'fix/e2e-shards';
117
+
118
+ /** A model's answer as a `type/topic` branch name (`fix/login-timeout`), `undefined` when it is not one or is the prompt's
119
+ * own example (a model echoing it would name every branch the same). */
71
120
  export const typedBranch = (answer: string) => {
72
121
  // Its first line: a model may go on after the name (plugins#84).
73
122
  const name = (answer.trim().split('\n')[0] ?? '').trim().replace(/^`+|`+$/g, '');
74
123
  return name.length <= 40 &&
75
- /^(feat|fix|chore|ci|docs|refactor|test)\/[a-z0-9]+(-[a-z0-9]+)*$/.test(name)
124
+ /^(feat|fix|chore|ci|docs|refactor|test)\/[a-z0-9]+(-[a-z0-9]+)*$/.test(name) &&
125
+ name !== BRANCH_EXAMPLE
76
126
  ? name
77
127
  : undefined;
78
128
  };
@@ -98,9 +148,22 @@ export interface Repository {
98
148
  prefix: string;
99
149
  }
100
150
 
151
+ /** Past this size a file's fingerprint is its size and mtime, not its content: a turn's snapshot never reads a huge file
152
+ * whole (#112). ponytail: an edit of such a file that keeps both is not seen. */
153
+ const HASH_MAX = 16 * 1024 * 1024;
154
+ /** A snapshot reads (stat and content) this many files at most, in `git status`'s order (tracked changes first): a
155
+ * folder of thousands of untracked files (a `node_modules` not ignored) costs no more (#121). The others are `unread`:
156
+ * one that appears or goes is still a change. ponytail: an edit of an unread file is not seen. */
157
+ const READ_MAX = 2_000;
158
+
101
159
  /** The files of `top` that differ (read as `owner`) from `HEAD` (untracked ones included, ignored ones not), each with a fingerprint of
102
160
  * its content now (`deleted` when gone): two states compared give what changed between them. */
103
- export const stateOf = async (owner: Context, run: Run, top: string) => {
161
+ export const stateOf = async (
162
+ owner: Context,
163
+ run: Run,
164
+ top: string,
165
+ { hashMax = HASH_MAX, readMax = READ_MAX }: { hashMax?: number; readMax?: number } = {},
166
+ ) => {
104
167
  const { code, stdout } = await run(top, [
105
168
  'status',
106
169
  '--porcelain=v1',
@@ -116,17 +179,22 @@ export const stateOf = async (owner: Context, run: Run, top: string) => {
116
179
  .map((field) => field.slice(3));
117
180
  const state = new Map<string, string>();
118
181
  await Promise.all(
119
- paths.map(async (path) => state.set(path, await fingerprint(owner, join(top, path)))),
182
+ paths
183
+ .slice(0, readMax)
184
+ .map(async (path) => state.set(path, await fingerprint(owner, join(top, path), hashMax))),
120
185
  );
186
+ for (const path of paths.slice(readMax)) state.set(path, 'unread');
121
187
  return state;
122
188
  };
123
189
 
124
190
  /** Read through the host (`ctx.fs`) as `owner`. */
125
- const fingerprint = async (owner: Context, file: string) => {
191
+ const fingerprint = async (owner: Context, file: string, hashMax: number) => {
126
192
  try {
127
193
  const info = await owner.fs.stat(owner, file);
128
194
  if (!info) return 'deleted';
129
195
  if (!info.isFile) return `other:${info.mtimeMs}`;
196
+ // Never a SHA-1: a file that crosses the limit during a turn shows as changed.
197
+ if (info.size > hashMax) return `meta:${info.size}:${info.mtimeMs}`;
130
198
  return createHash('sha1')
131
199
  .update(await owner.fs.readFile(owner, file))
132
200
  .digest('hex');
@@ -135,11 +203,20 @@ const fingerprint = async (owner: Context, file: string) => {
135
203
  }
136
204
  };
137
205
 
138
- /** The paths whose fingerprint differs between `before` and `after`. */
206
+ /** The paths whose fingerprint differs between `before` and `after`. An `unread` file's content is unknown: in both
207
+ * states and gone from neither, it is no change (a path that entered before the cap pushed it past, #121). */
139
208
  export const changed = (before: Map<string, string>, after: Map<string, string>) =>
140
- [...new Set([...before.keys(), ...after.keys()])].filter(
141
- (path) => before.get(path) !== after.get(path),
142
- );
209
+ [...new Set([...before.keys(), ...after.keys()])].filter((path) => {
210
+ const was = before.get(path);
211
+ const now = after.get(path);
212
+ const unknown =
213
+ (was === 'unread' || now === 'unread') &&
214
+ was !== undefined &&
215
+ now !== undefined &&
216
+ was !== 'deleted' &&
217
+ now !== 'deleted';
218
+ return !unknown && was !== now;
219
+ });
143
220
 
144
221
  /** `path` (absolute, or relative to `folder`, a folder of `repository`) relative to the repository's top, `/`-separated
145
222
  * (`''`: the top itself); `undefined` outside it. The top git gives may be another spelling of `folder`'s (symbolic links resolved): a path in
@@ -154,23 +231,17 @@ export const within = ({ top, prefix }: Repository, folder: string, path: string
154
231
  return local === undefined ? inside(top, file) : `${prefix}${local}`.replace(/\/$/, '');
155
232
  };
156
233
 
157
- /** `git diff` printing git's own patch whatever the person's config: no external tool or textconv, the `a/` and `b/`
158
- * prefixes the Changes panel reads (not `diff.mnemonicPrefix`'s `w/`, `i/`…), paths not quoted for their non-ASCII. */
159
- const PATCH = [
160
- '-c',
161
- 'core.quotePath=false',
162
- 'diff',
163
- '--no-color',
164
- '--no-ext-diff',
165
- '--no-textconv',
166
- '--src-prefix=a/',
167
- '--dst-prefix=b/',
168
- ];
234
+ /** Git's own patch whatever the person's config: no external tool or textconv, the `a/` and `b/` prefixes the Changes
235
+ * panel reads (not `diff.mnemonicPrefix`'s `w/`, `i/`…), paths not quoted for their non-ASCII. */
236
+ const PATCH = ['--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
237
+ const QUOTE = ['-c', 'core.quotePath=false'];
169
238
 
170
239
  /** The diff of `files` against `HEAD` in `top` (an untracked file shown whole, as new), cut past `max` characters. */
171
240
  export const diffOf = async (run: Run, top: string, files: string[], max: number) => {
172
241
  if (!files.length) return '';
173
- const tracked = await run(top, [...PATCH, 'HEAD', '--', ...files]);
242
+ // `diff-index`, not `diff`: `diff` refreshes the index of a file whose stat moved (a `touch`), rewriting it through
243
+ // `index.lock` even under `GIT_OPTIONAL_LOCKS=0`, and the session's agent's own `git add` then fails on that lock.
244
+ const tracked = await run(top, [...QUOTE, 'diff-index', '-p', ...PATCH, 'HEAD', '--', ...files]);
174
245
  let text = tracked.stdout;
175
246
  const listed = await run(top, [
176
247
  'ls-files',
@@ -182,7 +253,7 @@ export const diffOf = async (run: Run, top: string, files: string[], max: number
182
253
  ]);
183
254
  for (const path of listed.stdout.split('\0').filter(Boolean)) {
184
255
  if (text.length > max) break;
185
- const added = await run(top, [...PATCH, '--no-index', '--', '/dev/null', path]);
256
+ const added = await run(top, [...QUOTE, 'diff', ...PATCH, '--no-index', '--', '/dev/null', path]);
186
257
  text += added.stdout;
187
258
  }
188
259
  return text.length > max ? `${cutText(text, max)}\n… [truncated]` : text;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/sessions",
3
- "version": "0.0.9",
3
+ "version": "0.0.20",
4
4
  "license": "MIT",
5
5
  "description": "Conversations with agents, in the workspace or in a project, through the Profile.",
6
6
  "keywords": [
@@ -31,6 +31,10 @@
31
31
  "storage": {},
32
32
  "harness": {}
33
33
  },
34
+ "dataVersions": {
35
+ "sessions": 1,
36
+ "pins": 1
37
+ },
34
38
  "needs": {
35
39
  "fs": [
36
40
  "data",
@@ -1021,5 +1025,8 @@
1021
1025
  "cordis": "4.0.0-rc.11",
1022
1026
  "react": "19.3.0"
1023
1027
  },
1024
- "releaseStage": "dev"
1028
+ "releaseStage": "dev",
1029
+ "engines": {
1030
+ "bridge": ">=0.0.1-nightly.20261114.1"
1031
+ }
1025
1032
  }
package/pull-requests.ts CHANGED
@@ -105,7 +105,7 @@ const withWake = <V extends Value>(value: V, text: string, at: number): V => ({
105
105
  { id: `${WAKE}${crypto.randomUUID()}`, text, at: new Date(at).toISOString(), from: 'bridge' as const },
106
106
  ],
107
107
  });
108
- /** `value` without the pull request news still queued: merged or closed, it is no longer news. */
108
+ /** `value` without the pull request news still queued: merged, closed, unwatched or unlinked, it is no longer news. */
109
109
  const withoutWakes = <V extends Value>(value: V): V => {
110
110
  if (!value.queue?.some((each) => each.id.startsWith(WAKE))) return value;
111
111
  const { queue, ...rest } = value;
@@ -516,7 +516,7 @@ export function createPullRequests<V extends Value>(deps: {
516
516
  if (!was.pullRequest) return was;
517
517
  const { pullRequest, ...rest } = was;
518
518
  return {
519
- ...rest,
519
+ ...withoutWakes(rest),
520
520
  pullRequestUnlinked: [...(was.pullRequestUnlinked ?? []).filter((each) => each !== pullRequest.url), pullRequest.url].slice(-20),
521
521
  } as V;
522
522
  });
@@ -586,7 +586,7 @@ export function createPullRequests<V extends Value>(deps: {
586
586
  "Stops watching a session's pull request (it stays linked): { id? }",
587
587
  async ({ actor, body }) => {
588
588
  const found = await target(actor, parse(idBody, body, 'POST /sessions/pull-request/unwatch takes { id? }'));
589
- const value = await change(found.id, unwatched);
589
+ const value = await change(found.id, (was) => withoutWakes(unwatched(was)));
590
590
  deps.changed(found.id);
591
591
  return { id: found.id, pullRequest: value.pullRequest ?? null };
592
592
  },
package/server.ts CHANGED
@@ -166,7 +166,9 @@ import {
166
166
  commit,
167
167
  diffOf,
168
168
  repositoryAt,
169
+ resolveRemote,
169
170
  runner,
171
+ sshHostname,
170
172
  stateOf,
171
173
  type Repository,
172
174
  within,
@@ -174,6 +176,7 @@ import {
174
176
  branchSlug,
175
177
  freeBranch,
176
178
  typedBranch,
179
+ BRANCH_EXAMPLE,
177
180
  } from './git.ts';
178
181
  import { changeOf, type Change } from './diff.ts';
179
182
  import { active, actsAs, createPeers, release } from './peers.ts';
@@ -828,6 +831,11 @@ const IDLE_CAP_MS = 4 * 3_600_000;
828
831
  * `continuationWindowMs` per session (bridge#212 S5). */
829
832
  const CONTINUATIONS = 3;
830
833
  const CONTINUATION_WINDOW_MS = 5 * 60_000;
834
+ /** Lines a failed history append left in a session's outbox are tried again after this, doubling each failure up to
835
+ * `FLUSH_RETRY_MAX_MS`, not only at the session's next line (an idle session kept them in memory until Bridge
836
+ * stopped, and its one last try was all that stood between the page and a lost line; plugins#93). */
837
+ const FLUSH_RETRY_MS = 2_000;
838
+ const FLUSH_RETRY_MAX_MS = 60_000;
831
839
  /** A turn its harness driver's reload cut is continued once that driver is registered again, checked this often, for
832
840
  * this long at most (past it, the next start of Sessions continues it). */
833
841
  const DRIVER_POLL_MS = 1_000;
@@ -847,6 +855,7 @@ export interface Options {
847
855
  pullRequestWatchMs?: number;
848
856
  pullRequestSyncMs?: number;
849
857
  branchNameMs?: number;
858
+ flushRetryMs?: number;
850
859
  }
851
860
  /** `config`'s positive number `key`, else `fallback`. */
852
861
  const optionOf = (config: unknown, key: keyof Options, fallback: number) => {
@@ -1017,6 +1026,8 @@ const glanceText = (glance: Glance | undefined, mode: string | undefined) => {
1017
1026
  ]
1018
1027
  : []),
1019
1028
  'Discover and act on Bridge with the `bridge` MCP tools (`search_plugins`, `plugin_details`, `get_settings`/`set_setting`, `bridge_routes`/`bridge_read`/`bridge_write`, `bridge_link`, `show_view`); the shell is for code and files.',
1029
+ // #116: an agent wrote its own Playwright script where the Browser plugin, not installed, did it.
1030
+ 'Before you build a workaround (a script of your own, a tool to install, a long detour), look for a plugin that does it: `search_plugins` with one word of what you need (`browser`, `database`…; every word given must match, so try several one at a time) lists the plugins this workspace can install, not only the installed ones. One that is not installed: say so to the user and propose it with `install_plugin`: it installs, or becomes a request the user approves in one click.',
1020
1031
  ].join('\n');
1021
1032
  };
1022
1033
 
@@ -1138,6 +1149,7 @@ export async function apply(ctx: Context, config?: unknown) {
1138
1149
  const driverPollMs = optionOf(config, 'driverPollMs', DRIVER_POLL_MS);
1139
1150
  const driverWaitMs = optionOf(config, 'driverWaitMs', DRIVER_WAIT_MS);
1140
1151
  const branchNameMs = optionOf(config, 'branchNameMs', BRANCH_NAME_MS);
1152
+ const flushRetryMs = optionOf(config, 'flushRetryMs', FLUSH_RETRY_MS);
1141
1153
  // Cordis unloads independent effects in parallel. Group each storage release after the same
1142
1154
  // drain, so turn finalization can still update objects as well as append its closing history.
1143
1155
  let drain = async () => {};
@@ -1358,7 +1370,7 @@ export async function apply(ctx: Context, config?: unknown) {
1358
1370
  // waited for, a model may go on with the work itself (plugins#84).
1359
1371
  answered: (text, more) =>
1360
1372
  (more || text.trimStart().includes('\n')) && typedBranch(text) !== undefined,
1361
- prompt: `Name the git branch of this work. Answer with the name only, \`type/topic\`: type is one of feat, fix, chore, ci, docs, refactor, test; topic is 2 to 4 lowercase words saying what the work does, joined by \`-\` (a-z, 0-9 only), never the words of a URL; 40 characters at most. For example: fix/e2e-shards. Do not do the work: only name it.\n\nThe work, as the user asked it:\n\n${text.slice(0, 4000)}`,
1373
+ prompt: `Name the git branch of this work. Answer with the name only, \`type/topic\`: type is one of feat, fix, chore, ci, docs, refactor, test; topic is 2 to 4 lowercase words saying what the work does, joined by \`-\` (a-z, 0-9 only), never the words of a URL; 40 characters at most. For example: ${BRANCH_EXAMPLE}. Do not do the work: only name it.\n\nThe work, as the user asked it:\n\n${cutText(text, 4000)}`,
1362
1374
  }),
1363
1375
  new Promise<never>((_, reject) =>
1364
1376
  signal.addEventListener(
@@ -1922,7 +1934,7 @@ export async function apply(ctx: Context, config?: unknown) {
1922
1934
  /** The running turns: `take` removes an open decision (`false` when it is not open), `record` stores its answer
1923
1935
  * (`null` with `expired`: no answer reached the agent), `expire` both for a decision past its `expiresAt`; `abort` closes the turn as this plugin disposes; `stop` closes
1924
1936
  * it `interrupted` while it is not prompting yet (its harness session still opening: an agent that never answers
1925
- * would otherwise hold the session busy). */
1937
+ * would otherwise hold the session busy), or with `force` while prompting (its agent could not be asked to stop). */
1926
1938
  const turns = new Map<
1927
1939
  string,
1928
1940
  {
@@ -1930,7 +1942,7 @@ export async function apply(ctx: Context, config?: unknown) {
1930
1942
  record: (decision: string, option: Answer, expired?: boolean, by?: string) => void;
1931
1943
  expire: (decision: string) => void;
1932
1944
  abort: () => void;
1933
- stop: () => void;
1945
+ stop: (force?: boolean) => void;
1934
1946
  /** Puts a message into this turn (bridge#212 S6): `unavailable` when its harness cannot steer, `declined` when the
1935
1947
  * turn cannot take it now (its agent not prompted yet, stopping, ended, or the agent said no), `steered` once the
1936
1948
  * agent took it, its `user/message {steered: true}` written where it entered the turn. */
@@ -2140,8 +2152,31 @@ export async function apply(ctx: Context, config?: unknown) {
2140
2152
  );
2141
2153
  return chosen?.efforts?.find((each) => each.id === effort);
2142
2154
  };
2155
+ /** Per session, the timer of the next try after a failed flush, and how many failed in a row. */
2156
+ const flushRetries = new Map<string, { timer: ReturnType<typeof setTimeout>; failures: number }>();
2157
+ const clearFlushRetry = (id: string) => {
2158
+ const retry = flushRetries.get(id);
2159
+ if (!retry) return;
2160
+ clearTimeout(retry.timer);
2161
+ flushRetries.delete(id);
2162
+ };
2163
+ /** After a failed flush of `id`: its next try, `flushRetryMs` doubled per failure in a row, up to the cap. */
2164
+ const scheduleFlushRetry = (id: string) => {
2165
+ if (disposed) return;
2166
+ const failures = (flushRetries.get(id)?.failures ?? 0) + 1;
2167
+ clearFlushRetry(id);
2168
+ const timer = setTimeout(
2169
+ () => {
2170
+ flushRetries.delete(id);
2171
+ void queueFlush(id);
2172
+ },
2173
+ Math.min(flushRetryMs * 2 ** (failures - 1), FLUSH_RETRY_MAX_MS),
2174
+ );
2175
+ timer.unref?.();
2176
+ flushRetries.set(id, { timer, failures });
2177
+ };
2143
2178
  /** Stores session `id`'s outbox in one append, `after` the `seq` before its first line; on a failure (logged) the
2144
- * lines stay for the next try. */
2179
+ * lines stay for the next try, which a timer brings (`scheduleFlushRetry`) when no new line does. */
2145
2180
  const flush = async (id: string) => {
2146
2181
  const pending = outbox.get(id);
2147
2182
  if (!pending?.length) return;
@@ -2155,6 +2190,7 @@ export async function apply(ctx: Context, config?: unknown) {
2155
2190
  );
2156
2191
  pending.splice(0, batch.length);
2157
2192
  if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
2193
+ clearFlushRetry(id);
2158
2194
  } catch (error) {
2159
2195
  ctx
2160
2196
  .logger('sessions')
@@ -2171,6 +2207,7 @@ export async function apply(ctx: Context, config?: unknown) {
2171
2207
  if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
2172
2208
  }
2173
2209
  }
2210
+ if (pending.length) scheduleFlushRetry(id);
2174
2211
  }
2175
2212
  };
2176
2213
  /** Queues `flush(id)` on session `id`'s chain, after its steps queued before. */
@@ -2224,6 +2261,7 @@ export async function apply(ctx: Context, config?: unknown) {
2224
2261
  // still in an outbox get one last try. The storage owner's grouped effects release only after this drain.
2225
2262
  drain = async () => {
2226
2263
  disposed = true;
2264
+ for (const id of [...flushRetries.keys()]) clearFlushRetry(id);
2227
2265
  for (const id of [...idleClose.keys()]) clearIdle(id);
2228
2266
  for (const turn of [...turns.values()]) turn.abort();
2229
2267
  for (const each of namings.values()) each.stop.abort('disposed');
@@ -2969,21 +3007,35 @@ export async function apply(ctx: Context, config?: unknown) {
2969
3007
  },
2970
3008
  });
2971
3009
 
2972
- /** Stops session `id` as the user's Stop does: its running turn asked to stop, its queue held. */
2973
3010
  /** How many times the user stopped each session, in memory (a watch asked before a Stop does not start after it). */
2974
3011
  const stopped = new Map<string, number>();
3012
+ /** Stops session `id`'s running turn: asked to its agent; when the agent cannot be asked (its interrupt rejects, a
3013
+ * closed query), the turn ends interrupted anyway and its harness session is closed, the next message opening a new
3014
+ * one. Never rejects. */
3015
+ const stopTurn = async (id: string) => {
3016
+ stopping.add(id);
3017
+ turns.get(id)?.stop();
3018
+ await open
3019
+ .get(id)
3020
+ ?.interrupt()
3021
+ .catch((error: unknown) => {
3022
+ log(`session ${id}: its agent not interrupted`)(error);
3023
+ turns.get(id)?.stop(true);
3024
+ void drop(id);
3025
+ });
3026
+ };
3027
+ /** Stops session `id` as the user's Stop does: its running turn asked to stop, its queue held. Never rejects: a Stop
3028
+ * goes on to its subtree whatever failed here (logged). */
2975
3029
  const stopSession = async (id: string) => {
2976
3030
  halt(id);
2977
3031
  stopNaming(id);
2978
3032
  stopped.set(id, (stopped.get(id) ?? 0) + 1);
3033
+ if (running.has(id)) await stopTurn(id);
2979
3034
  // The user's Stop ends its pull request's watch (research-086).
2980
- if ((await sessions.get(id))?.value.pullRequest?.watching)
2981
- await change(id, unwatched).catch(log(`session ${id}: watch not ended`));
2982
- if (running.has(id)) {
2983
- stopping.add(id);
2984
- turns.get(id)?.stop();
2985
- await open.get(id)?.interrupt();
2986
- }
3035
+ await sessions
3036
+ .get(id)
3037
+ .then((found) => found?.value.pullRequest?.watching && change(id, unwatched))
3038
+ .catch(log(`session ${id}: watch not ended`));
2987
3039
  };
2988
3040
  ctx.router.route(ctx, {
2989
3041
  method: 'POST',
@@ -3345,9 +3397,14 @@ export async function apply(ctx: Context, config?: unknown) {
3345
3397
  );
3346
3398
  };
3347
3399
  /** Adds `item` last in session `id`'s queue (`first`: first), its lock held. Its children's results and questions
3348
- * waiting there are beyond the limit: only the messages count. */
3400
+ * waiting there are beyond the limit: only the messages count. A scheduled task's prompt while one of that task
3401
+ * still waits there adds none: the waiting one is returned (#113). */
3349
3402
  const push = async (id: string, item: NonNullable<Session['queue']>[number], first = false) => {
3403
+ let waiting: typeof item | undefined;
3350
3404
  await change(id, (now) => {
3405
+ waiting =
3406
+ item.scheduled && now.queue?.find((each) => each.scheduled?.id === item.scheduled!.id);
3407
+ if (waiting) return now;
3351
3408
  const messages = (now.queue ?? []).filter((each) => !each.delegations && !each.questions);
3352
3409
  if (messages.length >= QUEUE_LIMIT)
3353
3410
  throw refused(
@@ -3357,18 +3414,16 @@ export async function apply(ctx: Context, config?: unknown) {
3357
3414
  );
3358
3415
  return { ...now, queue: first ? [item, ...(now.queue ?? [])] : [...(now.queue ?? []), item] };
3359
3416
  });
3417
+ if (waiting) return waiting;
3360
3418
  emit(id, { type: 'queue' });
3361
3419
  return item;
3362
3420
  };
3363
3421
  /** Stops session `id`'s running turn to send its queue's first message at once, when that turn ends. */
3364
3422
  const restartTurn = (id: string) => {
3423
+ // No turn left to stop: flags set now would cut the next turn before its prompt (#105).
3424
+ if (!running.has(id)) return;
3365
3425
  sendNow.add(id);
3366
- stopping.add(id);
3367
- turns.get(id)?.stop();
3368
- void open
3369
- .get(id)
3370
- ?.interrupt()
3371
- .catch(log(`session ${id}: its turn not stopped`));
3426
+ void stopTurn(id);
3372
3427
  };
3373
3428
  /** A new message: it starts a turn when the session is free; while one runs, `delivery` says what it does
3374
3429
  * (bridge#212 S6, `prompt_session`'s): `queue` (the default) goes last in the queue, a turn of its own after the
@@ -3424,10 +3479,16 @@ export async function apply(ctx: Context, config?: unknown) {
3424
3479
  ...(attachments.length && { attachments }),
3425
3480
  ...options,
3426
3481
  };
3427
- if (delivery !== 'restart') return { ok: true, queued: await push(id, item) };
3482
+ if (delivery !== 'restart') {
3483
+ const queued = await push(id, item);
3484
+ // A scheduled task's prompt already waiting: this one added none.
3485
+ return { ok: true, queued, ...(queued !== item && { waiting: true as const }) };
3486
+ }
3428
3487
  const queued = await push(id, item, true);
3429
3488
  unhalt(id);
3430
- restartTurn(id);
3489
+ // The turn may have ended during the write: then the message starts a turn of its own, after this lock.
3490
+ if (running.has(id)) restartTurn(id);
3491
+ else void dequeue(id).catch(log(`session ${id}: restart not sent`));
3431
3492
  return { ok: true, queued, restarted: true };
3432
3493
  };
3433
3494
  return serial(found.id, () =>
@@ -3880,8 +3941,8 @@ export async function apply(ctx: Context, config?: unknown) {
3880
3941
  aborted = true;
3881
3942
  finish({ reason: 'interrupted', message: 'Sessions stopped during this turn' });
3882
3943
  },
3883
- stop: () => {
3884
- if (!prompting) finish({ reason: 'interrupted' });
3944
+ stop: (force) => {
3945
+ if (force || !prompting) finish({ reason: 'interrupted' });
3885
3946
  },
3886
3947
  steerable: () => !!agent?.steer && steerOpen(),
3887
3948
  steer: async (message, attachments, options) => {
@@ -4410,6 +4471,16 @@ export async function apply(ctx: Context, config?: unknown) {
4410
4471
  log,
4411
4472
  });
4412
4473
 
4474
+ // An ssh alias's host, once per alias: `ssh -G` reads ~/.ssh/config (plugins#114). A failure is asked again.
4475
+ const hosts = new Map<string, Promise<string | undefined>>();
4476
+ const hostOf = (folder: string, alias: string) => {
4477
+ let host = hosts.get(alias);
4478
+ if (!host) {
4479
+ hosts.set(alias, (host = sshHostname(ctx, folder, alias)));
4480
+ void host.then((name) => name || hosts.delete(alias));
4481
+ }
4482
+ return host;
4483
+ };
4413
4484
  // A session's pull request (research-086): linked, read, settled on merge, watched; `pull-requests.ts`.
4414
4485
  const pullRequests = createPullRequests<Session>({
4415
4486
  route: (method, path, description, handle) =>
@@ -4433,7 +4504,7 @@ export async function apply(ctx: Context, config?: unknown) {
4433
4504
  return undefined;
4434
4505
  const remote = await run(folder, ['remote', 'get-url', 'origin']);
4435
4506
  return remote.code === 0 && remote.stdout.trim()
4436
- ? { branch, remote: remote.stdout.trim() }
4507
+ ? { branch, remote: await resolveRemote(remote.stdout.trim(), (alias) => hostOf(folder, alias)) }
4437
4508
  : undefined;
4438
4509
  },
4439
4510
  // A wake already in the queue: sent as after a turn (at once when none runs, held after the user's Stop).
@@ -4641,20 +4712,22 @@ export async function apply(ctx: Context, config?: unknown) {
4641
4712
  );
4642
4713
  // Never a steer: no turn running starts one; one running takes the prompt in its queue.
4643
4714
  const scheduled = { id: task.taskId, title: task.title };
4715
+ // One queued prompt per task (#113): a run while its previous prompt still waits adds none.
4716
+ const waits = { summary: "Its previous prompt is still waiting in the session's queue" };
4644
4717
  try {
4645
- await sendOrQueue(found, prompt, [], { scheduled });
4718
+ const sent = await sendOrQueue(found, prompt, [], { scheduled });
4719
+ if (sent && 'waiting' in sent) return waits;
4646
4720
  } catch (error) {
4647
4721
  const code = (error as { code?: unknown } | undefined)?.code;
4648
4722
  // A restart, or a Stop as it started: the message waits in its queue, never lost.
4649
4723
  if (code !== 'restart_pending' && code !== 'turn_stopped') throw error;
4650
- await serial(id, () =>
4651
- push(id, {
4652
- id: crypto.randomUUID(),
4653
- text: prompt,
4654
- at: new Date().toISOString(),
4655
- scheduled,
4656
- }),
4657
- );
4724
+ const item = {
4725
+ id: crypto.randomUUID(),
4726
+ text: prompt,
4727
+ at: new Date().toISOString(),
4728
+ scheduled,
4729
+ };
4730
+ if ((await serial(id, () => push(id, item))) !== item) return waits;
4658
4731
  }
4659
4732
  },
4660
4733
  });
@@ -5063,12 +5136,8 @@ export async function apply(ctx: Context, config?: unknown) {
5063
5136
  if (!chosen) throw refused('not_found', `no queued message ${item}`, 404);
5064
5137
  return { ...now, queue: [chosen, ...(queue ?? []).filter((each) => each !== chosen)] };
5065
5138
  });
5066
- if (running.has(found.id)) {
5067
- sendNow.add(found.id);
5068
- stopping.add(found.id);
5069
- turns.get(found.id)?.stop();
5070
- await open.get(found.id)?.interrupt();
5071
- } else await dequeue(found.id);
5139
+ if (running.has(found.id)) restartTurn(found.id);
5140
+ else await dequeue(found.id);
5072
5141
  return { ok: true };
5073
5142
  },
5074
5143
  });
@@ -5374,21 +5443,20 @@ export async function apply(ctx: Context, config?: unknown) {
5374
5443
  // Its turn ends once this answer is on its way: its agent opens again in the branch's folder at the next turn,
5375
5444
  // which `prompt` starts.
5376
5445
  setTimeout(() => {
5377
- const next = input.prompt
5378
- ? sendOrQueue(
5379
- { id, node: found.node, value },
5380
- input.prompt,
5381
- [],
5382
- { from: 'bridge' },
5383
- false,
5384
- running.has(id) ? 'restart' : 'queue',
5446
+ const { prompt } = input;
5447
+ const deliver = (text: string, delivery: Delivery) =>
5448
+ sendOrQueue({ id, node: found.node, value }, text, [], { from: 'bridge' }, false, delivery);
5449
+ const next = prompt
5450
+ ? deliver(prompt, running.has(id) ? 'restart' : 'queue').catch((error: unknown) =>
5451
+ // The turn ended before the prompt took the session's lock: the prompt starts a turn of its own (#120).
5452
+ (error as { code?: unknown } | null)?.code === 'turn_not_running'
5453
+ ? deliver(prompt, 'queue')
5454
+ : Promise.reject(error),
5385
5455
  )
5386
5456
  : (async () => {
5387
5457
  if (!running.has(id)) return;
5388
5458
  // Its queue is not held, unlike the user's Stop: the next message starts at once.
5389
- stopping.add(id);
5390
- turns.get(id)?.stop();
5391
- await open.get(id)?.interrupt();
5459
+ await stopTurn(id);
5392
5460
  })();
5393
5461
  void next.catch(log(`session ${id}: handoff turn not ended`));
5394
5462
  }, 0);