pi-daddy 0.54.1 → 0.56.0

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 (51) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/kernel/dashboard-choice.d.ts +58 -0
  4. package/dist/kernel/dashboard-choice.d.ts.map +1 -0
  5. package/dist/kernel/dashboard-choice.js +34 -0
  6. package/dist/kernel/dashboard-choice.js.map +1 -0
  7. package/dist/kernel/dashboard-observation.d.ts +2 -0
  8. package/dist/kernel/dashboard-observation.d.ts.map +1 -1
  9. package/dist/kernel/dashboard-observation.js +2 -0
  10. package/dist/kernel/dashboard-observation.js.map +1 -1
  11. package/dist/products/dashboard-choice-picker.d.ts +22 -0
  12. package/dist/products/dashboard-choice-picker.d.ts.map +1 -0
  13. package/dist/products/dashboard-choice-picker.js +219 -0
  14. package/dist/products/dashboard-choice-picker.js.map +1 -0
  15. package/dist/products/dashboard-cli.d.ts.map +1 -1
  16. package/dist/products/dashboard-cli.js +16 -4
  17. package/dist/products/dashboard-cli.js.map +1 -1
  18. package/dist/products/dashboard-components.d.ts +2 -0
  19. package/dist/products/dashboard-components.d.ts.map +1 -1
  20. package/dist/products/dashboard-components.js +55 -3
  21. package/dist/products/dashboard-components.js.map +1 -1
  22. package/dist/products/dashboard-display-controls.d.ts +1 -1
  23. package/dist/products/dashboard-display-controls.d.ts.map +1 -1
  24. package/dist/products/dashboard-display-controls.js +6 -1
  25. package/dist/products/dashboard-display-controls.js.map +1 -1
  26. package/dist/products/dashboard-panels.d.ts.map +1 -1
  27. package/dist/products/dashboard-panels.js +7 -1
  28. package/dist/products/dashboard-panels.js.map +1 -1
  29. package/dist/products/dashboard-screen.d.ts +5 -1
  30. package/dist/products/dashboard-screen.d.ts.map +1 -1
  31. package/dist/products/dashboard-screen.js +18 -6
  32. package/dist/products/dashboard-screen.js.map +1 -1
  33. package/dist/products/dashboard-session-client.d.ts +18 -5
  34. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  35. package/dist/products/dashboard-session-client.js +92 -14
  36. package/dist/products/dashboard-session-client.js.map +1 -1
  37. package/extensions/dashboard-choice-controls.ts +152 -0
  38. package/extensions/dashboard-session-server.ts +92 -17
  39. package/extensions/dashboard-sources.ts +14 -0
  40. package/extensions/runtime-snapshot.ts +1 -0
  41. package/extensions/session.ts +1 -0
  42. package/package.json +1 -1
  43. package/src/kernel/dashboard-choice.ts +73 -0
  44. package/src/kernel/dashboard-observation.ts +4 -0
  45. package/src/products/dashboard-choice-picker.ts +228 -0
  46. package/src/products/dashboard-cli.ts +18 -3
  47. package/src/products/dashboard-components.ts +60 -3
  48. package/src/products/dashboard-display-controls.ts +7 -1
  49. package/src/products/dashboard-panels.ts +6 -0
  50. package/src/products/dashboard-screen.ts +20 -6
  51. package/src/products/dashboard-session-client.ts +129 -19
@@ -5,9 +5,13 @@ import type {
5
5
  DashboardSourceSnapshot,
6
6
  } from "../kernel/dashboard-observation.ts";
7
7
  import type { DashboardItem, DashboardScreenOptions } from "./dashboard-screen.ts";
8
+ import { validChoiceId } from "../kernel/dashboard-choice.ts";
9
+ import { isBookieChoice } from "../kernel/dashboard-observation.ts";
8
10
  import type { EcosystemVersionRow } from "./ecosystem-versions.ts";
9
11
  import { safeDashboardSummary } from "./activity-summary.ts";
10
12
 
