sideby 0.39.0 → 0.40.1

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 (41) hide show
  1. package/README.md +2 -2
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +34 -3
  4. package/dist/src/cli/json-schemas.js +9 -2
  5. package/dist/src/cli/main.js +10 -2
  6. package/dist/src/core/cli-commands.js +12 -0
  7. package/dist/src/core/config.d.ts +1 -0
  8. package/dist/src/core/config.js +3 -0
  9. package/dist/src/core/handoff-run.js +192 -175
  10. package/dist/src/core/progress-state.d.ts +21 -7
  11. package/dist/src/core/progress-state.js +32 -8
  12. package/dist/src/core/search-catalog.js +18 -0
  13. package/dist/src/core/session-hooks.d.ts +7 -0
  14. package/dist/src/core/session-hooks.js +27 -0
  15. package/dist/src/core/unattended-pending.d.ts +14 -2
  16. package/dist/src/core/unattended-pending.js +27 -3
  17. package/dist/src/core/unattended-state.d.ts +19 -1
  18. package/dist/src/core/unattended-state.js +31 -5
  19. package/dist/src/core/unattended-wait.d.ts +86 -0
  20. package/dist/src/core/unattended-wait.js +125 -0
  21. package/dist/src/core/unattended.d.ts +19 -0
  22. package/dist/src/core/unattended.js +37 -4
  23. package/dist/src/families/claude/handoff.js +3 -1
  24. package/dist/src/panel/handler.js +16 -1
  25. package/dist/src/panel/i18n.d.ts +9 -0
  26. package/dist/src/panel/i18n.js +26 -8
  27. package/dist/src/panel/page-script.js +51 -2
  28. package/dist/src/panel/page-styles.js +7 -0
  29. package/dist/src/progress/hook.d.ts +7 -0
  30. package/dist/src/progress/hook.js +18 -11
  31. package/dist/src/types.d.ts +5 -0
  32. package/dist/src/unattended/hook.d.ts +21 -6
  33. package/dist/src/unattended/hook.js +261 -19
  34. package/package.json +2 -2
  35. package/schemas/config.json +14 -0
  36. package/schemas/unattended-defer.json +5 -0
  37. package/schemas/unattended-pending.json +5 -0
  38. package/schemas/unattended.json +16 -2
  39. package/skills/sideby/SKILL.md +3 -2
  40. package/skills/sideby/references/progress.md +3 -3
  41. package/skills/sideby/references/unattended.md +16 -2
@@ -11,7 +11,8 @@ import { sidebyHookCommand } from './session-hooks.js';
11
11
  import { ATTENDED_HOOK_TIMEOUT_S, listAttended } from './unattended-attended.js';
12
12
  import { listPendingDecisions } from './unattended-pending.js';
13
13
  import { RETRY_HOOK_TIMEOUT_S } from './unattended-retry.js';
14
- import { clearUnattendedOverride, clockText, ensureUnattendedDir, MAX_MANUAL_MS, parseClock, parseDays, parseSlot, readUnattendedConfig, readUnattendedOverride, scheduleStretchAt, slotEnd, UNATTENDED_ENV, unattendedState, writeUnattendedOverride, } from './unattended-state.js';
14
+ import { ANSWER_WAIT_DEFAULT, clearUnattendedOverride, clockText, ensureUnattendedDir, MAX_MANUAL_MS, parseClock, parseDays, parseSlot, readUnattendedConfig, readUnattendedOverride, scheduleStretchAt, slotEnd, UNATTENDED_ENV, unattendedState, validAnswerWait, writeUnattendedOverride, } from './unattended-state.js';
15
+ import { ANSWER_HOOK_TIMEOUT_S } from './unattended-wait.js';
15
16
  /** Families whose sessions Unattended Mode covers in v1. */
16
17
  export const UNATTENDED_FAMILIES = ['claude', 'codex'];
17
18
  const DEFAULT_HOURS = 12;
