sideby 0.41.2 → 0.41.3

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 (39) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.js +163 -32
  3. package/dist/src/cli/json-schemas.js +41 -4
  4. package/dist/src/cli/main.js +17 -6
  5. package/dist/src/core/cli-commands.js +1 -1
  6. package/dist/src/core/config.d.ts +16 -0
  7. package/dist/src/core/config.js +262 -42
  8. package/dist/src/core/history-project.d.ts +14 -0
  9. package/dist/src/core/history-project.js +42 -12
  10. package/dist/src/core/history.d.ts +4 -6
  11. package/dist/src/core/history.js +5 -15
  12. package/dist/src/core/local-build.d.ts +12 -0
  13. package/dist/src/core/local-build.js +32 -0
  14. package/dist/src/core/search-catalog.js +27 -0
  15. package/dist/src/core/unattended-followup.d.ts +62 -0
  16. package/dist/src/core/unattended-followup.js +205 -0
  17. package/dist/src/core/unattended-pending.d.ts +11 -3
  18. package/dist/src/core/unattended-pending.js +34 -8
  19. package/dist/src/families/claude/history.js +9 -1
  20. package/dist/src/families/history.d.ts +22 -2
  21. package/dist/src/families/history.js +55 -0
  22. package/dist/src/handoff/messages.js +1 -1
  23. package/dist/src/panel/handler.d.ts +11 -4
  24. package/dist/src/panel/handler.js +50 -25
  25. package/dist/src/panel/i18n.d.ts +23 -1
  26. package/dist/src/panel/i18n.js +48 -4
  27. package/dist/src/panel/page-logic.d.ts +53 -0
  28. package/dist/src/panel/page-logic.js +96 -0
  29. package/dist/src/panel/page-script.js +140 -36
  30. package/dist/src/panel/page-styles.js +17 -0
  31. package/dist/src/unattended/hook.d.ts +10 -5
  32. package/dist/src/unattended/hook.js +17 -12
  33. package/package.json +1 -1
  34. package/schemas/unattended-pending.json +156 -56
  35. package/skills/sideby/SKILL.md +2 -1
  36. package/skills/sideby/references/diagnose.md +1 -0
  37. package/skills/sideby/references/handoff.md +1 -1
  38. package/skills/sideby/references/panel.md +1 -1
  39. package/skills/sideby/references/unattended.md +16 -5