13
+ const BOOKIE_LIMIT_MESSAGE = "Only a bounded selection of saved open choices could be displayed.";
14
+
11
15
  type KnownSource = "bookie" | "scout-local" | "scout-worker";
12
16
 
13
17
  export function isComponentObservation(source: DashboardSourceSnapshot, item: DashboardContribution): boolean {
@@ -67,6 +71,52 @@ function scoutDescription(worker: boolean, item: DashboardContribution): [string
67
71
  }
68
72
  }
69
73
 
74
+ /** Choices are current project observations; a saved question never creates a live input request. */
75
+ export function bookieOpenChoices(options: DashboardScreenOptions): DashboardItem[] {
76
+ const source = options.session?.observation?.sources.find((s) => s.producer === "bookie-memory");
77
+ if (
78
+ !options.session?.auto.enabled ||
79
+ !source ||
80
+ !current(source, options) ||
81
+ !source.items.some((i) => isComponentObservation(source, i) && i.state === "observed")
82
+ )
83
+ return [];
84
+ const owner = options.session.observation;
85
+ const canAnswer = owner && options.session.choiceControls?.sourceGeneration === source.generation;
86
+ return source.items
87
+ .filter((i) => isBookieChoice(source.producer, i) && i.kind === "work" && i.state === "observed")
88
+ .map((i) => ({
89
+ key: `source:${source.producer}:${source.generation}:${i.id}`,
90
+ label: i.label,
91
+ status: "open-choice",
92
+ ...(canAnswer && validChoiceId(i.id)
93
+ ? {
94
+ choice: {
95
+ choiceId: i.id,
96
+ sourceGeneration: source.generation,
97
+ expectedOwner: {
98
+ sessionId: owner.sessionId,
99
+ cwd: owner.cwd,
100
+ generation: owner.generation,
101
+ },
102
+ },
103
+ }
104
+ : {}),
105
+ elapsed: "",
106
+ briefDetails: [
107
+ "Saved in this project’s notes.",
108
+ ...(i.details ?? []),
109
+ ...(canAnswer ? [] : ["This Bookie connection offers viewing only."]),
110
+ ],
111
+ details: [
112
+ ...(i.details ?? []),
113
+ `Source: Bookie ${source.producerVersion}`,
114
+ `Observed at: ${source.observedAt}`,
115
+ ...(i.reference ? [`Reference: ${i.reference}`] : []),
116
+ ],
117
+ }));
118
+ }
119
+
70
120
  function componentItem(producer: KnownSource, options: DashboardScreenOptions): DashboardItem | undefined {
71
121
  const bookie = producer === "bookie";
72
122
  const worker = producer === "scout-worker";
@@ -123,18 +173,25 @@ function componentItem(producer: KnownSource, options: DashboardScreenOptions):
123
173
  ? "Check for /bookie-work in the main Pi chat and select a project. Open Versions for installation details."
124
174
  : "Check the loaded Scout extension in the main Pi chat. Research readiness has not been reported.";
125
175
  }