@@ -50,7 +51,7 @@ function coverageOf(families, configured) {
50
51
  /** The full status. `env` matters only for a session started with `--unattended`. */
51
52
  export async function unattendedStatus(opts) {
52
53
  const now = opts.now ?? new Date();
53
- const { configured, schedule } = await readUnattendedConfig(opts.paths.configFile);
54
+ const { configured, schedule, answerWait } = await readUnattendedConfig(opts.paths.configFile);
54
55
  const override = await readUnattendedOverride(opts.paths.stateDir);
55
56
  const state = unattendedState({ schedule, override, now, session: opts.env?.[UNATTENDED_ENV] === '1' });
56
57
  const end = slotEnd(schedule, now);
@@ -60,6 +61,7 @@ export async function unattendedStatus(opts) {
60
61
  ...state,
61
62
  configured,
62
63
  schedule,
64
+ answerWait,
63
65
  pending: (await listPendingDecisions(opts.paths.stateDir, { now, prune: !opts.readOnly })).length,
64
66
  attended: await listAttended(opts.paths.stateDir, now, { prune: !opts.readOnly }),
65
67
  coverage: coverageOf(opts.families, configured),
@@ -270,6 +272,28 @@ export async function setUnattendedSchedule(opts) {
270
272
  });
271
273
  return { changed: r.changed, status: await unattendedStatus(opts), previous };
272
274
  }
275
+ /** The command that sets the Answer Wait to `minutes` (null: never). */
276
+ const waitCommand = (minutes) => `sideby unattended wait ${minutes === null ? 'off' : minutes}`;
277
+ /**
278
+ * Sets the Answer Wait (ADR-0077): whole minutes from 1 to 120, or null for never, creating the config section. It
279
+ * reaches running sessions at once (their hooks read it at every look). Throws a UserError for any other value.
280
+ */
281
+ export async function setAnswerWait(opts) {
282
+ if (opts.minutes !== null && !validAnswerWait(opts.minutes))
283
+ throw new UserError('the wait takes whole minutes from 1 to 120, or off; for example `sideby unattended wait 10`', {
284
+ code: 'bad-wait',
285
+ });
286
+ let before = ANSWER_WAIT_DEFAULT;
287
+ const r = await editConfigUnattended(opts.paths.configFile, (current) => {
288
+ before = current?.answerWait === false ? null : (current?.answerWait ?? ANSWER_WAIT_DEFAULT);
289
+ if (current && current.answerWait !== undefined && before === opts.minutes)
290
+ return null;
291
+ return { ...current, answerWait: opts.minutes === null ? false : opts.minutes };
292
+ });
293
+ const status = await unattendedStatus(opts);
294
+ const changed = r.changed && before !== opts.minutes;
295
+ return { changed, status, before, ...(changed ? { undo: waitCommand(before) } : {}) };
296
+ }
273
297
  /** The preset names `schedule preset` takes, with what each adds. */
274
298
  export const UNATTENDED_PRESETS = { weeknights: WEEKNIGHTS };
275
299
  /** The Slot `schedule add` was given, or why it cannot be one (the message says what to do). */
@@ -297,6 +321,8 @@ export const unattendedClock = (iso, now, zh = false) => clockText(Date.parse(is
297
321
  * about to show, every MCP server form (`Elicitation`), every turn that failed on an API error (`StopFailure`, in the
298
322
  * background with `asyncRewake`, so its exit 2 wakes the session: Turn Retry, ADR-0067), and every prompt
299
323
  * (`UserPromptSubmit`, in the background with `async`, so it never holds a prompt back: Attended Sessions, ADR-0075).
324
+ * For Answer Wait (ADR-0077) the `PermissionRequest` entry may wait while its prompt is on screen, so it has a long
325
+ * `timeout`, and a second `Stop` entry waits in the background (`asyncRewake`) after a turn that ended on a question.
300
326
  * Codex has no such events for them; its own approval prompts and failed turns are not covered.
301
327
  */
302
328
  export function unattendedHookPart() {
@@ -307,8 +333,15 @@ export function unattendedHookPart() {
307
333
  id: 'unattended',
308
334
  claude: {
309
335
  PreToolUse: [{ matcher: 'AskUserQuestion', hooks: claude('PreToolUse') }],
310
- PermissionRequest: [{ matcher: '*', hooks: claude('PermissionRequest') }],
311
- Stop: [{ hooks: claude('Stop') }],
336
+ // Waits while its prompt is on screen (Answer Wait), so Claude Code's 10-minute default would cut it short.
337
+ PermissionRequest: [
338
+ { matcher: '*', hooks: [{ ...claude('PermissionRequest')[0], timeout: ANSWER_HOOK_TIMEOUT_S }] },
339
+ ],
340
+ Stop: [
341
+ { hooks: claude('Stop') },
342
+ // Answer Wait for a question written as text: in the background, so the turn ends at once.
343
+ { hooks: [{ ...claude('StopWait')[0], asyncRewake: true, timeout: ANSWER_HOOK_TIMEOUT_S }] },
344
+ ],
312
345
  Elicitation: [{ matcher: '*', hooks: claude('Elicitation') }],
313
346
  // Waits up to 4 minutes before it wakes the session; Claude Code still enforces `timeout` on `asyncRewake`.
314
347
  // No matcher: every failed turn reaches it, so a later failure that is not retried still ends an earlier wait.
@@ -1,5 +1,7 @@
1
1
  // How Claude Code takes part in a Handoff (spec §3.17): hooks through `--settings`, which merges with the
2
- // Account's own settings hooks (verified 2026-10-09), and the Brief's directory through `--add-dir`.
2
+ // Account's own settings hooks (verified 2026-10-09). The Brief's directory goes into that file's
3
+ // `permissions.additionalDirectories` (`withClaudeDirs`): Claude Code 2.1.326 asks to trust an `--add-dir` folder it
4
+ // has not seen, so `dirArgs` is used only where sideby cannot add to `--settings`.
3
5
  import { mkdir } from 'node:fs/promises';
4
6
  import { join } from 'node:path';
5
7
  import { locate, readObject } from '../../core/claude-settings-file.js';
@@ -37,7 +37,7 @@ import { SKILL_INSTALL } from '../core/skill-check.js';
37
37
  import { launchArgs, TERMINALS } from '../core/terminal.js';
38
38
  import { checkThemeData, listThemes, NO_THEME, previewColors, removeThemeFile, resolveColors, saveThemeFile, undoTheme, useTheme, } from '../core/themes.js';
39
39
  import { MIN_CALLS } from '../core/tuning.js';
40
- import { onUntil, setUnattendedSchedule, turnUnattendedOff, turnUnattendedOn, unattendedStatus, } from '../core/unattended.js';
40
+ import { onUntil, setAnswerWait, setUnattendedSchedule, turnUnattendedOff, turnUnattendedOn, unattendedStatus, } from '../core/unattended.js';
41
41
  import { checkUnattendedEnded } from '../core/unattended-ended.js';
42
42
  import { listPendingDecisions, markPendingDone, reopenPendingDecision, } from '../core/unattended-pending.js';
43
43
  import { readUnattendedConfig } from '../core/unattended-state.js';
@@ -2000,6 +2000,21 @@ export function createPanelHandler(opts) {
2000
2000
  };
2001
2001
  },
2002
2002
  },
2003
+ // Answer Wait (ADR-0077): `minutes` from 1 to 120, or null for never. Its Undo sends `before` back.
2004
+ '/api/unattended/wait': {
2005
+ async run(body) {
2006
+ const minutes = body.minutes;
2007
+ if (minutes !== null && typeof minutes !== 'number')
2008
+ throw new HttpError(400, '"minutes" must be whole minutes from 1 to 120, or null for never', 'bad-wait');
2009
+ const rt = await getRuntime();
2010
+ const r = await setAnswerWait({ paths: rt.paths, families: [...rt.families.keys()], minutes });
2011
+ return {
2012
+ changed: r.changed,
2013
+ status: await withPendingIds(r.status, rt.paths.stateDir),
2014
+ before: r.before,
2015
+ };
2016
+ },
2017
+ },
2003
2018
  // Marks one Pending Decision done (or every open one with `all`), or with `done: false` opens one again.
2004
2019
  '/api/unattended/pending': {
2005
2020
  async run(body) {
@@ -1718,6 +1718,15 @@ declare const en: {
1718
1718
  'ua.hereNote': string;
1719
1719
  'ua.hereHint': string;
1720
1720
  'ua.hereSession': string;
1721
+ 'ua.wait': string;
1722
+ 'ua.waitNote': string;
1723
+ 'ua.waitLabel': string;
1724
+ 'ua.waitMin': string;
1725
+ 'ua.waitNever': string;
1726
+ 'ua.waitToast': string;
1727
+ 'ua.waitNeverToast': string;
1728
+ 'ua.waitFailed': string;
1729
+ 'ua.waited': string;
1721
1730
  'ua.pending': string;
1722
1731
  'ua.pendingNote': string;
1723
1732
  'ua.pendingEmpty': string;
@@ -1720,8 +1720,17 @@ const en = {
1720
1720
  'ua.hereNote': 'You typed in these sessions in the last 30 minutes, so they ask you as usual. Each message you send gives that session another 30 minutes. Every other session stays unattended.',
1721
1721
  'ua.hereHint': 'Back early? Type in a session and it asks you as usual for 30 minutes. The others stay unattended.',
1722
1722
  'ua.hereSession': 'Session {id}',
1723
+ 'ua.wait': 'If nobody answers',
1724
+ 'ua.waitNote': 'A question in a session you are in waits this long for your answer. If Unattended Mode is on by then, the session goes on without you: it takes the recommended choice where that can be undone, and skips a step that needs your OK. Each one shows up under Waiting for you.',
1725
+ 'ua.waitLabel': 'Go on after',
1726
+ 'ua.waitMin': '{n} min',
1727
+ 'ua.waitNever': 'Never',
1728
+ 'ua.waitToast': 'Questions now wait {n} min for you.',
1729
+ 'ua.waitNeverToast': 'Questions now wait for you, however long.',
1730
+ 'ua.waitFailed': 'Could not change it: {msg}',
1731
+ 'ua.waited': 'No answer for {n} min',
1723
1732
  'ua.pending': 'Waiting for you',
1724
- 'ua.pendingNote': 'Questions sessions did not ask you, steps that needed your OK, and steps they skipped. Nothing here was done.',
1733
+ 'ua.pendingNote': 'Questions sessions did not ask you or nobody answered, steps that needed your OK, and steps they skipped. Nothing here was done.',
1725
1734
  'ua.pendingEmpty': 'Nothing is waiting for you.',
1726
1735
  'ua.pendingBlocked': 'sideby cannot read them until the folder named above is fixed.',
1727
1736
  'ua.loading': 'Reading…',
@@ -1753,14 +1762,14 @@ const en = {
1753
1762
  'ua.problem': 'sideby cannot keep its state: {msg}',
1754
1763
  'ua.unreadable': 'sideby could not read Unattended Mode. Refresh to try again.',
1755
1764
  'ai.ask.unattended': 'Run unattended tonight, until 8 tomorrow morning.',
1756
- 'ai.ask.progress': 'While background tasks run, tell me every 10 minutes what my sessions are waiting for.',
1765
+ 'ai.ask.progress': 'While background tasks run, tell me every 30 minutes what my sessions are waiting for.',
1757
1766
  'pr.title': 'Progress updates',
1758
- 'pr.hint': 'When a Claude session waits on background work (subagents, long commands), it tells you every few minutes what it is waiting for and for how long.',
1767
+ 'pr.hint': 'When a Claude session waits on background work (subagents, long commands), it tells you what it is waiting for and for how long, every 30 minutes or as often as you pick.',
1759
1768
  'pr.switch': 'Report progress while waiting',
1760
1769
  'pr.every': 'How often',
1761
1770
  'pr.minutes': '{n} min',
1762
1771
  'pr.everyLong': 'Every {n} minutes',
1763
- 'pr.cost': 'Each update is one model turn, which reads the whole conversation, so it uses quota.',
1772
+ 'pr.cost': 'Each update is one model turn, which reads the whole conversation, so it uses quota; a longer interval uses less.',
1764
1773
  'pr.scope': 'Claude sessions you start after turning it on get it. Turning it off stops it in open sessions too. No updates while you are away (Unattended Mode).',
1765
1774
  'pr.codex': 'Codex is not covered: it has no way to wake a waiting session.',
1766
1775
  'pr.onToast': 'Progress updates on, every {n} minutes. Claude sessions you start from now on get them.',
@@ -3487,8 +3496,17 @@ const zh = {
3487
3496
  'ua.hereNote': '你 30 分钟内在这些会话里打过字,它们照常问你;每发一条消息,那个会话再算 30 分钟。其他会话仍然无人值守。',
3488
3497
  'ua.hereHint': '提前回来了?在哪个会话里打字,那个会话 30 分钟内照常问你,其他会话不受影响。',
3489
3498
  'ua.hereSession': '会话 {id}',
3499
+ 'ua.wait': '没人回答时',
3500
+ 'ua.waitNote': '你在的会话里出现提问,会等你这么久。到时无人值守开着,会话就不再等:能撤回的按推荐选项继续,要你确认的操作跳过不做。每一条都记在下面“待你决定”里。',
3501
+ 'ua.waitLabel': '等多久后继续',
3502
+ 'ua.waitMin': '{n} 分钟',
3503
+ 'ua.waitNever': '一直等',
3504
+ 'ua.waitToast': '提问现在等你 {n} 分钟。',
3505
+ 'ua.waitNeverToast': '提问现在一直等你回答。',
3506
+ 'ua.waitFailed': '没改成:{msg}',
3507
+ 'ua.waited': '等了 {n} 分钟没人回答',
3490
3508
  'ua.pending': '待你决定',
3491
- 'ua.pendingNote': '会话没问你的问题、要你确认的操作和跳过的操作。这里的事都还没做。',
3509
+ 'ua.pendingNote': '会话没问你或没人回答的问题、要你确认的操作和跳过的操作。这里的事都还没做。',
3492
3510
  'ua.pendingEmpty': '没有待你决定的事',
3493
3511
  'ua.pendingBlocked': '上面说的文件夹修好之前,sideby 读不到它们。',
3494
3512
  'ua.loading': '正在读取…',
@@ -3520,14 +3538,14 @@ const zh = {
3520
3538
  'ua.problem': 'sideby 没法保存状态:{msg}',
3521
3539
  'ua.unreadable': 'sideby 读不到无人值守的状态。刷新再试一次。',
3522
3540
  'ai.ask.unattended': '今晚无人值守,到明早 8 点',
3523
- 'ai.ask.progress': '后台任务跑着时,每 10 分钟告诉我会话在等什么。',
3541
+ 'ai.ask.progress': '后台任务跑着时,每 30 分钟告诉我会话在等什么。',
3524
3542
  'pr.title': '进度提醒',
3525
- 'pr.hint': 'Claude 会话等后台任务(子任务、长命令)时,每隔几分钟告诉你在等什么、等了多久。',
3543
+ 'pr.hint': 'Claude 会话等后台任务(子任务、长命令)时,告诉你在等什么、等了多久:默认每 30 分钟一次,也可以自己选。',
3526
3544
  'pr.switch': '等待时报进度',
3527
3545
  'pr.every': '多久一次',
3528
3546
  'pr.minutes': '{n} 分钟',
3529
3547
  'pr.everyLong': '每 {n} 分钟',
3530
- 'pr.cost': '每次提醒是一轮模型调用,会读一遍整个对话,会用额度。',
3548
+ 'pr.cost': '每次提醒是一轮模型调用,会读一遍整个对话,会用额度;间隔越长用得越少。',
3531
3549
  'pr.scope': '打开后启动的 Claude 会话才有;关掉对已经开着的会话也生效。无人值守时不提醒。',
3532
3550
  'pr.codex': 'Codex 不支持:它没有办法叫醒等待中的会话。',
3533
3551
  'pr.onToast': '已打开进度提醒,每 {n} 分钟一次。之后启动的 Claude 会话会有。',
@@ -6274,7 +6274,7 @@ const MAIN = String.raw `
6274
6274
  const UA_MS = 15000
6275
6275
  const UA_DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
6276
6276
  const UA_PRESET = { name: 'Weeknights', days: ['mon', 'tue', 'wed', 'thu', 'fri'], start: '23:00', end: '08:00' }
6277
- const ua = { data: null, error: null, loading: null, at: 0, nextAt: 0, inflight: new Map(), opening: false, choosing: false, choice: null, time: '08:00', timeInit: '08:00', busy: false, local: null, saves: 0, rows: [], seq: 0, gone: {}, open: {}, firstUse: false, focus: null }
6277
+ const ua = { data: null, error: null, loading: null, at: 0, nextAt: 0, inflight: new Map(), opening: false, choosing: false, choice: null, time: '08:00', timeInit: '08:00', busy: false, local: null, saves: 0, rows: [], seq: 0, gone: {}, open: {}, firstUse: false, focus: null, wait: undefined, waitSaves: 0 }
6278
6278
  let uaSaving = Promise.resolve()
6279
6279
  function uaStatusNow() { return (S.state && S.state.unattended) || null }
6280
6280
  // The latest status's count, less the ones being marked done right now (the page shows them gone already).
@@ -6741,6 +6741,7 @@ const MAIN = String.raw `
6741
6741
  h('div', { class: 'ua-item-meta' },
6742
6742
  h('span', { class: 'chip chip-sm' + (x.kind === 'question' ? ' chip-accent' : x.kind === 'permission' ? ' chip-warn' : '') }, t('ua.kind.' + x.kind)),
6743
6743
  h('time', { class: 'muted small', datetime: x.at }, uaWhenShort(x.at)),
6744
+ x.waited ? h('span', { class: 'muted small' }, t('ua.waited', { n: x.waited })) : null,
6744
6745
  x.agentType ? h('span', { class: 'muted small' }, t('ua.agent', { type: x.agentType })) : null),
6745
6746
  h('p', { class: 'ua-text' + (long && !open ? ' is-clamped' : '') }, x.text),
6746
6747
  h('div', { class: 'ua-item-actions' },
@@ -6754,6 +6755,52 @@ const MAIN = String.raw `
6754
6755
  h('p', { class: 'muted small' }, t('ua.pendingNote'))), box]
6755
6756
  }
6756
6757
 
6758
+ // ---------- Answer Wait (ADR-0077) ----------
6759
+ // How long a question shown in a session waits for you before, with the mode on, the session goes on. One row of
6760
+ // choices that writes at once (the toast carries the undo); the choice moves before the answer comes back, stays on
6761
+ // the latest click while earlier ones are still being written, and a failure puts it back. A wait set elsewhere (the CLI takes any 1 to 120) shows as one more choice.
6762
+ const UA_WAITS = [5, 10, 15, 30, 60]
6763
+ function uaWaitNow(st) {
6764
+ return ua.wait !== undefined ? ua.wait : st.answerWait === undefined ? 10 : st.answerWait
6765
+ }
6766
+ async function uaSetWait(minutes, opts) {
6767
+ opts = opts || {}
6768
+ const st = uaStatusNow()
6769
+ if (!st) return
6770
+ const was = uaWaitNow(st)
6771
+ if (minutes === was) return
6772
+ ua.wait = minutes
6773
+ ua.waitSaves++
6774
+ if (!st.configured) ua.firstUse = true
6775
+ renderUaPage()
6776
+ uaSaving = uaSaving.then(async () => {
6777
+ try {
6778
+ const r = await api('/api/unattended/wait', { minutes })
6779
+ uaKeepStatus(r.status)
6780
+ if (r.changed) {
6781
+ const text = opts.undone ? t('ua.undone') : minutes === null ? t('ua.waitNeverToast') : t('ua.waitToast', { n: minutes })
6782
+ toast(text, opts.undone ? { key: 'ua-wait' } : { key: 'ua-wait', action: { label: t('toast.undo'), run: () => uaSetWait(r.before, { undone: true }) }, duration: 10000 })
6783
+ }
6784
+ } catch (e) { toast(t('ua.waitFailed', { msg: e.message }), { kind: 'fail' }) }
6785
+ // The latest choice stays shown until every change is written; then the page shows what the config holds.
6786
+ if (!--ua.waitSaves) ua.wait = undefined
6787
+ uaRedraw()
6788
+ })
6789
+ }
6790
+ function uaWaitBlock(st) {
6791
+ const cur = uaWaitNow(st)
6792
+ const opts = UA_WAITS.slice()
6793
+ if (cur !== null && !opts.includes(cur)) { opts.push(cur); opts.sort((a, b) => a - b) }
6794
+ const label = t('ua.waitLabel')
6795
+ const choices = [...opts.map((n) => [n, t('ua.waitMin', { n })]), [null, t('ua.waitNever')]]
6796
+ const control = BOOT.readOnly || st.problem
6797
+ ? h('span', { class: 'chip chip-sm' }, cur === null ? t('ua.waitNever') : t('ua.waitMin', { n: cur }))
6798
+ : h('div', { class: 'seg ua-wait-seg', role: 'group', 'aria-label': label, 'data-patch': '' }, choices.map(([v, text]) =>
6799
+ h('button', { class: 'seg-btn', type: 'button', 'data-key': 'ua-wait-' + (v === null ? 'never' : v), 'aria-pressed': String(v === cur), onclick: () => uaSetWait(v) }, text)))
6800
+ return [h('div', { class: 'page-sec-head', 'data-key': 'ua-wait-head' }, h('h3', { class: 'page-sec' }, t('ua.wait')), h('p', { class: 'muted small' }, t('ua.waitNote'))),
6801
+ fm('ua-wait', h('div', { class: 'set-row ua-wait', 'data-key': 'ua-wait', 'data-patch': '' }, h('span', { class: 'set-label' }, label), control))]
6802
+ }
6803
+
6757
6804
  // ---------- Attended Sessions (ADR-0075) ----------
6758
6805
  // While it is on: the sessions someone typed into within the last 30 minutes, which ask as usual, each with until
6759
6806
  // when; with none, one line that says typing in a session is all it takes. Only shown: nothing here sets it.
@@ -6818,7 +6865,7 @@ const MAIN = String.raw `
6818
6865
  if (box.hidden || (!ua.data && !ua.error)) { if (++tries < 40) setTimeout(look, 100); return }
6819
6866
  const st = uaStatusNow()
6820
6867
  if (what === 'on' && st && uaStatusParts(st).state !== 'on' && !BOOT.readOnly && !st.problem) { if (!ua.choosing) uaOpenChooser(); return }
6821
- const el = box.querySelector(what === 'on' ? '[data-key="ua-main"]' : '[data-find="ua-add"]')
6868
+ const el = box.querySelector(what === 'on' ? '[data-key="ua-main"]' : what === 'wait' ? '[data-find="ua-wait"]' : '[data-find="ua-add"]')
6822
6869
  if (!el) return
6823
6870
  el.scrollIntoView({ behavior: REDUCED ? 'auto' : 'smooth', block: 'center' })
6824
6871
  palFlash(el)
@@ -6860,6 +6907,7 @@ const MAIN = String.raw `
6860
6907
  if (!st.configured || ua.firstUse) kids.push(h('p', { class: 'note ua-first', 'data-key': 'ua-first', 'data-ua': 'first' }, icon('clock'), t('ua.firstUse')))
6861
6908
  kids.push(...uaHereBlock(st, p))
6862
6909
  kids.push(...uaScheduleBlock())
6910
+ kids.push(...uaWaitBlock(st))
6863
6911
  kids.push(...uaPendingBlock(st))
6864
6912
  kids.push(...uaCoverage(st))
6865
6913
  uaPatch(box, kids)
@@ -7219,6 +7267,7 @@ const MAIN = String.raw `
7219
7267
  inbound: { run: openInbound, ok: () => Boolean(S.state) },
7220
7268
  'unattended-on': { run: () => uaGo('on'), ok: () => Boolean(uaStatusNow()), nav: true },
7221
7269
  'unattended-add-slot': { run: () => uaGo('add'), ok: () => Boolean(uaStatusNow()), nav: true },
7270
+ 'unattended-wait': { run: () => uaGo('wait'), ok: () => Boolean(uaStatusNow()), nav: true },
7222
7271
  'limit-reset': { run: openResetPick, ok: () => resetCandidates().length > 0 },
7223
7272
  }
7224
7273
  function palHealth() {
@@ -1467,6 +1467,13 @@ input.ua-time::placeholder { color: var(--faint); }
1467
1467
  .ua-here-row { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 12px; padding: 12px 16px; border-top: 1px solid var(--border); }
1468
1468
  .ua-here-row:first-child { border-top: 0; }
1469
1469
  .ua-here-hint { gap: 8px; margin-top: 12px; }
1470
+ /* Answer Wait (ADR-0077): the label, then a row of choices that wraps under it on a narrow page; on a phone the
1471
+ choices make a grid of three, so "Never" is never hidden behind a sideways scroll. */
1472
+ .ua-wait { justify-content: flex-start; flex-wrap: wrap; gap: 8px 16px; padding: 12px 16px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-xl); box-shadow: var(--shadow); }
1473
+ .ua-wait .seg { max-width: 100%; }
1474
+ .ua-wait .seg-btn { white-space: nowrap; }
1475
+ :where(:root[data-width=phone]) .ua-wait .seg { display: grid; grid-template-columns: repeat(3, 1fr); width: 100%; height: auto; }
1476
+ :where(:root[data-width=phone]) .ua-wait .seg-btn { justify-content: center; height: calc(var(--ctl-h-sm) - 4px); padding: 0 8px; }
1470
1477
  .ua-here-hint .ic { width: 15px; height: 15px; flex: none; }
1471
1478
  :where(:root[data-width=narrow], :root[data-width=phone]) .ua-item { grid-template-columns: minmax(0, 1fr); }
1472
1479
  :where(:root[data-width=narrow], :root[data-width=phone]) .ua-item-actions { grid-column: 1; grid-row: auto; }
@@ -10,6 +10,11 @@ export interface ProgressHookDeps {
10
10
  parentGone?: () => boolean;
11
11
  /** This watch's id; random by default. */
12
12
  id?: string;
13
+ /**
14
+ * When the hook began, before it read its input: the order of the session's `Stop`s, kept as the watch's `at`.
15
+ * `runProgressHook` sets it; by default when the watch starts.
16
+ */
17
+ entered?: Date;
13
18
  checkEveryMs?: number;
14
19
  /** How long a write waits for the session's lock (for tests). */
15
20
  lockWait?: {
@@ -18,6 +23,8 @@ export interface ProgressHookDeps {
18
23
  };
19
24
  /** Runs between the last check of the watch record and marking it woken, inside the lock (for tests). */
20
25
  beforeWake?: () => Promise<void>;
26
+ /** Runs after the loop's last checks, before taking the session's lock to mark the watch woken (for tests). */
27
+ beforeLock?: () => Promise<void>;
21
28
  }
22
29
  type Input = AsyncIterable<string | Uint8Array> | string;
23
30
  /** The background tasks as the reminder names them: kind and description, never the command. */
@@ -13,7 +13,7 @@ import { randomBytes } from 'node:crypto';
13
13
  import { join } from 'node:path';
14
14
  import { FILES, HANDOFF_ENV, readJsonFile } from '../core/handoff-chain.js';
15
15
  import { resolvePaths } from '../core/paths.js';
16
- import { hashOf, markWatchWoken, progressReminderTurn, readProgressEvery, readPromptRecord, readWatch, writePromptRecord, writeWatch, } from '../core/progress-state.js';
16
+ import { hashOf, markWatchWoken, newerPrompt, progressReminderTurn, readProgressEvery, readPromptRecord, readWatch, writePromptRecord, writeWatch, } from '../core/progress-state.js';
17
17
  import { PROGRESS_MARK, progressWakeUp } from '../core/prompt-origin.js';
18
18
  import { sessionUnattended } from '../core/unattended-attended.js';
19
19
  import { UNATTENDED_ENV } from '../core/unattended-state.js';
@@ -157,14 +157,16 @@ export async function watchWhileWaiting(input, env, deps = {}) {
157
157
  const promptId = str(input.prompt_id);
158
158
  const paths = resolvePaths(env);
159
159
  const start = clock().getTime();
160
+ const stopAt = deps.entered ? deps.entered.getTime() : start;
160
161
  // The wait goes on across the turns reminders start; any other turn starts a new one.
161
162
  const prev = await readWatch(paths.stateDir, sessionId);
162
163
  const afterReminder = await progressReminderTurn(paths.stateDir, sessionId, promptId);
163
164
  const since = afterReminder && prev ? prev.since : iso(start);
164
165
  const id = deps.id ?? randomBytes(8).toString('hex');
165
166
  // Written first, so a watch left by an earlier Stop ends even when this one has nothing to watch. When the session's
166
- // lock stays held nothing is written, and this Stop does not watch: an earlier watch may still hold the record.
167
- if (!(await writeWatch(paths.stateDir, sessionId, { id, since, at: iso(start) }, deps)))
167
+ // lock stays held nothing is written, and this Stop does not watch: an earlier watch may still hold the record. Nor
168
+ // does it when the record is a later Stop's watch (its hook began after this one's): that turn's wait goes on.
169
+ if (!(await writeWatch(paths.stateDir, sessionId, { id, since, at: iso(stopAt) }, deps)))
168
170
  return { exit: 0 };
169
171
  const tasks = input.background_tasks;
170
172
  if (!Array.isArray(tasks) || tasks.length === 0)
@@ -183,11 +185,8 @@ export async function watchWhileWaiting(input, env, deps = {}) {
183
185
  return { exit: 0 };
184
186
  if ((await readWatch(paths.stateDir, sessionId))?.id !== id)
185
187
  return { exit: 0 };
186
- // The latest prompt is another one: a turn began after this Stop's, and its own Stop decides again. Compared by
187
- // the prompt's id, never by time: the next prompt's record can be written before this watch even starts. Only a
188
- // Stop without an id falls back to whether the record came after it.
189
- const p = await readPromptRecord(paths.stateDir, sessionId);
190
- if (p && (ownPrompt ? p.prompt !== ownPrompt : Date.parse(p.at) > start))
188
+ // The latest prompt is another one: a turn began after this Stop's, and its own Stop decides again.
189
+ if (newerPrompt(await readPromptRecord(paths.stateDir, sessionId), ownPrompt, stopAt))
191
190
  return { exit: 0 };
192
191
  // Read every time: turning it off, or another interval, reaches a running session.
193
192
  every = await readProgressEvery(paths.configFile, env);
@@ -215,8 +214,14 @@ export async function watchWhileWaiting(input, env, deps = {}) {
215
214
  continue;
216
215
  }
217
216
  // Checked and marked under the session's lock just before waking, so a Stop that came meanwhile is never
218
- // answered by this watch, and never has its record put back to this one.
219
- const hook = deps.beforeWake ? { beforeWrite: deps.beforeWake } : {};
217
+ // answered by this watch, and never has its record put back to this one; a prompt noted meanwhile drops the
218
+ // reminder, which would only queue behind that turn. A prompt whose own (background) hook has not noted it yet,
219
+ // or that comes between this check and the Host reading the exit code, still gets the reminder after its turn.
220
+ const hook = {
221
+ turn: { ...(ownPrompt ? { prompt: ownPrompt } : {}), stopAt },
222
+ ...(deps.beforeWake ? { beforeWrite: deps.beforeWake } : {}),
223
+ };
224
+ await deps.beforeLock?.();
220
225
  if (!(await markWatchWoken(paths.stateDir, sessionId, id, now, hook)))
221
226
  return { exit: 0 };
222
227
  return { exit: 2, message: reminderMessage({ tasks, since, now, every }) };
@@ -234,10 +239,12 @@ export async function runProgressHook(argv, env, input, io, deps = {}) {
234
239
  }
235
240
  if (event !== 'Stop')
236
241
  return 0;
242
+ // Taken before the input is read, which may wait: it orders this Stop among the session's others.
243
+ const entered = deps.entered ?? (deps.now ? deps.now() : new Date());
237
244
  const v = await parseInput(input);
238
245
  if (!v)
239
246
  return 0;
240
- const w = await watchWhileWaiting(v, env, deps);
247
+ const w = await watchWhileWaiting(v, env, { ...deps, entered });
241
248
  // Exit 2 wakes the session (asyncRewake), which hands stderr to the model.
242
249
  if (w.exit === 2 && w.message) {
243
250
  io.err.write(`${w.message}\n`);
@@ -738,6 +738,11 @@ export interface PendingDecisionInfo {
738
738
  agentType?: string;
739
739
  /** The question with its options, the tool and what it was to do, or the deferred text (at most 4000 characters). */
740
740
  text: string;
741
+ /**
742
+ * Minutes the question or permission prompt was on screen with nobody answering before the session went on without
743
+ * an answer (Answer Wait, spec §3.37). Absent when it was never shown.
744
+ */
745
+ waited?: number;
741
746
  doneAt?: string;
742
747
  }
743
748
  /**
@@ -9,6 +9,12 @@ export interface UnattendedHookDeps {
9
9
  sleep?: (ms: number) => Promise<void>;
10
10
  /** Whether the Host that started the hook is gone (`ppid` 1 by default): nothing is left to wake. */
11
11
  parentGone?: () => boolean;
12
+ /** The Host's pid, whose session record says what is on screen (Answer Wait); `process.ppid` by default. */
13
+ hostPid?: number;
14
+ /** Answer Wait, for tests: runs once the wait is over, before the last check. */
15
+ beforeAct?: () => Promise<unknown>;
16
+ /** Answer Wait, for tests: runs after the Pending Decision is kept, before the check that may take it back. */
17
+ afterKeep?: () => Promise<unknown>;
12
18
  }
13
19
  /**
14
20
  * The question as the user should read it later: each question (with its short header) and its options' labels.
@@ -16,8 +22,11 @@ export interface UnattendedHookDeps {
16
22
  * the tool's input.
17
23
  */
18
24
  export declare function questionText(input: Record<string, unknown>): string;
19
- /** What the model reads instead of an answer. */
20
- export declare function questionReason(state: UnattendedState, now: Date, zh: boolean, kept: boolean): string;
25
+ /**
26
+ * What the model reads instead of an answer. `waited`: the question was on screen this many minutes with nobody
27
+ * answering (Answer Wait); the session shows the text too, so it opens with what happened for the person coming back.
28
+ */
29
+ export declare function questionReason(state: UnattendedState, now: Date, zh: boolean, kept: boolean, waited?: number): string;
21
30
  /** How much of the end of the model's last message is read to tell whether it ends on a question. */
22
31
  export declare const QUESTION_TAIL = 600;
23
32
  /**
@@ -34,8 +43,11 @@ export declare const QUESTION_PATTERNS: readonly RegExp[];
34
43
  * paragraph (and the one before it when the last is a list), unless a negation comes just before it ("无需你来决定").
35
44
  */
36
45
  export declare function endingQuestion(message: string): string | undefined;
37
- /** What the model reads when it ended its turn on a question and nobody is here to answer. */
38
- export declare function stopReason(state: UnattendedState, now: Date, zh: boolean, kept: boolean): string;
46
+ /**
47
+ * What the model reads when it ended its turn on a question and nobody is here to answer. `waited`: the question was
48
+ * left this many minutes with no reply (Answer Wait); this note then wakes the session, and is not the user's reply.
49
+ */
50
+ export declare function stopReason(state: UnattendedState, now: Date, zh: boolean, kept: boolean, waited?: number): string;
39
51
  /** What a declined MCP form is kept as: the server's name and what it asked, never a field's value. */
40
52
  export declare function elicitationText(v: Record<string, unknown>): string;
41
53
  /**
@@ -52,8 +64,11 @@ export declare function commandProgram(command: string): string | undefined;
52
64
  * other tool its name only.
53
65
  */
54
66
  export declare function permissionText(tool: string, input: Record<string, unknown>): string;
55
- /** What the model reads instead of the permission prompt Claude Code would have shown. */
56
- export declare function permissionReason(state: UnattendedState, now: Date, kept: boolean): string;
67
+ /**
68
+ * What the model reads instead of the permission prompt Claude Code would have shown. `waited`: the prompt was on
69
+ * screen this many minutes with nobody answering (Answer Wait).
70
+ */
71
+ export declare function permissionReason(state: UnattendedState, now: Date, kept: boolean, waited?: number): string;
57
72
  /**
58
73
  * What the user reads once in an Attended Session while Unattended Mode is on (ADR-0075), as a `systemMessage`: shown
59
74
  * in the session, never to the model.