@@ -0,0 +1,62 @@
1
+ import type { Account } from '../types.ts';
2
+ import type { PendingDecision } from './unattended-pending.ts';
3
+ /**
4
+ * done: marked done; replied: not marked, and the user typed in the session after it was kept (which does not tell
5
+ * whether it was finished: the user looks before marking it done); open: not marked, and nothing typed after it.
6
+ */
7
+ export type PendingState = 'open' | 'replied' | 'done';
8
+ /** One Pending Decision as it is listed: with its Project, its state, and when the user replied. */
9
+ export interface PendingRow extends PendingDecision {
10
+ /** The Project's path (spec §3.33), or '' when the decision has no folder. */
11
+ project: string;
12
+ /** The Project's short name, or '' when it has none. */
13
+ projectName: string;
14
+ state: PendingState;
15
+ /** The first message the user typed in the session after `at` (ISO); only when `state` is `replied`. */
16
+ repliedAt?: string;
17
+ /**
18
+ * Why sideby could not tell whether the user replied: no-record, the session's record was not found; unsupported,
19
+ * sideby reads no session records of this Family. Only on an open decision with a session id.
20
+ */
21
+ replyCheck?: 'no-record' | 'unsupported';
22
+ }
23
+ /** One Project's counts, in the order the Panel lists them. */
24
+ export interface PendingProject {
25
+ project: string;
26
+ projectName: string;
27
+ open: number;
28
+ replied: number;
29
+ done: number;
30
+ }
31
+ export interface PendingOverview {
32
+ /** In the order given (oldest first). */
33
+ rows: PendingRow[];
34
+ projects: PendingProject[];
35
+ }
36
+ /**
37
+ * Marks of the notes sideby puts into a session, should a Host keep one as a message from the user: Unattended Mode's
38
+ * reasons and wake-ups (src/unattended/hook.ts, core/unattended-retry.ts), in English and Chinese, and the Progress
39
+ * Reminder. Claude Code keeps them as `isMeta` lines or `<task-notification>`s, which Session History's reader leaves
40
+ * out already; these catch any Host that does not.
41
+ */
42
+ export declare const SIDEBY_NOTE_MARKS: readonly string[];
43
+ /**
44
+ * Whether a message Session History's reader gives as the user's counts as a reply to a Pending Decision. When unsure
45
+ * it does not, so a decision is shown as untouched rather than as written in afterwards.
46
+ */
47
+ export declare function typedReply(text: string): boolean;
48
+ /**
49
+ * Each Pending Decision with its Project, state and reply (in the order given), and every Project's counts in the
50
+ * order the Panel lists them. `accounts` are where session records are looked for; `stateDir` holds the memo cache.
51
+ */
52
+ export declare function pendingOverview(opts: {
53
+ decisions: readonly PendingDecision[];
54
+ accounts: readonly Account[];
55
+ stateDir: string;
56
+ }): Promise<PendingOverview>;
57
+ /**
58
+ * The Projects a `--project` value names among `projects`, as Session History's `--project` reads one: a path
59
+ * (absolute, or from `~`) names the Project it is, or the one it is in; a name is a short name, else the end of a
60
+ * Project's path.
61
+ */
62
+ export declare function pendingProjectsNamed(projects: readonly PendingProject[], name: string, home: string): Promise<string[]>;
@@ -0,0 +1,205 @@
1
+ // Pending Decisions by Project, and whether the user wrote in the session afterwards (spec §3.37 "按项目看",
2
+ // ADR-0078). The CLI's `sideby unattended pending` and the Panel's Unattended page list them through `pendingOverview`.
3
+ //
4
+ // A Pending Decision is `replied` when the session's own record holds a message the user typed later than the decision
5
+ // was kept: the record is found by the session id in the decision's Account (then the Family's other Accounts) and
6
+ // read read-only with Session History's reader, which gives only what a person typed. Of each record only the times
7
+ // of those messages are kept (per file version, in a FileMemo), never their text. Nothing is written into a Host
8
+ // directory, no credential is read and no model is called.
9
+ import { stat } from 'node:fs/promises';
10
+ import { isAbsolute, join, resolve } from 'node:path';
11
+ import { findsSessionRecords, historyReader, sessionRecords, } from '../families/history.js';
12
+ import { uaGroupByProject } from '../panel/page-logic.js';
13
+ import { FileMemo } from './file-memo.js';
14
+ import { SAFE_ID } from './history.js';
15
+ import { ProjectResolver, projectNames, projectsNamed } from './history-project.js';
16
+ import { memoStore } from './memo-store.js';
17
+ import { hostMade, PROGRESS_MARK, sidebyMessage } from './prompt-origin.js';
18
+ /**
19
+ * The times of the messages the user typed in each session record, by file version. Kept in the memo cache file with
20
+ * the usage readers' memos (times only), so a restarted Panel does not read every record again.
21
+ */
22
+ const replyMemo = new FileMemo({ name: 'pending-replies', version: 2 });
23
+ const MEMO_SCOPE = 'pending-replies';
24
+ /**
25
+ * Marks of the notes sideby puts into a session, should a Host keep one as a message from the user: Unattended Mode's
26
+ * reasons and wake-ups (src/unattended/hook.ts, core/unattended-retry.ts), in English and Chinese, and the Progress
27
+ * Reminder. Claude Code keeps them as `isMeta` lines or `<task-notification>`s, which Session History's reader leaves
28
+ * out already; these catch any Host that does not.
29
+ */
30
+ export const SIDEBY_NOTE_MARKS = [
31
+ "sideby's Unattended Mode is on",
32
+ "sideby's Unattended Mode: ",
33
+ 'sideby 无人值守已开启',
34
+ 'sideby 无人值守:',
35
+ PROGRESS_MARK,
36
+ ];
37
+ /**
38
+ * Lines a person did not type as a reply: a slash command, a `!` shell line, a summary of an earlier conversation,
39
+ * and sideby's own notes, should a Host keep one as the user's: Auto Handoff's all start with `sideby: `, and the first
40
+ * prompt of the session a task was handed to starts the same way every time (src/handoff/messages.ts).
41
+ */
42
+ const NOT_TYPED = /^\s*(?:[/!]|This session is being continued|sideby: |This task was handed over from \S+ by sideby\b)/;
43
+ /**
44
+ * Whether a message Session History's reader gives as the user's counts as a reply to a Pending Decision. When unsure
45
+ * it does not, so a decision is shown as untouched rather than as written in afterwards.
46
+ */
47
+ export function typedReply(text) {
48
+ if (!text.trim() || NOT_TYPED.test(text))
49
+ return false;
50
+ if (hostMade(text) || sidebyMessage(text))
51
+ return false;
52
+ return !SIDEBY_NOTE_MARKS.some((m) => text.includes(m));
53
+ }
54
+ /** The times (ms) of the messages the user typed in one session record, oldest first. */
55
+ async function replyTimes(family, path) {
56
+ const reader = historyReader(family);
57
+ if (!reader)
58
+ return [];
59
+ const out = [];
60
+ for await (const m of reader.messages(path)) {
61
+ // A person's message: Claude Code marks one `human`, and a notification or a peer's message as something else.
62
+ if (m.role !== 'user' || !m.at || (m.origin && m.origin !== 'human') || !typedReply(m.text))
63
+ continue;
64
+ const t = Date.parse(m.at);
65
+ if (Number.isFinite(t))
66
+ out.push(t);
67
+ }
68
+ return out.sort((a, b) => a - b);
69
+ }
70
+ /** Lists each Account's Session records at most once per overview, however many sessions are looked up in it. */
71
+ function recordLists() {
72
+ const listed = new Map();
73
+ return (a) => {
74
+ let got = listed.get(a.ref);
75
+ if (!got) {
76
+ got = sessionRecords(a.family, a).catch(() => undefined);
77
+ listed.set(a.ref, got);
78
+ }
79
+ return got;
80
+ };
81
+ }
82
+ /**
83
+ * The session's record: in the decision's Account first, then in the Family's other Accounts. Undefined when none has
84
+ * it, or the session id is not of the plain form Session History accepts.
85
+ */
86
+ async function findRecord(d, accounts, recordsOf) {
87
+ if (!d.sessionId || !SAFE_ID.test(d.sessionId))
88
+ return undefined;
89
+ const own = accounts.filter((a) => a.family === d.family);
90
+ const ordered = [...own.filter((a) => a.ref === d.account), ...own.filter((a) => a.ref !== d.account)];
91
+ for (const a of ordered) {
92
+ const path = (await recordsOf(a))?.find(d.sessionId);
93
+ if (path)
94
+ return path;
95
+ }
96
+ return undefined;
97
+ }
98
+ /**
99
+ * When the user replied after each open decision of one session: the first typed message later than its `at`, or
100
+ * undefined. The record is read only when it was written after the earliest of them.
101
+ */
102
+ async function sessionReplies(family, path, decisions, pass) {
103
+ const out = new Map();
104
+ const st = await stat(path);
105
+ const earliest = Math.min(...decisions.map((d) => Date.parse(d.at)));
106
+ const times = st.mtimeMs <= earliest ? [] : await pass.get(path, st, () => replyTimes(family, path));
107
+ for (const d of decisions)
108
+ out.set(d.id, times.find((t) => t > Date.parse(d.at)));
109
+ return out;
110
+ }
111
+ /**
112
+ * Each Pending Decision with its Project, state and reply (in the order given), and every Project's counts in the
113
+ * order the Panel lists them. `accounts` are where session records are looked for; `stateDir` holds the memo cache.
114
+ */
115
+ export async function pendingOverview(opts) {
116
+ const resolver = new ProjectResolver({ nearest: true });
117
+ const projectOf = new Map();
118
+ await Promise.all(opts.decisions.map(async (d) => {
119
+ projectOf.set(d.id, d.cwd ? (await resolver.resolve(d.cwd)).path : '');
120
+ }));
121
+ const names = projectNames([...projectOf.values()].filter(Boolean));
122
+ // Open decisions with a session id, by Family and session.
123
+ const bySession = new Map();
124
+ for (const d of opts.decisions)
125
+ if (!d.doneAt && d.sessionId) {
126
+ const key = `${d.family}\0${d.sessionId}`;
127
+ bySession.set(key, [...(bySession.get(key) ?? []), d]);
128
+ }
129
+ const replied = new Map();
130
+ const check = new Map();
131
+ if (bySession.size) {
132
+ const store = memoStore(opts.stateDir);
133
+ await store.ready();
134
+ const pass = replyMemo.pass(MEMO_SCOPE);
135
+ const recordsOf = recordLists();
136
+ await eachAtMost(READ_AT_ONCE, [...bySession.values()], async (list) => {
137
+ const first = list[0];
138
+ if (!findsSessionRecords(first.family)) {
139
+ for (const d of list)
140
+ check.set(d.id, 'unsupported');
141
+ return;
142
+ }
143
+ const found = await findRecord(first, opts.accounts, recordsOf);
144
+ const got = found
145
+ ? await sessionReplies(first.family, found, list, pass).catch(() => undefined)
146
+ : undefined;
147
+ if (!got)
148
+ for (const d of list)
149
+ check.set(d.id, 'no-record');
150
+ else
151
+ for (const [id, t] of got)
152
+ replied.set(id, t);
153
+ });
154
+ pass.done();
155
+ if (replyMemo.dirty)
156
+ store.saveSoon();
157
+ }
158
+ const rows = opts.decisions.map((d) => {
159
+ const project = projectOf.get(d.id) ?? '';
160
+ const at = replied.get(d.id);
161
+ const state = d.doneAt ? 'done' : at !== undefined ? 'replied' : 'open';
162
+ const why = check.get(d.id);
163
+ return {
164
+ ...d,
165
+ project,
166
+ projectName: project ? (names.get(project) ?? project) : '',
167
+ state,
168
+ ...(state === 'replied' ? { repliedAt: new Date(at).toISOString() } : {}),
169
+ ...(state === 'open' && why ? { replyCheck: why } : {}),
170
+ };
171
+ });
172
+ const projects = uaGroupByProject(rows).map((g) => ({
173
+ project: g.project,
174
+ projectName: g.name,
175
+ open: g.open,
176
+ replied: g.replied,
177
+ done: g.done,
178
+ }));
179
+ return { rows, projects };
180
+ }
181
+ /**
182
+ * The Projects a `--project` value names among `projects`, as Session History's `--project` reads one: a path
183
+ * (absolute, or from `~`) names the Project it is, or the one it is in; a name is a short name, else the end of a
184
+ * Project's path.
185
+ */
186
+ export async function pendingProjectsNamed(projects, name, home) {
187
+ const paths = projects.filter((p) => p.project);
188
+ if (isAbsolute(name) || name === '~' || name.startsWith('~/')) {
189
+ const abs = resolve(name.startsWith('~') ? join(home, name.slice(1)) : name);
190
+ if (paths.some((p) => p.project === abs))
191
+ return [abs];
192
+ const found = (await new ProjectResolver({ nearest: true }).resolve(abs)).path;
193
+ return paths.some((p) => p.project === found) ? [found] : [];
194
+ }
195
+ return projectsNamed(new Map(paths.map((p) => [p.project, p.projectName])), name.replace(/\/+$/, ''));
196
+ }
197
+ /** How many session records are read at once. */
198
+ const READ_AT_ONCE = 4;
199
+ async function eachAtMost(n, items, fn) {
200
+ let next = 0;
201
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
202
+ while (next < items.length)
203
+ await fn(items[next++]);
204
+ }));
205
+ }
@@ -59,10 +59,18 @@ opts?: {
59
59
  }): Promise<PendingDecision[]>;
