@rarog/server 1.1.0 → 1.1.2-beta.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 (66) hide show
  1. package/node_modules/@rarog/shared/package.json +1 -1
  2. package/node_modules/@rarog/shared/src/decode.js +3 -0
  3. package/node_modules/@rarog/shared/src/notify-copy.js +1 -0
  4. package/node_modules/@rarog/shared/src/protocol/background.js +7 -0
  5. package/node_modules/@rarog/shared/src/sentences/dialogs.js +10 -0
  6. package/node_modules/@rarog/shared/src/sentences/push.js +3 -0
  7. package/package.json +2 -2
  8. package/server/src/bootstrap/pr-status.js +15 -7
  9. package/server/src/bootstrap/push.js +36 -5
  10. package/server/src/cli/doctor-pr-status.js +10 -6
  11. package/server/src/cli/update-registry.js +31 -1
  12. package/server/src/cli/update.js +128 -6
  13. package/server/src/demo/control.js +4 -2
  14. package/server/src/demo/mock-herdr.js +2 -2
  15. package/server/src/demo/scenarios.js +31 -17
  16. package/server/src/demo/seeds.js +62 -38
  17. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  18. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  19. package/server/src/drivers/herdr/start-dialog-gate.js +132 -0
  20. package/server/src/drivers/herdr-driver.js +75 -15
  21. package/server/src/herdr/background/cli-shapes.js +16 -15
  22. package/server/src/herdr/background/index.js +7 -7
  23. package/server/src/herdr/background/merge.js +17 -5
  24. package/server/src/herdr/background/notification.js +0 -4
  25. package/server/src/herdr/background/pull-request-files.js +53 -161
  26. package/server/src/herdr/background/pull-requests.js +54 -632
  27. package/server/src/herdr/background/work.js +84 -0
  28. package/server/src/herdr/dialogs/copy.js +7 -0
  29. package/server/src/herdr/dialogs/index.js +4 -1
  30. package/server/src/herdr/dialogs/screen/form.js +2 -1
  31. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  32. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  33. package/server/src/herdr/dialogs/screen/signatures.js +55 -0
  34. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  35. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  36. package/server/src/herdr/jsonl-follow.js +6 -2
  37. package/server/src/herdr/label-code.js +104 -0
  38. package/server/src/herdr/label-migration.js +142 -0
  39. package/server/src/herdr/launcher.js +30 -5
  40. package/server/src/herdr/provenance.js +80 -40
  41. package/server/src/herdr/start-dialog-wait.js +96 -0
  42. package/server/src/herdr/supervisor.js +33 -10
  43. package/server/src/herdr/workspace-resolver.js +5 -4
  44. package/server/src/index.js +8 -3
  45. package/server/src/notify/apns-payload.js +5 -3
  46. package/server/src/notify/content.js +37 -0
  47. package/server/src/notify/index.js +4 -0
  48. package/server/src/notify/live-activity-state.js +9 -5
  49. package/server/src/notify/live-activity.js +5 -2
  50. package/server/src/notify/policy.js +4 -2
  51. package/server/src/notify/stalled-wait.js +213 -0
  52. package/server/src/pr-status/facts.js +87 -0
  53. package/server/src/pr-status/gh.js +76 -9
  54. package/server/src/pr-status/index.js +1 -10
  55. package/server/src/pr-status/source.js +20 -6
  56. package/server/src/pr-status/tracker.js +32 -9
  57. package/server/src/sessions/conversation-lists.js +8 -2
  58. package/server/src/sessions/driver-events.js +7 -3
  59. package/server/src/sessions/interrupt-windows.js +28 -4
  60. package/server/src/sessions/manager.js +14 -5
  61. package/server/src/sessions/pr-status-link.js +64 -16
  62. package/server/src/sessions/session.js +10 -3
  63. package/server/src/sessions/state-machine.js +11 -0
  64. package/server/src/sessions/test-session.js +50 -0
  65. package/server/src/term/herdr-backend.js +15 -12
  66. package/server/src/term/lifecycle.js +4 -6
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Facts of PRs from GitHub: author, creation time and the latest title, kept in process memory until restart and
3
+ * shared by every conversation, plus the `gh` login (`viewer.login`) and the queue that verifies each linked URL
4
+ * without facts once. Author and creation time never change, so a stored fact is never asked again; only the title
5
+ * follows later answers.
6
+ *
7
+ * No process, no timer, no log: the tracker (`tracker.ts`) asks what is due, puts it into its reads and hands every
8
+ * successful answer back. Nothing here touches the state map.
9
+ */
10
+ import { parsePrUrl } from './source.js';
11
+ export function createPrFactsQueue() {
12
+ const known = new Map();
13
+ const links = new Map();
14
+ const waiting = new Map();
15
+ let viewer = null;
16
+ const sync = (dueAt) => {
17
+ const wanted = new Set();
18
+ for (const urls of links.values())
19
+ for (const url of urls)
20
+ wanted.add(url);
21
+ for (const url of waiting.keys())
22
+ if (!wanted.has(url))
23
+ waiting.delete(url);
24
+ for (const url of wanted) {
25
+ if (known.has(url) || waiting.has(url))
26
+ continue;
27
+ const ref = parsePrUrl(url);
28
+ if (ref !== null)
29
+ waiting.set(url, { ref, dueAt });
30
+ }
31
+ };
32
+ return {
33
+ factsOf: (url) => known.get(url),
34
+ viewerLogin: () => viewer,
35
+ setSessionLinks: (sessionId, urls, dueAt) => {
36
+ links.set(sessionId, new Set(urls));
37
+ sync(dueAt);
38
+ },
39
+ dropSession: (sessionId) => {
40
+ if (!links.delete(sessionId))
41
+ return false;
42
+ sync(Infinity);
43
+ return true;
44
+ },
45
+ nextDueAt: () => {
46
+ let next = Infinity;
47
+ for (const entry of waiting.values())
48
+ if (entry.dueAt < next)
49
+ next = entry.dueAt;
50
+ return next;
51
+ },
52
+ due: (now, max, skip) => [...waiting.values()]
53
+ .filter((entry) => entry.dueAt <= now && !skip.has(entry.ref.url))
54
+ .sort((a, b) => a.dueAt - b.dueAt)
55
+ .slice(0, Math.max(0, max))
56
+ .map((entry) => entry.ref),
57
+ apply: (urls, answer, retryAt) => {
58
+ const changed = new Set();
59
+ for (const url of urls) {
60
+ const read = answer.facts.get(url);
61
+ const title = answer.titles.get(url);
62
+ const before = known.get(url);
63
+ if (before !== undefined) {
64
+ if (title !== undefined && title !== before.title) {
65
+ known.set(url, { ...before, title });
66
+ changed.add(url);
67
+ }
68
+ }
69
+ else if (read?.kind === 'found') {
70
+ const { author, createdAtMs } = read;
71
+ known.set(url, title === undefined ? { author, createdAtMs } : { author, createdAtMs, title });
72
+ waiting.delete(url);
73
+ changed.add(url);
74
+ }
75
+ else {
76
+ const entry = waiting.get(url);
77
+ if (entry !== undefined)
78
+ entry.dueAt = retryAt;
79
+ }
80
+ }
81
+ const viewerChanged = answer.viewer !== null && answer.viewer !== viewer;
82
+ if (viewerChanged)
83
+ viewer = answer.viewer;
84
+ return { urls: changed, viewerChanged };
85
+ },
86
+ };
87
+ }
@@ -1,6 +1,8 @@
1
1
  /**
2
- * The `gh` state source: one batched GraphQL query for up to {@link PR_BATCH_MAX} PRs, run with the user's `gh` login
3
- * for `github.com`. The only place in the server that starts `gh` (guard: `server/test/pr-status-granice.test.ts`).
2
+ * The `gh` source: one batched GraphQL query for up to {@link PR_BATCH_MAX} PRs, run with the user's `gh` login for
3
+ * `github.com`. Every read asks the same fields: state, draft mark, title, creation time and author of each PR, and
4
+ * the login of the account (`viewer`). The only place in the server that starts `gh` (guard:
5
+ * `server/test/pr-status-granice.test.ts`).
4
6
  *
5
7
  * - program: the first executable `gh` in the closed directory list {@link GH_DIRECTORIES}, looked up once, on the
6
8
  * first read; `execFile` without a shell;
@@ -16,6 +18,7 @@ import { execFile } from 'node:child_process';
16
18
  import { accessSync, constants, statSync } from 'node:fs';
17
19
  import { isAbsolute, join } from 'node:path';
18
20
  import { PR_STATUS_ENV_PASSTHROUGH } from '../config-env.js';
21
+ import { clipUnits, stripControlChars } from '../text.js';
19
22
  /**
20
23
  * Where `gh` is looked for, in this order; `~/` is the server's `HOME`. A closed list of absolute paths, no `PATH`
21
24
  * search: the server's `PATH` is minimal, and Homebrew on an Intel Mac, linuxbrew and `~/.local/bin` are not on it.
@@ -35,6 +38,10 @@ export const GH_TIMEOUT_MS = 20_000;
35
38
  export const GH_OUTPUT_CAP_BYTES = 1024 * 1024;
36
39
  /** PRs per call (aliases in one query). */
