@bridgebrew/sessions 0.0.27 → 0.0.33

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,7 +1,7 @@
1
1
  // A session's branch from its page (research-083): its Git button (`@bridge/session-ui/git-actions`) acts on its branch's
2
2
  // folder, and archiving the branch's last session offers to delete that folder (never one with work not committed or not pushed; the git branch
3
- // stays). Both go through the project's Branches routes (`/_bridge/host/branches/…`, `project-branches.ts`), as the
4
- // Branches screen does: the same checks, the owner's page.
3
+ // stays). Both go through the project plugin's Branches routes (`/<slug>/api/project/branches/…`, bridgebrew/bridge#557),
4
+ // as the Branches screen does: the same checks, the owner's page.
5
5
  // ponytail: cleanup is asked, never automatic (merged, inactive, unchanged): its rules are bridge#348.
6
6
  import * as React from 'react';
7
7
  import {
@@ -18,11 +18,15 @@ import {
18
18
  } from '@bridge/ui';
19
19
  import {
20
20
  GitActions,
21
- branchesRoute,
22
21
  useBranch,
23
22
  type BranchesAnswer,
23
+ type BranchesRoute,
24
24
  } from '@bridge/session-ui/git-actions';
25
25
 
26
+ /** The project plugin's Branches route of project `node` in workspace `slug`, or one of its actions. */
27
+ export const branchesRoute: BranchesRoute = (slug, node, action) =>
28
+ `/${encodeURIComponent(slug)}/api/project/branches${action ? `/${action}` : ''}?node=${encodeURIComponent(node)}`;
29
+
26
30
  const post = async (slug: string, node: string, action: string, body: Record<string, unknown>) =>
27
31
  readJson(
28
32
  await fetch(branchesRoute(slug, node, action), {
@@ -53,7 +57,7 @@ export function BranchActions({
53
57
  pullRequestOpen?: boolean;
54
58
  onGitAnswer?: () => void;
55
59
  }) {
56
- const [state, take] = useBranch(slug, node, branch, refresh);
60
+ const [state, take] = useBranch(slug, node, branch, refresh, branchesRoute);
57
61
  if (!state) return null;
58
62
  return (
59
63
  <GitActions
@@ -61,6 +65,7 @@ export function BranchActions({
61
65
  node={node}
62
66
  branch={pullRequestOpen && !state.prOpen ? { ...state, prOpen: true } : state}
63
67
  session={session}
68
+ route={branchesRoute}
64
69
  onAnswer={(answer) => {
65
70
  take(answer);
66
71
  onGitAnswer?.();
@@ -85,7 +90,7 @@ export const cleanupOf = async (
85
90
  node: string,
86
91
  branch: string,
87
92
  ): Promise<Cleanup | undefined> => {
88
- // The host's own answer: typed once where it is read.
93
+ // The project plugin's own answer: typed once where it is read.
89
94
  const view = (await readJson(
90
95
  await fetch(branchesRoute(slug, node), { cache: 'no-store' }),
91
96
  )) as BranchesAnswer;
@@ -102,14 +102,7 @@ const fileNamed = <T extends { path: string }>(files: T[], wanted: string, repos
102
102
  files.find(({ path }) => wanted.endsWith(`/${path}`)) ??
103
103
  files.find(({ path }) => path.endsWith(`/${wanted}`));
104
104
 
105
- export function SessionDetails({
106
- session,
107
- known,
108
- focus,
109
- post,
110
- onChanged,
111
- onOpen,
112
- }: {
105
+ interface DetailsProps {
113
106
  session: Details;
114
107
  known: string[];
115
108
  /** The file to show (a tool call's change counts asked for it), again at each new `at`. */
@@ -117,15 +110,36 @@ export function SessionDetails({
117
110
  post: Post;
118
111
  onChanged: () => void;
119
112
  onOpen: (id: string) => void;
120
- }) {
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 }) {
121
136
  const [changes, setChanges] = React.useState<Changes | null>();
122
137
  const [outside, setOutside] = React.useState(false);
123
138
  const [error, setError] = React.useState('');
124
139
  const [picked, setPicked] = React.useState<Set<string>>(new Set());
125
140
  const [message, setMessage] = React.useState('');
126
141
  const [committing, setCommitting] = React.useState(false);
127
- /** The nested repositories the last commit of `session` left out (plugins#145): another session's are not shown. */
128
- const [left, setLeft] = React.useState<{ session: string; paths: string[] }>();
142
+ // Another session's are not shown.
129
143
  const leftOut = left?.session === session.id ? left.paths : [];
130
144
  /** Other sessions share the picked files: Commit asks again before it takes their changes. */
131
145
  const [confirming, setConfirming] = React.useState(false);
package/browser/index.tsx CHANGED
@@ -143,6 +143,7 @@ import {
143
143
  import { SubagentView } from './subagent-view.tsx';
144
144
  import {
145
145
  acquire,
146
+ back,
146
147
  childState as childStateOf,
147
148
  claimMark,
148
149
  inbox,
@@ -224,7 +225,7 @@ const useBranches = (slug: string, node: string, startNew = false) => {
224
225
  choose(undefined);
225
226
  if (node === 'root') return;
226
227
  fetch(
227
- `/_bridge/host/branches?workspace=${encodeURIComponent(slug)}&node=${encodeURIComponent(node)}`,
228
+ `/${encodeURIComponent(slug)}/api/project/branches?node=${encodeURIComponent(node)}`,
228
229
  { cache: 'no-store' },
229
230
  )
230
231
  .then((res) => (res.ok ? readJson(res) : undefined))
@@ -1434,14 +1435,32 @@ function Sessions({
1434
1435
  );
1435
1436
  };
1436
1437
  const setListing = (change: (was: Listing) => Listing) => latest.current.store?.patch(change);
1437
- const loadArchived = () =>
1438
- workspace
1438
+ /** Whether the archived list is wanted (shown, or its first read on the way), and the last read asked: the answer
1439
+ * of an older read, or one after Hide, is dropped (plugins#150). */
1440
+ const archivedWanted = React.useRef(false);
1441
+ const archivedRead = React.useRef(0);
1442
+ const loadArchived = () => {
1443
+ archivedWanted.current = true;
1444
+ const run = ++archivedRead.current;
1445
+ return workspace
1439
1446
  .fetch(forWorktree(`${api}?archived=1`, shownWorktree(workspace)), { headers })
1440
1447
  .then(readJson)
1441
- .then((body) => setArchived((body as Listing).sessions), report);
1442
- React.useEffect(() => {
1448
+ .then((body) => {
1449
+ if (run === archivedRead.current) setArchived((body as Listing).sessions);
1450
+ }, report);
1451
+ };
1452
+ const hideArchived = () => {
1453
+ archivedWanted.current = false;
1454
+ archivedRead.current += 1;
1443
1455
  setArchived(undefined);
1444
- }, [node]);
1456
+ };
1457
+ React.useEffect(hideArchived, [node]);
1458
+ // Archived or restored elsewhere (another window, the phone): the live listing gains or loses a session, and the
1459
+ // archived list wanted is read again (plugins#150).
1460
+ const listed = listing?.sessions.map((each) => each.id).join('\n');
1461
+ React.useEffect(() => {
1462
+ if (archivedWanted.current) void loadArchived();
1463
+ }, [listed]);
1445
1464
  // The session shown, for the shared listing: not polled (its own stream lists again), not counted unread.
1446
1465
  React.useEffect(() => store?.watch(current), [store, current]);
1447
1466
 
@@ -2040,7 +2059,7 @@ function Sessions({
2040
2059
  if (undoable.current === entry) undoable.current = null;
2041
2060
  dismiss(id);
2042
2061
  void run().then(
2043
- () => Promise.all([load(), archived && loadArchived()]),
2062
+ () => Promise.all([load(), archivedWanted.current && loadArchived()]),
2044
2063
  failed('Could not undo'),
2045
2064
  );
2046
2065
  },
@@ -2100,7 +2119,7 @@ function Sessions({
2100
2119
  );
2101
2120
  else if (action === 'archive')
2102
2121
  offerUndo('Session archived', each.title, () => triage(each.id, 'restore').then(back));
2103
- await Promise.all([load(), (archived || action === 'restore') && loadArchived()]);
2122
+ await Promise.all([load(), (archivedWanted.current || action === 'restore') && loadArchived()]);
2104
2123
  // Its branch's last session archived (research-083): its folder may go too, asked.
2105
2124
  const branch = each.branch;
2106
2125
  if (
@@ -2258,7 +2277,11 @@ function Sessions({
2258
2277
  promptHandle.current?.openModels();
2259
2278
  } else if (event.code === 'BracketLeft' || event.code === 'BracketRight') {
2260
2279
  event.preventDefault();
2261
- const index = ordered.findIndex((each) => each.id === current);
2280
+ // An open child has no row: it steps from its listed ancestor's (bounded, should a parent loop).
2281
+ let from = current;
2282
+ for (let hop = 0; hop < kin.size && from && !ordered.some((each) => each.id === from); hop++)
2283
+ from = kin.get(from)?.parent;
2284
+ const index = ordered.findIndex((each) => each.id === from);
2262
2285
  const step = event.code === 'BracketLeft' ? -1 : 1;
2263
2286
  const to = ordered[index < 0 ? (step > 0 ? 0 : ordered.length - 1) : index + step];
2264
2287
  if (to) choose(to.id);
@@ -2429,7 +2452,12 @@ function Sessions({
2429
2452
  stamp={
2430
2453
  each.snoozedUntil
2431
2454
  ? snoozeWakeLabel(each.snoozedUntil)
2432
- : ago(each.updatedAt ?? each.createdAt)
2455
+ : // Active, folded: the time the inbox orders it by (plugins#61).
2456
+ ago(
2457
+ folding && shelf === 'active' && depth === 0
2458
+ ? back(each)
2459
+ : (each.updatedAt ?? each.createdAt),
2460
+ )
2433
2461
  }
2434
2462
  worktreeName={
2435
2463
  // A child names its worktree in every list; a top row in the workspace's own (research-045).
@@ -2876,7 +2904,7 @@ function Sessions({
2876
2904
  <Button
2877
2905
  size="sm"
2878
2906
  className="justify-start text-muted"
2879
- onClick={() => (archived ? setArchived(undefined) : void loadArchived())}
2907
+ onClick={() => (archived ? hideArchived() : void loadArchived())}
2880
2908
  >
2881
2909
  <Icon name="archive" size={14} />
2882
2910
  {archived ? 'Hide archived' : 'Show archived'}
@@ -34,7 +34,7 @@ import {
34
34
  type Listing,
35
35
  type Session,
36
36
  } from './index.tsx';
37
- import { inbox, lineage } from '../listing.ts';
37
+ import { back, inbox, lineage } from '../listing.ts';
38
38
  import type { Lineage } from './children.tsx';
39
39
  import { answerBody, type Answer } from '../answers.ts';
40
40
 
@@ -117,7 +117,8 @@ export function MobileSessions({
117
117
  );
118
118
  }
119
119
 
120
- function Row({ each, onOpen }: { each: Session; onOpen: () => void }) {
120
+ /** `stamp`: the time the row is ordered by, when not its last message's. */
121
+ function Row({ each, stamp, onOpen }: { each: Session; stamp?: string; onOpen: () => void }) {
121
122
  const state = stateOf(each);
122
123
  const needs = state === 'Needs you' || state === 'Your call';
123
124
  return (
@@ -148,7 +149,9 @@ function Row({ each, onOpen }: { each: Session; onOpen: () => void }) {
148
149
  {state}
149
150
  </span>
150
151
  ) : null}
151
- <span className="shrink-0 text-xs text-muted">{ago(each.updatedAt ?? each.createdAt)}</span>
152
+ <span className="shrink-0 text-xs text-muted">
153
+ {ago(stamp ?? each.updatedAt ?? each.createdAt)}
154
+ </span>
152
155
  </span>
153
156
  <span className="truncate text-sm text-secondary">{each.preview ?? 'No messages yet'}</span>
154
157
  </button>
@@ -277,7 +280,13 @@ function MobileList({
277
280
  {isOpen && (
278
281
  <>
279
282
  {rows.map((each) => (
280
- <Row key={each.id} each={each} onOpen={() => ctx.screen.open(each.id)} />
283
+ <Row
284
+ key={each.id}
285
+ each={each}
286
+ // Active, folded: the time the inbox orders it by (plugins#61).
287
+ stamp={folding && key === 'active' ? back(each) : undefined}
288
+ onOpen={() => ctx.screen.open(each.id)}
289
+ />
281
290
  ))}
282
291
  {rows.length < sessions.length && (
283
292
  <Button
package/git.ts CHANGED
@@ -127,9 +127,10 @@ export const typedBranch = (answer: string) => {
127
127
  : undefined;
128
128
  };
129
129
 
130
- /** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has. */
130
+ /** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has. Each read as its full
131
+ * name, not git's short form (`heads/<name>` beside a tag of the same name: plugins#198). */
131
132
  export const freeBranch = async (run: Run, folder: string, name: string) => {
132
- const { stdout } = await run(folder, ['branch', '--list', '--format=%(refname:short)']);
133
+ const { stdout } = await run(folder, ['branch', '--list', '--format=%(refname:lstrip=2)']);
133
134
  const taken = new Set(stdout.split('\n'));
134
135
  let free = name;
135
136
  for (let n = 2; taken.has(free); n++) free = `${name}-${n}`;
package/listing.ts CHANGED
@@ -244,6 +244,13 @@ export interface Inboxed {
244
244
  pullRequest?: { watching?: true | undefined } | undefined;
245
245
  }
246
246
 
247
+ /** When a session came back to the user: the later of its turn's end and its last message sent. The inbox orders
248
+ * Active by it, and an Active row shows it (plugins#61). */
249
+ export const back = (each: Pick<Inboxed, 'createdAt' | 'updatedAt' | 'lastTurn'>) => {
250
+ const sent = each.updatedAt ?? each.createdAt;
251
+ return each.lastTurn && each.lastTurn.endedAt > sent ? each.lastTurn.endedAt : sent;
252
+ };
253
+
247
254
  /** The inbox (bridge#210): of the Active sessions, the ones working fold into Working (a turn running, a message the
248
255
  * user queued, held by a restart until it runs, a question sent to another session and not answered yet, or its pull
249
256
  * request watched, research-086: its agent waits for news), newest sent first (`updatedAt`: the user's last message); the others
@@ -251,8 +258,6 @@ export interface Inboxed {
251
258
  * ended or they were last sent work. */
252
259
  export function inbox<S extends Inboxed>(sessions: S[]): { active: S[]; working: S[] } {
253
260
  const sent = (each: S) => each.updatedAt ?? each.createdAt;
254
- const back = (each: S) =>
255
- each.lastTurn && each.lastTurn.endedAt > sent(each) ? each.lastTurn.endedAt : sent(each);
256
261
  const working = sessions.filter(
257
262
  (each) =>
258
263
  !each.waiting &&
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/sessions",
3
- "version": "0.0.27",
3
+ "version": "0.0.33",
4
4
  "license": "MIT",
5
5
  "description": "Conversations with agents, in the workspace or in a project, through the Profile.",
6
6
  "keywords": [
@@ -1005,7 +1005,8 @@
1005
1005
  },
1006
1006
  "bodies": {
1007
1007
  "/sessions/write": 524288
1008
- }
1008
+ },
1009
+ "placement": "workspace"
1009
1010
  },
1010
1011
  "scripts": {
1011
1012
  "test": "node ../bridge/node_modules/vitest/vitest.mjs run --config vitest.config.ts",
@@ -1027,6 +1028,6 @@
1027
1028
  },
1028
1029
  "releaseStage": "dev",
1029
1030
  "engines": {
1030
- "bridge": ">=0.0.1-nightly.20261118.1"
1031
+ "bridge": ">=0.0.1-nightly.20261119.1"
1031
1032
  }
1032
1033
  }
package/server.ts CHANGED
@@ -229,6 +229,11 @@ const attachment = z.strictObject({
229
229
  size: z.number().int().positive(),
230
230
  });
231
231
  type Attachment = z.infer<typeof attachment>;
232
+ /** The project plugin's `projectBranches` service (bridgebrew/bridge#557), never imported: what Sessions uses of it. */
233
+ interface ProjectBranches {
234
+ newBranch(input: { node: string; name: string; existing?: boolean }): Promise<{ name: string; folder: string }>;
235
+ branchForPlugins(input: { plugins: string[]; name: string }): Promise<{ repository: string; name: string; folder: string }>;
236
+ }
232
237
  /** What the gallery keeps, by a file's extension: the images and videos a browser shows (never SVG: it would run). */
233
238
  const PIN_TYPES = {
234
239
  '.png': 'image/png',
@@ -1250,10 +1255,13 @@ export async function apply(ctx: Context, config?: unknown) {
1250
1255
  /** A new branch `name` of the project on `node` (research-083), made by the host as the Branches screen makes one
1251
1256
  * (its worktree under `.worktrees/`, installed); `name` numbered when taken. */
1252
1257
  const makeBranch = async (node: string, name: string, temporary = false) => {
1253
- const service = bridgeMcp();
1258
+ const service = projectBranches();
1254
1259
  const project = node === 'root' ? undefined : await folderOf(node);
1255
1260
  if (!service || project === undefined)
1256
- throw refused('branches_unavailable', `node ${node} has no branches here`);
1261
+ throw refused(
1262
+ 'branches_unavailable',
1263
+ service ? `node ${node} has no branches here` : 'branches need Projects 0.0.2 or later in this workspace: install or update it (Plugins)',
1264
+ );
1257
1265
  try {
1258
1266
  const made = await service.newBranch({ node, name: await freeBranch(run, project, name) });
1259
1267
  return { ...made, ...(temporary && { temporary: true as const }) };
@@ -1484,7 +1492,7 @@ export async function apply(ctx: Context, config?: unknown) {
1484
1492
  const kept =
1485
1493
  project !== undefined &&
1486
1494
  (await run(project, ['branch', '--list', branch.name])).stdout.trim() !== '';
1487
- const service = bridgeMcp();
1495
+ const service = projectBranches();
1488
1496
  if (!kept || !service)
1489
1497
  throw new Error(
1490
1498
  `branch ${branch.name} is gone: its folder ${branch.folder}${kept ? ' cannot be made again here' : ' and its git branch were deleted'}; start a new session`,
@@ -1838,6 +1846,16 @@ export async function apply(ctx: Context, config?: unknown) {
1838
1846
  /** The host's per-session MCP tokens: optional (not in `inject`), so a host without them still loads this plugin, its
1839
1847
  * sessions' MCP calls then running as `agent`. */
1840
1848
  const bridgeMcp = () => ctx.get('bridgeMcp', false) as Context['bridgeMcp'] | undefined;
1849
+ /** The project plugin's branches (bridgebrew/bridge#557): a session's branch and a child's are made there. */
1850
+ const projectBranches = () => {
1851
+ const service: unknown = ctx.get('projectBranches', false);
1852
+ return isRecord(service) &&
1853
+ typeof service.newBranch === 'function' &&
1854
+ typeof service.branchForPlugins === 'function'
1855
+ ? // oxlint-disable-next-line bridge/no-new-unchecked-cast -- its two functions checked above, project's own service
1856
+ (service as unknown as ProjectBranches)
1857
+ : undefined;
1858
+ };
1841
1859
  /** A new MCP token for session `id`, `undefined` without the service or when the host refused (logged): the session
1842
1860
  * then opens without one. Not claimed yet (`claim`). */
1843
1861
  const issueToken = async (id: string, worktree?: string) => {
@@ -4424,9 +4442,14 @@ export async function apply(ctx: Context, config?: unknown) {
4424
4442
  // A child's own worktree (S7): added by the host, as `stage_add` adds one.
4425
4443
  addWorktree: async (input) => {
4426
4444
  const service = bridgeMcp();
4445
+ const branches = projectBranches();
4427
4446
  if (!service) throw refused('worktrees_unavailable', 'this Bridge cannot add a worktree');
4447
+ if (!branches)
4448
+ throw refused('worktrees_unavailable', "a child's own branch needs Projects 0.0.2 or later in this workspace: install or update it (Plugins)");
4428
4449
  try {
4429
- return await service.addWorktree(input);
4450
+ // Its branch made by the project plugin, in the checkout the plugins run from; the stage chooses it.
4451
+ const made = await branches.branchForPlugins({ plugins: input.plugins, name: input.branch });
4452
+ return await service.addWorktree({ branch: made.name, plugins: input.plugins, existing: true });
4430
4453
  } catch (error) {
4431
4454
  throw refused('worktree_refused', error instanceof Error ? error.message : String(error));
4432
4455
  }
@@ -4501,9 +4524,12 @@ export async function apply(ctx: Context, config?: unknown) {
4501
4524
  if (value.branch?.temporary) return undefined;
4502
4525
  const folder = await sessionFolder(node, value);
4503
4526
  if (folder === undefined) return undefined;
4504
- const head = await run(folder, ['rev-parse', '--abbrev-ref', 'HEAD']);
4527
+ // Its branch's own name (empty when detached), never git's short form: `heads/<name>` beside a tag (plugins#198).
4528
+ const head = await run(folder, ['branch', '--show-current']);
4505
4529
  const branch = head.code === 0 ? head.stdout.trim() : '';
4506
- if (!branch || branch === 'HEAD') return undefined;
4530
+ // A branch with no commit yet (unborn, orphan) has no pull request of its own.
4531
+ if (!branch || (await run(folder, ['rev-parse', '--verify', '--quiet', 'HEAD'])).code !== 0)
4532
+ return undefined;
4507
4533
  // The branch's upstream remote, else `origin`, else the only one (as the host's Branches, plugins#148).
4508
4534
  const tracked = (await run(folder, ['config', '--get', `branch.${branch}.remote`])).stdout.trim();
4509
4535
  const names = (await run(folder, ['remote'])).stdout.split('\n').filter(Boolean);
@@ -4516,9 +4542,10 @@ export async function apply(ctx: Context, config?: unknown) {
4516
4542
  : undefined;
4517
4543
  if (name === undefined) return undefined;
4518
4544
  // The default branch: no pull request of its own.
4519
- const base = (await run(folder, ['symbolic-ref', '--short', `refs/remotes/${name}/HEAD`])).stdout
4545
+ // Read as a full ref: a local branch named `<remote>/main` makes the short form `remotes/<remote>/main`.
4546
+ const base = (await run(folder, ['symbolic-ref', `refs/remotes/${name}/HEAD`])).stdout
4520
4547
  .trim()
4521
- .slice(name.length + 1);
4548
+ .slice(`refs/remotes/${name}/`.length);
4522
4549
  if (branch === base || branch === 'main' || branch === 'master') return undefined;
4523
4550
  const remote = await run(folder, ['remote', 'get-url', name]);
4524
4551
  return remote.code === 0 && remote.stdout.trim()