@bridgebrew/sessions 0.0.0-stage → 0.0.8

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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +43 -2
  3. package/answers.ts +167 -0
  4. package/browser/branch-actions.tsx +166 -0
  5. package/browser/changes.tsx +415 -0
  6. package/browser/children.tsx +650 -0
  7. package/browser/conversation.tsx +2381 -0
  8. package/browser/decision-questions.tsx +191 -0
  9. package/browser/elapsed.tsx +44 -0
  10. package/browser/gallery.tsx +218 -0
  11. package/browser/index.tsx +3434 -0
  12. package/browser/media-origins.tsx +38 -0
  13. package/browser/mobile.tsx +663 -0
  14. package/browser/open-link.tsx +30 -0
  15. package/browser/pull-request.tsx +116 -0
  16. package/browser/questions.tsx +156 -0
  17. package/browser/session-scheduled.tsx +203 -0
  18. package/browser/subagent-view.tsx +136 -0
  19. package/browser/subagents.tsx +339 -0
  20. package/browser/tabs.tsx +228 -0
  21. package/browser/tsconfig.json +15 -0
  22. package/browser/views/view.tsx +1064 -0
  23. package/browser/views.tsx +166 -0
  24. package/contract.ts +287 -0
  25. package/delegations.ts +1975 -0
  26. package/diff.ts +88 -0
  27. package/docs/en/images.mdx +51 -0
  28. package/docs/en/index.mdx +22 -0
  29. package/docs/en/meta.json +4 -0
  30. package/docs/en/organize-sessions.mdx +53 -0
  31. package/docs/en/start-a-session.mdx +63 -0
  32. package/docs/meta.json +4 -0
  33. package/git.ts +223 -0
  34. package/listing.ts +382 -0
  35. package/package.json +1023 -4
  36. package/peers.ts +677 -0
  37. package/pull-request-watch.ts +282 -0
  38. package/pull-requests.ts +606 -0
  39. package/server.ts +5920 -0
  40. package/text.ts +19 -0
  41. package/tsconfig.json +3 -0
  42. package/viewer-activity.ts +57 -0
  43. package/views/examples.ts +153 -0
  44. package/views/library.ts +1116 -0