37
40
  export const PR_BATCH_MAX = 50;
41
+ /** Longest title kept, in UTF-16 code units: the limit of `SessionPullRequest.title`. */
42
+ export const PR_TITLE_MAX = 120;
43
+ /** Fields asked of every PR. */
44
+ const PR_FIELDS = 'state isDraft title createdAt author{login}';
38
45
  /** `gh` exit code for "authentication required". */
39
46
  const NOT_LOGGED_IN_EXIT = 4;
40
47
  /** GitHub's wording of the primary and the secondary rate limit. */
@@ -91,12 +98,12 @@ export function buildQueryBody(prs) {
91
98
  const variables = {};
92
99
  prs.forEach((pr, i) => {
93
100
  declarations.push(`$o${i}:String!,$r${i}:String!,$n${i}:Int!`);
94
- fields.push(`p${i}:repository(owner:$o${i},name:$r${i}){pullRequest(number:$n${i}){state isDraft}}`);
101
+ fields.push(`p${i}:repository(owner:$o${i},name:$r${i}){pullRequest(number:$n${i}){${PR_FIELDS}}}`);
95
102
  variables[`o${i}`] = pr.owner;
96
103
  variables[`r${i}`] = pr.repo;
97
104
  variables[`n${i}`] = pr.number;
98
105
  });
99
- const query = `query(${declarations.join(',')}){${fields.join(' ')} rateLimit{remaining resetAt}}`;
106
+ const query = `query(${declarations.join(',')}){${fields.join(' ')} viewer{login} rateLimit{remaining resetAt}}`;
100
107
  return JSON.stringify({ query, variables });
101
108
  }