60
60
  /** Opens a Pending Decision marked done again (the Panel's Undo after "Done"); throws when there is no such id. */
61
61
  export declare function reopenPendingDecision(stateDir: string, id: string): Promise<PendingDecision>;
62
+ /**
63
+ * Opens Pending Decisions marked done again, reading the folder once (the Panel's Undo after a bulk "Done", and
64
+ * `sideby unattended pending reopen`). Ids no Pending Decision has, and ones that are open already, are left out:
65
+ * it returns only the ones it opened. When none of the ids is there it throws.
66
+ */
67
+ export declare function reopenPendingDecisions(stateDir: string, ids: readonly string[]): Promise<PendingDecision[]>;
62
68
  /** The open Pending Decision an id names: the whole id, or a start of it that only one has. */
63
69
  export declare function findPendingDecision(stateDir: string, id: string): Promise<PendingDecision | undefined>;
64
70
  /**
65
- * Marks Pending Decisions done: one by id (or a unique start of it), or every open one with `'all'`. Returns the ones
66
- * it marked; an id no Pending Decision has throws an Error whose message says how to list them.
71
+ * Marks Pending Decisions done: one by id (or a unique start of it), every open one with `'all'`, or a list of whole
72
+ * ids read in one go (ADR-0078; ids no Pending Decision has, and ones done already, are left out, so a list returns
73
+ * only the ones this call marked). An id, or a list, that names no Pending Decision throws an Error whose message
74
+ * says how to list them.
67
75
  */
