@saadnvd1/agent-os 0.3.592 → 0.3.595

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 (55) hide show
  1. package/app/api/bus/resurrect/route.test.ts +47 -0
  2. package/app/api/bus/resurrect/route.ts +36 -0
  3. package/app/api/sessions/[id]/pause/route.ts +5 -2
  4. package/app/api/sessions/[id]/resurrect/route.test.ts +32 -0
  5. package/app/api/sessions/[id]/resurrect/route.ts +24 -0
  6. package/app/api/sessions/ended/route.ts +19 -0
  7. package/components/Archived/ArchivedRow.tsx +11 -7
  8. package/components/Chat/PausedBanner.tsx +1 -1
  9. package/components/Providers.tsx +5 -1
  10. package/components/SessionList/LiveLine.tsx +1 -1
  11. package/components/SessionList/OrchestratorPinRow.tsx +10 -5
  12. package/components/SessionList/QuickChangeRow.tsx +1 -1
  13. package/components/SessionList/RowParts.tsx +37 -2
  14. package/components/SessionList/RowShell.tsx +6 -2
  15. package/components/SessionList/RowSubtitle.tsx +20 -12
  16. package/components/SessionList/SessionRow.tsx +28 -17
  17. package/components/SessionList/SessionRowMenu.tsx +12 -1
  18. package/components/SessionList/SessionShelves.tsx +40 -8
  19. package/components/SessionList/SidebarExtras.tsx +7 -1
  20. package/components/SessionList/index.tsx +2 -0
  21. package/components/SessionList/useDoneAction.ts +14 -0
  22. package/components/SessionList/useResurrectAction.test.ts +96 -0
  23. package/components/SessionList/useSessionTips.ts +62 -0
  24. package/components/Tasks/TaskRow.tsx +18 -0
  25. package/components/ui/HoverTip.tsx +20 -0
  26. package/data/done/index.ts +17 -0
  27. package/data/presence/index.ts +14 -7
  28. package/lib/db/migrations.ts +11 -0
  29. package/lib/db/types.ts +2 -0
  30. package/lib/done/worktree.ts +18 -2
  31. package/lib/hover-tip.ts +161 -0
  32. package/lib/orchestrator/act.ts +44 -5
  33. package/lib/orchestrator/brief.ts +2 -1
  34. package/lib/orchestrator/digest.ts +3 -2
  35. package/lib/orchestrator/serve.ts +6 -0
  36. package/lib/orchestrator/shell-guard.ts +2 -1
  37. package/lib/orchestrator/tool-names.ts +1 -0
  38. package/lib/orchestrator/tool-schemas.ts +6 -0
  39. package/lib/orchestrator/tools.ts +3 -1
  40. package/lib/resurrect/find.ts +111 -0
  41. package/lib/resurrect/index.ts +422 -0
  42. package/lib/resurrect/plan.ts +61 -0
  43. package/lib/resurrect/snapshot.ts +229 -0
  44. package/lib/security/demo.ts +1 -0
  45. package/lib/sidebar/paused.ts +8 -1
  46. package/lib/sidebar/row-actions.ts +7 -3
  47. package/lib/sidebar/row-badge.ts +40 -0
  48. package/lib/sidebar/row-details.ts +53 -0
  49. package/lib/sidebar/shelves.ts +7 -1
  50. package/lib/tasks/auto-hold.ts +17 -0
  51. package/lib/tasks/finish.ts +9 -0
  52. package/lib/tasks/pause-hold.ts +1 -1
  53. package/lib/tasks/pause.ts +76 -8
  54. package/lib/tasks/queue.ts +39 -12
  55. package/package.json +1 -1
