@microvac/plugin-decisions-native 0.0.0-stage → 0.1.0-rc.17

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.
package/lib/client.js ADDED
@@ -0,0 +1,808 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@microvac/plugin-decisions-native",
3
+ factory: (require) => {
4
+ require("@microvac/ui").requireVersion("^1.1.0", "@microvac/plugin-decisions-native");
5
+ const module = { exports: {} };
6
+ const exports = module.exports;
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name2 in all)
14
+ __defProp(target, name2, { get: all[name2], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/client.tsx
27
+ var client_exports = {};
28
+ __export(client_exports, {
29
+ AnswerFirstInteractionCard: () => AnswerFirstInteractionCard,
30
+ apply: () => apply,
31
+ inject: () => inject,
32
+ name: () => name
33
+ });
34
+ module.exports = __toCommonJS(client_exports);
35
+ var import_react5 = require("react");
36
+ var import_ui3 = require("@microvac/ui");
37
+
38
+ // src/fold.ts
39
+ var import_react = require("react");
40
+ var FOLD_ATTRIBUTE = "data-microvac-fold";
41
+ var FOLD_TOGGLE_ATTRIBUTE = "data-microvac-fold-toggle";
42
+ var QUESTION_SELECTOR = "[data-decision-prompt], [data-decision-note], [data-needs-you-panel]";
43
+ var CONTROL_SELECTOR = "input, textarea, select, [role='radio'], [role='checkbox'], [role='radiogroup'], [role='textbox']";
44
+ var TOGGLE_CLASS = "block text-xs text-muted-foreground underline-offset-2 hover:underline";
45
+ var STYLE_ID = "microvac-decisions-fold";
46
+ var FOLD_CSS = `
47
+ [${FOLD_ATTRIBUTE}="folded"], [${FOLD_ATTRIBUTE}="overflow"] { max-height: 4lh; overflow: hidden; }
48
+ [data-needs-you-panel][${FOLD_ATTRIBUTE}="folded"], [data-needs-you-panel][${FOLD_ATTRIBUTE}="overflow"] { max-height: calc(4lh + 1.5rem); }
49
+ [${FOLD_ATTRIBUTE}="overflow"] { mask-image: linear-gradient(to bottom, #000 55%, transparent); }
50
+ `;
51
+ function questions(container) {
52
+ const found = [...container.querySelectorAll(QUESTION_SELECTOR)];
53
+ return found.filter((element) => {
54
+ if (element.matches("[data-needs-you-panel]") && element.querySelector(CONTROL_SELECTOR)) return false;
55
+ return !found.some((other) => other !== element && other.contains(element));
56
+ });
57
+ }
58
+ function setAttribute(element, name2, value) {
59
+ if (element.getAttribute(name2) !== value) element.setAttribute(name2, value);
60
+ }
61
+ function setText(element, text) {
62
+ if (element.textContent !== text) element.textContent = text;
63
+ }
64
+ function isToggle(element) {
65
+ return Boolean(element?.hasAttribute(FOLD_TOGGLE_ATTRIBUTE));
66
+ }
67
+ function onToggle(event) {
68
+ const toggle = event.currentTarget;
69
+ const question = toggle.previousElementSibling;
70
+ if (!question?.hasAttribute(FOLD_ATTRIBUTE)) return;
71
+ const expanded = question.getAttribute(FOLD_ATTRIBUTE) === "expanded";
72
+ question.setAttribute(FOLD_ATTRIBUTE, expanded ? "overflow" : "expanded");
73
+ syncToggle(toggle, !expanded);
74
+ }
75
+ function syncToggle(toggle, expanded) {
76
+ setText(toggle, expanded ? "Show less" : "Show more");
77
+ setAttribute(toggle, "aria-expanded", String(expanded));
78
+ }
79
+ function createToggle(document) {
80
+ const toggle = document.createElement("button");
81
+ toggle.type = "button";
82
+ toggle.className = TOGGLE_CLASS;
83
+ toggle.setAttribute(FOLD_TOGGLE_ATTRIBUTE, "");
84
+ toggle.addEventListener("click", onToggle);
85
+ return toggle;
86
+ }
87
+ function foldLongQuestions(container) {
88
+ const kept = /* @__PURE__ */ new Set();
89
+ for (const question of questions(container)) {
90
+ let state = question.getAttribute(FOLD_ATTRIBUTE);
91
+ if (state !== "folded" && state !== "overflow" && state !== "expanded") {
92
+ state = "folded";
93
+ question.setAttribute(FOLD_ATTRIBUTE, state);
94
+ }
95
+ if (state !== "expanded") {
96
+ state = question.scrollHeight > question.clientHeight + 1 ? "overflow" : "folded";
97
+ setAttribute(question, FOLD_ATTRIBUTE, state);
98
+ }
99
+ if (state === "folded") continue;
100
+ const next = question.nextElementSibling;
101
+ let toggle;
102
+ if (isToggle(next)) {
103
+ toggle = next;
104
+ } else {
105
+ toggle = createToggle(question.ownerDocument);
106
+ question.after(toggle);
107
+ }
108
+ syncToggle(toggle, state === "expanded");
109
+ kept.add(toggle);
110
+ }
111
+ for (const toggle of container.querySelectorAll(`[${FOLD_TOGGLE_ATTRIBUTE}]`)) {
112
+ if (!kept.has(toggle)) toggle.remove();
113
+ }
114
+ }
115
+ function ensureFoldStyle(document) {
116
+ if (document.getElementById(STYLE_ID)) return;
117
+ const style = document.createElement("style");
118
+ style.id = STYLE_ID;
119
+ style.textContent = FOLD_CSS;
120
+ document.head.appendChild(style);
121
+ }
122
+ function useQuestionFold(ref, active = true) {
123
+ (0, import_react.useEffect)(() => {
124
+ const root = ref.current;
125
+ if (!root || !active) return;
126
+ ensureFoldStyle(root.ownerDocument);
127
+ const fold = () => foldLongQuestions(root);
128
+ fold();
129
+ const mutations = typeof MutationObserver === "undefined" ? null : new MutationObserver(fold);
130
+ mutations?.observe(root, { childList: true, subtree: true, characterData: true });
131
+ const resizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(fold);
132
+ resizes?.observe(root);
133
+ return () => {
134
+ mutations?.disconnect();
135
+ resizes?.disconnect();
136
+ };
137
+ }, [ref, active]);
138
+ }
139
+
140
+ // src/page.tsx
141
+ var import_react4 = require("react");
142
+ var import_ui2 = require("@microvac/ui");
143
+
144
+ // src/keyboard.ts
145
+ var SHORTCUT_HELP = Object.freeze([
146
+ { keys: ["1", "\u2026", "9"], label: "Pick an option" },
147
+ { keys: ["Enter"], label: "Send the answer" },
148
+ { keys: ["J"], label: "Next card" },
149
+ { keys: ["K"], label: "Previous card" },
150
+ { keys: ["S"], label: "Snooze the card" },
151
+ { keys: ["?"], label: "Show or hide this help" }
152
+ ]);
153
+ var TEXT_INPUT_TYPES = /* @__PURE__ */ new Set(["text", "search", "email", "url", "tel", "password", "number", "date", "datetime-local", "time", "month", "week"]);
154
+ function isTextEntryTarget(target) {
155
+ if (!target || typeof target.closest !== "function") return false;
156
+ const element = target;
157
+ if (element.isContentEditable || element.closest("[contenteditable=''], [contenteditable='true']")) return true;
158
+ const tag = element.tagName;
159
+ if (tag === "TEXTAREA" || tag === "SELECT") return true;
160
+ if (tag === "INPUT") return TEXT_INPUT_TYPES.has((element.type || "text").toLowerCase());
161
+ return element.getAttribute("role") === "textbox" || element.getAttribute("role") === "combobox";
162
+ }
163
+ function decisionShortcut(event) {
164
+ if (event.altKey || event.ctrlKey || event.metaKey || event.isComposing) return null;
165
+ if (isTextEntryTarget(event.target)) return null;
166
+ const key = event.key;
167
+ if (key.length === 1 && key >= "1" && key <= "9") return { kind: "option", index: Number(key) - 1 };
168
+ switch (key) {
169
+ case "Enter": {
170
+ const tag = event.target?.tagName;
171
+ if (tag === "BUTTON" || tag === "A") return null;
172
+ return { kind: "send" };
173
+ }
174
+ case "j":
175
+ case "J":
176
+ return { kind: "next" };
177
+ case "k":
178
+ case "K":
179
+ return { kind: "previous" };
180
+ case "s":
181
+ case "S":
182
+ return { kind: "snooze" };
183
+ case "?":
184
+ return { kind: "help" };
185
+ case "Escape":
186
+ return { kind: "close-help" };
187
+ default:
188
+ return null;
189
+ }
190
+ }
191
+ function isTouchDevice() {
192
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
193
+ return window.matchMedia("(pointer: coarse)").matches && !window.matchMedia("(any-pointer: fine)").matches;
194
+ }
195
+ var OPTION_SELECTOR = "[role='radio'], [role='checkbox'], input[type='radio'], input[type='checkbox']";
196
+ var BUTTON_SELECTOR = "button[data-slot='button']";
197
+ var KBD_HINT_ATTRIBUTE = "data-microvac-kbd";
198
+ function enabled(element) {
199
+ return !element.disabled && element.getAttribute("aria-disabled") !== "true";
200
+ }
201
+ function answerOptions(container) {
202
+ return [...container.querySelectorAll(OPTION_SELECTOR)].filter(enabled);
203
+ }
204
+ function sendButton(container) {
205
+ const primaries = [...container.querySelectorAll(`${BUTTON_SELECTOR}[data-variant='default']`)];
206
+ return primaries.length > 0 ? primaries[primaries.length - 1] : null;
207
+ }
208
+ function markKeyHints(container, show) {
209
+ const wanted = /* @__PURE__ */ new Map();
210
+ if (show) {
211
+ answerOptions(container).slice(0, 9).forEach((option, index) => wanted.set(option, String(index + 1)));
212
+ const send = sendButton(container);
213
+ if (send && !wanted.has(send)) wanted.set(send, "\u21B5");
214
+ }
215
+ for (const element of container.querySelectorAll(`[${KBD_HINT_ATTRIBUTE}]`)) {
216
+ if (!wanted.has(element)) element.removeAttribute(KBD_HINT_ATTRIBUTE);
217
+ }
218
+ for (const [element, hint] of wanted) {
219
+ if (element.getAttribute(KBD_HINT_ATTRIBUTE) !== hint) element.setAttribute(KBD_HINT_ATTRIBUTE, hint);
220
+ }
221
+ }
222
+
223
+ // src/model.ts
224
+ var DECISION_SOURCE_KINDS = Object.freeze([
225
+ "issue_thread_interaction",
226
+ "decision",
227
+ "approval",
228
+ "budget_alert",
229
+ "join_request"
230
+ ]);
231
+ var DECISION_FEED_VIEWS = ["mine", "unassigned", "company"];
232
+ function decisionKey(item) {
233
+ return `${item.sourceKind}:${item.subject.id}`;
234
+ }
235
+ function parseCardParam(value) {
236
+ if (!value) return null;
237
+ const at = value.indexOf(":");
238
+ return at > 0 && at < value.length - 1 ? value : null;
239
+ }
240
+ function time(value) {
241
+ if (!value) return 0;
242
+ const parsed = Date.parse(value);
243
+ return Number.isFinite(parsed) ? parsed : 0;
244
+ }
245
+ function isDecisionItem(item) {
246
+ return DECISION_SOURCE_KINDS.includes(item.sourceKind);
247
+ }
248
+ function isAutomatic(item) {
249
+ return Boolean(item.providerLimit && item.providerLimit.state !== "needs_retry");
250
+ }
251
+ function toDecision(item, marker, now) {
252
+ if (!isDecisionItem(item) || item.archivedAt || isAutomatic(item)) return null;
253
+ let snoozedUntil = null;
254
+ let snoozeSource = null;
255
+ if (item.snoozedUntil && time(item.snoozedUntil) > now) {
256
+ snoozedUntil = item.snoozedUntil;
257
+ snoozeSource = "triage";
258
+ }
259
+ const dismissal = item.dismissal;
260
+ if (dismissal?.isActive) {
261
+ if (dismissal.kind !== "snooze") return null;
262
+ if (!snoozedUntil && dismissal.snoozedUntil && time(dismissal.snoozedUntil) > now) {
263
+ snoozedUntil = dismissal.snoozedUntil;
264
+ snoozeSource = "inbox";
265
+ }
266
+ }
267
+ return { key: decisionKey(item), item, marker, snoozedUntil, snoozeSource };
268
+ }
269
+ function collectDecisions(feeds, now, fold = (items) => ({ cards: [...items] })) {
270
+ const byKey = /* @__PURE__ */ new Map();
271
+ for (const view of DECISION_FEED_VIEWS) {
272
+ const items = feeds[view];
273
+ if (!items) continue;
274
+ const marker = view === "mine" ? "for-you" : "anyone";
275
+ for (const item of fold(items).cards) {
276
+ const decision = toDecision(item, marker, now);
277
+ if (!decision || byKey.has(decision.key)) continue;
278
+ byKey.set(decision.key, decision);
279
+ }
280
+ }
281
+ const open = [];
282
+ const snoozed = [];
283
+ for (const decision of byKey.values()) (decision.snoozedUntil ? snoozed : open).push(decision);
284
+ snoozed.sort((a, b) => time(a.snoozedUntil) - time(b.snoozedUntil) || a.key.localeCompare(b.key));
285
+ return { open, snoozed };
286
+ }
287
+ var INTERACTION_TYPE_LABELS = {
288
+ ask_user_questions: "Question",
289
+ request_confirmation: "Confirmation",
290
+ request_checkbox_confirmation: "Confirmation",
291
+ request_item_verdicts: "Verdicts",
292
+ suggest_tasks: "Suggested tasks",
293
+ connection_intent: "Connection"
294
+ };
295
+ var APPROVAL_TYPE_LABELS = {
296
+ hire_agent: "Hire",
297
+ budget_override_required: "Budget"
298
+ };
299
+ function decisionTypeLabel(item) {
300
+ switch (item.sourceKind) {
301
+ case "issue_thread_interaction": {
302
+ if (item.detail?.kind === "plan_approval") return "Plan review";
303
+ const kind = item.subject.metadata?.kind;
304
+ return typeof kind === "string" && INTERACTION_TYPE_LABELS[kind] || "Question";
305
+ }
306
+ case "decision":
307
+ return "Choice";
308
+ case "approval": {
309
+ const type = item.detail?.kind === "approval" ? item.detail.approvalType : item.subject.metadata?.type;
310
+ return typeof type === "string" && APPROVAL_TYPE_LABELS[type] || "Approval";
311
+ }
312
+ case "budget_alert":
313
+ return "Budget";
314
+ case "join_request":
315
+ return "Join request";
316
+ default:
317
+ return "Decision";
318
+ }
319
+ }
320
+ function decisionAgentName(item) {
321
+ const name2 = item.originAgentName ?? item.requester?.name ?? null;
322
+ return name2 && name2.trim() ? name2.trim() : null;
323
+ }
324
+ var DECISION_GROUPINGS = ["project", "type", "agent", "none"];
325
+ var DEFAULT_GROUPING = "project";
326
+ var DECISION_SORTS = ["oldest", "newest"];
327
+ var DEFAULT_SORT = "oldest";
328
+ var GROUPING_LABELS = {
329
+ project: "Project",
330
+ type: "Type",
331
+ agent: "Agent",
332
+ none: "None"
333
+ };
334
+ var NO_GROUP_KEY = "__none__";
335
+ var NO_PROJECT_LABEL = "No project";
336
+ var NO_AGENT_LABEL = "No agent";
337
+ function decisionAskedAt(decision) {
338
+ return decision.item.createdAt || decision.item.activityAt;
339
+ }
340
+ function sortDecisions(decisions3, order) {
341
+ const direction = order === "oldest" ? 1 : -1;
342
+ return [...decisions3].sort(
343
+ (a, b) => direction * (time(decisionAskedAt(a)) - time(decisionAskedAt(b))) || a.key.localeCompare(b.key)
344
+ );
345
+ }
346
+ function groupOf(decision, grouping) {
347
+ const { item } = decision;
348
+ switch (grouping) {
349
+ case "project":
350
+ return item.project ? { key: item.project.id, label: item.project.name, project: item.project } : { key: NO_GROUP_KEY, label: NO_PROJECT_LABEL, project: null };
351
+ case "type": {
352
+ const label = decisionTypeLabel(item);
353
+ return { key: label, label, project: null };
354
+ }
355
+ case "agent": {
356
+ const name2 = decisionAgentName(item);
357
+ return name2 ? { key: name2, label: name2, project: null } : { key: NO_GROUP_KEY, label: NO_AGENT_LABEL, project: null };
358
+ }
359
+ default:
360
+ return { key: NO_GROUP_KEY, label: "", project: null };
361
+ }
362
+ }
363
+ function groupDecisions(decisions3, grouping, order) {
364
+ const groups = /* @__PURE__ */ new Map();
365
+ for (const decision of sortDecisions(decisions3, order)) {
366
+ const head = groupOf(decision, grouping);
367
+ let group = groups.get(head.key);
368
+ if (!group) {
369
+ group = { ...head, decisions: [] };
370
+ groups.set(head.key, group);
371
+ }
372
+ group.decisions.push(decision);
373
+ }
374
+ const list = [...groups.values()];
375
+ if (grouping === "none") return list;
376
+ const rest = list.filter((group) => group.key !== NO_GROUP_KEY);
377
+ const missing = list.find((group) => group.key === NO_GROUP_KEY);
378
+ return missing ? [...rest, missing] : rest;
379
+ }
380
+ function displayOrder(groups) {
381
+ return groups.flatMap((group) => group.decisions);
382
+ }
383
+ function nextOpenKey(previousOrder, answeredKey, remaining) {
384
+ const left = new Set(remaining);
385
+ const at = previousOrder.indexOf(answeredKey);
386
+ if (at >= 0) {
387
+ for (let index = at + 1; index < previousOrder.length; index++) if (left.has(previousOrder[index])) return previousOrder[index];
388
+ for (let index = at - 1; index >= 0; index--) if (left.has(previousOrder[index])) return previousOrder[index];
389
+ }
390
+ return remaining[0] ?? null;
391
+ }
392
+ var HOUR_MS = 36e5;
393
+ function snoozePresets(now) {
394
+ const inThreeHours = new Date(now.getTime() + 3 * HOUR_MS);
395
+ const tomorrow = new Date(now);
396
+ tomorrow.setDate(tomorrow.getDate() + 1);
397
+ tomorrow.setHours(9, 0, 0, 0);
398
+ const monday = new Date(now);
399
+ const daysToMonday = (8 - monday.getDay()) % 7 || 7;
400
+ monday.setDate(monday.getDate() + daysToMonday);
401
+ monday.setHours(9, 0, 0, 0);
402
+ const week = new Date(now.getTime() + 7 * 24 * HOUR_MS);
403
+ return [
404
+ { key: "3h", label: "3 hours", until: inThreeHours },
405
+ { key: "tomorrow", label: "Tomorrow 9:00", until: tomorrow },
406
+ { key: "monday", label: "Monday 9:00", until: monday },
407
+ { key: "week", label: "One week", until: week }
408
+ ];
409
+ }
410
+
411
+ // src/preferences.ts
412
+ var import_react2 = require("react");
413
+ var GROUPING_STORAGE_KEY = "microvac.decisions.grouping";
414
+ var SORT_STORAGE_KEY = "microvac.decisions.sort";
415
+ function storage() {
416
+ try {
417
+ return typeof window === "undefined" ? null : window.localStorage;
418
+ } catch {
419
+ return null;
420
+ }
421
+ }
422
+ function readStoredChoice(key, choices, fallback) {
423
+ const value = storage()?.getItem(key);
424
+ return value && choices.includes(value) ? value : fallback;
425
+ }
426
+ function writeStoredChoice(key, value) {
427
+ try {
428
+ storage()?.setItem(key, value);
429
+ } catch {
430
+ }
431
+ }
432
+ function useStoredChoice(key, choices, fallback) {
433
+ const [value, setValue] = (0, import_react2.useState)(() => readStoredChoice(key, choices, fallback));
434
+ const update = (0, import_react2.useCallback)((next) => {
435
+ setValue(next);
436
+ writeStoredChoice(key, next);
437
+ }, [key]);
438
+ return [value, update];
439
+ }
440
+
441
+ // src/useNativeDecisions.ts
442
+ var import_react3 = require("react");
443
+ var import_ui = require("@microvac/ui");
444
+ var REFRESH_MS = 6e4;
445
+ function nativeDecisionsQueryKey(companyId, view) {
446
+ return [...import_ui.queryKeys.attention(companyId), "microvac-native", view];
447
+ }
448
+ function useNativeDecisions(companyId) {
449
+ const results = (0, import_ui.useQueries)({
450
+ queries: DECISION_FEED_VIEWS.map((view) => ({
451
+ queryKey: nativeDecisionsQueryKey(companyId ?? "", view),
452
+ queryFn: () => import_ui.decisions.listAttention(companyId, { view, all: true, includeDismissed: true }),
453
+ enabled: Boolean(companyId),
454
+ refetchInterval: REFRESH_MS,
455
+ refetchOnWindowFocus: true
456
+ }))
457
+ });
458
+ const mine = results[0]?.data?.items;
459
+ const unassigned = results[1]?.data?.items;
460
+ const company = results[2]?.data?.items;
461
+ const fetchedAt = Math.max(0, ...results.map((result) => result.dataUpdatedAt));
462
+ const list = (0, import_react3.useMemo)(() => {
463
+ const feeds = { mine, unassigned, company };
464
+ return collectDecisions(feeds, Math.max(fetchedAt, Date.now()), import_ui.decisions.foldObligations);
465
+ }, [mine, unassigned, company, fetchedAt]);
466
+ const failed = results.find((result) => result.error)?.error;
467
+ const error = failed ? failed instanceof Error ? failed : new Error(String(failed)) : null;
468
+ return {
469
+ ...list,
470
+ isLoading: Boolean(companyId) && results.some((result) => result.isPending),
471
+ error,
472
+ refetch: () => {
473
+ for (const result of results) void result.refetch();
474
+ }
475
+ };
476
+ }
477
+ function useNativeDecisionCount({ companyId }) {
478
+ const { open, isLoading, error } = useNativeDecisions(companyId);
479
+ if (!companyId || isLoading || error) return void 0;
480
+ return open.length;
481
+ }
482
+
483
+ // src/page.tsx
484
+ var import_jsx_runtime = require("react/jsx-runtime");
485
+ var KEY_HINT_CSS = `
486
+ [${KBD_HINT_ATTRIBUTE}] { position: relative; }
487
+ [${KBD_HINT_ATTRIBUTE}]::after {
488
+ content: attr(${KBD_HINT_ATTRIBUTE});
489
+ margin-inline-start: 0.375rem;
490
+ padding: 0 0.25rem;
491
+ border: 1px solid var(--border);
492
+ border-radius: 0.25rem;
493
+ font: 500 0.625rem/1rem ui-monospace, monospace;
494
+ color: var(--muted-foreground);
495
+ }
496
+ `;
497
+ function cardSelector(key) {
498
+ return `[data-decision-key="${CSS.escape(key)}"]`;
499
+ }
500
+ function DecisionsPage() {
501
+ const { companyId } = (0, import_ui2.useSelectedCompany)();
502
+ if (!companyId) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "p-4 text-sm text-muted-foreground", children: "Select a company to see its decisions." });
503
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DecisionsList, { companyId });
504
+ }
505
+ function DecisionsList({ companyId }) {
506
+ const viewerId = (0, import_ui2.useViewerId)();
507
+ const toast = (0, import_ui2.useToast)();
508
+ const queryClient = (0, import_ui2.useQueryClient)();
509
+ const state = useNativeDecisions(companyId);
510
+ const [grouping, setGrouping] = useStoredChoice(GROUPING_STORAGE_KEY, DECISION_GROUPINGS, DEFAULT_GROUPING);
511
+ const [sort, setSort] = useStoredChoice(SORT_STORAGE_KEY, DECISION_SORTS, DEFAULT_SORT);
512
+ const groups = (0, import_react4.useMemo)(() => groupDecisions(state.open, grouping, sort), [state.open, grouping, sort]);
513
+ const keys = (0, import_react4.useMemo)(() => displayOrder(groups).map((decision) => decision.key), [groups]);
514
+ const [openKey, setOpenKey] = (0, import_react4.useState)(null);
515
+ const [snoozeMenuKey, setSnoozeMenuKey] = (0, import_react4.useState)(null);
516
+ const [showSnoozed, setShowSnoozed] = (0, import_react4.useState)(false);
517
+ const [showHelp, setShowHelp] = (0, import_react4.useState)(false);
518
+ const [historyOpen, setHistoryOpen] = (0, import_react4.useState)(false);
519
+ const [searchParams, setSearchParams] = (0, import_ui2.useSearchParams)();
520
+ const touch = (0, import_react4.useMemo)(() => isTouchDevice(), []);
521
+ const rootRef = (0, import_react4.useRef)(null);
522
+ const previousKeys = (0, import_react4.useRef)([]);
523
+ const started = (0, import_react4.useRef)(false);
524
+ (0, import_react4.useEffect)(() => {
525
+ if (state.isLoading) return;
526
+ const previous = previousKeys.current;
527
+ previousKeys.current = keys;
528
+ if (openKey && previous.includes(openKey) && !keys.includes(openKey)) {
529
+ setOpenKey(nextOpenKey(previous, openKey, keys));
530
+ } else if (!started.current && !openKey && !searchParams.get("card")) {
531
+ setOpenKey(keys[0] ?? null);
532
+ }
533
+ started.current = true;
534
+ }, [keys, state.isLoading, openKey, searchParams]);
535
+ const cardParam = searchParams.get("card");
536
+ (0, import_react4.useEffect)(() => {
537
+ if (!cardParam || state.isLoading) return;
538
+ const wanted = parseCardParam(cardParam);
539
+ if (wanted && keys.includes(wanted)) {
540
+ setOpenKey(wanted);
541
+ } else if (wanted && state.snoozed.some((decision) => decision.key === wanted)) {
542
+ setShowSnoozed(true);
543
+ setOpenKey(wanted);
544
+ } else {
545
+ toast({ title: "This decision was already answered", tone: "info" });
546
+ setOpenKey(keys[0] ?? null);
547
+ }
548
+ const next = new URLSearchParams(searchParams);
549
+ next.delete("card");
550
+ setSearchParams(next, { replace: true });
551
+ }, [cardParam, state.isLoading, keys, state.snoozed, searchParams, setSearchParams, toast]);
552
+ (0, import_react4.useEffect)(() => {
553
+ if (!openKey) return;
554
+ const card = rootRef.current?.querySelector(cardSelector(openKey));
555
+ card?.scrollIntoView?.({ block: "nearest" });
556
+ }, [openKey]);
557
+ (0, import_react4.useEffect)(() => {
558
+ const root = rootRef.current;
559
+ if (!root || typeof MutationObserver === "undefined") return;
560
+ const mark = () => {
561
+ for (const card of root.querySelectorAll("[data-decision-key]")) {
562
+ markKeyHints(card, !touch && card.dataset.decisionKey === openKey);
563
+ }
564
+ };
565
+ mark();
566
+ const observer = new MutationObserver(mark);
567
+ observer.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ["disabled", "aria-disabled", "data-variant"] });
568
+ return () => observer.disconnect();
569
+ }, [openKey, touch]);
570
+ const refresh = (0, import_react4.useCallback)(() => queryClient.invalidateQueries({ queryKey: import_ui2.queryKeys.attention(companyId) }), [queryClient, companyId]);
571
+ const snooze = (0, import_react4.useCallback)(
572
+ async (decision, until) => {
573
+ try {
574
+ await import_ui2.decisions.snooze(companyId, decision.item, until.toISOString());
575
+ await refresh();
576
+ } catch (error) {
577
+ toast({ title: "Snooze failed", body: error instanceof Error ? error.message : void 0, tone: "error" });
578
+ }
579
+ },
580
+ [companyId, refresh, toast]
581
+ );
582
+ const wake = (0, import_react4.useCallback)(
583
+ async (decision) => {
584
+ try {
585
+ await import_ui2.decisions.wake(companyId, decision.item);
586
+ await refresh();
587
+ } catch (error) {
588
+ toast({ title: "Wake up failed", body: error instanceof Error ? error.message : void 0, tone: "error" });
589
+ }
590
+ },
591
+ [companyId, refresh, toast]
592
+ );
593
+ (0, import_react4.useEffect)(() => {
594
+ if (touch) return;
595
+ const onKey = (event) => {
596
+ const shortcut = decisionShortcut(event);
597
+ if (!shortcut) return;
598
+ const card = openKey ? rootRef.current?.querySelector(cardSelector(openKey)) : null;
599
+ const move = (step) => {
600
+ if (keys.length === 0) return;
601
+ const at = openKey ? keys.indexOf(openKey) : -1;
602
+ const target = at < 0 ? 0 : Math.min(keys.length - 1, Math.max(0, at + step));
603
+ setOpenKey(keys[target]);
604
+ };
605
+ switch (shortcut.kind) {
606
+ case "option": {
607
+ const option = card ? answerOptions(card)[shortcut.index] : void 0;
608
+ if (!option) return;
609
+ option.click();
610
+ break;
611
+ }
612
+ case "send": {
613
+ const send = card ? sendButton(card) : null;
614
+ if (!send || send.disabled) return;
615
+ send.click();
616
+ break;
617
+ }
618
+ case "next":
619
+ move(1);
620
+ break;
621
+ case "previous":
622
+ move(-1);
623
+ break;
624
+ case "snooze":
625
+ if (!openKey) return;
626
+ setSnoozeMenuKey(openKey);
627
+ break;
628
+ case "help":
629
+ setShowHelp((shown) => !shown);
630
+ break;
631
+ case "close-help":
632
+ if (!showHelp) return;
633
+ setShowHelp(false);
634
+ break;
635
+ }
636
+ event.preventDefault();
637
+ };
638
+ window.addEventListener("keydown", onKey);
639
+ return () => window.removeEventListener("keydown", onKey);
640
+ }, [touch, openKey, keys, showHelp]);
641
+ const toggle = (key) => setOpenKey((current) => current === key ? null : key);
642
+ const cardProps = (decision) => ({
643
+ decision,
644
+ companyId,
645
+ viewerId,
646
+ open: openKey === decision.key,
647
+ onToggle: () => toggle(decision.key),
648
+ snoozeMenuOpen: snoozeMenuKey === decision.key,
649
+ onSnoozeMenuChange: (open) => setSnoozeMenuKey(open ? decision.key : null),
650
+ onSnooze: (until) => void snooze(decision, until),
651
+ onWake: () => void wake(decision)
652
+ });
653
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { ref: rootRef, className: "max-w-3xl space-y-4", "data-microvac-decisions": "native", children: [
654
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { children: KEY_HINT_CSS }),
655
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
656
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-baseline gap-2", children: [
657
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", { className: "text-xl font-bold", children: "Decisions" }),
658
+ !state.isLoading ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "text-sm text-muted-foreground", "data-testid": "decisions-left", children: [
659
+ state.open.length,
660
+ " left"
661
+ ] }) : null
662
+ ] }),
663
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center gap-2", children: [
664
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { className: "flex items-center gap-1 text-xs text-muted-foreground", children: [
665
+ "Group by",
666
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
667
+ "select",
668
+ {
669
+ className: "rounded-md border bg-background px-2 py-1 text-xs text-foreground",
670
+ value: grouping,
671
+ onChange: (event) => setGrouping(event.target.value),
672
+ children: DECISION_GROUPINGS.map((choice) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { value: choice, children: GROUPING_LABELS[choice] }, choice))
673
+ }
674
+ )
675
+ ] }),
676
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Button, { variant: "ghost", size: "sm", onClick: () => setSort(sort === "oldest" ? "newest" : "oldest"), children: sort === "oldest" ? "Oldest first" : "Newest first" }),
677
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Button, { variant: "ghost", size: "sm", onClick: () => setHistoryOpen(true), children: "Decision history" }),
678
+ !touch ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Button, { variant: "ghost", size: "sm", "aria-label": "Keyboard shortcuts", onClick: () => setShowHelp((shown) => !shown), children: "?" }) : null
679
+ ] })
680
+ ] }),
681
+ showHelp && !touch ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ShortcutHelp, { onClose: () => setShowHelp(false) }) : null,
682
+ state.error ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-center gap-2 rounded-md border border-destructive/40 p-3 text-sm", children: [
683
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
684
+ "Decisions could not load: ",
685
+ state.error.message
686
+ ] }),
687
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Button, { variant: "outline", size: "sm", onClick: state.refetch, children: "Retry" })
688
+ ] }) : null,
689
+ state.isLoading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "text-sm text-muted-foreground", children: "Loading decisions\u2026" }) : null,
690
+ !state.isLoading && !state.error && state.open.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "rounded-lg border border-dashed p-8 text-center", "data-testid": "decisions-empty", children: [
691
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "text-sm font-medium", children: "No decisions left" }),
692
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "mt-1 text-xs text-muted-foreground", children: "Agents will ask here when they need you." })
693
+ ] }) : null,
694
+ groups.map((group) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: "space-y-2", children: [
695
+ group.label ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h2", { className: "flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: [
696
+ group.project ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "inline-block h-2.5 w-2.5 rounded-sm", style: { backgroundColor: group.project.color ?? "currentColor" } }) : null,
697
+ group.label,
698
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "font-normal", children: group.decisions.length })
699
+ ] }) : null,
700
+ group.decisions.map((decision) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DecisionCard, { ...cardProps(decision) }, decision.key))
701
+ ] }, group.key)),
702
+ state.snoozed.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: "space-y-2", children: [
703
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
704
+ "button",
705
+ {
706
+ type: "button",
707
+ className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground",
708
+ "aria-expanded": showSnoozed,
709
+ onClick: () => setShowSnoozed((shown) => !shown),
710
+ children: [
711
+ showSnoozed ? "\u25BE" : "\u25B8",
712
+ " Snoozed ",
713
+ state.snoozed.length
714
+ ]
715
+ }
716
+ ),
717
+ showSnoozed ? state.snoozed.map((decision) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DecisionCard, { ...cardProps(decision) }, decision.key)) : null
718
+ ] }) : null,
719
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.decisions.History, { companyId, open: historyOpen, onOpenChange: setHistoryOpen })
720
+ ] });
721
+ }
722
+ function ShortcutHelp({ onClose }) {
723
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "rounded-lg border bg-card p-3 text-sm", role: "dialog", "aria-label": "Keyboard shortcuts", children: [
724
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "mb-2 flex items-center justify-between", children: [
725
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "font-medium", children: "Keyboard shortcuts" }),
726
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Button, { variant: "ghost", size: "sm", onClick: onClose, children: "Close" })
727
+ ] }),
728
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: "grid gap-1 sm:grid-cols-2", children: SHORTCUT_HELP.map((entry) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: "flex items-center gap-2", children: [
729
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "flex gap-1", children: entry.keys.map((key) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("kbd", { className: "rounded border px-1 font-mono text-[10px] text-muted-foreground", children: key }, key)) }),
730
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "text-muted-foreground", children: entry.label })
731
+ ] }, entry.label)) })
732
+ ] });
733
+ }
734
+ function DecisionCard({ decision, companyId, viewerId, open, onToggle: onToggle2, snoozeMenuOpen, onSnoozeMenuChange, onSnooze, onWake }) {
735
+ const { item } = decision;
736
+ const [showContext, setShowContext] = (0, import_react4.useState)(false);
737
+ const bodyRef = (0, import_react4.useRef)(null);
738
+ useQuestionFold(bodyRef, open);
739
+ const agent = decisionAgentName(item);
740
+ const title = item.subject.title ?? item.relatedIssue?.title ?? decisionTypeLabel(item);
741
+ const issue = item.relatedIssue ?? (item.subject.href ? item.subject : null);
742
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
743
+ "article",
744
+ {
745
+ "data-decision-key": decision.key,
746
+ "data-open": open || void 0,
747
+ className: (0, import_ui2.cn)("rounded-lg border bg-card", open && "ring-1 ring-primary/40"),
748
+ children: [
749
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-start gap-1 p-3", children: [
750
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { type: "button", className: "min-w-0 flex-1 text-left", "aria-expanded": open, onClick: onToggle2, children: [
751
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground", children: [
752
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Badge, { variant: decision.marker === "for-you" ? "default" : "outline", children: decision.marker === "for-you" ? "For you" : "Anyone" }),
753
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: decisionTypeLabel(item) }),
754
+ agent ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
755
+ "\xB7 ",
756
+ agent
757
+ ] }) : null,
758
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
759
+ "\xB7 ",
760
+ (0, import_ui2.relativeTime)(decisionAskedAt(decision))
761
+ ] }),
762
+ decision.snoozedUntil ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
763
+ "\xB7 snoozed until ",
764
+ new Date(decision.snoozedUntil).toLocaleString()
765
+ ] }) : null
766
+ ] }),
767
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h3", { className: "mt-1 text-sm font-medium leading-snug", children: title })
768
+ ] }),
769
+ decision.snoozedUntil ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Button, { variant: "outline", size: "sm", onClick: onWake, children: "Wake up" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ui2.DropdownMenu, { open: snoozeMenuOpen, onOpenChange: onSnoozeMenuChange, children: [
770
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Button, { variant: "ghost", size: "sm", "aria-label": "More actions", children: "\u2026" }) }),
771
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ui2.DropdownMenuContent, { align: "end", children: [
772
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.DropdownMenuLabel, { children: "Snooze" }),
773
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.DropdownMenuSeparator, {}),
774
+ snoozePresets(/* @__PURE__ */ new Date()).map((preset) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.DropdownMenuItem, { onSelect: () => onSnooze(preset.until), children: preset.label }, preset.key))
775
+ ] })
776
+ ] })
777
+ ] }),
778
+ open ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { ref: bodyRef, className: "space-y-3 border-t px-3 pb-3 pt-3", children: [
779
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.decisions.AnswerForm, { item, companyId, currentUserId: viewerId }),
780
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center gap-3 text-xs", children: [
781
+ item.whyNow ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "text-muted-foreground underline-offset-2 hover:underline", onClick: () => setShowContext((shown) => !shown), children: showContext ? "Hide context" : "Show context" }) : null,
782
+ issue?.href ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Link, { to: issue.href, className: "text-muted-foreground underline-offset-2 hover:underline", children: issue.identifier ?? "Open issue" }) : null
783
+ ] }),
784
+ showContext && item.whyNow ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.MarkdownBody, { className: "text-sm", children: item.whyNow }) : null
785
+ ] }) : null
786
+ ]
787
+ }
788
+ );
789
+ }
790
+
791
+ // src/client.tsx
792
+ var import_jsx_runtime2 = require("react/jsx-runtime");
793
+ var name = "@microvac/plugin-decisions-native";
794
+ var inject = ["pages"];
795
+ function AnswerFirstInteractionCard(props) {
796
+ const pending = props.interaction?.status === "pending";
797
+ const ref = (0, import_react5.useRef)(null);
798
+ useQuestionFold(ref, pending);
799
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { ref, className: "contents", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui3.upstream.InteractionCard, { ...props, presentationVariant: pending ? "coordinator-decision" : props.presentationVariant }) });
800
+ }
801
+ function apply(ctx) {
802
+ ctx.pages.provide("decisions", { id: name, component: DecisionsPage, useCount: useNativeDecisionCount });
803
+ ctx.pages.provide("interaction-card", { id: name, component: AnswerFirstInteractionCard });
804
+ }
805
+
806
+ return module.exports;
807
+ },
808
+ });