176
+ const sourceDetails = item?.details ?? [];
177
+ const isMemory = source?.producer === "bookie-memory";
178
+ const limited =
179
+ isMemory && state === "observed" && options.session?.auto.enabled && sourceDetails.includes(BOOKIE_LIMIT_MESSAGE);
180
+ const briefDetails = limited
181
+ ? [explanation, "Bookie could only show part of this project’s open choices."]
182
+ : [explanation];
126
183
  return {
127
184
  key: `component:${producer}`,
128
185
  label: `${title} · ${status}`,
129
186
  status: state,
130
187
  elapsed: "",
131
- briefDetails: [explanation],
188
+ briefDetails,
132
189
  details: [
133
- explanation,
190
+ ...briefDetails,
134
191
  ...(source
135
192
  ? [`Source: ${source.producer} · ${source.producerVersion}`, `Last update: ${source.observedAt}`]
136
193
  : []),
137
- ...(item?.details ?? []),
194
+ ...sourceDetails.filter((line) => !isMemory || line !== BOOKIE_LIMIT_MESSAGE),
138
195
  ...(pkg?.installedVersion ? [`Installed version: ${pkg.installedVersion}`] : []),
139
196
  ...(pkg?.loadedVersion ? [`Running version: ${pkg.loadedVersion}`] : []),
140
197
  ],
@@ -1,3 +1,4 @@
1
+ import { openChoice, choiceKey } from "./dashboard-choice-picker.ts";
1
2
  import { DASHBOARD_DESTINATIONS } from "./dashboard-panels.ts";
2
3
  import { DASHBOARD_SETTING_KEYS } from "./dashboard-settings.ts";
3
4
  /** Local display controls; these never dispatch actions to an owner or change ledger state. */
@@ -19,7 +20,11 @@ export function createDashboardDisplayControls(details: boolean, ledger: boolean
19
20
  return {
20
21
  state,
21
22
  screen,
22
- key(key: string): "auto" | "quit" | "command" | "setting" | undefined {
23
+ key(
24
+ key: string,
25
+ text?: string,
26
+ ): "auto" | "quit" | "command" | "setting" | "inspect-choice" | "answer-choice" | undefined {
27
+ if (screen.view === "choice") return choiceKey(screen, key, text);
23
28
  if (key === "?" || key === "r") {
24
29
  const reading = key === "?" ? "help" : "recap";
25
30
  if (screen.view === reading) key = "escape";
@@ -86,6 +91,7 @@ export function createDashboardDisplayControls(details: boolean, ledger: boolean
86
91
  screen.offset = 0;
87
92
  } else if (key === "return" || key === "d") {
88
93
  if (screen.view !== "versions" && (screen.view !== "main" || !screen.selectedKey)) return;
94
+ if (screen.view === "main" && key === "return" && openChoice(screen)) return "inspect-choice";
89
95
  screen.view = screen.view === "versions" ? "version-details" : "details";
90
96
  screen.sourceDetails = false;
91
97
  screen.offset = 0;
@@ -1,9 +1,11 @@
1
1
  /** Six current-session destinations share stable row identities; contributions are labels, never authority. */
2
2
  import type { DashboardContribution, DashboardSourceSnapshot } from "../kernel/dashboard-observation.ts";
3
+ import { isBookieChoice } from "../kernel/dashboard-observation.ts";
3
4
  import type { DashboardItem, DashboardScreenOptions } from "./dashboard-screen.ts";
4
5
  import { dashboardText, friendlyStatus } from "./dashboard-screen.ts";
5
6
  import { activityStoryItems } from "./dashboard-activity.ts";
6
7
  import {
8
+ bookieOpenChoices,
7
9
  componentItems,
8
10
  isComponentObservation,
9
11
  publishedEvidenceItem,
@@ -227,6 +229,7 @@ export function sessionDashboardItems(options: DashboardScreenOptions): Dashboar
227
229
  (item) =>
228
230
  wanted.includes(item.kind) &&
229
231
  !isComponentObservation(source, item) &&
232
+ !isBookieChoice(source.producer, item) &&
230
233
  !(
231
234
  destination === "reviews" &&
232
235
  !options.screen.expanded &&
@@ -292,6 +295,7 @@ export function sessionDashboardItems(options: DashboardScreenOptions): Dashboar
292
295
  ? [row(ownerTurn, `owner:${observed.generation}:${ownerTurn.id}`, "Pi owner", staleOwner)]
293
296
  : []),
294
297
  ...tasks,
298
+ ...bookieOpenChoices(options),
295
299
  ...published,
296
300
  ];
297
301
  items.sort((a, b) => {
@@ -337,6 +341,7 @@ const workGroups = [
337
341
  "Needs your decision",
338
342
  "Needs your input",
339
343
  "In progress",
344
+ "Open choices",
340
345
  "Waiting on a dependency",
341
346
  "Outcome unknown",
342
347
  "Other tasks",
@@ -355,6 +360,7 @@ function workGroup(item: DashboardItem): string {
355
360
  if (item.approval) return "Needs your permission";
356
361
  return item.status === "approval-wait" ? "Needs your decision" : "Needs your input";
357
362
  }
363
+ if (item.status === "open-choice") return "Open choices";
358
364
  if (item.status === "dependency-wait") return "Waiting on a dependency";
359
365
  if (item.status === "incomplete") return "Outcome unknown";
360
366
  if (["running", "active", "starting", "authorised", "cancel-requested"].includes(item.status)) return "In progress";
@@ -1,3 +1,5 @@
1
+ import { choiceBody, choiceKeys, type ChoicePicker } from "./dashboard-choice-picker.ts";
2
+ import type { DashboardChoiceTarget } from "../kernel/dashboard-choice.ts";
1
3
  import type { DashboardAcknowledgment } from "./dashboard-session-client.ts";
2
4
  import {
3
5
  needsUserInput,
@@ -32,12 +34,14 @@ export interface DashboardItem {
32
34
  observation?: string;
33
35
  taskKey?: string;
34
36
  timelinePath?: string;
37
+ choice?: DashboardChoiceTarget;
35
38
  approval?: boolean;
36
39
  skills?: boolean;
37
40
  agent?: boolean;
38
41
  }
39
42
  export interface DashboardScreenState {
40
- view: "main" | "details" | "models" | "help" | "versions" | "version-details" | "settings" | "recap";
43
+ view: "main" | "details" | "models" | "help" | "versions" | "version-details" | "settings" | "recap" | "choice";
44
+ picker?: ChoicePicker;
41
45
  destination?: DashboardDestination;
42
46
  expanded?: boolean;
43
47
  sourceDetails?: boolean;
@@ -100,6 +104,7 @@ export const friendlyStatus = (status: string) =>
100
104
  starting: "Starting",
101
105
  authorised: "Authorized",
102
106
  observed: "Reported",
107
+ "open-choice": "Open",
103
108
  "cancel-requested": "Cancel requested",
104
109
  unknown: "Unknown",
105
110
  unavailable: "Unavailable",
@@ -226,6 +231,7 @@ function sessionLocation(screen: DashboardScreenState, width: number): string {
226
231
  versions: "Versions",
227
232
  "version-details": "Version details",
228
233
  recap: "Session recap",
234
+ choice: "Answer choice",
229
235
  };
230
236
  const name = destinationNames[destination];
231
237
  if (screen.view in overlays) return `${name} / ${overlays[screen.view as keyof typeof overlays]}`;
@@ -240,7 +246,9 @@ function sessionLocation(screen: DashboardScreenState, width: number): string {
240
246
  function sessionKeys(screen: DashboardScreenState, selected: DashboardItem | undefined, width: number): string[] {
241
247
  const view = screen.view;
242
248
  const brief = width < 34;
249
+ if (view === "choice") return choiceKeys(screen);
243
250
  if (view === "main") {
251
+ if (selected?.choice) return ["↑↓ select · Enter answer", "d details · q close"];
244
252
  const keys = selected ? (brief ? "↑↓ · Enter details" : "↑↓ select · Enter details") : "1–6 views";
245
253
  return [keys + (brief ? " · ?" : " · ? help"), "r recap · q close"];
246
254
  }
@@ -314,7 +322,7 @@ export function renderDashboardScreen(options: DashboardScreenOptions): string {
314
322
  }
315
323
  if (
316
324
  !screen.items.some((item) => item.key === screen.selectedKey) &&
317
- !(screen.view === "details" && screen.selectedKey)
325
+ !((screen.view === "details" || screen.view === "choice") && screen.selectedKey)
318
326
  )
319
327
  screen.selectedKey = screen.items[0]?.key;
320
328
  const selectedIndex = screen.items.findIndex((item) => item.key === screen.selectedKey),
@@ -325,6 +333,7 @@ export function renderDashboardScreen(options: DashboardScreenOptions): string {
325
333
  const mode =
326
334
  session && options.connected !== false ? `Auto ${session.auto.enabled ? "ON" : "OFF"}` : "Auto unavailable";
327
335
  const header = `PI DADDY | ${mode}${options.pending ? " …" : session && options.connected !== false ? " [a]" : ""}`;
336
+ const choiceLines = screen.view === "choice" ? choiceBody(screen) : [];
328
337
  const footer =
329
338
  options.command !== undefined
330
339
  ? [`: ${clean(options.command)}`]
@@ -354,8 +363,9 @@ export function renderDashboardScreen(options: DashboardScreenOptions): string {
354
363
  fixed.push("Disconnected · showing last known status");
355
364
  if (screen.view === "main" && (screen.destination ?? "now") === "now")
356
365
  fixed.push(...wrapDashboardLines(["In the current Pi chat, run /grants dashboard."], width));
357
- } else if (options.notice || options.problem) fixed.push(`! ${clean(options.notice || options.problem || "")}`);
358
- const ack = options.acknowledgment;
366
+ } else if (screen.view !== "choice" && (options.notice || options.problem))
367
+ fixed.push(`! ${clean(options.notice || options.problem || "")}`);
368
+ const ack = options.acknowledgment?.action === "answer-choice" ? undefined : options.acknowledgment;
359
369
  if (ack?.state === "unconfirmed") {
360
370
  const setting =
361
371
  (
@@ -392,7 +402,8 @@ export function renderDashboardScreen(options: DashboardScreenOptions): string {
392
402
  if (options.height >= 22) fixed.push("");
393
403
  }
394
404
  const body: string[] = [];
395
- if (screen.view === "recap") {
405
+ if (screen.view === "choice") body.push(...choiceLines);
406
+ else if (screen.view === "recap") {
396
407
  const recap = sessionRecapLines(options);
397
408
  const activity = recap.findIndex(
398
409
  (line) => line === "Recent activity · newest first" || line === "No recent session events recorded.",
@@ -408,6 +419,7 @@ export function renderDashboardScreen(options: DashboardScreenOptions): string {
408
419
  body.push(
409
420
  "DASHBOARD KEYS",
410
421
  "↑/↓ or j/k: select; Enter/d: details",
422
+ "Enter on an open choice: answer in Bookie when available. d: details",
411
423
  "a: toggle Daddy permission Auto",
412
424
  "m: session models; v: ecosystem versions; s: settings",
413
425
  "1 Overview · what needs you and what Pi is doing",
@@ -596,11 +608,13 @@ export function renderDashboardScreen(options: DashboardScreenOptions): string {
596
608
  screen.offset = Math.max(0, Math.min(row, Math.max(screen.offset, last - room + 1)));
597
609
  }
598
610
  }
599
- if (modern && screen.view === "main" && room > 0 && !screen.manualScroll) {
611
+ if (modern && (screen.view === "main" || screen.view === "choice") && room > 0 && !screen.manualScroll) {
600
612
  const selectedRow = detailBody.findIndex((line) => line.startsWith(">"));
601
613
  if (selectedRow >= screen.offset + room) screen.offset = selectedRow - room + 1;
602
614
  else if (selectedRow >= 0 && selectedRow < screen.offset) screen.offset = selectedRow;
603
615
  }
616
+ if (screen.view === "choice" && screen.picker?.phase === "custom" && !screen.manualScroll && !screen.picker.error)
617
+ screen.offset = Math.max(0, detailBody.length - room);
604
618
  const offset =
605
619
  screen.view === "main" && !modern ? 0 : Math.max(0, Math.min(screen.offset, Math.max(0, detailBody.length - room)));
606
620
  screen.offset = offset;
@@ -1,3 +1,9 @@
1
+ import {
2
+ validChoiceDetail,
3
+ type DashboardChoiceAction,
4
+ type DashboardChoiceDetail,
5
+ type DashboardChoiceTarget,
6
+ } from "../kernel/dashboard-choice.ts";
1
7
  import type { DashboardOwnerObservation } from "../kernel/dashboard-observation.ts";
2
8
  import type { DashboardSettingsSnapshot, JevEditAction } from "./dashboard-settings.ts";
3
9
  import type { EcosystemVersions } from "./ecosystem-versions.ts";
@@ -6,6 +12,7 @@ import { createConnection } from "node:net";
6
12
  export interface DashboardSessionSnapshot {
7
13
  rows: Array<{ definition: string; model: string; thinking: string; source: string }>;
8
14
  cost: number | null;
15
+ choiceControls?: { sourceGeneration: string };
9
16
  observation?: DashboardOwnerObservation;
10
17
  activity?: { rootId: string; path: string; taskId: string };
11
18
  versions?: EcosystemVersions;
@@ -14,8 +21,25 @@ export interface DashboardSessionSnapshot {
14
21
  pendingApprovals: Array<{ id: string; subject: string; capability: string }>;
15
22
  }
16
23
 
24
+ interface DashboardSessionReply extends DashboardSessionSnapshot {
25
+ choiceDetail?: DashboardChoiceDetail;
26
+ choiceSaved?: true;
27
+ choiceRefreshRequested?: true;
28
+ }
29
+ class ChoiceDeclined extends Error {
30
+ readonly stale: boolean;
31
+ constructor(stale: boolean) {
32
+ super(
33
+ stale
34
+ ? "Choice is no longer available. Refresh and reopen it."
35
+ : "Bookie declined the answer. Refresh and check the choice and answer.",
36
+ );
37
+ this.stale = stale;
38
+ }
39
+ }
17
40
  export type DashboardSessionAction = (
18
- | { action: "get" }
41
+ | DashboardChoiceAction
42
+ | { action: "get"; refreshChoices?: true }
19
43
  | { action: "set"; edits: string }
20
44
  | { action: "set-auto"; enabled: boolean }
21
45
  | { action: "set-jev"; enabled: boolean }
@@ -27,12 +51,15 @@ export async function dashboardSessionRequest(
27
51
  socketPath: string,
28
52
  token: string,
29
53
  request: DashboardSessionAction,
30
- ): Promise<DashboardSessionSnapshot> {
54
+ ): Promise<DashboardSessionReply> {
31
55
  return new Promise((resolve, reject) => {
32
56
  const socket = createConnection(socketPath);
33
57
  let output = "";
34
58
  socket.setEncoding("utf8");
35
- socket.setTimeout(2_000, () => socket.destroy(new Error("dashboard session request timed out")));
59
+ const choiceAction = request.action === "inspect-choice" || request.action === "answer-choice";
60
+ socket.setTimeout(choiceAction ? 30_000 : 2_000, () =>
61
+ socket.destroy(new Error("dashboard session request timed out")),
62
+ );
36
63
  socket.once("error", reject);
37
64
  socket.on("data", (chunk) => {
38
65
  output += chunk;
@@ -40,8 +67,26 @@ export async function dashboardSessionRequest(
40
67
  });
41
68
  socket.once("end", () => {
42
69
  try {
43
- const parsed = JSON.parse(output) as DashboardSessionSnapshot & { ok?: boolean; error?: string };
44
- if (!parsed.ok) throw new Error(parsed.error ?? "dashboard session request failed");
70
+ const parsed = JSON.parse(output) as DashboardSessionReply & {
71
+ ok?: boolean;
72
+ error?: string;
73
+ choiceOutcome?: string;
74
+ };
75
+ if (!parsed.ok) {
76
+ if (choiceAction) {
77
+ if (parsed.choiceOutcome === "stale" || parsed.choiceOutcome === "refused")
78
+ throw new ChoiceDeclined(parsed.choiceOutcome === "stale");
79
+ throw Error("The owner could not confirm the choice request.");
80
+ }
81
+ throw new Error(parsed.error ?? "dashboard session request failed");
82
+ }
83
+ if (
84
+ request.action === "inspect-choice" &&
85
+ (!validChoiceDetail(parsed.choiceDetail) || parsed.choiceDetail.id !== request.choiceId)
86
+ )
87
+ throw Error("The owner returned an unavailable choice.");
88
+ if (request.action === "answer-choice" && parsed.choiceSaved !== true)
89
+ throw Error("Bookie did not confirm the answer.");
45
90
  if (
46
91
  !parsed.auto ||
47
92
  typeof parsed.auto.enabled !== "boolean" ||
@@ -67,7 +112,7 @@ export type DashboardAcknowledgment = {
67
112
 
68
113
  /** Controls use only a connected owner; last observations remain explicitly disconnected evidence. */
69
114
  export function createDashboardConnection(
70
- request?: (action: DashboardSessionAction) => Promise<DashboardSessionSnapshot>,
115
+ request?: (action: DashboardSessionAction) => Promise<DashboardSessionReply>,
71
116
  ) {
72
117
  const state: {
73
118
  snapshot?: DashboardSessionSnapshot;
@@ -79,6 +124,8 @@ export function createDashboardConnection(
79
124
  let generation = 0,
80
125
  poll = 0,
81
126
  requestedJev: boolean | undefined;
127
+ let choiceInterest = 0,
128
+ consumedInterest = 0;
82
129
  const retired = new Set<string>();
83
130
  const accept = (snapshot: DashboardSessionSnapshot) => {
84
131
  const previous = state.lastObserved?.observation,
@@ -102,14 +149,55 @@ export function createDashboardConnection(
102
149
  state.acknowledgment.state = snapshot.settings.jev.enabled === requestedJev ? "applied" : "refused";
103
150
  return true;
104
151
  };
152
+ const matchesOwner = (snapshot: DashboardSessionSnapshot | undefined, target: DashboardChoiceTarget) => {
153
+ const owner = snapshot?.observation,
154
+ expected = target.expectedOwner;
155
+ return (
156
+ !!owner &&
157
+ owner.sessionId === expected.sessionId &&
158
+ owner.cwd === expected.cwd &&
159
+ owner.generation === expected.generation
160
+ );
161
+ };
162
+ const matches = (snapshot: DashboardSessionSnapshot | undefined, target: DashboardChoiceTarget) => {
163
+ const source = snapshot?.observation?.sources.find(
164
+ (s) => s.producer === "bookie-memory" && s.generation === target.sourceGeneration,
165
+ );
166
+ return (
167
+ matchesOwner(snapshot, target) &&
168
+ snapshot?.choiceControls?.sourceGeneration === target.sourceGeneration &&
169
+ source?.availability === "observed" &&
170
+ source.items.some((i) => i.id === target.choiceId && i.kind === "work" && i.state === "observed")
171
+ );
172
+ };
105
173
  return {
106
174
  state,
107
- async refresh() {
175
+ async inspectChoice(target: DashboardChoiceTarget): Promise<DashboardChoiceDetail> {
176
+ if (!request || state.pending || !matches(state.snapshot, target)) throw new ChoiceDeclined(true);
177
+ const result = await request({ ...target, action: "inspect-choice" });
178
+ if (
179
+ !matches(state.snapshot, target) ||
180
+ !matches(result, target) ||
181
+ !validChoiceDetail(result.choiceDetail) ||
182
+ result.choiceDetail.id !== target.choiceId
183
+ )
184
+ throw new ChoiceDeclined(true);
185
+ return result.choiceDetail;
186
+ },
187
+ requestChoiceRefresh() {
188
+ choiceInterest++;
189
+ },
190
+ async refresh(visibleChoices?: "picker" | "list") {
108
191
  if (!request || state.pending) return;
109
192
  const observed = generation,
110
193
  order = ++poll;
111
194
  try {
112
- const snapshot = await request({ action: "get" });
195
+ const interest = choiceInterest;
196
+ const wanted = visibleChoices === "picker" || (visibleChoices === "list" && interest !== consumedInterest);
197
+ const { choiceRefreshRequested, ...snapshot } = await request(
198
+ wanted ? { action: "get", refreshChoices: true } : { action: "get" },
199
+ );
200
+ if (choiceRefreshRequested) consumedInterest = Math.max(consumedInterest, interest);
113
201
  if (generation === observed && order === poll && !accept(snapshot)) {
114
202
  state.snapshot = undefined;
115
203
  state.error = "Owner observation is stale or unavailable; controls disabled until a fresh reply.";
@@ -121,25 +209,35 @@ export function createDashboardConnection(
121
209
  }
122
210
  }
123
211
  },
124
- async change(action: Exclude<DashboardSessionAction, { action: "get" }>) {
212
+ async change(action: Exclude<DashboardSessionAction, { action: "get" | "inspect-choice" }>) {
125
213
  if (!request || !state.snapshot || state.pending) return false;
214
+ if (action.action === "answer-choice" && !matches(state.snapshot, action)) {
215
+ state.acknowledgment = {
216
+ action: action.action,
217
+ state: "refused",
218
+ effect: "Choice changed. Refresh and reopen it.",
219
+ };
220
+ return false;
221
+ }
126
222
  const observedOwner = state.snapshot.observation;
127
223
  generation++;
128
224
  state.pending = true;
129
225
  requestedJev = action.action === "set-jev" ? action.enabled : undefined;
130
226
  const effect =
131
- action.action === "set-auto"
132
- ? "current permission handling; admitted work unchanged"
133
- : action.action === "edit-jev"
134
- ? "use the main Pi session; current values shown below"
135
- : action.action === "set-jev"
136
- ? "current JEV session; separate paid-call and storage choices"
137
- : "future children; running children unchanged";
227
+ action.action === "answer-choice"
228
+ ? "Save this answer in project memory"
229
+ : action.action === "set-auto"
230
+ ? "current permission handling; admitted work unchanged"
231
+ : action.action === "edit-jev"
232
+ ? "use the main Pi session; current values shown below"
233
+ : action.action === "set-jev"
234
+ ? "current JEV session; separate paid-call and storage choices"
235
+ : "future children; running children unchanged";
138
236
  state.acknowledgment = { action: action.action, state: "pending", effect };
139
237
  try {
140
238
  const snapshot = await request({
141
239
  ...action,
142
- ...(observedOwner
240
+ ...(observedOwner && !action.expectedOwner
143
241
  ? {
144
242
  expectedOwner: {
145
243
  sessionId: observedOwner.sessionId,
@@ -149,7 +247,10 @@ export function createDashboardConnection(
149
247
  }
150
248
  : {}),
151
249
  });
152
- if (!accept(snapshot)) throw Error("owner acknowledgment is stale; reconcile before another action");
250
+ if (action.action === "answer-choice" && (snapshot.choiceSaved !== true || !matchesOwner(snapshot, action)))
251
+ throw Error("Bookie did not confirm the answer.");
252
+ const { choiceDetail: _detail, choiceSaved: _saved, ...observed } = snapshot;
253
+ if (!accept(observed)) throw Error("owner acknowledgment is stale; reconcile before another action");
153
254
  state.acknowledgment.state =
154
255
  action.action === "edit-jev"
155
256
  ? "opened"
@@ -162,9 +263,18 @@ export function createDashboardConnection(
162
263
  : "applied";
163
264
  return true;
164
265
  } catch (error) {
266
+ if (action.action === "answer-choice" && error instanceof ChoiceDeclined) {
267
+ if (error.stale) state.snapshot = undefined;
268
+ state.acknowledgment.state = "refused";
269
+ state.error = error.message;
270
+ return false;
271
+ }
165
272
  state.snapshot = undefined;
166
273
  state.acknowledgment.state = "unconfirmed";
167
- state.error = `Control change not confirmed; inspect owner before retrying: ${error instanceof Error ? error.message : String(error)}`;
274
+ state.error =
275
+ action.action === "answer-choice"
276
+ ? "Save unconfirmed. Check project memory before retrying."
277
+ : `Control change not confirmed; inspect owner before retrying: ${error instanceof Error ? error.message : String(error)}`;
168
278
  return false;
169
279
  } finally {
170
280
  state.pending = false;