68
- export declare function markPendingDone(stateDir: string, id: string | 'all', at?: Date): Promise<PendingDecision[]>;
76
+ export declare function markPendingDone(stateDir: string, id: string | 'all' | readonly string[], at?: Date): Promise<PendingDecision[]>;
@@ -171,6 +171,27 @@ export async function reopenPendingDecision(stateDir, id) {
171
171
  await writeFileAtomic(fileOf(stateDir, d.id), `${JSON.stringify(open)}\n`, 0o600);
172
172
  return open;
173
173
  }
174
+ /**
175
+ * Opens Pending Decisions marked done again, reading the folder once (the Panel's Undo after a bulk "Done", and
176
+ * `sideby unattended pending reopen`). Ids no Pending Decision has, and ones that are open already, are left out:
177
+ * it returns only the ones it opened. When none of the ids is there it throws.
178
+ */
179
+ export async function reopenPendingDecisions(stateDir, ids) {
180
+ const want = new Set(ids);
181
+ const found = (await readAll(stateDir)).filter((d) => want.has(d.id));
182
+ if (!found.length)
183
+ throw new Error(`no Pending Decision has the id "${ids[0] ?? ''}"; \`sideby unattended pending --all\` lists them`);
184
+ const out = [];
185
+ for (const d of found) {
186
+ if (!d.doneAt)
187
+ continue;
188
+ const { doneAt: _, ...open } = d;
189
+ await ensureDir(stateDir);
190
+ await writeFileAtomic(fileOf(stateDir, d.id), `${JSON.stringify(open)}\n`, 0o600);
191
+ out.push(open);
192
+ }
193
+ return out;
194
+ }
174
195
  /** The open Pending Decision an id names: the whole id, or a start of it that only one has. */
