@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/src/page.tsx ADDED
@@ -0,0 +1,441 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import {
3
+ Badge,
4
+ Button,
5
+ cn,
6
+ decisions,
7
+ DropdownMenu,
8
+ DropdownMenuContent,
9
+ DropdownMenuItem,
10
+ DropdownMenuLabel,
11
+ DropdownMenuSeparator,
12
+ DropdownMenuTrigger,
13
+ Link,
14
+ MarkdownBody,
15
+ queryKeys,
16
+ relativeTime,
17
+ useQueryClient,
18
+ useSearchParams,
19
+ useSelectedCompany,
20
+ useToast,
21
+ useViewerId,
22
+ } from "@microvac/ui";
23
+ import { useQuestionFold } from "./fold.js";
24
+ import { decisionShortcut, isTouchDevice, KBD_HINT_ATTRIBUTE, answerOptions, markKeyHints, sendButton, SHORTCUT_HELP } from "./keyboard.js";
25
+ import {
26
+ DECISION_GROUPINGS,
27
+ DECISION_SORTS,
28
+ decisionAgentName,
29
+ decisionAskedAt,
30
+ decisionTypeLabel,
31
+ DEFAULT_GROUPING,
32
+ DEFAULT_SORT,
33
+ displayOrder,
34
+ groupDecisions,
35
+ GROUPING_LABELS,
36
+ nextOpenKey,
37
+ parseCardParam,
38
+ snoozePresets,
39
+ type DecisionGrouping,
40
+ type DecisionSort,
41
+ type NativeDecision,
42
+ } from "./model.js";
43
+ import { GROUPING_STORAGE_KEY, SORT_STORAGE_KEY, useStoredChoice } from "./preferences.js";
44
+ import { useNativeDecisions } from "./useNativeDecisions.js";
45
+
46
+ /** Key hints on the upstream controls; the host's CSS does not know this attribute. */
47
+ const KEY_HINT_CSS = `
48
+ [${KBD_HINT_ATTRIBUTE}] { position: relative; }
49
+ [${KBD_HINT_ATTRIBUTE}]::after {
50
+ content: attr(${KBD_HINT_ATTRIBUTE});
51
+ margin-inline-start: 0.375rem;
52
+ padding: 0 0.25rem;
53
+ border: 1px solid var(--border);
54
+ border-radius: 0.25rem;
55
+ font: 500 0.625rem/1rem ui-monospace, monospace;
56
+ color: var(--muted-foreground);
57
+ }
58
+ `;
59
+
60
+ function cardSelector(key: string) {
61
+ return `[data-decision-key="${CSS.escape(key)}"]`;
62
+ }
63
+
64
+ /** The Microvac Decisions page: one answer-first list, grouped, with an answer session and a keyboard. */
65
+ export function DecisionsPage() {
66
+ const { companyId } = useSelectedCompany();
67
+ if (!companyId) return <p className="p-4 text-sm text-muted-foreground">Select a company to see its decisions.</p>;
68
+ return <DecisionsList companyId={companyId} />;
69
+ }
70
+
71
+ function DecisionsList({ companyId }: { companyId: string }) {
72
+ const viewerId = useViewerId();
73
+ const toast = useToast();
74
+ const queryClient = useQueryClient();
75
+ const state = useNativeDecisions(companyId);
76
+ const [grouping, setGrouping] = useStoredChoice<DecisionGrouping>(GROUPING_STORAGE_KEY, DECISION_GROUPINGS, DEFAULT_GROUPING);
77
+ const [sort, setSort] = useStoredChoice<DecisionSort>(SORT_STORAGE_KEY, DECISION_SORTS, DEFAULT_SORT);
78
+ const groups = useMemo(() => groupDecisions(state.open, grouping, sort), [state.open, grouping, sort]);
79
+ const keys = useMemo(() => displayOrder(groups).map((decision) => decision.key), [groups]);
80
+
81
+ const [openKey, setOpenKey] = useState<string | null>(null);
82
+ const [snoozeMenuKey, setSnoozeMenuKey] = useState<string | null>(null);
83
+ const [showSnoozed, setShowSnoozed] = useState(false);
84
+ const [showHelp, setShowHelp] = useState(false);
85
+ const [historyOpen, setHistoryOpen] = useState(false);
86
+ const [searchParams, setSearchParams] = useSearchParams();
87
+ const touch = useMemo(() => isTouchDevice(), []);
88
+ const rootRef = useRef<HTMLDivElement>(null);
89
+
90
+ // Answer session: the answered card leaves the list, the next one opens in place.
91
+ const previousKeys = useRef<string[]>([]);
92
+ const started = useRef(false);
93
+ useEffect(() => {
94
+ if (state.isLoading) return;
95
+ const previous = previousKeys.current;
96
+ previousKeys.current = keys;
97
+ // Answered or snoozed: it left the list it was open in.
98
+ if (openKey && previous.includes(openKey) && !keys.includes(openKey)) {
99
+ setOpenKey(nextOpenKey(previous, openKey, keys));
100
+ } else if (!started.current && !openKey && !searchParams.get("card")) {
101
+ setOpenKey(keys[0] ?? null);
102
+ }
103
+ started.current = true;
104
+ }, [keys, state.isLoading, openKey, searchParams]);
105
+
106
+ // A push notification opens `?card=<kind>:<id>`; the card may have been answered meanwhile.
107
+ const cardParam = searchParams.get("card");
108
+ useEffect(() => {
109
+ if (!cardParam || state.isLoading) return;
110
+ const wanted = parseCardParam(cardParam);
111
+ if (wanted && keys.includes(wanted)) {
112
+ setOpenKey(wanted);
113
+ } else if (wanted && state.snoozed.some((decision) => decision.key === wanted)) {
114
+ setShowSnoozed(true);
115
+ setOpenKey(wanted);
116
+ } else {
117
+ toast({ title: "This decision was already answered", tone: "info" });
118
+ setOpenKey(keys[0] ?? null);
119
+ }
120
+ const next = new URLSearchParams(searchParams);
121
+ next.delete("card");
122
+ setSearchParams(next, { replace: true });
123
+ }, [cardParam, state.isLoading, keys, state.snoozed, searchParams, setSearchParams, toast]);
124
+
125
+ // Bring the open card into view (keyboard moves, push clicks, the next card of a session).
126
+ useEffect(() => {
127
+ if (!openKey) return;
128
+ const card = rootRef.current?.querySelector<HTMLElement>(cardSelector(openKey));
129
+ card?.scrollIntoView?.({ block: "nearest" });
130
+ }, [openKey]);
131
+
132
+ // Key hints on the open card's upstream controls, kept as the form changes.
133
+ useEffect(() => {
134
+ const root = rootRef.current;
135
+ if (!root || typeof MutationObserver === "undefined") return;
136
+ const mark = () => {
137
+ for (const card of root.querySelectorAll<HTMLElement>("[data-decision-key]")) {
138
+ markKeyHints(card, !touch && card.dataset.decisionKey === openKey);
139
+ }
140
+ };
141
+ mark();
142
+ const observer = new MutationObserver(mark);
143
+ observer.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ["disabled", "aria-disabled", "data-variant"] });
144
+ return () => observer.disconnect();
145
+ }, [openKey, touch]);
146
+
147
+ const refresh = useCallback(() => queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) }), [queryClient, companyId]);
148
+
149
+ const snooze = useCallback(
150
+ async (decision: NativeDecision, until: Date) => {
151
+ try {
152
+ await decisions.snooze(companyId, decision.item, until.toISOString());
153
+ await refresh();
154
+ } catch (error) {
155
+ toast({ title: "Snooze failed", body: error instanceof Error ? error.message : undefined, tone: "error" });
156
+ }
157
+ },
158
+ [companyId, refresh, toast],
159
+ );
160
+
161
+ const wake = useCallback(
162
+ async (decision: NativeDecision) => {
163
+ try {
164
+ await decisions.wake(companyId, decision.item);
165
+ await refresh();
166
+ } catch (error) {
167
+ toast({ title: "Wake up failed", body: error instanceof Error ? error.message : undefined, tone: "error" });
168
+ }
169
+ },
170
+ [companyId, refresh, toast],
171
+ );
172
+
173
+ // Keyboard (desktop): 1–9, Enter, J/K, S, ?.
174
+ useEffect(() => {
175
+ if (touch) return;
176
+ const onKey = (event: KeyboardEvent) => {
177
+ const shortcut = decisionShortcut(event);
178
+ if (!shortcut) return;
179
+ const card = openKey ? rootRef.current?.querySelector<HTMLElement>(cardSelector(openKey)) : null;
180
+ const move = (step: number) => {
181
+ if (keys.length === 0) return;
182
+ const at = openKey ? keys.indexOf(openKey) : -1;
183
+ const target = at < 0 ? 0 : Math.min(keys.length - 1, Math.max(0, at + step));
184
+ setOpenKey(keys[target]!);
185
+ };
186
+ switch (shortcut.kind) {
187
+ case "option": {
188
+ const option = card ? answerOptions(card)[shortcut.index] : undefined;
189
+ if (!option) return;
190
+ option.click();
191
+ break;
192
+ }
193
+ case "send": {
194
+ const send = card ? sendButton(card) : null;
195
+ if (!send || (send as HTMLButtonElement).disabled) return;
196
+ send.click();
197
+ break;
198
+ }
199
+ case "next":
200
+ move(1);
201
+ break;
202
+ case "previous":
203
+ move(-1);
204
+ break;
205
+ case "snooze":
206
+ if (!openKey) return;
207
+ setSnoozeMenuKey(openKey);
208
+ break;
209
+ case "help":
210
+ setShowHelp((shown) => !shown);
211
+ break;
212
+ case "close-help":
213
+ if (!showHelp) return;
214
+ setShowHelp(false);
215
+ break;
216
+ }
217
+ event.preventDefault();
218
+ };
219
+ window.addEventListener("keydown", onKey);
220
+ return () => window.removeEventListener("keydown", onKey);
221
+ }, [touch, openKey, keys, showHelp]);
222
+
223
+ const toggle = (key: string) => setOpenKey((current) => (current === key ? null : key));
224
+ const cardProps = (decision: NativeDecision) => ({
225
+ decision,
226
+ companyId,
227
+ viewerId,
228
+ open: openKey === decision.key,
229
+ onToggle: () => toggle(decision.key),
230
+ snoozeMenuOpen: snoozeMenuKey === decision.key,
231
+ onSnoozeMenuChange: (open: boolean) => setSnoozeMenuKey(open ? decision.key : null),
232
+ onSnooze: (until: Date) => void snooze(decision, until),
233
+ onWake: () => void wake(decision),
234
+ });
235
+
236
+ return (
237
+ <div ref={rootRef} className="max-w-3xl space-y-4" data-microvac-decisions="native">
238
+ <style>{KEY_HINT_CSS}</style>
239
+ <div className="flex flex-wrap items-center justify-between gap-2">
240
+ <div className="flex items-baseline gap-2">
241
+ <h1 className="text-xl font-bold">Decisions</h1>
242
+ {!state.isLoading ? (
243
+ <span className="text-sm text-muted-foreground" data-testid="decisions-left">
244
+ {state.open.length} left
245
+ </span>
246
+ ) : null}
247
+ </div>
248
+ <div className="flex flex-wrap items-center gap-2">
249
+ <label className="flex items-center gap-1 text-xs text-muted-foreground">
250
+ Group by
251
+ <select
252
+ className="rounded-md border bg-background px-2 py-1 text-xs text-foreground"
253
+ value={grouping}
254
+ onChange={(event) => setGrouping(event.target.value as DecisionGrouping)}
255
+ >
256
+ {DECISION_GROUPINGS.map((choice) => (
257
+ <option key={choice} value={choice}>
258
+ {GROUPING_LABELS[choice]}
259
+ </option>
260
+ ))}
261
+ </select>
262
+ </label>
263
+ <Button variant="ghost" size="sm" onClick={() => setSort(sort === "oldest" ? "newest" : "oldest")}>
264
+ {sort === "oldest" ? "Oldest first" : "Newest first"}
265
+ </Button>
266
+ <Button variant="ghost" size="sm" onClick={() => setHistoryOpen(true)}>
267
+ Decision history
268
+ </Button>
269
+ {!touch ? (
270
+ <Button variant="ghost" size="sm" aria-label="Keyboard shortcuts" onClick={() => setShowHelp((shown) => !shown)}>
271
+ ?
272
+ </Button>
273
+ ) : null}
274
+ </div>
275
+ </div>
276
+
277
+ {showHelp && !touch ? <ShortcutHelp onClose={() => setShowHelp(false)} /> : null}
278
+
279
+ {state.error ? (
280
+ <div className="flex items-center gap-2 rounded-md border border-destructive/40 p-3 text-sm">
281
+ <span>Decisions could not load: {state.error.message}</span>
282
+ <Button variant="outline" size="sm" onClick={state.refetch}>
283
+ Retry
284
+ </Button>
285
+ </div>
286
+ ) : null}
287
+
288
+ {state.isLoading ? <p className="text-sm text-muted-foreground">Loading decisions…</p> : null}
289
+
290
+ {!state.isLoading && !state.error && state.open.length === 0 ? (
291
+ <div className="rounded-lg border border-dashed p-8 text-center" data-testid="decisions-empty">
292
+ <p className="text-sm font-medium">No decisions left</p>
293
+ <p className="mt-1 text-xs text-muted-foreground">Agents will ask here when they need you.</p>
294
+ </div>
295
+ ) : null}
296
+
297
+ {groups.map((group) => (
298
+ <section key={group.key} className="space-y-2">
299
+ {group.label ? (
300
+ <h2 className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
301
+ {group.project ? (
302
+ <span className="inline-block h-2.5 w-2.5 rounded-sm" style={{ backgroundColor: group.project.color ?? "currentColor" }} />
303
+ ) : null}
304
+ {group.label}
305
+ <span className="font-normal">{group.decisions.length}</span>
306
+ </h2>
307
+ ) : null}
308
+ {group.decisions.map((decision) => (
309
+ <DecisionCard key={decision.key} {...cardProps(decision)} />
310
+ ))}
311
+ </section>
312
+ ))}
313
+
314
+ {state.snoozed.length > 0 ? (
315
+ <section className="space-y-2">
316
+ <button
317
+ type="button"
318
+ className="text-xs font-semibold uppercase tracking-wide text-muted-foreground"
319
+ aria-expanded={showSnoozed}
320
+ onClick={() => setShowSnoozed((shown) => !shown)}
321
+ >
322
+ {showSnoozed ? "▾" : "▸"} Snoozed {state.snoozed.length}
323
+ </button>
324
+ {showSnoozed ? state.snoozed.map((decision) => <DecisionCard key={decision.key} {...cardProps(decision)} />) : null}
325
+ </section>
326
+ ) : null}
327
+
328
+ <decisions.History companyId={companyId} open={historyOpen} onOpenChange={setHistoryOpen} />
329
+ </div>
330
+ );
331
+ }
332
+
333
+ function ShortcutHelp({ onClose }: { onClose: () => void }) {
334
+ return (
335
+ <div className="rounded-lg border bg-card p-3 text-sm" role="dialog" aria-label="Keyboard shortcuts">
336
+ <div className="mb-2 flex items-center justify-between">
337
+ <span className="font-medium">Keyboard shortcuts</span>
338
+ <Button variant="ghost" size="sm" onClick={onClose}>
339
+ Close
340
+ </Button>
341
+ </div>
342
+ <ul className="grid gap-1 sm:grid-cols-2">
343
+ {SHORTCUT_HELP.map((entry) => (
344
+ <li key={entry.label} className="flex items-center gap-2">
345
+ <span className="flex gap-1">
346
+ {entry.keys.map((key) => (
347
+ <kbd key={key} className="rounded border px-1 font-mono text-[10px] text-muted-foreground">
348
+ {key}
349
+ </kbd>
350
+ ))}
351
+ </span>
352
+ <span className="text-muted-foreground">{entry.label}</span>
353
+ </li>
354
+ ))}
355
+ </ul>
356
+ </div>
357
+ );
358
+ }
359
+
360
+ interface DecisionCardProps {
361
+ decision: NativeDecision;
362
+ companyId: string;
363
+ viewerId: string | null;
364
+ open: boolean;
365
+ onToggle: () => void;
366
+ snoozeMenuOpen: boolean;
367
+ onSnoozeMenuChange: (open: boolean) => void;
368
+ onSnooze: (until: Date) => void;
369
+ onWake: () => void;
370
+ }
371
+
372
+ function DecisionCard({ decision, companyId, viewerId, open, onToggle, snoozeMenuOpen, onSnoozeMenuChange, onSnooze, onWake }: DecisionCardProps) {
373
+ const { item } = decision;
374
+ const [showContext, setShowContext] = useState(false);
375
+ const bodyRef = useRef<HTMLDivElement>(null);
376
+ // A long question folds to four lines, so the answer controls stay in view.
377
+ useQuestionFold(bodyRef, open);
378
+ const agent = decisionAgentName(item);
379
+ const title = item.subject.title ?? item.relatedIssue?.title ?? decisionTypeLabel(item);
380
+ const issue = item.relatedIssue ?? (item.subject.href ? item.subject : null);
381
+ return (
382
+ <article
383
+ data-decision-key={decision.key}
384
+ data-open={open || undefined}
385
+ className={cn("rounded-lg border bg-card", open && "ring-1 ring-primary/40")}
386
+ >
387
+ <div className="flex items-start gap-1 p-3">
388
+ <button type="button" className="min-w-0 flex-1 text-left" aria-expanded={open} onClick={onToggle}>
389
+ <div className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
390
+ <Badge variant={decision.marker === "for-you" ? "default" : "outline"}>{decision.marker === "for-you" ? "For you" : "Anyone"}</Badge>
391
+ <span>{decisionTypeLabel(item)}</span>
392
+ {agent ? <span>· {agent}</span> : null}
393
+ <span>· {relativeTime(decisionAskedAt(decision))}</span>
394
+ {decision.snoozedUntil ? <span>· snoozed until {new Date(decision.snoozedUntil).toLocaleString()}</span> : null}
395
+ </div>
396
+ <h3 className="mt-1 text-sm font-medium leading-snug">{title}</h3>
397
+ </button>
398
+ {decision.snoozedUntil ? (
399
+ <Button variant="outline" size="sm" onClick={onWake}>
400
+ Wake up
401
+ </Button>
402
+ ) : (
403
+ <DropdownMenu open={snoozeMenuOpen} onOpenChange={onSnoozeMenuChange}>
404
+ <DropdownMenuTrigger asChild>
405
+ <Button variant="ghost" size="sm" aria-label="More actions">
406
+ …
407
+ </Button>
408
+ </DropdownMenuTrigger>
409
+ <DropdownMenuContent align="end">
410
+ <DropdownMenuLabel>Snooze</DropdownMenuLabel>
411
+ <DropdownMenuSeparator />
412
+ {snoozePresets(new Date()).map((preset) => (
413
+ <DropdownMenuItem key={preset.key} onSelect={() => onSnooze(preset.until)}>
414
+ {preset.label}
415
+ </DropdownMenuItem>
416
+ ))}
417
+ </DropdownMenuContent>
418
+ </DropdownMenu>
419
+ )}
420
+ </div>
421
+ {open ? (
422
+ <div ref={bodyRef} className="space-y-3 border-t px-3 pb-3 pt-3">
423
+ <decisions.AnswerForm item={item} companyId={companyId} currentUserId={viewerId} />
424
+ <div className="flex flex-wrap items-center gap-3 text-xs">
425
+ {item.whyNow ? (
426
+ <button type="button" className="text-muted-foreground underline-offset-2 hover:underline" onClick={() => setShowContext((shown) => !shown)}>
427
+ {showContext ? "Hide context" : "Show context"}
428
+ </button>
429
+ ) : null}
430
+ {issue?.href ? (
431
+ <Link to={issue.href} className="text-muted-foreground underline-offset-2 hover:underline">
432
+ {issue.identifier ?? "Open issue"}
433
+ </Link>
434
+ ) : null}
435
+ </div>
436
+ {showContext && item.whyNow ? <MarkdownBody className="text-sm">{item.whyNow}</MarkdownBody> : null}
437
+ </div>
438
+ ) : null}
439
+ </article>
440
+ );
441
+ }
@@ -0,0 +1,39 @@
1
+ import { useCallback, useState } from "react";
2
+
3
+ /**
4
+ * Choices the native Decisions page remembers in this browser (V1 of
5
+ * `docs/microvac/decisions.md`; instance and user defaults come later).
6
+ */
7
+ export const GROUPING_STORAGE_KEY = "microvac.decisions.grouping";
8
+ export const SORT_STORAGE_KEY = "microvac.decisions.sort";
9
+
10
+ function storage(): Storage | null {
11
+ try {
12
+ return typeof window === "undefined" ? null : window.localStorage;
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+
18
+ export function readStoredChoice<T extends string>(key: string, choices: readonly T[], fallback: T): T {
19
+ const value = storage()?.getItem(key);
20
+ return value && (choices as readonly string[]).includes(value) ? (value as T) : fallback;
21
+ }
22
+
23
+ export function writeStoredChoice(key: string, value: string): void {
24
+ try {
25
+ storage()?.setItem(key, value);
26
+ } catch {
27
+ // Private mode or a full quota: the choice lasts for this page only.
28
+ }
29
+ }
30
+
31
+ /** A choice read from, and written back to, the browser's storage. */
32
+ export function useStoredChoice<T extends string>(key: string, choices: readonly T[], fallback: T): [T, (next: T) => void] {
33
+ const [value, setValue] = useState<T>(() => readStoredChoice(key, choices, fallback));
34
+ const update = useCallback((next: T) => {
35
+ setValue(next);
36
+ writeStoredChoice(key, next);
37
+ }, [key]);
38
+ return [value, update];
39
+ }
package/src/types.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The part of an attention card (`AttentionItem` of `@paperclipai/shared`,
3
+ * returned by `GET /companies/:id/attention`) this plugin reads. Declared here
4
+ * so the plugin depends on Microvac UI only, not on host packages.
5
+ */
6
+
7
+ export type AttentionSourceKind =
8
+ | "issue_thread_interaction"
9
+ | "decision"
10
+ | "approval"
11
+ | "budget_alert"
12
+ | "join_request"
13
+ | (string & {});
14
+
15
+ export interface AttentionSubject {
16
+ id: string;
17
+ title: string | null;
18
+ identifier: string | null;
19
+ href: string | null;
20
+ metadata?: Record<string, unknown>;
21
+ }
22
+
23
+ export interface AttentionProjectRef {
24
+ id: string;
25
+ name: string;
26
+ color: string | null;
27
+ icon: string | null;
28
+ }
29
+
30
+ export interface AttentionItem {
31
+ id: string;
32
+ sourceKind: AttentionSourceKind;
33
+ subject: AttentionSubject;
34
+ whyNow: string;
35
+ dismissalKey: string;
36
+ dismissal: { kind: string; snoozedUntil: string | null; isActive: boolean } | null;
37
+ activityAt: string;
38
+ createdAt: string;
39
+ relatedIssue: AttentionSubject | null;
40
+ project: AttentionProjectRef | null;
41
+ originAgentName: string | null;
42
+ requester?: { kind: "agent" | "user"; id: string; name: string | null } | null;
43
+ providerLimit?: { state: string } | null;
44
+ archivedAt: string | null;
45
+ snoozedUntil: string | null;
46
+ detail: ({ kind: string; approvalType?: string } & Record<string, unknown>) | null;
47
+ }
48
+
49
+ export interface AttentionFeed {
50
+ items: AttentionItem[];
51
+ }
52
+
53
+ /** Props the host gives the `interaction-card` slot: the upstream card's (only what this plugin reads is typed). */
54
+ export interface InteractionCardProps {
55
+ interaction: { id: string; kind: string; status: string; title?: string | null };
56
+ presentationVariant?: "default" | "coordinator-decision";
57
+ [prop: string]: unknown;
58
+ }
@@ -0,0 +1,62 @@
1
+ import { useMemo } from "react";
2
+ import { decisions, queryKeys, useQueries } from "@microvac/ui";
3
+ import { collectDecisions, DECISION_FEED_VIEWS, type DecisionFeeds, type DecisionList } from "./model.js";
4
+
5
+ /** Live updates: the feed refreshes on its own every minute and when the tab regains focus. */
6
+ const REFRESH_MS = 60_000;
7
+
8
+ /**
9
+ * Under the upstream `attention` key, so every upstream invalidation (an
10
+ * answer, a live update, the issue thread) refreshes the native page too.
11
+ */
12
+ export function nativeDecisionsQueryKey(companyId: string, view: string) {
13
+ return [...queryKeys.attention(companyId), "microvac-native", view] as const;
14
+ }
15
+
16
+ export interface NativeDecisionsState extends DecisionList {
17
+ isLoading: boolean;
18
+ error: Error | null;
19
+ refetch: () => void;
20
+ }
21
+
22
+ /**
23
+ * The native Decisions page's data: the three audience views of the attention
24
+ * feed (whole lists, snoozed cards included), merged into one list. The page
25
+ * and its navigation badge both read it, so the badge always matches the page.
26
+ */
27
+ export function useNativeDecisions(companyId: string | null): NativeDecisionsState {
28
+ const results = useQueries({
29
+ queries: DECISION_FEED_VIEWS.map((view) => ({
30
+ queryKey: nativeDecisionsQueryKey(companyId ?? "", view),
31
+ queryFn: () => decisions.listAttention(companyId!, { view, all: true, includeDismissed: true }),
32
+ enabled: Boolean(companyId),
33
+ refetchInterval: REFRESH_MS,
34
+ refetchOnWindowFocus: true,
35
+ })),
36
+ });
37
+ const mine = results[0]?.data?.items;
38
+ const unassigned = results[1]?.data?.items;
39
+ const company = results[2]?.data?.items;
40
+ const fetchedAt = Math.max(0, ...results.map((result) => result.dataUpdatedAt));
41
+ const list = useMemo(() => {
42
+ const feeds: DecisionFeeds = { mine, unassigned, company };
43
+ return collectDecisions(feeds, Math.max(fetchedAt, Date.now()), decisions.foldObligations);
44
+ }, [mine, unassigned, company, fetchedAt]);
45
+ const failed = results.find((result) => result.error)?.error;
46
+ const error = failed ? (failed instanceof Error ? failed : new Error(String(failed))) : null;
47
+ return {
48
+ ...list,
49
+ isLoading: Boolean(companyId) && results.some((result) => result.isPending),
50
+ error,
51
+ refetch: () => {
52
+ for (const result of results) void result.refetch();
53
+ },
54
+ };
55
+ }
56
+
57
+ /** The navigation badge of the native page: the open decisions it lists. */
58
+ export function useNativeDecisionCount({ companyId }: { companyId: string | null }): number | undefined {
59
+ const { open, isLoading, error } = useNativeDecisions(companyId);
60
+ if (!companyId || isLoading || error) return undefined;
61
+ return open.length;
62
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.