102
109
  function record(value) {
@@ -135,7 +142,56 @@ function epochOf(value) {
135
142
  const ms = Date.parse(value);
136
143
  return Number.isFinite(ms) ? ms : null;
137
144
  }
138
- /** States of `prs` from one run. Reads stdout whatever the exit code; stdout without a `data` object fails the call. */
145
+ /**
146
+ * A title from GitHub as the list may show it: control characters out, trimmed, at most {@link PR_TITLE_MAX} UTF-16
147
+ * code units. Empty after that, or not a string: no title.
148
+ */
149
+ export function prTitle(value) {
150
+ if (typeof value !== 'string')
151
+ return undefined;
152
+ const title = clipUnits(stripControlChars(value).trim(), PR_TITLE_MAX);
153
+ return title === '' ? undefined : title;
154
+ }
155
+ /**
156
+ * What `errors[]` says about each alias (the first element of the error path). Only `NOT_FOUND` at the repository
157
+ * (`[pN]`) or at the PR (`[pN, "pullRequest"]`) means the PR is missing; any other error on the alias path, also next
158
+ * to a not-found one, is an error.
159
+ */
160
+ function aliasVerdicts(answer) {
161
+ const verdicts = new Map();
162
+ const errors = answer?.['errors'];
163
+ if (!Array.isArray(errors))
164
+ return verdicts;
165
+ for (const item of errors) {
166
+ const error = record(item);
167
+ const path = error?.['path'];
168
+ if (!Array.isArray(path) || typeof path[0] !== 'string')
169
+ continue;
170
+ const alias = path[0];
171
+ const notFound = error?.['type'] === 'NOT_FOUND'
172
+ && (path.length === 1 || (path.length === 2 && path[1] === 'pullRequest'));
173
+ if (!notFound)
174
+ verdicts.set(alias, 'error');
175
+ else if (verdicts.get(alias) !== 'error')
176
+ verdicts.set(alias, 'missing');
177
+ }
178
+ return verdicts;
179
+ }
180
+ /** Author and creation time of one `pullRequest` object; a verdict from `errors[]` wins over the object. */
181
+ function factsOf(pullRequest, verdict) {
182
+ if (verdict !== undefined)
183
+ return { kind: verdict };
184
+ const author = record(pullRequest?.['author'])?.['login'];
185
+ const createdAtMs = epochOf(pullRequest?.['createdAt']);
186
+ if (typeof author !== 'string' || author === '' || createdAtMs === null)
187
+ return { kind: 'error' };
188
+ return { kind: 'found', author, createdAtMs };
189
+ }
190
+ /**
191
+ * Answers for `prs` from one run. Reads stdout whatever the exit code; stdout without a `data` object fails the call.
192
+ * The state reads only the PR object, whatever `errors[]` or the facts say; an answer without `viewer.login` makes
193
+ * the facts of every PR an error.
194
+ */
139
195
  export function readGhOutput(run, prs) {
140
196
  if (run.failure === 'timeout')
141
197
  return { ok: false, failure: 'timeout' };
@@ -151,14 +207,25 @@ export function readGhOutput(run, prs) {
151
207
  }
152
208
  return { ok: false, failure: run.code === NOT_LOGGED_IN_EXIT ? 'not-logged-in' : 'error' };
153
209
  }
210
+ const login = record(data['viewer'])?.['login'];
211
+ const viewer = typeof login === 'string' && login !== '' ? login : null;
212
+ const verdicts = aliasVerdicts(answer);
154
213
  const states = new Map();
214
+ const titles = new Map();
215
+ const facts = new Map();
155
216
  prs.forEach((pr, i) => {
156
- states.set(pr.url, stateOf(record(record(data[`p${i}`])?.['pullRequest'])));
217
+ const pullRequest = record(record(data[`p${i}`])?.['pullRequest']);
218
+ states.set(pr.url, stateOf(pullRequest));
219
+ const title = prTitle(pullRequest?.['title']);
220
+ if (title !== undefined)
221
+ titles.set(pr.url, title);
222
+ facts.set(pr.url, viewer === null ? { kind: 'error' } : factsOf(pullRequest, verdicts.get(`p${i}`)));
157
223
  });
158
224
  const limit = record(data['rateLimit']);
225
+ const result = { ok: true, states, titles, facts, viewer };
159
226
  if (limit?.['remaining'] === 0)
160
- return { ok: true, states, limitReached: { resetAt: epochOf(limit['resetAt']) } };
161
- return { ok: true, states };
227
+ return { ...result, limitReached: { resetAt: epochOf(limit['resetAt']) } };
228
+ return result;
162
229
  }