175
196
  export async function findPendingDecision(stateDir, id) {
176
197
  const all = await readAll(stateDir);
@@ -181,23 +202,28 @@ export async function findPendingDecision(stateDir, id) {
181
202
  return starts.length === 1 ? starts[0] : undefined;
182
203
  }
183
204
  /**
184
- * Marks Pending Decisions done: one by id (or a unique start of it), or every open one with `'all'`. Returns the ones
185
- * it marked; an id no Pending Decision has throws an Error whose message says how to list them.
205
+ * Marks Pending Decisions done: one by id (or a unique start of it), every open one with `'all'`, or a list of whole
206
+ * ids read in one go (ADR-0078; ids no Pending Decision has, and ones done already, are left out, so a list returns
207
+ * only the ones this call marked). An id, or a list, that names no Pending Decision throws an Error whose message
208
+ * says how to list them.
186
209
  */
187
210
  export async function markPendingDone(stateDir, id, at = new Date()) {
211
+ const many = typeof id !== 'string';
212
+ const listed = new Set(many ? id : []);
188
213
  const targets = id === 'all'
189
214
  ? (await readAll(stateDir)).filter((d) => !d.doneAt)
190
- : [await findPendingDecision(stateDir, id)].filter((d) => d !== undefined);
191
- if (id !== 'all' && !targets.length)
192
- throw new Error(`no Pending Decision has the id "${id}"; \`sideby unattended pending --all\` lists them`);
215
+ : many
216
+ ? (await readAll(stateDir)).filter((d) => listed.has(d.id))
217
+ : [await findPendingDecision(stateDir, id)].filter((d) => d !== undefined);
218
+ if (id !== 'all' && !targets.length && (!many || id.length))
219
+ throw new Error(`no Pending Decision has the id "${many ? (id[0] ?? '') : id}"; \`sideby unattended pending --all\` lists them`);
193
220
  if (targets.length)
194
221
  await ensureDir(stateDir);
195
222
  const out = [];
196
223
  for (const d of targets) {
197
- if (d.doneAt) {
198
- out.push(d);
224
+ // Only the ones this call marks: one done already (elsewhere, a moment ago) is left out, so an Undo never opens it.
225
+ if (d.doneAt)
199
226
  continue;
200
- }
201
227
  const done = { ...d, doneAt: at.toISOString() };
202
228
  await writeFileAtomic(fileOf(stateDir, d.id), `${JSON.stringify(done)}\n`, 0o600);
203
229
  out.push(done);
@@ -162,8 +162,16 @@ export const claudeHistory = {
162
162
  const at = isoTime(rec.timestamp);
163
163
  if (rec.type === 'user') {
164
164
  const text = userText(rec);
165
+ // Who made it, as Claude Code records it (seen in 2.1.312 to 2.1.325): `human` for a person, else a notification
166
+ // or a peer's message.
167
+ const origin = str(rec.origin?.kind);
165
168
  if (text)
166
- yield { role: 'user', text, ...(at ? { at } : {}) };
169
+ yield {
170
+ role: 'user',
171
+ text,
172
+ ...(at ? { at } : {}),
173
+ ...(origin ? { origin } : {}),
174
+ };
167
175
  }
168
176
  else if (rec.type === 'assistant') {
169
177
  const text = assistantText(rec);
@@ -1,8 +1,17 @@
1
- import type { FamilyDef, FamilyHistory, ParsedSession } from '../types.ts';
1
+ import type { Account, FamilyDef, FamilyHistory, HistoryMessage, ParsedSession } from '../types.ts';
2
2
  export type { HistoryFile, HistoryMessage, ParsedSession, TitleSource } from '../types.ts';
3
+ /**
4
+ * A message as a reader gives it inside sideby: a user message may say who made it, when the Host records that
5
+ * (Claude Code's `origin.kind`: `human`, `task-notification`, `peer`, …). Never shown, and not part of the plugin
6
+ * contract (`HistoryMessage`).
7
+ */
8
+ export interface ReadMessage extends HistoryMessage {
9
+ origin?: string;
10
+ }
3
11
  /** A Session History reader: a built-in Family's, or a plugin Family's `history` with its Family id. */
4
- export interface HistoryReader extends Omit<FamilyHistory, 'resumeArgs' | 'toolText'> {
12
+ export interface HistoryReader extends Omit<FamilyHistory, 'resumeArgs' | 'toolText' | 'messages'> {
5
13
  family: string;
14
+ messages(path: string): AsyncIterable<ReadMessage>;
6
15
  /**
7
16
  * The text of the Session's tool calls (their input) and tool results, for searching tool output. Never the
8
17
  * record's other fields (ids, instructions, settings), so a search cannot match or show them.
@@ -18,3 +27,14 @@ export interface HistoryReader extends Omit<FamilyHistory, 'resumeArgs' | 'toolT
18
27
  export declare function checkParsed(family: string, p: ParsedSession | undefined): ParsedSession | undefined;
19
28
  /** The Session History reader of a Family: a built-in one's, else the `history` a plugin Family declares. */
20
29
  export declare function historyReader(familyId: string, families?: ReadonlyMap<string, FamilyDef>): HistoryReader | undefined;
30
+ /**
31
+ * One Account's Session records, listed once: `find` gives where Session `id`'s record is, or undefined. The id is
32
+ * matched against the names listed and never put into a path.
33
+ */
34
+ export interface SessionRecords {
35
+ find(id: string): string | undefined;
36
+ }
37
+ /** Whether sideby can find one Session's record by its id in a Family's Accounts (`sessionRecords`). */
38
+ export declare const findsSessionRecords: (familyId: string) => boolean;
39
+ /** The Session records of `account`, read-only; undefined when its Family is another one or keeps none sideby finds. */
40
+ export declare function sessionRecords(familyId: string, account: Account): Promise<SessionRecords | undefined>;
@@ -1,3 +1,5 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
1
3
  import { claudeHistory } from './claude/history.js';
2
4
  import { codexHistory } from './codex/history.js';
3
5
  import { grokHistory } from './grok/history.js';
@@ -79,3 +81,56 @@ export function historyReader(familyId, families) {
79
81
  }
80
82
  return r;
81
83
  }
84
+ async function entries(dir) {
85
+ try {
86
+ return await readdir(dir, { withFileTypes: true });
87
+ }
88
+ catch {
89
+ return [];
90
+ }
91
+ }
92
+ /** Claude's `projects/<folder>/<id>.jsonl` (the first folder that has one). */
93
+ async function claudeRecords(account) {
94
+ const root = join(account.dir, 'projects');
95
+ const byId = new Map();
96
+ const folders = (await entries(root)).filter((e) => e.isDirectory());
97
+ const listed = await Promise.all(folders.map((f) => entries(join(root, f.name))));
98
+ folders.forEach((f, i) => {
99
+ for (const e of listed[i]) {
100
+ const id = e.name.slice(0, -'.jsonl'.length);
101
+ if (e.name.endsWith('.jsonl') && !e.isDirectory() && !byId.has(id))
102
+ byId.set(id, join(root, f.name, e.name));
103
+ }
104
+ });
105
+ return { find: (id) => byId.get(id) };
106
+ }
107
+ /** Codex's `sessions/<date folders>/rollout-…-<id>.jsonl`. */
108
+ async function codexRecords(account) {
109
+ const root = join(account.dir, 'sessions');
110
+ let names = [];
111
+ try {
112
+ names = (await readdir(root, { recursive: true })).filter((n) => n.endsWith('.jsonl'));
113
+ }
114
+ catch {
115
+ // no sessions yet
116
+ }
117
+ return {
118
+ find: (id) => {
119
+ const name = names.find((n) => n.endsWith(`-${id}.jsonl`));
120
+ return name === undefined ? undefined : join(root, name);
121
+ },
122
+ };
123
+ }
124
+ /** Where each built-in Family keeps its Session records in an Account (the files `list` finds). */
125
+ const RECORD_LISTS = {
126
+ claude: claudeRecords,
127
+ codex: codexRecords,
128
+ };
129
+ /** Whether sideby can find one Session's record by its id in a Family's Accounts (`sessionRecords`). */
130
+ export const findsSessionRecords = (familyId) => Object.hasOwn(RECORD_LISTS, familyId) && READERS.has(familyId);
131
+ /** The Session records of `account`, read-only; undefined when its Family is another one or keeps none sideby finds. */
132
+ export async function sessionRecords(familyId, account) {
133
+ if (account.family !== familyId || !Object.hasOwn(RECORD_LISTS, familyId))
134
+ return undefined;
135
+ return RECORD_LISTS[familyId](account);
136
+ }
@@ -8,7 +8,7 @@ const TEMPLATE = [
8
8
  'key decisions and why',
9
9
  'the files that matter',
10
10
  ].join('; ');
11
- const RULES = `Reference specs, ADRs, commits and diffs by path instead of repeating them, list the skills the next agent should use, and never include keys, passwords or personal data. End the brief with the line ${BRIEF_DONE} once it covers all of this.`;
11
+ const RULES = `Reference specs, ADRs, commits and diffs by path instead of repeating them, list the skills the next agent should use, and never include keys, passwords or personal data. Copy any standing permission or limit the user gave word for word, saying where it comes from (a file's path, or the user's message), and add no limit the user did not give. End the brief with the line ${BRIEF_DONE} once it covers all of this.`;
12
12
  const WINDOW_NAMES = { '5h': '5-hour', '7d': 'weekly' };
13
13
  const when = (iso) => {
14
14
  const t = new Date(iso);
@@ -12,7 +12,7 @@ import { type NetworkOverview } from '../core/network.ts';
12
12
  import { type ProgressView } from '../core/progress.ts';
13
13
  import { type RemoteControlGroup } from '../core/remote-control.ts';
14
14
  import { type UnattendedStatus } from '../core/unattended.ts';
15
- import { type PendingDecision } from '../core/unattended-pending.ts';
15
+ import { type PendingProject, type PendingRow } from '../core/unattended-followup.ts';
16
16
  import * as update from '../core/update.ts';
17
17
  import type { AccountStatus, DoctorHistory, FamilyInfo, QuotaCheckInfo, Runtime } from '../runtime.ts';
18
18
  import type { Account, FamilyLogo, QuotaResult, QuotaSetupPlan, UsageResult } from '../types.ts';
@@ -319,8 +319,11 @@ export interface PanelTrust {
319
319
  at: string;
320
320
  }[];
321
321
  }
322
- /** One Pending Decision as the Panel's Unattended page lists it, with the way back to its Session. */
323
- export interface PanelPendingDecision extends PendingDecision {
322
+ /**
323
+ * One Pending Decision as the Panel's Unattended page lists it, with its Project, state and reply (ADR-0078; `project`
324
+ * and `cwd` shortened with `~`) and the way back to its Session.
325
+ */
326
+ export interface PanelPendingDecision extends PendingRow {
324
327
  /** The Account's short name (its Alias when it has one). */
325
328
  accountLabel?: string;
326
329
  /** The Session still runs: its label, so the Sessions page finds it. */
@@ -338,10 +341,14 @@ export interface PanelPendingDecision extends PendingDecision {
338
341
  export type PanelUnattendedStatus = UnattendedStatus & {
339
342
  pendingIds: string[];
340
343
  };
341
- /** The Unattended page: the status and every open Pending Decision. */
344
+ /** The Unattended page: the status and every open Pending Decision, with each Project's counts in page order. */
342
345
  export interface PanelUnattended {
343
346
  status: PanelUnattendedStatus;
347
+ /** The open ones (`state` open or replied). */
344
348
  pending: PanelPendingDecision[];
349
+ projects: PendingProject[];
350
+ /** The ones marked done and kept (30 days), newest mark first, so one marked by mistake can be reopened. */
351
+ done: PanelPendingDecision[];
345
352
  }
346
353
  /** What a change on the Unattended page did, and the request that puts back what was there. */
347
354
  export interface PanelUnattendedChange {
@@ -39,7 +39,8 @@ import { checkThemeData, listThemes, NO_THEME, previewColors, removeThemeFile, r
39
39
  import { MIN_CALLS } from '../core/tuning.js';
40
40
  import { onUntil, setAnswerWait, setUnattendedSchedule, turnUnattendedOff, turnUnattendedOn, unattendedStatus, } from '../core/unattended.js';
41
41
  import { checkUnattendedEnded } from '../core/unattended-ended.js';
42
- import { listPendingDecisions, markPendingDone, reopenPendingDecision, } from '../core/unattended-pending.js';
42
+ import { pendingOverview, } from '../core/unattended-followup.js';
43
+ import { listPendingDecisions, markPendingDone, reopenPendingDecisions } from '../core/unattended-pending.js';
43
44
  import { readUnattendedConfig } from '../core/unattended-state.js';
44
45
  import * as update from '../core/update.js';
45
46
  import { buildId, localBuild, packageVersion } from '../core/version.js';
@@ -738,31 +739,46 @@ async function unattendedView(rt, readOnly, live) {
738
739
  const families = [...rt.families.keys()];
739
740
  const [status, decisions, accounts] = await Promise.all([
740
741
  unattendedStatus({ paths: rt.paths, families, readOnly }),
741
- listPendingDecisions(rt.paths.stateDir, { prune: !readOnly }),
742
+ listPendingDecisions(rt.paths.stateDir, { prune: !readOnly, all: true }),
742
743
  rt.accounts(),
743
744
  ]);
745
+ const open = decisions.filter((d) => !d.doneAt);
744
746
  const labels = accountLabels(rt, accounts);
745
- const running = decisions.some((d) => d.sessionId)
747
+ const running = open.some((d) => d.sessionId)
746
748
  ? (await live(rt).catch(() => ({ sessions: [], problems: [] }))).sessions
747
749
  : [];
748
750
  const home = rt.paths.home;
751
+ // Each one's Project and whether the user replied in its session since (ADR-0078); a failure only leaves them out.
752
+ const overview = await pendingOverview({ decisions, accounts, stateDir: rt.paths.stateDir }).catch(() => ({
753
+ rows: decisions.map((d) => ({ ...d, project: '', projectName: '', state: d.doneAt ? 'done' : 'open' })),
754
+ projects: [],
755
+ }));
756
+ const shown = (d) => {
757
+ const label = d.account ? labels.get(d.account) : undefined;
758
+ const session = d.sessionId ? running.find((s) => s.sessionId === d.sessionId) : undefined;
759
+ const known = d.account && accounts.some((a) => a.ref === d.account);
760
+ const resume = d.sessionId && SAFE_SESSION_ID.test(d.sessionId) && known
761
+ ? resumeCommandFor(d.family, d.account, d.sessionId)
762
+ : undefined;
763
+ return {
764
+ ...d,
765
+ project: d.project && tildify(d.project, home),
766
+ ...(d.cwd ? { cwd: tildify(d.cwd, home) } : {}),
767
+ ...(label ? { accountLabel: label } : {}),
768
+ ...(session ? { live: { label: session.label, accountLabel: session.accountLabel } } : {}),
769
+ ...(resume ? { resume: d.cwd ? `cd ${shellArg(d.cwd)} && ${resume}` : resume } : {}),
770
+ };
771
+ };
749
772
  return {
750
- status: { ...status, pending: decisions.length, pendingIds: decisions.map((d) => d.id) },
751
- pending: decisions.map((d) => {
752
- const label = d.account ? labels.get(d.account) : undefined;
753
- const session = d.sessionId ? running.find((s) => s.sessionId === d.sessionId) : undefined;
754
- const known = d.account && accounts.some((a) => a.ref === d.account);
755
- const resume = d.sessionId && SAFE_SESSION_ID.test(d.sessionId) && known
756
- ? resumeCommandFor(d.family, d.account, d.sessionId)
757
- : undefined;
758
- return {
759
- ...d,
760
- ...(d.cwd ? { cwd: tildify(d.cwd, home) } : {}),
761
- ...(label ? { accountLabel: label } : {}),
762
- ...(session ? { live: { label: session.label, accountLabel: session.accountLabel } } : {}),
763
- ...(resume ? { resume: d.cwd ? `cd ${shellArg(d.cwd)} && ${resume}` : resume } : {}),
764
- };
765
- }),
773
+ status: { ...status, pending: open.length, pendingIds: open.map((d) => d.id) },
774
+ projects: overview.projects
775
+ .filter((p) => p.open + p.replied > 0)
776
+ .map((p) => ({ ...p, project: p.project && tildify(p.project, home) })),
777
+ pending: overview.rows.filter((d) => d.state !== 'done').map(shown),
778
+ done: overview.rows
779
+ .filter((d) => d.state === 'done')
780
+ .sort((a, b) => Date.parse(b.doneAt) - Date.parse(a.doneAt))
781
+ .map(shown),
766
782
  };
767
783
  }
768
784
  /** The `display` of a /api/display-order body: null, or string lists only; anything else is refused. */
@@ -2070,18 +2086,27 @@ export function createPanelHandler(opts) {
2070
2086
  };
2071
2087
  },
2072
2088
  },
2073
- // Marks one Pending Decision done (or every open one with `all`), or with `done: false` opens one again.
2089
+ // Marks one Pending Decision done (or every open one with `all`, or the `ids` the page showed: a Project's replied
2090
+ // ones, ADR-0078), or with `done: false` opens them again.
2074
2091
  '/api/unattended/pending': {
2075
2092
  async run(body) {
2076
2093
  const id = optString(body, 'id');
2077
2094
  const all = body.all === true;
2078
- if (!id && !all)
2079
- throw new HttpError(400, '"id" or "all" is required');
2095
+ const ids = body.ids;
2096
+ if (ids !== undefined &&
2097
+ (!Array.isArray(ids) ||
2098
+ !ids.length ||
2099
+ ids.length > 10_000 ||
2100
+ !ids.every((x) => typeof x === 'string' && x.length <= 64)))
2101
+ throw new HttpError(400, '"ids" must be a list of Pending Decision ids');
2102
+ const list = ids;
2103
+ if (!id && !all && !list)
2104
+ throw new HttpError(400, '"id", "ids" or "all" is required');
2080
2105
  const rt = await getRuntime();
2081
2106
  try {
2082
- const changed = body.done === false && id
2083
- ? [await reopenPendingDecision(rt.paths.stateDir, id)]
2084
- : await markPendingDone(rt.paths.stateDir, all ? 'all' : id);
2107
+ const changed = body.done === false && (id || list)
2108
+ ? await reopenPendingDecisions(rt.paths.stateDir, list ?? [id])
2109
+ : await markPendingDone(rt.paths.stateDir, all ? 'all' : (list ?? id));
2085
2110
  return { ids: changed.map((d) => d.id) };
2086
2111
  }
2087
2112
  catch (err) {