@@ -0,0 +1,161 @@
1
+ // One hover tooltip for the whole app. An element opts in with data-tip
2
+ // (plain text) or data-tip-key ("session:<id>", resolved when it opens by
3
+ // whoever registered that prefix). Rows carry an attribute and nothing
4
+ // else: one element and a few passive document listeners do the rest, and
5
+ // a touch screen attaches none. It opens after resting on something, and
6
+ // once one is open the next opens at once, so a list can be scanned.
7
+
8
+ export interface TipContent {
9
+ title: string;
10
+ lines: [label: string, value: string][];
11
+ }
12
+ export type TipValue = string | TipContent | null | undefined;
13
+
14
+ export const OPEN_DELAY_MS = 600;
15
+ export const WARM_MS = 400;
16
+ const SELECTOR = "[data-tip],[data-tip-key]";
17
+ const TIP_ID = "hover-tip";
18
+
19
+ const resolvers = new Map<string, (id: string) => TipValue>();
20
+
21
+ export function registerTip(
22
+ prefix: string,
23
+ resolve: (id: string) => TipValue
24
+ ): () => void {
25
+ resolvers.set(prefix, resolve);
26
+ return () => {
27
+ if (resolvers.get(prefix) === resolve) resolvers.delete(prefix);
28
+ };
29
+ }
30
+
31
+ export function resolveTip(el: Element): TipValue {
32
+ const key = el.getAttribute("data-tip-key");
33
+ if (key) {
34
+ const at = key.indexOf(":");
35
+ const value = resolvers.get(key.slice(0, at))?.(key.slice(at + 1));
36
+ if (value) return value;
37
+ }
38
+ return el.getAttribute("data-tip");
39
+ }
40
+
41
+ // Text only: names are user text and never parsed as HTML.
42
+ function fill(el: HTMLElement, value: string | TipContent) {
43
+ if (typeof value === "string") {
44
+ el.textContent = value;
45
+ return;
46
+ }
47
+ const doc = el.ownerDocument;
48
+ const title = doc.createElement("div");
49
+ title.className = "font-medium";
50
+ title.textContent = value.title;
51
+ const rows = value.lines.map(([label, text]) => {
52
+ const line = doc.createElement("div");
53
+ const k = doc.createElement("span");
54
+ k.className = "text-muted-foreground";
55
+ k.textContent = `${label} `;
56
+ line.append(k, text);
57
+ return line;
58
+ });
59
+ el.replaceChildren(title, ...rows);
60
+ }
61
+
62
+ // Beside the target (a sidebar row's tip opens over the page, not the
63
+ // list), flipped or dropped below when there's no room. One measure.
64
+ function place(el: HTMLElement, target: Element, win: Window) {
65
+ const r = target.getBoundingClientRect();
66
+ const w = el.offsetWidth;
67
+ const h = el.offsetHeight;
68
+ const gap = 8;
69
+ let x = r.right + gap;
70
+ let y = r.top;
71
+ if (x + w > win.innerWidth - gap) x = r.left - w - gap;
72
+ if (x < gap) {
73
+ x = Math.min(Math.max(gap, r.left), win.innerWidth - w - gap);
74
+ y = r.bottom + gap;
75
+ }
76
+ y = Math.max(gap, Math.min(y, win.innerHeight - h - gap));
77
+ el.style.transform = `translate(${Math.round(x)}px, ${Math.round(y)}px)`;
78
+ }
79
+
80
+ // Works across documents (tests, frames), unlike instanceof Element.
81
+ const isElement = (node: EventTarget | null): node is Element =>
82
+ !!node && typeof (node as Element).closest === "function";
83
+
84
+ export function installHoverTip(win: Window = window): () => void {
85
+ if (!win.matchMedia?.("(hover: hover) and (pointer: fine)").matches)
86
+ return () => {};
87
+ const doc = win.document;
88
+ const el = doc.createElement("div");
89
+ el.id = TIP_ID;
90
+ el.setAttribute("role", "tooltip");
91
+ el.className =
92
+ "popover-surface text-popover-foreground pointer-events-none fixed top-0 left-0 z-[60] max-w-72 rounded-lg px-2.5 py-1.5 text-xs leading-relaxed whitespace-pre-line";
93
+ el.hidden = true;
94
+ doc.body.append(el);
95
+
96
+ let timer: ReturnType<typeof setTimeout> | undefined;
97
+ let pending: Element | null = null;
98
+ let shown: Element | null = null;
99
+ let warmUntil = 0;
100
+
101
+ const hide = () => {
102
+ clearTimeout(timer);
103
+ timer = undefined;
104
+ pending = null;
105
+ if (shown) {
106
+ shown.removeAttribute("aria-describedby");
107
+ warmUntil = Date.now() + WARM_MS;
108
+ shown = null;
109
+ }
110
+ el.hidden = true;
111
+ };
112
+ const show = (target: Element) => {
113
+ timer = undefined;
114
+ if (!target.isConnected) return;
115
+ const value = resolveTip(target);
116
+ if (!value) return;
117
+ fill(el, value);
118
+ el.hidden = false;
119
+ place(el, target, win);
120
+ target.setAttribute("aria-describedby", TIP_ID);
121
+ shown = target;
122
+ };
123
+ const arm = (target: Element | null) => {
124
+ if (target && (target === pending || target === shown)) return;
125
+ hide();
126
+ if (!target) return;
127
+ pending = target;
128
+ if (Date.now() < warmUntil) show(target);
129
+ else timer = setTimeout(() => show(target), OPEN_DELAY_MS);
130
+ };
131
+ const tipOf = (node: EventTarget | null) =>
132
+ isElement(node) ? node.closest(SELECTOR) : null;
133
+
134
+ const onOver = (e: Event) => arm(tipOf(e.target));
135
+ const onOut = (e: Event) => {
136
+ if (!(e as PointerEvent).relatedTarget) hide();
137
+ };
138
+ const onFocusIn = (e: Event) => {
139
+ const t = e.target;
140
+ if (isElement(t) && t.matches(SELECTOR) && t.matches(":focus-visible"))
141
+ arm(t);
142
+ };
143
+ const passive = { passive: true } as const;
144
+ const listeners: [string, (e: Event) => void, AddEventListenerOptions][] = [
145
+ ["pointerover", onOver, passive],
146
+ ["pointerout", onOut, passive],
147
+ ["pointerdown", hide, passive],
148
+ ["keydown", hide, passive],
149
+ ["focusin", onFocusIn, passive],
150
+ ["focusout", hide, passive],
151
+ ["scroll", hide, { passive: true, capture: true }],
152
+ ];
153
+ for (const [type, fn, opts] of listeners)
154
+ doc.addEventListener(type, fn, opts);
155
+ return () => {
156
+ hide();
157
+ for (const [type, fn, opts] of listeners)
158
+ doc.removeEventListener(type, fn, opts);
159
+ el.remove();
160
+ };
161
+ }
@@ -36,7 +36,9 @@ import type { StackItemView } from "../stacks/types";
36
36
  import { doneSession } from "../done";