163
230
  /** One `gh` run; resolves, never rejects. */
164
231
  export function runGh(bin, opts) {
@@ -211,7 +278,7 @@ export function createGhSource(opts) {
211
278
  try {
212
279
  const batch = prs.slice(0, PR_BATCH_MAX);
213
280
  if (batch.length === 0)
214
- return { ok: true, states: new Map() };
281
+ return { ok: true, states: new Map(), titles: new Map(), facts: new Map(), viewer: null };
215
282
  if (bin === undefined) {
216
283
  bin = findGh({ home, ...(opts.directories === undefined ? {} : { directories: opts.directories }) });
217
284
  }
@@ -1,12 +1,3 @@
1
- /**
2
- * PR status (`SessionPullRequest.state`): the state of the PRs that sessions created, read from GitHub with the
3
- * user's `gh` login while a client is connected. The entry of the directory; callers import only from here.
4
- *
5
- * - `source.ts`: PR reference from an address, the read result, the state source contract, the fixed-map source;
6
- * - `gh.ts`: the `gh` source (program lookup, closed environment, batched query on stdin, output reader) and the
7
- * login check of `rarog doctor`;
8
- * - `tracker.ts`: the URL → state map, the rhythm, pauses after failures and the change callback.
9
- */
10
- export { GH_ARGV, GH_AUTH_ARGV, GH_AUTH_TIMEOUT_MS, GH_DIRECTORIES, GH_HOST, GH_OUTPUT_CAP_BYTES, GH_TIMEOUT_MS, PR_BATCH_MAX, PR_STATUS_ENV_PASSTHROUGH, buildQueryBody, checkGhAuth, createGhSource, findGh, ghCandidates, ghEnv, readGhOutput, } from './gh.js';
1
+ export { GH_ARGV, GH_AUTH_ARGV, GH_AUTH_TIMEOUT_MS, GH_DIRECTORIES, GH_HOST, GH_OUTPUT_CAP_BYTES, GH_TIMEOUT_MS, PR_BATCH_MAX, PR_STATUS_ENV_PASSTHROUGH, PR_TITLE_MAX, buildQueryBody, checkGhAuth, createGhSource, findGh, ghCandidates, ghEnv, prTitle, readGhOutput, } from './gh.js';
11
2
  export { createFixedPrStateSource, parsePrUrl } from './source.js';
12
3
  export { FAILURE_PAUSE_MS, NEW_URL_DELAY_MS, OPEN_REFRESH_MS, RATE_LIMIT_PAUSE_MAX_MS, UNKNOWN_REFRESH_MS, createPrStatusTracker, } from './tracker.js';
@@ -11,12 +11,26 @@ export function parsePrUrl(url) {
11
11
  const [, owner = '', repo = '', number = ''] = match;
12
12
  return { url, owner, repo, number: Number(number) };
13
13
  }
14
- /** A source that answers from a fixed map and never starts a process. URLs outside the map have no state. */
15
- export function createFixedPrStateSource(states) {
14
+ /** A source that answers from a fixed map and never starts a process. URLs outside the map are `missing`. */
15
+ export function createFixedPrStateSource(github) {
16
16
  return {
17
- read: (prs) => Promise.resolve({
18
- ok: true,
19
- states: new Map(prs.map((pr) => [pr.url, states.get(pr.url) ?? null])),
20
- }),
17
+ read: (prs) => {
18
+ const states = new Map();
19
+ const titles = new Map();
20
+ const facts = new Map();
21
+ for (const { url } of prs) {
22
+ const pr = github.prs.get(url);
23
+ states.set(url, pr?.state ?? null);
24
+ if (pr?.title !== undefined)
25
+ titles.set(url, pr.title);
26
+ if (pr === undefined)
27
+ facts.set(url, { kind: 'missing' });
28
+ else if (github.viewer === null)
29
+ facts.set(url, { kind: 'error' });
30
+ else
31
+ facts.set(url, { kind: 'found', author: pr.author, createdAtMs: pr.createdAtMs });
32
+ }
33
+ return Promise.resolve({ ok: true, states, titles, facts, viewer: github.viewer });
34
+ },
21
35
  };
22
36
  }
@@ -1,3 +1,4 @@
1
+ import { createPrFactsQueue } from './facts.js';
1
2
  import { PR_BATCH_MAX } from './gh.js';
2
3
  import { parsePrUrl } from './source.js';
3
4
  export const NEW_URL_DELAY_MS = 5_000;
@@ -23,6 +24,7 @@ export function createPrStatusTracker(opts) {
23
24
  const newUrlDelayMs = Math.max(0, opts.newUrlDelayMs ?? NEW_URL_DELAY_MS);
24
25
  const entries = new Map();
25
26
  const sessions = new Map();
27
+ const facts = createPrFactsQueue();
26
28
  let connected = false;
27
29
  let disabled = false;
28
30
  let closed = false;
@@ -47,7 +49,7 @@ export function createPrStatusTracker(opts) {
47
49
  clearTimer();
48
50
  if (closed || disabled || !connected || reading !== null)
49
51
  return;
50
- let next = Infinity;
52
+ let next = facts.nextDueAt();
51
53
  for (const entry of entries.values())
52
54
  if (entry.dueAt < next)
53
55
  next = entry.dueAt;
@@ -59,7 +61,8 @@ export function createPrStatusTracker(opts) {
59
61
  const pause = (ms) => {
60
62
  pausedUntil = scheduler.now() + ms;
61
63
  };
62
- const apply = (batch, result) => {
64
+ /** One read's answer: `batch` are the state entries asked, `verified` the facts-only URLs asked with them. */
65
+ const apply = (batch, verified, result) => {
63
66
  if (!result.ok) {
64
67
  if (result.failure === 'missing-gh') {
65
68
  disabled = true;
@@ -70,7 +73,7 @@ export function createPrStatusTracker(opts) {
70
73
  ? rateLimitPause(result.resetAt)
71
74
  : FAILURE_PAUSE_MS;
72
75
  pause(ms);
73
- const count = plural(batch.length);
76
+ const count = plural(batch.length + verified.length);
74
77
  safeLog(`pr-status: gh call failed (${result.failure}) for ${count}, paused for ${minutes(ms)} min`);
75
78
  return;
76
79
  }
@@ -88,15 +91,19 @@ export function createPrStatusTracker(opts) {
88
91
  else
89
92
  entry.dueAt = now + (state === undefined ? UNKNOWN_REFRESH_MS : OPEN_REFRESH_MS);
90
93
  }
94
+ const asked = [...batch.map((entry) => entry.ref.url), ...verified.map((ref) => ref.url)];
95
+ const learned = facts.apply(asked, result, now + UNKNOWN_REFRESH_MS);
96
+ for (const url of learned.urls)
97
+ changed.add(url);
91
98
  if (result.limitReached !== undefined) {
92
99
  const ms = rateLimitPause(result.limitReached.resetAt);
93
100
  pause(ms);
94
101
  safeLog(`pr-status: GitHub rate limit reached, paused for ${minutes(ms)} min`);
95
102
  }
96
- if (changed.size === 0)
103
+ if (changed.size === 0 && !learned.viewerChanged)
97
104
  return;
98
105
  try {
99
- opts.onChange(changed);
106
+ opts.onChange({ urls: changed, viewerChanged: learned.viewerChanged });
100
107
  }
101
108
  catch {
102
109
  // The caller's failure must not stop the rhythm.
@@ -121,7 +128,8 @@ export function createPrStatusTracker(opts) {
121
128
  .filter((entry) => entry.dueAt <= now)
122
129
  .sort((a, b) => a.dueAt - b.dueAt)
123
130
  .slice(0, PR_BATCH_MAX);
124
- if (batch.length === 0) {
131
+ const verified = facts.due(now, PR_BATCH_MAX - batch.length, new Set(batch.map((entry) => entry.ref.url)));
132
+ if (batch.length === 0 && verified.length === 0) {
125
133
  schedule();
126
134
  return;
127
135
  }
@@ -129,7 +137,7 @@ export function createPrStatusTracker(opts) {
129
137
  reading = controller;
130
138
  let read;
131
139
  try {
132
- read = opts.source.read(batch.map((entry) => entry.ref), controller.signal);
140
+ read = opts.source.read([...batch.map((entry) => entry.ref), ...verified], controller.signal);
133
141
  }
134
142
  catch {
135
143
  read = Promise.resolve({ ok: false, failure: 'error' });
@@ -139,7 +147,7 @@ export function createPrStatusTracker(opts) {
139
147
  .then((result) => {
140
148
  reading = null;
141
149
  if (!closed)
142
- apply(batch, result);
150
+ apply(batch, verified, result);
143
151
  })
144
152
  .catch(() => {
145
153
  reading = null;
@@ -169,6 +177,8 @@ export function createPrStatusTracker(opts) {
169
177
  };
170
178
  return {
171
179
  stateOf: (url) => entries.get(url)?.state,
180
+ factsOf: (url) => facts.factsOf(url),
181
+ viewerLogin: () => facts.viewerLogin(),
172
182
  setSessionUrls: (sessionId, urls) => {
173
183
  if (closed)
174
184
  return;
@@ -180,10 +190,23 @@ export function createPrStatusTracker(opts) {
180
190
  // Keeps the previous list; nothing to undo.
181
191
  }
182
192
  },
193
+ setSessionLinks: (sessionId, urls) => {
194
+ if (closed)
195
+ return;
196
+ try {
197
+ facts.setSessionLinks(sessionId, urls, scheduler.now() + newUrlDelayMs);
198
+ schedule();
199
+ }
200
+ catch {
201
+ // Keeps the previous linked set; nothing to undo.
202
+ }
203
+ },
183
204
  dropSession: (sessionId) => {
184
205
  if (closed)
185
206
  return;
186
- if (sessions.delete(sessionId))
207
+ const listed = sessions.delete(sessionId);
208
+ const linked = facts.dropSession(sessionId);
209
+ if (listed || linked)
187
210
  sync();
188
211
  },
189
212
  setClientConnected: (value) => {
@@ -1,4 +1,4 @@
1
- import { holdsOwedDone } from '../herdr/background/work.js';
1
+ import { holdsOwedDone, stuckWaits } from '../herdr/background/work.js';
2
2
  export function applyConversationList(session, event, port) {
3
3
  switch (event.type) {
4
4
  /*
@@ -15,8 +15,14 @@ export function applyConversationList(session, event, port) {
15
15
  if (tasks === undefined && session.backgroundTasks === undefined)
16
16
  return;
17
17
  const held = holdsOwedDone(session.backgroundTasks);
18
+ const waits = stuckWaits(session.state, session.backgroundTasks, tasks);
18
19
  session.backgroundTasks = tasks;
19
20
  port.emitSessionChanged(session);
21
+ /*
22
+ * The stalled wait alarm on every swap, also without an edge: the alarm drops its tries and its memory of waits
23
+ * that left the list. Before `quiet`, on the same swap; the alarm never touches the owed "done".
24
+ */
25
+ port.stuckWaits(session, waits);
20
26
  /*
21
27
  * Cisza w tle bez końca tury: lista przestała wstrzymywać
22
28
  * zaległe „gotowe" — skończyła się praca albo komenda subagenta w postoju. Raz na przejście,
@@ -43,7 +49,7 @@ export function applyConversationList(session, event, port) {
43
49
  }
44
50
  // Pull requesty sesji: reguła artefaktów, lista i jej stan na GitHubie w `pr-status-link.ts`.
45
51
  case 'pull-requests':
46
- port.prStatus.applyList(session, event.pullRequests);
52
+ port.prStatus.applyList(session, event.pullRequests, event.windowStart);
47
53
  return;
48
54
  /*
49
55
  * Scheduled tasks: the artifacts rule. An empty list clears the field; an empty one over an absent field sends
@@ -27,6 +27,8 @@ export function applyInitEvent(session, event, port) {
27
27
  */
28
28
  if (previousEngineSession !== undefined && previousEngineSession !== event.engineSessionId) {
29
29
  port.config.notifier?.forget(session.id);
30
+ // The stalled wait alarm of the previous conversation stops its tries too.
31
+ port.config.stalledWait?.forget(session.id);
30
32
  // A claim window of the previous conversation does not hold a dialog of the new one (`claim-window.ts`).
31
33
  port.claimWindows.conversationChanged(session);
32
34
  }
@@ -77,11 +79,13 @@ export function applyInitEvent(session, event, port) {
77
79
  * PR-y należą do rozmowy jak artefakty. Driver po wymianie startuje z pustym podpisem listy, więc
78
80
  * pusta lista nowej rozmowy nie wyszłaby z niego nigdy: lista poprzedniej schodzi tu, przy zmianie rozmowy.
79
81
  */
80
- const pullRequestsDropped = conversationChanged
81
- && (session.pullRequests !== undefined || session.scheduledTasks !== undefined);
82
+ const pullRequestsDropped = conversationChanged && (session.pullRequests !== undefined
83
+ || session.pullRequestLinks !== undefined || session.scheduledTasks !== undefined);
82
84
  if (pullRequestsDropped) {
83
- // Scheduled tasks too; the driver sends the new conversation's list after this `init`, also when empty.
85
+ // The links and the window too, and scheduled tasks; the driver sends the new conversation's after this `init`.
84
86
  session.pullRequests = undefined;
87
+ session.pullRequestLinks = undefined;
88
+ session.pullRequestWindowStart = undefined;
85
89
  session.scheduledTasks = undefined;
86
90
  }
87
91
  const moved = port.applyTransition(session, { type: 'driver-init' });
@@ -56,9 +56,17 @@ export class InterruptWindows {
56
56
  * Porównanie tożsamości przy rozstrzygnięciu nie jest asekuracją: nowa tura użytkownika
57
57
  * unieważnia oba okna (`resetInterruptWindows`), a spóźniony `escape` sprzed tej tury nie
58
58
  * ma prawa ani skasować cudzego wpisu, ani otworzyć debounce'u NAD nową turą.
59
+ *
60
+ * @param fromCard for an interrupt taken from `waiting-permission`: the session's `stateSince` right after the
61
+ * interrupt moved it to `waiting-input`; `null` otherwise. The transition runs before the driver's answer, and an
62
+ * `escape` the driver refused or could not send (the pause, a start dialog, a failed send) leaves the dialog
63
+ * standing: the card goes back on its decision while herdr still reports the pane `blocked` and the session has
64
+ * not moved since, instead of standing sendable until the driver shows its card again. A dialog answered at the
65
+ * desk in the meantime does not bring it back: herdr `idle` on `waiting-input` changes neither the state nor
66
+ * `stateSince`, and nothing else would clear the card.
59
67
  */
60
- trackInterrupt(id, delivered) {
61
- const tracked = delivered.then((sent) => this.#settleInterrupt(id, tracked, sent), (err) => {
68
+ trackInterrupt(id, delivered, fromCard = null) {
69
+ const tracked = delivered.then((sent) => this.#settleInterrupt(id, tracked, sent, fromCard), (err) => {
62
70
  /*
63
71
  * Kontrakt mówi, że odmowy lecą SYNCHRONICZNIE, więc odrzucona obietnica to
64
72
  * awaria kanału, nie decyzja. „Nie dostarczono" jest tu jedyną uczciwą odpowiedzią:
@@ -66,20 +74,36 @@ export class InterruptWindows {
66
74
  * gorszym kłamstwem niż `delivered: 'no'`.
67
75
  */
68
76
  this.#port.logger?.(`interrupt ${id}: ${describeError(err)}`);
69
- return this.#settleInterrupt(id, tracked, false);
77
+ return this.#settleInterrupt(id, tracked, false, fromCard);
70
78
  });
71
79
  this.#interruptsInFlight.set(id, tracked);
72
80
  return tracked;
73
81
  }
74
82
  /** Rozstrzygnięcie: zamyka okno „w locie", a dostarczony klawisz otwiera debounce. */
75
- #settleInterrupt(id, tracked, sent) {
83
+ #settleInterrupt(id, tracked, sent, fromCard) {
76
84
  if (this.#interruptsInFlight.get(id) !== tracked)
77
85
  return sent;
78
86
  this.#interruptsInFlight.delete(id);
79
87
  if (sent)
80
88
  this.#lastInterruptAtMs.set(id, this.#port.now());
89
+ else if (fromCard !== null)
90
+ this.#cardBack(id, fromCard);
81
91
  return sent;
82
92
  }
93
+ /**
94
+ * The card of an interrupt not delivered goes back on its decision: same session, driver and state since then, and
95
+ * herdr still reports the pane `blocked`.
96
+ */
97
+ #cardBack(id, since) {
98
+ const session = this.#port.sessions.get(id);
99
+ if (session === undefined || session.driver === null || !this.#port.herdrBlocked.has(id))
100
+ return;
101
+ if (session.state !== 'waiting-input' || session.stateSince !== since)
102
+ return;
103
+ if (this.#port.applyTransition(session, { type: 'agent-blocked' })) {
104
+ this.#port.logger?.(`interrupt ${id}: not delivered, the card is back on its decision`);
105
+ }
106
+ }
83
107
  /** Zeruje OBA okna przerwania tej sesji — nowa tura i zniknięcie karty. */
84
108
  resetInterruptWindows(id) {
85
109
  this.#interruptsInFlight.delete(id);
@@ -24,7 +24,7 @@ import { DEFAULT_MODEL_CHOICE, DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR, F
24
24
  import { foreign, say, sentenceOfArglessRef, } from '@rarog/shared/sentences';
25
25
  import { isFallbackLabel, nextFallbackLabel } from './fallback-label.js';
26
26
  export { isFallbackLabel, nextFallbackLabel };
27
- import { MAX_TURNS_DETAIL, transition } from './state-machine.js';
27
+ import { MAX_TURNS_DETAIL, transition, zeroTurnEvents } from './state-machine.js';
28
28
  import { Session, wireStateDetail } from './session.js';
29
29
  import { BadRequestError, BadStateError, NotFoundError, TooManyRequestsError, } from './errors.js';
30
30
  import { createSendRegistry, sendDigest } from './send-registry.js';
@@ -46,6 +46,7 @@ import { SessionPrStatus } from './pr-status-link.js';
46
46
  import { HerdrLifecycle } from './herdr-lifecycle.js';
47
47
  import { LaunchGate } from './launch-gate.js';
48
48
  import { SessionRestart, resumeUltracodeOf } from './session-restart.js';
49
+ import { inTemporaryDirectory } from './test-session.js';
49
50
  import { SessionTakeBack } from './session-take-back.js';
50
51
  import { applyAgentStateEvent, applyHistoryEvent, applyInitEvent } from './driver-events.js';
51
52
  import { applyUsage } from './context-usage.js';
@@ -248,7 +249,9 @@ class RarogManager {
248
249
  emitSessionChanged: (session) => { this.#emitSessionChanged(session); },
249
250
  });
250
251
  this.#interrupts = new InterruptWindows({
251
- sessions: this.#sessions, now: () => this.#now(), logger: (line) => { this.#config.logger?.(line); },
252
+ sessions: this.#sessions, herdrBlocked: this.#herdrBlocked, now: () => this.#now(),
253
+ logger: (line) => { this.#config.logger?.(line); },
254
+ applyTransition: (session, event) => this.#applyTransition(session, event),
252
255
  });
253
256
  this.#timing = new DialogTimings({ now: () => this.#now(), logger: (line) => { this.#config.logger?.(line); } });
254
257
  this.#claimWindows = new ClaimWindows({
@@ -269,6 +272,7 @@ class RarogManager {
269
272
  this.#conversationLists = {
270
273
  emitSessionChanged: this.#emit.emitSessionChanged, prStatus: this.#prStatus,
271
274
  quiet: (sessionId) => { this.#config.notifier?.quiet(sessionId); },
275
+ stuckWaits: (session, waits) => { this.#config.stalledWait?.stuckWaits(session, waits); },
272
276
  };
273
277
  this.#herdrLifecycle = new HerdrLifecycle(config, {
274
278
  sessions: this.#sessions,
@@ -1682,6 +1686,7 @@ class RarogManager {
1682
1686
  const driver = session.driver;
1683
1687
  if (driver === null)
1684
1688
  throw new BadStateError(HERDR_NO_DRIVER_INTERRUPT_MESSAGE);
1689
+ const fromCard = session.state === 'waiting-permission';
1685
1690
  this.#expirePending(session, true);
1686
1691
  // Karty kanału zgód: przerwanie z telefonu to zwolnienie do terminala, nigdy cyfra.
1687
1692
  this.#consentCards.releaseConsentCards(session);
@@ -1707,7 +1712,7 @@ class RarogManager {
1707
1712
  */
1708
1713
  this.#note(session, { type: 'interrupt-requested' });
1709
1714
  }
1710
- return this.#interrupts.trackInterrupt(id, delivered);
1715
+ return this.#interrupts.trackInterrupt(id, delivered, fromCard ? session.stateSince : null);
1711
1716
  }
1712
1717
  /**
1713
1718
  * „Zamknij" ma DWA znaczenia i to jest jedyne miejsce, w którym się rozchodzą.
@@ -1877,6 +1882,7 @@ class RarogManager {
1877
1882
  * kilkanaście dziennie.
1878
1883
  */
1879
1884
  this.#config.notifier?.forget(session.id);
1885
+ this.#config.stalledWait?.forget(session.id);
1880
1886
  }
1881
1887
  /**
1882
1888
  * Ponowne otwarcie panelu, który zniknął z herdr — TA SAMA karta, nowy panel.
@@ -2423,9 +2429,9 @@ class RarogManager {
2423
2429
  if (!session.emptyStart)
2424
2430
  return;
2425
2431
  session.emptyStart = false;
2426
- this.#applyTransition(session, { type: 'driver-init' });
2427
2432
  // Bez „gotowe”: karta dalej wstaje (`awaitingFirstTurn`), więc to nie koniec tury.
2428
- this.#applyTransition(session, { type: 'result', subtype: 'success' });
2433
+ for (const event of zeroTurnEvents(session.state))
2434
+ this.#applyTransition(session, event);
2429
2435
  // „Tura zerowa" nie jest turą: rachunek wiadomości zostaje niepełny do końca pierwszej
2430
2436
  // prawdziwej.
2431
2437
  session.turnInput = undefined;
@@ -2435,6 +2441,7 @@ class RarogManager {
2435
2441
  if (driver === null)
2436
2442
  return;
2437
2443
  session.driver = null;
2444
+ this.#config.stalledWait?.forget(session.id); // The alarm's tries end with the driver (`stalled-wait.ts`).
2438
2445
  // Przycisk ponownej wysyłki po blokadzie hooka należał do tego drivera (jego pole promptu, jego echo).
2439
2446
  session.promptBlocked = undefined;
2440
2447
  session.turnOpenedBySend = undefined;
@@ -3363,6 +3370,8 @@ class RarogManager {
3363
3370
  ? { afterHerdrRestore: true } : {}),
3364
3371
  // Sesja wstała, żadna tura się nie skończyła: bez „gotowe”.
3365
3372
  ...(started ? { afterStart: true } : {}),
3373
+ // A helper session of another agent (tests, measurements): its "done" is not news.
3374
+ ...(inTemporaryDirectory(session.cwd) ? { testSession: true } : {}),
3366
3375
  // Terminal Raroga pod wpisem (także Claude): baner ma
3367
3376
  // prowadzić tam, gdzie prowadzi wiersz listy, a nie na ekran sesji, którego klient nie pokazuje.
3368
3377
  ...(session.termId === undefined ? {} : { termId: session.termId }),