package/listing.ts ADDED
@@ -0,0 +1,382 @@
1
+ // One listing per page (research-018 slice 5): every copy of the Sessions screen on a node (two windows side by side,
2
+ // the same session on two desks) shares one store: the node's listing and the workspace's tags, fetched once for all;
3
+ // the poll while a session nobody watches runs (every 3 s), the timer at the soonest snooze wake, and the Sessions row's
4
+ // sidebar mark. The first copy starts it (tried again while it fails, 1 s doubling to 30 s), the last one stops it. Each
5
+ // copy says which session it shows (`watch`): its own event stream lists again when that one changes, so a session
6
+ // shown is not polled, and it does not count as unread in the mark. One row, one mark: with Sessions on two nodes, the
7
+ // node of the focused Sessions window marks it (`claimMark`); the last copy gone clears it, or hands it to a node still
8
+ // shown.
9
+ // Child sessions (bridge#212 S3): a child whose parent is listed has no row of its own (`lineage`): it is listed under
10
+ // its parent, whose row works while one of its descendants runs and needs the user while one waits for a decision; the
11
+ // mark counts the top rows only, so a child waiting counts once, as its parent. A child's row says its state in words
12
+ // (`childState`): Working, Asking, Done, Failed, Stopped or Cancelled; a child whose worktree is being made (S7) works,
13
+ // with the detail "Preparing its branch and stage".
14
+
15
+ /** The fields of a listed session the store reads. */
16
+ export interface Listed {
17
+ id: string;
18
+ /** A child session's parent (`delegations.ts`). */
19
+ parent?: string;
20
+ running?: boolean;
21
+ waiting?: boolean;
22
+ unread?: boolean;
23
+ woke?: boolean;
24
+ snoozedUntil?: string;
25
+ }
26
+ export interface Snapshot<L> {
27
+ listing: L | undefined;
28
+ tags: string[];
29
+ }
30
+ export interface Source<L> {
31
+ /** The node's listing; rejects with the cause (`code: 'starting'`: the workspace restarting). */
32
+ list(): Promise<L>;
33
+ /** The workspace's tags, most used first (a failure keeps the last ones). */
34
+ tags?(): Promise<string[]>;
35
+ /** The Sessions row's mark, after each listing or a change of the sessions shown, while this store marks it;
36
+ * `undefined` clears it. */
37
+ mark?(mark: { count: number; working: boolean } | undefined): void;
38
+ }
39
+
40
+ /** While a session no copy shows runs, the listing is fetched again this often, ms. */
41
+ export const POLL_MS = 3000;
42
+
43
+ export function listingStore<L extends { sessions: Listed[] }>(source: Source<L>) {
44
+ let snapshot: Snapshot<L> = { listing: undefined, tags: [] };
45
+ const listeners = new Set<() => void>();
46
+ /** The sessions shown, each with the number of copies showing it. */
47
+ const watched = new Map<string, number>();
48
+ let stopped = false;
49
+ /** This store marks the Sessions row (its node is the one shown in the focused Sessions window). */
50
+ let marking = false;
51
+ let latest = 0;
52
+ let applied = 0;
53
+ let poll: ReturnType<typeof setInterval> | undefined;
54
+ let wake: ReturnType<typeof setTimeout> | undefined;
55
+ let wakeAt: string | undefined;
56
+ let retry: ReturnType<typeof setTimeout> | undefined;
57
+
58
+ const emit = () => {
59
+ for (const listener of listeners) listener();
60
+ };
61
+ const set = (next: Partial<Snapshot<L>>) => {
62
+ snapshot = { ...snapshot, ...next };
63
+ emit();
64
+ };
65
+ /** The poll, the wake timer and the mark, for the listing held and the sessions shown. */
66
+ const follow = () => {
67
+ const sessions = snapshot.listing?.sessions ?? [];
68
+ const unseen = !stopped && sessions.some((each) => each.running && !watched.has(each.id));
69
+ if (unseen && !poll) poll = setInterval(() => void store.load().catch(() => {}), POLL_MS);
70
+ else if (!unseen && poll) {
71
+ clearInterval(poll);
72
+ poll = undefined;
73
+ }
74
+ const soonest = stopped
75
+ ? undefined
76
+ : sessions
77
+ .map((each) => each.snoozedUntil)
78
+ .filter((at): at is string => !!at)
79
+ .sort()[0];
80
+ if (soonest !== wakeAt) {
81
+ clearTimeout(wake);
82
+ wakeAt = soonest;
83
+ // A snoozed session wakes on the server: listed again just after the soonest wake (a timer in this page).
84
+ if (soonest)
85
+ wake = setTimeout(
86
+ () => void store.load().catch(() => {}),
87
+ Math.min(2_147_483_647, Math.max(0, Date.parse(soonest) - Date.now()) + 1500),
88
+ );
89
+ }
90
+ if (snapshot.listing && !stopped && marking) {
91
+ source.mark?.({
92
+ count: lineage(sessions).top.filter(
93
+ (each) => each.waiting || ((each.unread || each.woke) && !watched.has(each.id)),
94
+ ).length,
95
+ working: sessions.some((each) => each.running),
96
+ });
97
+ }
98
+ };
99
+
100
+ const store = {
101
+ get: () => snapshot,
102
+ subscribe(listener: () => void) {
103
+ listeners.add(listener);
104
+ return () => {
105
+ listeners.delete(listener);
106
+ };
107
+ },
108
+ /** Fetches the listing (and the tags); an answer older than one applied already is dropped. Rejects with the cause. */
109
+ async load(): Promise<void> {
110
+ const run = ++latest;
111
+ const listing = await source.list();
112
+ if (stopped || run < applied) return;
113
+ applied = run;
114
+ // A session unchanged keeps its object: its row is not drawn again (bridge#193).
115
+ const was = new Map(snapshot.listing?.sessions.map((each) => [each.id, each]));
116
+ const sessions = listing.sessions.map((each) => {
117
+ const held = was.get(each.id);
118
+ return held && JSON.stringify(held) === JSON.stringify(each) ? held : each;
119
+ });
120
+ set({ listing: { ...listing, sessions } });
121
+ follow();
122
+ void source.tags?.().then(
123
+ (tags) => {
124
+ if (!stopped) set({ tags });
125
+ },
126
+ () => {},
127
+ );
128
+ },
129
+ /** A change made here before the server confirms it (a reorder, a rename): the next listing replaces it. */
130
+ patch(change: (listing: L) => L) {
131
+ if (snapshot.listing) set({ listing: change(snapshot.listing) });
132
+ },
133
+ /** A copy shows session `id` (none: nothing to watch); returns the end of it. */
134
+ watch(id: string | undefined): () => void {
135
+ if (id === undefined) return () => {};
136
+ watched.set(id, (watched.get(id) ?? 0) + 1);
137
+ follow();
138
+ return () => {
139
+ const count = (watched.get(id) ?? 1) - 1;
140
+ if (count > 0) watched.set(id, count);
141
+ else watched.delete(id);
142
+ follow();
143
+ };
144
+ },
145
+ /** The first listing, tried again while it fails: 1 s later, doubling to 30 s. */
146
+ start() {
147
+ let delay = 1000;
148
+ const attempt = () =>
149
+ void store.load().catch(() => {
150
+ if (stopped) return;
151
+ retry = setTimeout(attempt, delay);
152
+ delay = Math.min(delay * 2, 30_000);
153
+ });
154
+ attempt();
155
+ },
156
+ /** Whether this store marks the Sessions row (on: its mark now; off: left to the next store that marks). */
157
+ setMarking(on: boolean) {
158
+ marking = on;
159
+ if (on) follow();
160
+ },
161
+ /** Clears the mark (the last store gone). */
162
+ clearMark() {
163
+ source.mark?.(undefined);
164
+ },
165
+ stop() {
166
+ stopped = true;
167
+ clearTimeout(retry);
168
+ clearInterval(poll);
169
+ clearTimeout(wake);
170
+ poll = undefined;
171
+ listeners.clear();
172
+ },
173
+ };
174
+ return store;
175
+ }
176
+ export type ListingStore<L extends { sessions: Listed[] }> = ReturnType<typeof listingStore<L>>;
177
+
178
+ /** Any listing's store, as the registry holds it: what the copies that share it start, stop and mark. */
179
+ type AnyStore = ListingStore<{ sessions: Listed[] }>;
180
+ /** The stores in use, by owner (the plugin's context: a workspace's plugins) and key (the node). */
181
+ const stores = new WeakMap<object, Map<string, { store: AnyStore; copies: number }>>();
182
+ /** The store that marks the Sessions row, by owner. */
183
+ const markers = new WeakMap<object, AnyStore>();
184
+
185
+ /** `store` marks the Sessions row for `owner` (its node is shown in the focused Sessions window); the one before stops. */
186
+ export function claimMark(owner: object, store: AnyStore) {
187
+ const was = markers.get(owner);
188
+ if (was === store) return;
189
+ was?.setMarking(false);
190
+ markers.set(owner, store);
191
+ store.setMarking(true);
192
+ }
193
+
194
+ /** The store of `key` for `owner`, made by `make` and started for the first copy; `release` when the copy goes (the last
195
+ * one stops it). */
196
+ export function acquire<L extends { sessions: Listed[] }>(
197
+ owner: object,
198
+ key: string,
199
+ make: () => ListingStore<L>,
200
+ ): { store: ListingStore<L>; release: () => void } {
201
+ let byKey = stores.get(owner);
202
+ if (!byKey) {
203
+ byKey = new Map<string, { store: AnyStore; copies: number }>();
204
+ stores.set(owner, byKey);
205
+ }
206
+ // The store `key`'s maker made, listed with the `L` that maker lists: one key, one kind of listing (the node's).
207
+ let entry = byKey.get(key) as { store: ListingStore<L>; copies: number } | undefined;
208
+ if (!entry) {
209
+ entry = { store: make(), copies: 0 };
210
+ byKey.set(key, entry);
211
+ entry.store.start();
212
+ if (!markers.has(owner)) claimMark(owner, entry.store);
213
+ }
214
+ entry.copies++;
215
+ const held = entry;
216
+ let released = false;
217
+ return {
218
+ store: held.store,
219
+ release() {
220
+ if (released) return;
221
+ released = true;
222
+ if (--held.copies > 0) return;
223
+ held.store.stop();
224
+ if (byKey.get(key) === held) byKey.delete(key);
225
+ if (markers.get(owner) !== held.store) return;
226
+ // The marking store gone: another node still shown marks the row, else it is cleared.
227
+ markers.delete(owner);
228
+ const next = [...byKey.values()][0];
229
+ if (next) claimMark(owner, next.store);
230
+ else held.store.clearMark();
231
+ },
232
+ };
233
+ }
234
+
235
+ /** The fields of an Active session the inbox reads. */
236
+ export interface Inboxed {
237
+ running?: boolean;
238
+ waiting?: boolean;
239
+ createdAt: string;
240
+ updatedAt?: string;
241
+ lastTurn?: { endedAt: string };
242
+ questions?: { role: 'asker' | 'target'; expired: boolean }[];
243
+ queue?: { scheduled?: unknown }[];
244
+ pullRequest?: { watching?: true | undefined } | undefined;
245
+ }
246
+
247
+ /** The inbox (bridge#210): of the Active sessions, the ones working fold into Working (a turn running, a message the
248
+ * user queued, held by a restart until it runs, a question sent to another session and not answered yet, or its pull
249
+ * request watched, research-086: its agent waits for news), newest sent first (`updatedAt`: the user's last message); the others
250
+ * need the user, newest back first: a decision open or a question expired (`waiting`) on top, then by when their turn
251
+ * ended or they were last sent work. */
252
+ export function inbox<S extends Inboxed>(sessions: S[]): { active: S[]; working: S[] } {
253
+ 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
+ const working = sessions.filter(
257
+ (each) =>
258
+ !each.waiting &&
259
+ (each.running ||
260
+ !!each.queue?.some((queued) => !queued.scheduled) ||
261
+ !!each.pullRequest?.watching ||
262
+ !!each.questions?.some((asked) => asked.role === 'asker' && !asked.expired)),
263
+ );
264
+ return {
265
+ active: sessions
266
+ .filter((each) => !working.includes(each))
267
+ .sort((a, b) => Number(!!b.waiting) - Number(!!a.waiting) || back(b).localeCompare(back(a))),
268
+ working: working.sort((a, b) => sent(b).localeCompare(sent(a))),
269
+ };
270
+ }
271
+
272
+ /** The fields of a listed session its lineage reads. */
273
+ interface Kin {
274
+ id: string;
275
+ parent?: string | undefined;
276
+ running?: boolean | undefined;
277
+ waiting?: boolean | undefined;
278
+ createdAt?: string | undefined;
279
+ }
280
+ /** A top row with its descendants' state, by the listed object it was made from: the same object while both stay. */
281
+ const rolled = new WeakMap<object, { running: boolean; waiting: boolean; value: object }>();
282
+ /** The sessions as the list shows them (bridge#212 S3): `top`, those without a listed parent, each with `running` and
283
+ * `waiting` its own or one of its descendants' (a new object only when that changes it: an unchanged row is not drawn
284
+ * again); `children`, each parent's listed children (as listed, oldest first); `parentOf`, each child's parent. A child
285
+ * whose parent is not listed (another node's, archived) is a top row. */
286
+ export function lineage<S extends Kin>(
287
+ sessions: readonly S[],
288
+ ): { top: S[]; children: Map<string, S[]>; parentOf: Map<string, string> } {
289
+ const listed = new Set(sessions.map((each) => each.id));
290
+ const children = new Map<string, S[]>();
291
+ const parentOf = new Map<string, string>();
292
+ for (const each of sessions)
293
+ if (each.parent !== undefined && each.parent !== each.id && listed.has(each.parent)) {
294
+ children.set(each.parent, [...(children.get(each.parent) ?? []), each]);
295
+ parentOf.set(each.id, each.parent);
296
+ }
297
+ /** Whether one of `id`'s descendants runs or waits (`seen`: a cycle is never followed twice). */
298
+ const below = (id: string, seen: Set<string>): { running: boolean; waiting: boolean } => {
299
+ let running = false;
300
+ let waiting = false;
301
+ for (const child of children.get(id) ?? []) {
302
+ if (seen.has(child.id)) continue;
303
+ seen.add(child.id);
304
+ const deeper = below(child.id, seen);
305
+ running ||= !!child.running || deeper.running;
306
+ waiting ||= !!child.waiting || deeper.waiting;
307
+ }
308
+ return { running, waiting };
309
+ };
310
+ const top = sessions
311
+ .filter((each) => !parentOf.has(each.id))
312
+ .map((each) => {
313
+ if (!children.has(each.id)) return each;
314
+ const { running, waiting } = below(each.id, new Set([each.id]));
315
+ if (!(running && !each.running) && !(waiting && !each.waiting)) return each;
316
+ const held = rolled.get(each);
317
+ if (held && held.running === running && held.waiting === waiting) return held.value as S;
318
+ const value = {
319
+ ...each,
320
+ running: !!each.running || running,
321
+ waiting: !!each.waiting || waiting,
322
+ };
323
+ rolled.set(each, { running, waiting, value });
324
+ return value;
325
+ });
326
+ for (const [id, list] of children)
327
+ children.set(
328
+ id,
329
+ [...list].sort((a, b) => (a.createdAt ?? '').localeCompare(b.createdAt ?? '')),
330
+ );
331
+ return { top, children, parentOf };
332
+ }
333
+
334
+ /** A child session's state as its row says it (bridge#212 S3). */
335
+ export type ChildState = 'working' | 'asking' | 'done' | 'failed' | 'stopped' | 'cancelled';
336
+ /** A child's state and its times: `since`, when its work started (while it works or asks); `ended`, when it ended.
337
+ * Its own activity first (it asks while it waits for the user, works while it runs), then its delegation in its
338
+ * parent's record (running: it starts; interrupted, the user's Stop, reads as stopped), else its last turn. */
339
+ export function childState(
340
+ child: {
341
+ running?: boolean | undefined;
342
+ waiting?: boolean | undefined;
343
+ createdAt?: string | undefined;
344
+ updatedAt?: string | undefined;
345
+ lastTurn?: { endedAt: string; reason: 'completed' | 'interrupted' | 'failed' } | undefined;
346
+ },
347
+ delegation?: {
348
+ status: string;
349
+ createdAt: string;
350
+ endedAt?: string | undefined;
351
+ preparing?: true | undefined;
352
+ },
353
+ ): { state: ChildState; since?: string; ended?: string; detail?: string } {
354
+ const since =
355
+ delegation?.status === 'running' ? delegation.createdAt : (child.updatedAt ?? child.createdAt);
356
+ const started = since === undefined ? {} : { since };
357
+ if (child.waiting) return { state: 'asking', ...started };
358
+ if (child.running || delegation?.status === 'running')
359
+ return {
360
+ state: 'working',
361
+ ...started,
362
+ // Its worktree is being made (S7): working, its task not started yet.
363
+ ...(!child.running && delegation?.preparing && { detail: 'Preparing its branch and stage' }),
364
+ };
365
+ const ended = (at: string | undefined) => (at === undefined ? {} : { ended: at });
366
+ if (delegation) {
367
+ const at = ended(delegation.endedAt ?? child.lastTurn?.endedAt);
368
+ if (delegation.status === 'completed') return { state: 'done', ...at };
369
+ if (delegation.status === 'failed') return { state: 'failed', ...at };
370
+ if (delegation.status === 'interrupted') return { state: 'stopped', ...at };
371
+ return { state: 'cancelled', ...at };
372
+ }
373
+ if (child.lastTurn) {
374
+ const at = ended(child.lastTurn.endedAt);
375
+ const reason = child.lastTurn.reason;
376
+ return {
377
+ state: reason === 'completed' ? 'done' : reason === 'failed' ? 'failed' : 'stopped',
378
+ ...at,
379
+ };
380
+ }
381
+ return { state: 'working', ...started };
382
+ }