37
37
  import { archiveChecked } from "../done/archive";
38
38
  import { amendBrief, amendmentsOf } from "./amendments";
39
- import type { Session } from "../db";
39
+ import { db, type Session } from "../db";
40
+ import { resurrectSession } from "../resurrect";
41
+ import { resolveEnded } from "../resurrect/find";
40
42
  import { approvePlanNow } from "../models/plan-step";
41
43
  import { braked } from "./brakes";
42
44
  import { getOrchestrator } from "./home";
@@ -54,7 +56,7 @@ import {
54
56
  PauseRefused,
55
57
  activePause,
56
58
  requestPause,
57
- requestResume,
59
+ resumeNow,
58
60
  } from "../tasks/pause";
59
61
  import { pauseUntil, type PausePreset } from "../sidebar/snooze";
60
62
  import type { Priority } from "../tasks/schedule-types";
@@ -411,6 +413,30 @@ export async function archive(
411
413
  return `Archived ${s.name}: out of the sidebar, in Archived.`;
412
414
  }
413
415
 
416
+ // Brings a dropped, done or archived session back, same id and conversation.
417
+ // A task takes a running slot again, so it goes through the brakes like a
418
+ // start; an unarchive or reopen starts nothing.
419
+ export async function resurrect(
420
+ workspaceId: string,
421
+ ref: string,
422
+ reason: string
423
+ ): Promise<string> {
424
+ if (!reason.trim()) throw new Error("Say why it's restored");
425
+ const id = resolveEnded(ref, { workspaceId });
426
+ const row = db
427
+ .prepare(`SELECT task_status, archived_at FROM sessions WHERE id = ?`)
428
+ .get(id) as { task_status: string | null; archived_at: string | null };
429
+ const task =
430
+ row.task_status === "dropped" ||
431
+ (row.task_status === "done" && !row.archived_at);
432
+ const go = () => resurrectSession(id);
433
+ const out = task
434
+ ? await braked(workspaceId, "task", go, (o) => o.id)
435
+ : await go();
436
+ addNote(workspaceId, `Restored ${out.name}: ${reason.trim()}`);
437
+ return out.text;
438
+ }
439
+
414
440
  // Stops the agent and keeps everything else: a chat's turn is interrupted,
415
441
  // a terminal's tmux session ends. Its worktree and branch stay.
416
442
  export async function stop(workspaceId: string, ref: string): Promise<string> {
@@ -507,14 +533,27 @@ export function pauseTask(
507
533
  return `Pausing ${task.name} ${now ? "now" : "at the end of its step"}. Its slot frees once it has stopped; an event says when.`;
508
534
  }
509
535
 
510
- export function resumeTask(workspaceId: string, ref: string): string {
536
+ export async function resumeTask(
537
+ workspaceId: string,
538
+ ref: string
539
+ ): Promise<string> {
511
540
  const task = workspaceTask(workspaceId, ref);
512
541
  if (!activePause(task.id)) throw new Error(`${task.name} isn't paused`);
542
+ const slots = task.project_id ? slotState(task.project_id) : null;
543
+ let out;
513
544
  try {
514
- requestResume(task.id, "orchestrator");
545
+ out = await resumeNow(task.id, "orchestrator");
515
546
  } catch (error) {
516
547
  if (error instanceof PauseRefused) throw new Error(error.message);
517
548
  throw error;
518
549
  }
519
- return `${task.name} will resume as soon as it has a slot.`;
550
+ if (out.outcome === "held")
551
+ return `${task.name} is ${out.note}. It resumes by itself when that clears.`;
552
+ if (out.outcome === "cancelled")
553
+ return `${task.name} keeps running: its pause was cancelled.`;
554
+ const past = slots?.full
555
+ ? ` past the running-task limit (${slots.running} of ${slots.limit} running)`
556
+ : "";
557
+ addNote(workspaceId, `Resumed ${task.name} now${past}.`);
558
+ return `Resumed ${task.name} now${past}. It carries on with what was held for it.`;
520
559
  }
@@ -137,10 +137,11 @@ Acting:
137
137
  - \`${TOOL_NAMES.set_priority}\` (task, priority): re-rank a queued task (urgent, blocking, normal, background), or tag a running one. Urgent is a bug Saad hit; background starts last.
138
138
  - \`${TOOL_NAMES.start_now}\` (task, reason): start a queued task now, past the running-task limit and its after. Still refused while paused or braked, and a Mac-only task stays queued. Use it sparingly, when Saad asks or it unblocks others; the reason is logged for Saad.
139
139
  - \`${TOOL_NAMES.pause_task}\` (task, for, now?, reason): pause a running task for 1h, 2h, until tomorrow 9 AM or until resumed. Its agent ends at the end of its step (now interrupts the step); its worktree and conversation stay and its slot frees for the next queued task. It resumes by itself, ahead of new arrivals, with what was held (CI and review notes, messages) in one prompt. Use it to make room for urgent work or to wait out a loaded machine. Refused for a task that is merging, moving, setting up or waiting on Saad.
140
- - \`${TOOL_NAMES.resume_task}\` (task): resume a pause you set now. A pause Saad set is his to lift.
140
+ - \`${TOOL_NAMES.resume_task}\` (task): resume a pause you set now, past the running-task limit unless the machine load holds it. A pause Saad set is his to lift.
141
141
  - \`${TOOL_NAMES.stop}\` (session): stop a session's agent, keeping its work.
142
142
  - \`${TOOL_NAMES.done}\` (session): finish a session whose work is complete. A task with an open PR merges through the same gates as sign_off first (refused naming the gate otherwise); then the agent stops, the worktree goes only if nothing in it would be lost, and the session lands on the sidebar's Done shelf (it is not archived). Not a rejection: use drop for that.
143
143
  - \`${TOOL_NAMES.archive}\` (session): put a session away, out of the sidebar, when Saad asks. Nothing is merged or cleaned up; refused while it works or has an open PR.
144
+ - \`${TOOL_NAMES.resurrect}\` (session, reason): bring a dropped, done or archived session back with its conversation and worktree, in the state it had (a plan-only task waits for approval again). Use it when a drop or done was a mistake, or when Saad asks; refused for a merged PR, a missing conversation or a removed project. A restored task counts against the running limit and the brakes like a start.
144
145
  - \`${TOOL_NAMES.add_project}\` (path, name?): make a git repository on this machine a project of this workspace, or move the project already at that path in when it's in no workspace. Use it rather than sending Saad steps. It refuses a folder that isn't a git repository or holds secrets, and a project another workspace has: moving that is Saad's call, so ask_saad.
145
146
  - \`${TOOL_NAMES.note}\` (text): a line in this workspace's decision log, shown in your chat. Note each decision that matters, with why.
146
147
  - \`${TOOL_NAMES.rule_add}\` (text): keep a standing rule for this workspace, in your brief on every start. Saad sees and edits them in Settings → Workspaces.
@@ -58,6 +58,7 @@ interface TaskRow {
58
58
  armed_at: string | null;
59
59
  pause_state: string | null;
60
60
  paused_until: string | null;
61
+ pause_note: string | null;
61
62
  placed_note: string | null;
62
63
  }
63
64
 
@@ -165,7 +166,7 @@ function tasksSection(
165
166
  const tasks = db
166
167
  .prepare(
167
168
  `SELECT s.id, s.name, p.name AS project, s.pr_number, s.pr_status, s.view,
168
- s.merge_armed_at AS armed_at, s.pause_state, s.paused_until, s.placed_note
169
+ s.merge_armed_at AS armed_at, s.pause_state, s.paused_until, s.pause_note, s.placed_note
169
170
  FROM sessions s JOIN projects p ON p.id = s.project_id
170
171
  WHERE p.workspace_id = ? AND s.role IS NULL AND s.archived_at IS NULL
171
172
  AND s.task_status = 'running'
@@ -181,7 +182,7 @@ function tasksSection(
181
182
  const gates = gateState(checks.get(t.id), failures.get(t.id));
182
183
  const arm = t.armed_at ? " | armed to merge" : "";
183
184
  const paused = t.pause_state
184
- ? ` | ${t.pause_state}${t.paused_until ? ` until ${t.paused_until} UTC` : t.pause_state === "paused" ? " until resumed" : ""}`
185
+ ? ` | ${t.pause_state}${t.paused_until ? ` until ${t.paused_until} UTC` : t.pause_state === "paused" ? " until resumed" : ""}${t.pause_note ? ` (${t.pause_note})` : ""}`
185
186
  : "";
186
187
  const placed = t.placed_note ? ` | ${t.placed_note}` : "";
187
188
  return `- ${clip(t.name, 80)} (${t.project ?? "?"}, ${t.view}, id ${shortId(t.id)}): ${pr}${arm}${paused}${placed}${gates ? ` | ${gates}` : ""}`;
@@ -6,6 +6,7 @@ import {
6
6
  archive,
7
7
  done,
8
8
  drop,
9
+ resurrect,
9
10
  moveTaskTo,
10
11
  send,
11
12
  stack,
@@ -64,6 +65,7 @@ const ACTING = new Set<ToolName>([
64
65
  "stack",
65
66
  "land",
66
67
  "drop",
68
+ "resurrect",
67
69
  "move",
68
70
  "approve_plan",
69
71
  "plan_pieces",
@@ -219,6 +221,10 @@ export async function runTool(
219
221
  return done(w, p(tool, raw).session);
220
222
  case "archive":
221
223
  return archive(w, p(tool, raw).session);
224
+ case "resurrect": {
225
+ const a = p(tool, raw);
226
+ return resurrect(w, a.session, a.reason);
227
+ }
222
228
  case "add_project": {
223
229
  const a = p(tool, raw);
224
230
  return addProject(w, a.path, a.name);
@@ -211,7 +211,7 @@ const PULL_MERGE = /(^|\/)pulls\/[^/?\s]+\/merge\/?(\?|$)/;
211
211
 
212
212
  const MERGE_MSG = `Refused: a PR merges only through the gates: ${T.sign_off} (or ${T.arm}) for a task's or an external PR, ${T.land} for a stack. Nothing merges, closes or retargets a PR from the shell.`;
213
213
 
214
- // aos move, done, archive, stop and drop reach a session by name, past the tools'
214
+ // aos move, done, archive, resurrect, stop and drop reach a session by name, past the tools'
215
215
  // Pause check and logging; the tools do the same work.
216
216
  function aosRefusal(args: string[]): string | null {
217
217
  const [sub] = positionals(args);
@@ -219,6 +219,7 @@ function aosRefusal(args: string[]): string | null {
219
219
  move: T.move,
220
220
  done: T.done,
221
221
  archive: T.archive,
222
+ resurrect: T.resurrect,
222
223
  stop: T.stop,
223
224
  };
224
225
  if (sub && tool[sub])
@@ -36,6 +36,7 @@ export const TOOL_NAMES = {
36
36
  stop: name("stop"),
37
37
  done: name("done"),
38
38
  archive: name("archive"),
39
+ resurrect: name("resurrect"),
39
40
  add_project: name("add_project"),
40
41
  note: name("note"),
41
42
  question: name("question"),
@@ -291,6 +291,12 @@ export const TOOL_SHAPES = {
291
291
  stop: { session },
292
292
  done: { session },
293
293
  archive: { session },
294
+ resurrect: {
295
+ session: ref(
296
+ "A dropped, done or archived session: its name, project/name or id (from the decision log, or as Saad named it)"
297
+ ),
298
+ reason: z.string().trim().min(1).max(2000),
299
+ },
294
300
  add_project: {
295
301
  path: z
296
302
  .string()
@@ -88,11 +88,13 @@ const DESCRIPTIONS: Record<ToolName, string> = {
88
88
  pause_task:
89
89
  "Pause a running task for a set time: its agent ends at the end of its current step (now true interrupts the step), its worktree and conversation stay, and it frees its slot so the next queued task can start. It resumes by itself at the time, ahead of new arrivals of the same priority, with whatever was held (CI and review notes, messages) in one continue prompt. Refused for a task that is merging, moving, setting up or waiting on Saad. Give a reason; it is shown with the pause.",
90
90
  resume_task:
91
- "Resume a task you paused (or the scheduler did) now. A pause Saad set is his to lift: this refuses and says so.",
91
+ "Resume a task you paused (or the scheduler did) now: it starts at once, past the running-task limit, unless the machine load holds it (the answer says so). A pause Saad set is his to lift: this refuses and says so.",
92
92
  stop: "Stop a session's agent mid-turn, even while it's thinking, keeping its conversation, worktree and branch; your next message runs as its next turn.",
93
93
  done: "Finish a session whose work is complete: a task's open PR merges through the sign-off gates first (refused naming the failing gate), then its agent stops, its worktree is removed if nothing would be lost, and it lands on the sidebar's Done shelf; it no longer archives (use archive for that). Not a rejection.",
94
94
  archive:
95
95
  "Put a finished session away, out of the sidebar (it stays in Archived, and Saad can unarchive it). Nothing is merged or cleaned up: refused while the session is working or has an open PR; done first for finished work.",
96
+ resurrect:
97
+ "Bring a dropped, done or archived session back: the same session and conversation, its worktree (with its uncommitted files and plan) back from what was saved or from its branch, its status as it was (a plan-only task waits for approval again, one with a PR is idle), and a PR a drop closed reopened. Archived sessions just unarchive. Held by Pause and braked like a start. Refused when its conversation is gone, its PR was merged, its project was removed or its branch is in use. Give a reason; it goes in the decision log.",
96
98
  add_project:
97
99
  "Make a git repository on this machine a project of this workspace, by its absolute path, or move the project already at that path into this workspace when it's in no workspace. Says its default branch, detected from git. Refuses a folder that isn't a git repository or that holds secrets, and a project another workspace has.",
98
100
  note: "Add a line to this workspace's decision log; it shows in your chat.",
@@ -0,0 +1,111 @@
1
+ /** Sessions that ended (dropped, done, archived) and can be asked for back. */
2
+
3
+ import { db } from "../db";
4
+ import { resolveRef } from "../bus/resolve";
5
+
6
+ export type EndedKind = "dropped" | "done" | "archived" | "settled";
7
+
8
+ export interface EndedSession {
9
+ id: string;
10
+ name: string;
11
+ projectId: string | null;
12
+ projectName: string | null;
13
+ kind: EndedKind;
14
+ taskStatus: string | null;
15
+ // A plan-only task whose plan was written and never approved.
16
+ planWaiting: boolean;
17
+ endedAt: string;
18
+ }
19
+
20
+ // A workspace's, or one project's, or everyone's (a person's own shell).
21
+ export type EndedScope = { workspaceId: string } | { projectId: string } | null;
22
+
23
+ interface Row {
24
+ id: string;
25
+ name: string;
26
+ tmux_name: string;
27
+ project_id: string | null;
28
+ project_name: string | null;
29
+ task_status: string | null;
30
+ archived_at: string | null;
31
+ plan_phase: string | null;
32
+ ended_at: string;
33
+ }
34
+
35
+ function kindOf(r: Row): EndedKind {
36
+ if (r.task_status === "dropped") return "dropped";
37
+ if (r.archived_at) return "archived";
38
+ return r.task_status === "done" ? "done" : "settled";
39
+ }
40
+
41
+ function rows(scope: EndedScope, limit: number, kind?: EndedKind): Row[] {
42
+ const where = [
43
+ "s.role IS NULL",
44
+ "s.peer_mirror = 0",
45
+ "s.held_by_device IS NULL",
46
+ ];
47
+ const args: (string | number)[] = [];
48
+ if (scope && "workspaceId" in scope) {
49
+ where.push("p.workspace_id = ?");
50
+ args.push(scope.workspaceId);
51
+ } else if (scope) {
52
+ where.push("s.project_id = ?");
53
+ args.push(scope.projectId);
54
+ }
55
+ where.push(
56
+ `(s.archived_at IS NOT NULL OR s.task_status IN ('dropped', 'done')
57
+ OR (s.task_status IS NULL AND s.settled_at IS NOT NULL))`
58
+ );
59
+ if (kind === "dropped") where.push("s.task_status = 'dropped'");
60
+ if (kind === "archived") where.push("s.archived_at IS NOT NULL");
61
+ if (kind === "done")
62
+ where.push("s.task_status = 'done' AND s.archived_at IS NULL");
63
+ return db
64
+ .prepare(
65
+ `SELECT s.id, s.name, s.tmux_name, s.project_id, p.name AS project_name,
66
+ s.task_status, s.archived_at, s.plan_phase,
67
+ COALESCE(s.task_ended_at, s.archived_at, s.settled_at, s.updated_at) AS ended_at
68
+ FROM sessions s LEFT JOIN projects p ON p.id = s.project_id
69
+ WHERE ${where.join(" AND ")}
70
+ ORDER BY ended_at DESC LIMIT ?`
71
+ )
72
+ .all(...args, limit) as Row[];
73
+ }
74
+
75
+ export function endedSessions(
76
+ scope: EndedScope,
77
+ opts: { limit?: number; kind?: EndedKind } = {}
78
+ ): EndedSession[] {
79
+ return rows(scope, opts.limit ?? 50, opts.kind).map((r) => ({
80
+ id: r.id,
81
+ name: r.name,
82
+ projectId: r.project_id,
83
+ projectName: r.project_name,
84
+ kind: kindOf(r),
85
+ taskStatus: r.task_status,
86
+ planWaiting: r.plan_phase === "awaiting",
87
+ endedAt: r.ended_at,
88
+ }));
89
+ }
90
+
91
+ /** An ended session by name, project/name, id or id prefix, within the scope. */
92
+ export function resolveEnded(ref: string, scope: EndedScope): string {
93
+ const all = rows(scope, 500);
94
+ const r = resolveRef(
95
+ ref,
96
+ all.map((s) => ({
97
+ id: s.id,
98
+ name: s.name,
99
+ projectName: s.project_name,
100
+ tmuxName: s.tmux_name,
101
+ previousNames: [],
102
+ }))
103
+ );
104
+ if (!r.ok)
105
+ throw new Error(
106
+ r.reason === "none"
107
+ ? `No dropped, done or archived session "${ref}"${scope ? " here" : ""}.`
108
+ : r.error
109
+ );
110
+ return r.id;
111
+ }