@arbidocs/react 0.5.162 → 0.5.164

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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkSUZORMAB_cjs = require('../chunk-SUZORMAB.cjs');
3
+ var chunkL5TQDBG4_cjs = require('../chunk-L5TQDBG4.cjs');
4
4
  var chunk2IJP73ZG_cjs = require('../chunk-2IJP73ZG.cjs');
5
5
  require('../chunk-WYZJLZ67.cjs');
6
6
  require('../chunk-HJDR5HEO.cjs');
@@ -10,187 +10,187 @@ require('../chunk-S6A6FSG7.cjs');
10
10
 
11
11
  Object.defineProperty(exports, "AUTOSAVE_MS", {
12
12
  enumerable: true,
13
- get: function () { return chunkSUZORMAB_cjs.AUTOSAVE_MS; }
13
+ get: function () { return chunkL5TQDBG4_cjs.AUTOSAVE_MS; }
14
14
  });
15
15
  Object.defineProperty(exports, "AnnotationPageOverlay", {
16
16
  enumerable: true,
17
- get: function () { return chunkSUZORMAB_cjs.AnnotationPageOverlay; }
17
+ get: function () { return chunkL5TQDBG4_cjs.AnnotationPageOverlay; }
18
18
  });
19
19
  Object.defineProperty(exports, "AnnotationStoreOfflineError", {
20
20
  enumerable: true,
21
- get: function () { return chunkSUZORMAB_cjs.AnnotationStoreOfflineError; }
21
+ get: function () { return chunkL5TQDBG4_cjs.AnnotationStoreOfflineError; }
22
22
  });
23
23
  Object.defineProperty(exports, "AnnotationToolbar", {
24
24
  enumerable: true,
25
- get: function () { return chunkSUZORMAB_cjs.AnnotationToolbar; }
25
+ get: function () { return chunkL5TQDBG4_cjs.AnnotationToolbar; }
26
26
  });
27
27
  Object.defineProperty(exports, "DEFAULT_SETTINGS", {
28
28
  enumerable: true,
29
- get: function () { return chunkSUZORMAB_cjs.DEFAULT_SETTINGS; }
29
+ get: function () { return chunkL5TQDBG4_cjs.DEFAULT_SETTINGS; }
30
30
  });
31
31
  Object.defineProperty(exports, "FreezeDialog", {
32
32
  enumerable: true,
33
- get: function () { return chunkSUZORMAB_cjs.FreezeDialog; }
33
+ get: function () { return chunkL5TQDBG4_cjs.FreezeDialog; }
34
34
  });
35
35
  Object.defineProperty(exports, "HIGHLIGHT_COLORS", {
36
36
  enumerable: true,
37
- get: function () { return chunkSUZORMAB_cjs.HIGHLIGHT_COLORS; }
37
+ get: function () { return chunkL5TQDBG4_cjs.HIGHLIGHT_COLORS; }
38
38
  });
39
39
  Object.defineProperty(exports, "MARK_COLORS", {
40
40
  enumerable: true,
41
- get: function () { return chunkSUZORMAB_cjs.MARK_COLORS; }
41
+ get: function () { return chunkL5TQDBG4_cjs.MARK_COLORS; }
42
42
  });
43
43
  Object.defineProperty(exports, "ProductionDialog", {
44
44
  enumerable: true,
45
- get: function () { return chunkSUZORMAB_cjs.ProductionDialog; }
45
+ get: function () { return chunkL5TQDBG4_cjs.ProductionDialog; }
46
46
  });
47
47
  Object.defineProperty(exports, "REDACTION_LOG_COLUMNS", {
48
48
  enumerable: true,
49
- get: function () { return chunkSUZORMAB_cjs.REDACTION_LOG_COLUMNS; }
49
+ get: function () { return chunkL5TQDBG4_cjs.REDACTION_LOG_COLUMNS; }
50
50
  });
51
51
  Object.defineProperty(exports, "REDACTION_REASONS", {
52
52
  enumerable: true,
53
- get: function () { return chunkSUZORMAB_cjs.REDACTION_REASONS; }
53
+ get: function () { return chunkL5TQDBG4_cjs.REDACTION_REASONS; }
54
54
  });
55
55
  Object.defineProperty(exports, "RETRY_MS", {
56
56
  enumerable: true,
57
- get: function () { return chunkSUZORMAB_cjs.RETRY_MS; }
57
+ get: function () { return chunkL5TQDBG4_cjs.RETRY_MS; }
58
58
  });
59
59
  Object.defineProperty(exports, "STAMP_PRESETS", {
60
60
  enumerable: true,
61
- get: function () { return chunkSUZORMAB_cjs.STAMP_PRESETS; }
61
+ get: function () { return chunkL5TQDBG4_cjs.STAMP_PRESETS; }
62
62
  });
63
63
  Object.defineProperty(exports, "annotationsOnPage", {
64
64
  enumerable: true,
65
- get: function () { return chunkSUZORMAB_cjs.annotationsOnPage; }
65
+ get: function () { return chunkL5TQDBG4_cjs.annotationsOnPage; }
66
66
  });
67
67
  Object.defineProperty(exports, "applyAction", {
68
68
  enumerable: true,
69
- get: function () { return chunkSUZORMAB_cjs.applyAction; }
69
+ get: function () { return chunkL5TQDBG4_cjs.applyAction; }
70
70
  });
71
71
  Object.defineProperty(exports, "canRedo", {
72
72
  enumerable: true,
73
- get: function () { return chunkSUZORMAB_cjs.canRedo; }
73
+ get: function () { return chunkL5TQDBG4_cjs.canRedo; }
74
74
  });
75
75
  Object.defineProperty(exports, "canUndo", {
76
76
  enumerable: true,
77
- get: function () { return chunkSUZORMAB_cjs.canUndo; }
77
+ get: function () { return chunkL5TQDBG4_cjs.canUndo; }
78
78
  });
79
79
  Object.defineProperty(exports, "containsPoint", {
80
80
  enumerable: true,
81
- get: function () { return chunkSUZORMAB_cjs.containsPoint; }
81
+ get: function () { return chunkL5TQDBG4_cjs.containsPoint; }
82
82
  });
83
83
  Object.defineProperty(exports, "createHistory", {
84
84
  enumerable: true,
85
- get: function () { return chunkSUZORMAB_cjs.createHistory; }
85
+ get: function () { return chunkL5TQDBG4_cjs.createHistory; }
86
86
  });
87
87
  Object.defineProperty(exports, "createLocalStorageStore", {
88
88
  enumerable: true,
89
- get: function () { return chunkSUZORMAB_cjs.createLocalStorageStore; }
89
+ get: function () { return chunkL5TQDBG4_cjs.createLocalStorageStore; }
90
90
  });
91
91
  Object.defineProperty(exports, "createMemoryStore", {
92
92
  enumerable: true,
93
- get: function () { return chunkSUZORMAB_cjs.createMemoryStore; }
93
+ get: function () { return chunkL5TQDBG4_cjs.createMemoryStore; }
94
94
  });
95
95
  Object.defineProperty(exports, "dragRect", {
96
96
  enumerable: true,
97
- get: function () { return chunkSUZORMAB_cjs.dragRect; }
97
+ get: function () { return chunkL5TQDBG4_cjs.dragRect; }
98
98
  });
99
99
  Object.defineProperty(exports, "dragToNorm", {
100
100
  enumerable: true,
101
- get: function () { return chunkSUZORMAB_cjs.dragToNorm; }
101
+ get: function () { return chunkL5TQDBG4_cjs.dragToNorm; }
102
102
  });
103
103
  Object.defineProperty(exports, "intersects", {
104
104
  enumerable: true,
105
- get: function () { return chunkSUZORMAB_cjs.intersects; }
105
+ get: function () { return chunkL5TQDBG4_cjs.intersects; }
106
106
  });
107
107
  Object.defineProperty(exports, "isTooSmall", {
108
108
  enumerable: true,
109
- get: function () { return chunkSUZORMAB_cjs.isTooSmall; }
109
+ get: function () { return chunkL5TQDBG4_cjs.isTooSmall; }
110
110
  });
111
111
  Object.defineProperty(exports, "layerStatusText", {
112
112
  enumerable: true,
113
- get: function () { return chunkSUZORMAB_cjs.layerStatusText; }
113
+ get: function () { return chunkL5TQDBG4_cjs.layerStatusText; }
114
114
  });
115
115
  Object.defineProperty(exports, "mergeLayers", {
116
116
  enumerable: true,
117
- get: function () { return chunkSUZORMAB_cjs.mergeLayers; }
117
+ get: function () { return chunkL5TQDBG4_cjs.mergeLayers; }
118
118
  });
119
119
  Object.defineProperty(exports, "mergeLineRects", {
120
120
  enumerable: true,
121
- get: function () { return chunkSUZORMAB_cjs.mergeLineRects; }
121
+ get: function () { return chunkL5TQDBG4_cjs.mergeLineRects; }
122
122
  });
123
123
  Object.defineProperty(exports, "moveItem", {
124
124
  enumerable: true,
125
- get: function () { return chunkSUZORMAB_cjs.moveItem; }
125
+ get: function () { return chunkL5TQDBG4_cjs.moveItem; }
126
126
  });
127
127
  Object.defineProperty(exports, "patchForRect", {
128
128
  enumerable: true,
129
- get: function () { return chunkSUZORMAB_cjs.patchForRect; }
129
+ get: function () { return chunkL5TQDBG4_cjs.patchForRect; }
130
130
  });
131
131
  Object.defineProperty(exports, "pendingRedactions", {
132
132
  enumerable: true,
133
- get: function () { return chunkSUZORMAB_cjs.pendingRedactions; }
133
+ get: function () { return chunkL5TQDBG4_cjs.pendingRedactions; }
134
134
  });
135
135
  Object.defineProperty(exports, "qrCornerFor", {
136
136
  enumerable: true,
137
- get: function () { return chunkSUZORMAB_cjs.qrCornerFor; }
137
+ get: function () { return chunkL5TQDBG4_cjs.qrCornerFor; }
138
138
  });
139
139
  Object.defineProperty(exports, "readSelection", {
140
140
  enumerable: true,
141
- get: function () { return chunkSUZORMAB_cjs.readSelection; }
141
+ get: function () { return chunkL5TQDBG4_cjs.readSelection; }
142
142
  });
143
143
  Object.defineProperty(exports, "redactionLogCsv", {
144
144
  enumerable: true,
145
- get: function () { return chunkSUZORMAB_cjs.redactionLogCsv; }
145
+ get: function () { return chunkL5TQDBG4_cjs.redactionLogCsv; }
146
146
  });
147
147
  Object.defineProperty(exports, "redactionLogRows", {
148
148
  enumerable: true,
149
- get: function () { return chunkSUZORMAB_cjs.redactionLogRows; }
149
+ get: function () { return chunkL5TQDBG4_cjs.redactionLogRows; }
150
150
  });
151
151
  Object.defineProperty(exports, "redo", {
152
152
  enumerable: true,
153
- get: function () { return chunkSUZORMAB_cjs.redo; }
153
+ get: function () { return chunkL5TQDBG4_cjs.redo; }
154
154
  });
155
155
  Object.defineProperty(exports, "reduceLayer", {
156
156
  enumerable: true,
157
- get: function () { return chunkSUZORMAB_cjs.reduceLayer; }
157
+ get: function () { return chunkL5TQDBG4_cjs.reduceLayer; }
158
158
  });
159
159
  Object.defineProperty(exports, "sameMarks", {
160
160
  enumerable: true,
161
- get: function () { return chunkSUZORMAB_cjs.sameMarks; }
161
+ get: function () { return chunkL5TQDBG4_cjs.sameMarks; }
162
162
  });
163
163
  Object.defineProperty(exports, "selectionToPageMarks", {
164
164
  enumerable: true,
165
- get: function () { return chunkSUZORMAB_cjs.selectionToPageMarks; }
165
+ get: function () { return chunkL5TQDBG4_cjs.selectionToPageMarks; }
166
166
  });
167
167
  Object.defineProperty(exports, "singleRect", {
168
168
  enumerable: true,
169
- get: function () { return chunkSUZORMAB_cjs.singleRect; }
169
+ get: function () { return chunkL5TQDBG4_cjs.singleRect; }
170
170
  });
171
171
  Object.defineProperty(exports, "toNorm", {
172
172
  enumerable: true,
173
- get: function () { return chunkSUZORMAB_cjs.toNorm; }
173
+ get: function () { return chunkL5TQDBG4_cjs.toNorm; }
174
174
  });
175
175
  Object.defineProperty(exports, "toPixels", {
176
176
  enumerable: true,
177
- get: function () { return chunkSUZORMAB_cjs.toPixels; }
177
+ get: function () { return chunkL5TQDBG4_cjs.toPixels; }
178
178
  });
179
179
  Object.defineProperty(exports, "undo", {
180
180
  enumerable: true,
181
- get: function () { return chunkSUZORMAB_cjs.undo; }
181
+ get: function () { return chunkL5TQDBG4_cjs.undo; }
182
182
  });
183
183
  Object.defineProperty(exports, "useAnnotationLayer", {
184
184
  enumerable: true,
185
- get: function () { return chunkSUZORMAB_cjs.useAnnotationLayer; }
185
+ get: function () { return chunkL5TQDBG4_cjs.useAnnotationLayer; }
186
186
  });
187
187
  Object.defineProperty(exports, "useAnnotationShortcuts", {
188
188
  enumerable: true,
189
- get: function () { return chunkSUZORMAB_cjs.useAnnotationShortcuts; }
189
+ get: function () { return chunkL5TQDBG4_cjs.useAnnotationShortcuts; }
190
190
  });
191
191
  Object.defineProperty(exports, "useTextSelectionMarks", {
192
192
  enumerable: true,
193
- get: function () { return chunkSUZORMAB_cjs.useTextSelectionMarks; }
193
+ get: function () { return chunkL5TQDBG4_cjs.useTextSelectionMarks; }
194
194
  });
195
195
  Object.defineProperty(exports, "AnnotationLayerError", {
196
196
  enumerable: true,
@@ -88,13 +88,17 @@ function useAnnotationLayer({
88
88
  setSavedLayer(null);
89
89
  setStoreReadOnly(false);
90
90
  savedRef.current = null;
91
- commit(createHistory(emptyLayer(documentId, nowRef.current())));
91
+ const placeholder = emptyLayer(documentId, nowRef.current());
92
+ commit(createHistory(placeholder));
92
93
  storeRef.current.load(documentId).then((layer) => {
93
94
  if (cancelled) return;
94
95
  savedRef.current = layer;
95
96
  setSavedLayer(layer);
96
- setStoreReadOnly(storeRef.current.canEdit?.(documentId) === false);
97
- commit(createHistory(layer));
97
+ const canEdit = storeRef.current.canEdit?.(documentId) !== false;
98
+ setStoreReadOnly(!canEdit);
99
+ commit(
100
+ canEdit ? rebaseHistory(historyRef.current, placeholder, layer) : createHistory(layer)
101
+ );
98
102
  setStatus("ready");
99
103
  }).catch((e) => {
100
104
  if (cancelled) return;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/annotations/useAnnotationLayer.ts"],
4
- "sourcesContent": ["/**\n * Annotation state for one document: loads its layer from a store, applies edits through the pure\n * reducer (so undo/redo is exact), and saves back after a short pause.\n *\n * Edits are applied from a ref, not inside a React state updater, so a mark that fails validation\n * is reported through `error` instead of throwing during render.\n *\n * With a shared store (other people edit the same layer) a save may come back merged with their\n * marks, and `pull` brings in their changes while this user is idle. Either way the remote layer is\n * REBASED in: the edits made here since are replayed on top of it with `mergeLayers`, and so is\n * every undo/redo step, so undoing never removes a colleague's mark or brings back one they deleted.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n DEFAULT_SETTINGS,\n type AnnotationController,\n type AnnotationTool,\n type LayerStatus,\n type NewMark,\n type ToolSettings,\n} from './controller'\nimport { mergeLayers } from './merge'\nimport { emptyLayer, type Annotation, type AnnotationLayer } from './model'\nimport {\n applyAction,\n canRedo as historyCanRedo,\n canUndo as historyCanUndo,\n createHistory,\n redo as historyRedo,\n undo as historyUndo,\n type AnnotationAction,\n type LayerHistory,\n} from './state'\nimport { AnnotationStoreOfflineError, type AnnotationStore } from './store'\n\nexport const AUTOSAVE_MS = 600\n/** After a failed save, try again this much later (while edits are still unsaved). */\nexport const RETRY_MS = 10_000\n\nexport interface UseAnnotationLayerOptions {\n documentId: string\n store: AnnotationStore\n /** Display name recorded as the author of new marks. */\n author: string\n autosaveMs?: number\n /** View only: marks are shown and comments can be read, nothing can be changed. */\n readOnly?: boolean\n /** False while the device is offline: edits are kept and saved when it comes back. */\n online?: boolean\n /** Ask the store for others' changes this often while idle (0 = never). Needs `store.pull`. */\n pullMs?: number\n now?: () => string\n makeId?: () => string\n}\n\nconst defaultNow = () => new Date().toISOString()\nconst defaultId = () => globalThis.crypto.randomUUID()\n\n/** Replay a history onto a remote layer: `sent` is what the remote layer was made from. */\nfunction rebaseHistory(\n history: LayerHistory,\n sent: AnnotationLayer,\n remote: AnnotationLayer\n): LayerHistory {\n const onto = (layer: AnnotationLayer) =>\n layer === sent ? remote : mergeLayers({ base: sent, mine: layer, theirs: remote })\n return {\n present: onto(history.present),\n past: history.past.map(onto),\n future: history.future.map(onto),\n }\n}\n\nexport function useAnnotationLayer({\n documentId,\n store,\n author,\n autosaveMs = AUTOSAVE_MS,\n readOnly: readOnlyProp = false,\n online = true,\n pullMs = 0,\n now = defaultNow,\n makeId = defaultId,\n}: UseAnnotationLayerOptions): AnnotationController {\n const [history, setHistory] = useState<LayerHistory>(() =>\n createHistory(emptyLayer(documentId, now()))\n )\n const [savedLayer, setSavedLayer] = useState<AnnotationLayer | null>(null)\n const [status, setStatus] = useState<LayerStatus>('loading')\n const [error, setError] = useState<string | null>(null)\n const [saving, setSaving] = useState(false)\n const [offlineFailure, setOfflineFailure] = useState(false)\n const [storeReadOnly, setStoreReadOnly] = useState(false)\n const [tool, setToolState] = useState<AnnotationTool>('select')\n const [settings, setSettingsState] = useState<ToolSettings>(DEFAULT_SETTINGS)\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const readOnly = readOnlyProp || storeReadOnly\n\n const historyRef = useRef(history)\n const savedRef = useRef<AnnotationLayer | null>(null)\n const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const retryRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const savingRef = useRef(false)\n const docRef = useRef(documentId)\n const storeRef = useRef(store)\n storeRef.current = store\n const nowRef = useRef(now)\n nowRef.current = now\n const idRef = useRef(makeId)\n idRef.current = makeId\n const readOnlyRef = useRef(readOnly)\n readOnlyRef.current = readOnly\n const onlineRef = useRef(online)\n onlineRef.current = online\n const autosaveMsRef = useRef(autosaveMs)\n autosaveMsRef.current = autosaveMs\n\n const commit = useCallback((next: LayerHistory) => {\n historyRef.current = next\n setHistory(next)\n }, [])\n\n /** Take in a layer the store produced from `sent` (a merged save, or others' changes). */\n const adoptRemote = useCallback(\n (sent: AnnotationLayer, remote: AnnotationLayer) => {\n commit(rebaseHistory(historyRef.current, sent, remote))\n savedRef.current = remote\n setSavedLayer(remote)\n },\n [commit]\n )\n\n // Load when the document changes.\n useEffect(() => {\n docRef.current = documentId\n let cancelled = false\n setStatus('loading')\n setError(null)\n setSelectedId(null)\n setSavedLayer(null)\n setStoreReadOnly(false)\n savedRef.current = null\n commit(createHistory(emptyLayer(documentId, nowRef.current())))\n storeRef.current\n .load(documentId)\n .then((layer) => {\n if (cancelled) return\n savedRef.current = layer\n setSavedLayer(layer)\n setStoreReadOnly(storeRef.current.canEdit?.(documentId) === false)\n commit(createHistory(layer))\n setStatus('ready')\n })\n .catch((e: unknown) => {\n if (cancelled) return\n setError(e instanceof Error ? e.message : 'The annotations could not be loaded')\n setStatus('error')\n })\n return () => {\n cancelled = true\n // Leaving this document (switching to another, or unmounting): write the edits still waiting\n // on the autosave timer. Without this they would be silently dropped.\n clearTimeout(timerRef.current)\n clearTimeout(retryRef.current)\n const layer = historyRef.current.present\n if (\n savedRef.current !== null &&\n layer !== savedRef.current &&\n layer.documentId === documentId &&\n !readOnlyRef.current\n ) {\n storeRef.current\n .save(layer)\n .catch((e: unknown) => console.error('Annotations could not be saved', e))\n }\n }\n }, [documentId, commit])\n\n const save = useCallback(async () => {\n clearTimeout(timerRef.current)\n clearTimeout(retryRef.current)\n const layer = historyRef.current.present\n // Nothing to write, not loaded yet (never overwrite a layer with the empty placeholder), view\n // only, or a write already in flight (its completion schedules the next one).\n if (layer === savedRef.current || savedRef.current === null) return\n if (readOnlyRef.current || savingRef.current) return\n if (!onlineRef.current) return // kept; the online effect saves it when the device is back\n savingRef.current = true\n setSaving(true)\n let failed = false\n try {\n const stored = await storeRef.current.save(layer)\n if (layer.documentId === docRef.current) {\n setError(null)\n setOfflineFailure(false)\n if (stored && stored !== layer) {\n adoptRemote(layer, stored)\n } else {\n savedRef.current = layer\n setSavedLayer(layer)\n }\n }\n } catch (e) {\n failed = true\n if (e instanceof AnnotationStoreOfflineError) {\n setOfflineFailure(true)\n } else {\n setError(e instanceof Error ? e.message : 'The annotations could not be saved')\n }\n // Try again later; any new edit also tries again.\n retryRef.current = setTimeout(() => void saveRef.current(), RETRY_MS)\n } finally {\n savingRef.current = false\n setSaving(false)\n // Edits made while this write was in flight go out next (their own timer found it busy).\n if (!failed && historyRef.current.present !== savedRef.current) {\n timerRef.current = setTimeout(() => void saveRef.current(), autosaveMsRef.current)\n }\n }\n }, [adoptRemote])\n const saveRef = useRef(save)\n saveRef.current = save\n\n const present = history.present\n const dirty = status === 'ready' && present !== savedLayer\n\n useEffect(() => {\n if (!dirty || !online || readOnly) return\n timerRef.current = setTimeout(() => void save(), autosaveMs)\n return () => clearTimeout(timerRef.current)\n }, [dirty, present, autosaveMs, save, online, readOnly])\n\n // Back online: the unsaved edits go out at once.\n useEffect(() => {\n if (online) setOfflineFailure(false)\n if (online && savedRef.current !== null && historyRef.current.present !== savedRef.current) {\n void save()\n }\n }, [online, save])\n\n // Others' changes, while this user is idle (nothing unsaved, nothing in flight).\n const pull = useCallback(async () => {\n const s = storeRef.current\n const base = savedRef.current\n if (!s.pull || !base || savingRef.current || !onlineRef.current) return\n if (historyRef.current.present !== base) return\n try {\n const remote = await s.pull(docRef.current)\n if (!remote || remote.documentId !== docRef.current || savedRef.current !== base) return\n adoptRemote(base, remote)\n } catch {\n // A failed pull changes nothing; the next one (or a save) catches up.\n }\n }, [adoptRemote])\n\n useEffect(() => {\n if (!pullMs || status !== 'ready') return\n const timer = setInterval(() => void pull(), pullMs)\n const onFocus = () => void pull()\n window.addEventListener('focus', onFocus)\n return () => {\n clearInterval(timer)\n window.removeEventListener('focus', onFocus)\n }\n }, [pullMs, status, pull])\n\n // The tab can close or reload with edits still waiting on the autosave timer, and React's own\n // cleanup does not run then. Write when the page is being left or hidden (mobile browsers often\n // fire only the latter). `save` starts the store write synchronously, which is what unload needs.\n useEffect(() => {\n const flush = () => void save()\n const onVisibility = () => {\n if (document.visibilityState === 'hidden') flush()\n }\n window.addEventListener('pagehide', flush)\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n window.removeEventListener('pagehide', flush)\n document.removeEventListener('visibilitychange', onVisibility)\n }\n }, [save])\n\n const dispatch = useCallback(\n (action: AnnotationAction): boolean => {\n if (readOnlyRef.current) return false\n try {\n commit(applyAction(historyRef.current, action))\n setError(null)\n return true\n } catch (e) {\n setError(e instanceof Error ? e.message : 'The change was rejected')\n return false\n }\n },\n [commit]\n )\n\n const stamp = useCallback(\n (mark: NewMark): Annotation => {\n const t = nowRef.current()\n return { ...mark, id: idRef.current(), author, createdAt: t, updatedAt: t } as Annotation\n },\n [author]\n )\n\n const offline = !online || offlineFailure\n\n const controller = useMemo<AnnotationController>(() => {\n const exists = (id: string | null) =>\n id !== null && present.annotations.some((a) => a.id === id) ? id : null\n return {\n layer: present,\n status,\n error,\n saving,\n dirty,\n offline,\n readOnly,\n author,\n tool: readOnly ? 'select' : tool,\n setTool: (next) => {\n if (readOnly && next !== 'select') return\n setToolState(next)\n if (next !== 'select') setSelectedId(null)\n },\n settings,\n setSettings: (patch) =>\n setSettingsState((s) => ({ ...s, ...patch, colors: { ...s.colors, ...patch.colors } })),\n selectedId: exists(selectedId),\n select: setSelectedId,\n add: (mark) => {\n const annotation = stamp(mark)\n return dispatch({ type: 'add', annotation }) ? annotation.id : null\n },\n addMany: (marks) => {\n const annotations = marks.map(stamp)\n return dispatch({ type: 'addMany', annotations }) ? annotations.map((a) => a.id) : []\n },\n update: (id, patch) => void dispatch({ type: 'update', id, patch, now: nowRef.current() }),\n remove: (id) => void dispatch({ type: 'remove', id, now: nowRef.current() }),\n setRedactionStatus: (ids, next) =>\n void dispatch({\n type: 'setRedactionStatus',\n ids,\n status: next,\n now: nowRef.current(),\n by: author,\n }),\n reply: (id, body) => {\n const t = nowRef.current()\n void dispatch({\n type: 'reply',\n id,\n reply: { id: idRef.current(), author, createdAt: t, body },\n now: t,\n })\n },\n resolve: (id, resolved) =>\n void dispatch({ type: 'resolve', id, resolved, now: nowRef.current() }),\n undo: () => {\n if (!readOnly) commit(historyUndo(historyRef.current))\n },\n redo: () => {\n if (!readOnly) commit(historyRedo(historyRef.current))\n },\n canUndo: !readOnly && historyCanUndo(history),\n canRedo: !readOnly && historyCanRedo(history),\n flush: save,\n }\n }, [\n present,\n history,\n status,\n error,\n saving,\n dirty,\n offline,\n readOnly,\n author,\n tool,\n settings,\n selectedId,\n stamp,\n dispatch,\n commit,\n save,\n ])\n\n return controller\n}\n"],
5
- "mappings": "AAaA,SAAS,aAAa,WAAW,SAAS,QAAQ,gBAAgB;AAClE;AAAA,EACE;AAAA,OAMK;AACP,SAAS,mBAAmB;AAC5B,SAAS,kBAAyD;AAClE;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX,WAAW;AAAA,EACX;AAAA,EACA,QAAQ;AAAA,EACR,QAAQ;AAAA,OAGH;AACP,SAAS,mCAAyD;AAE3D,MAAM,cAAc;AAEpB,MAAM,WAAW;AAkBxB,MAAM,aAAa,OAAM,oBAAI,KAAK,GAAE,YAAY;AAChD,MAAM,YAAY,MAAM,WAAW,OAAO,WAAW;AAGrD,SAAS,cACP,SACA,MACA,QACc;AACd,QAAM,OAAO,CAAC,UACZ,UAAU,OAAO,SAAS,YAAY,EAAE,MAAM,MAAM,MAAM,OAAO,QAAQ,OAAO,CAAC;AACnF,SAAO;AAAA,IACL,SAAS,KAAK,QAAQ,OAAO;AAAA,IAC7B,MAAM,QAAQ,KAAK,IAAI,IAAI;AAAA,IAC3B,QAAQ,QAAQ,OAAO,IAAI,IAAI;AAAA,EACjC;AACF;AAEO,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb,UAAU,eAAe;AAAA,EACzB,SAAS;AAAA,EAC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;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO;AACT;",
4
+ "sourcesContent": ["/**\n * Annotation state for one document: loads its layer from a store, applies edits through the pure\n * reducer (so undo/redo is exact), and saves back after a short pause.\n *\n * Edits are applied from a ref, not inside a React state updater, so a mark that fails validation\n * is reported through `error` instead of throwing during render.\n *\n * With a shared store (other people edit the same layer) a save may come back merged with their\n * marks, and `pull` brings in their changes while this user is idle. Either way the remote layer is\n * REBASED in: the edits made here since are replayed on top of it with `mergeLayers`, and so is\n * every undo/redo step, so undoing never removes a colleague's mark or brings back one they deleted.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n DEFAULT_SETTINGS,\n type AnnotationController,\n type AnnotationTool,\n type LayerStatus,\n type NewMark,\n type ToolSettings,\n} from './controller'\nimport { mergeLayers } from './merge'\nimport { emptyLayer, type Annotation, type AnnotationLayer } from './model'\nimport {\n applyAction,\n canRedo as historyCanRedo,\n canUndo as historyCanUndo,\n createHistory,\n redo as historyRedo,\n undo as historyUndo,\n type AnnotationAction,\n type LayerHistory,\n} from './state'\nimport { AnnotationStoreOfflineError, type AnnotationStore } from './store'\n\nexport const AUTOSAVE_MS = 600\n/** After a failed save, try again this much later (while edits are still unsaved). */\nexport const RETRY_MS = 10_000\n\nexport interface UseAnnotationLayerOptions {\n documentId: string\n store: AnnotationStore\n /** Display name recorded as the author of new marks. */\n author: string\n autosaveMs?: number\n /** View only: marks are shown and comments can be read, nothing can be changed. */\n readOnly?: boolean\n /** False while the device is offline: edits are kept and saved when it comes back. */\n online?: boolean\n /** Ask the store for others' changes this often while idle (0 = never). Needs `store.pull`. */\n pullMs?: number\n now?: () => string\n makeId?: () => string\n}\n\nconst defaultNow = () => new Date().toISOString()\nconst defaultId = () => globalThis.crypto.randomUUID()\n\n/** Replay a history onto a remote layer: `sent` is what the remote layer was made from. */\nfunction rebaseHistory(\n history: LayerHistory,\n sent: AnnotationLayer,\n remote: AnnotationLayer\n): LayerHistory {\n const onto = (layer: AnnotationLayer) =>\n layer === sent ? remote : mergeLayers({ base: sent, mine: layer, theirs: remote })\n return {\n present: onto(history.present),\n past: history.past.map(onto),\n future: history.future.map(onto),\n }\n}\n\nexport function useAnnotationLayer({\n documentId,\n store,\n author,\n autosaveMs = AUTOSAVE_MS,\n readOnly: readOnlyProp = false,\n online = true,\n pullMs = 0,\n now = defaultNow,\n makeId = defaultId,\n}: UseAnnotationLayerOptions): AnnotationController {\n const [history, setHistory] = useState<LayerHistory>(() =>\n createHistory(emptyLayer(documentId, now()))\n )\n const [savedLayer, setSavedLayer] = useState<AnnotationLayer | null>(null)\n const [status, setStatus] = useState<LayerStatus>('loading')\n const [error, setError] = useState<string | null>(null)\n const [saving, setSaving] = useState(false)\n const [offlineFailure, setOfflineFailure] = useState(false)\n const [storeReadOnly, setStoreReadOnly] = useState(false)\n const [tool, setToolState] = useState<AnnotationTool>('select')\n const [settings, setSettingsState] = useState<ToolSettings>(DEFAULT_SETTINGS)\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const readOnly = readOnlyProp || storeReadOnly\n\n const historyRef = useRef(history)\n const savedRef = useRef<AnnotationLayer | null>(null)\n const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const retryRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const savingRef = useRef(false)\n const docRef = useRef(documentId)\n const storeRef = useRef(store)\n storeRef.current = store\n const nowRef = useRef(now)\n nowRef.current = now\n const idRef = useRef(makeId)\n idRef.current = makeId\n const readOnlyRef = useRef(readOnly)\n readOnlyRef.current = readOnly\n const onlineRef = useRef(online)\n onlineRef.current = online\n const autosaveMsRef = useRef(autosaveMs)\n autosaveMsRef.current = autosaveMs\n\n const commit = useCallback((next: LayerHistory) => {\n historyRef.current = next\n setHistory(next)\n }, [])\n\n /** Take in a layer the store produced from `sent` (a merged save, or others' changes). */\n const adoptRemote = useCallback(\n (sent: AnnotationLayer, remote: AnnotationLayer) => {\n commit(rebaseHistory(historyRef.current, sent, remote))\n savedRef.current = remote\n setSavedLayer(remote)\n },\n [commit]\n )\n\n // Load when the document changes.\n useEffect(() => {\n docRef.current = documentId\n let cancelled = false\n setStatus('loading')\n setError(null)\n setSelectedId(null)\n setSavedLayer(null)\n setStoreReadOnly(false)\n savedRef.current = null\n const placeholder = emptyLayer(documentId, nowRef.current())\n commit(createHistory(placeholder))\n storeRef.current\n .load(documentId)\n .then((layer) => {\n if (cancelled) return\n savedRef.current = layer\n setSavedLayer(layer)\n const canEdit = storeRef.current.canEdit?.(documentId) !== false\n setStoreReadOnly(!canEdit)\n // Marks made while the layer loaded are kept on top of it (and saved), never overwritten by it.\n commit(\n canEdit ? rebaseHistory(historyRef.current, placeholder, layer) : createHistory(layer)\n )\n setStatus('ready')\n })\n .catch((e: unknown) => {\n if (cancelled) return\n setError(e instanceof Error ? e.message : 'The annotations could not be loaded')\n setStatus('error')\n })\n return () => {\n cancelled = true\n // Leaving this document (switching to another, or unmounting): write the edits still waiting\n // on the autosave timer. Without this they would be silently dropped.\n clearTimeout(timerRef.current)\n clearTimeout(retryRef.current)\n const layer = historyRef.current.present\n if (\n savedRef.current !== null &&\n layer !== savedRef.current &&\n layer.documentId === documentId &&\n !readOnlyRef.current\n ) {\n storeRef.current\n .save(layer)\n .catch((e: unknown) => console.error('Annotations could not be saved', e))\n }\n }\n }, [documentId, commit])\n\n const save = useCallback(async () => {\n clearTimeout(timerRef.current)\n clearTimeout(retryRef.current)\n const layer = historyRef.current.present\n // Nothing to write, not loaded yet (never overwrite a layer with the empty placeholder), view\n // only, or a write already in flight (its completion schedules the next one).\n if (layer === savedRef.current || savedRef.current === null) return\n if (readOnlyRef.current || savingRef.current) return\n if (!onlineRef.current) return // kept; the online effect saves it when the device is back\n savingRef.current = true\n setSaving(true)\n let failed = false\n try {\n const stored = await storeRef.current.save(layer)\n if (layer.documentId === docRef.current) {\n setError(null)\n setOfflineFailure(false)\n if (stored && stored !== layer) {\n adoptRemote(layer, stored)\n } else {\n savedRef.current = layer\n setSavedLayer(layer)\n }\n }\n } catch (e) {\n failed = true\n if (e instanceof AnnotationStoreOfflineError) {\n setOfflineFailure(true)\n } else {\n setError(e instanceof Error ? e.message : 'The annotations could not be saved')\n }\n // Try again later; any new edit also tries again.\n retryRef.current = setTimeout(() => void saveRef.current(), RETRY_MS)\n } finally {\n savingRef.current = false\n setSaving(false)\n // Edits made while this write was in flight go out next (their own timer found it busy).\n if (!failed && historyRef.current.present !== savedRef.current) {\n timerRef.current = setTimeout(() => void saveRef.current(), autosaveMsRef.current)\n }\n }\n }, [adoptRemote])\n const saveRef = useRef(save)\n saveRef.current = save\n\n const present = history.present\n const dirty = status === 'ready' && present !== savedLayer\n\n useEffect(() => {\n if (!dirty || !online || readOnly) return\n timerRef.current = setTimeout(() => void save(), autosaveMs)\n return () => clearTimeout(timerRef.current)\n }, [dirty, present, autosaveMs, save, online, readOnly])\n\n // Back online: the unsaved edits go out at once.\n useEffect(() => {\n if (online) setOfflineFailure(false)\n if (online && savedRef.current !== null && historyRef.current.present !== savedRef.current) {\n void save()\n }\n }, [online, save])\n\n // Others' changes, while this user is idle (nothing unsaved, nothing in flight).\n const pull = useCallback(async () => {\n const s = storeRef.current\n const base = savedRef.current\n if (!s.pull || !base || savingRef.current || !onlineRef.current) return\n if (historyRef.current.present !== base) return\n try {\n const remote = await s.pull(docRef.current)\n if (!remote || remote.documentId !== docRef.current || savedRef.current !== base) return\n adoptRemote(base, remote)\n } catch {\n // A failed pull changes nothing; the next one (or a save) catches up.\n }\n }, [adoptRemote])\n\n useEffect(() => {\n if (!pullMs || status !== 'ready') return\n const timer = setInterval(() => void pull(), pullMs)\n const onFocus = () => void pull()\n window.addEventListener('focus', onFocus)\n return () => {\n clearInterval(timer)\n window.removeEventListener('focus', onFocus)\n }\n }, [pullMs, status, pull])\n\n // The tab can close or reload with edits still waiting on the autosave timer, and React's own\n // cleanup does not run then. Write when the page is being left or hidden (mobile browsers often\n // fire only the latter). `save` starts the store write synchronously, which is what unload needs.\n useEffect(() => {\n const flush = () => void save()\n const onVisibility = () => {\n if (document.visibilityState === 'hidden') flush()\n }\n window.addEventListener('pagehide', flush)\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n window.removeEventListener('pagehide', flush)\n document.removeEventListener('visibilitychange', onVisibility)\n }\n }, [save])\n\n const dispatch = useCallback(\n (action: AnnotationAction): boolean => {\n if (readOnlyRef.current) return false\n try {\n commit(applyAction(historyRef.current, action))\n setError(null)\n return true\n } catch (e) {\n setError(e instanceof Error ? e.message : 'The change was rejected')\n return false\n }\n },\n [commit]\n )\n\n const stamp = useCallback(\n (mark: NewMark): Annotation => {\n const t = nowRef.current()\n return { ...mark, id: idRef.current(), author, createdAt: t, updatedAt: t } as Annotation\n },\n [author]\n )\n\n const offline = !online || offlineFailure\n\n const controller = useMemo<AnnotationController>(() => {\n const exists = (id: string | null) =>\n id !== null && present.annotations.some((a) => a.id === id) ? id : null\n return {\n layer: present,\n status,\n error,\n saving,\n dirty,\n offline,\n readOnly,\n author,\n tool: readOnly ? 'select' : tool,\n setTool: (next) => {\n if (readOnly && next !== 'select') return\n setToolState(next)\n if (next !== 'select') setSelectedId(null)\n },\n settings,\n setSettings: (patch) =>\n setSettingsState((s) => ({ ...s, ...patch, colors: { ...s.colors, ...patch.colors } })),\n selectedId: exists(selectedId),\n select: setSelectedId,\n add: (mark) => {\n const annotation = stamp(mark)\n return dispatch({ type: 'add', annotation }) ? annotation.id : null\n },\n addMany: (marks) => {\n const annotations = marks.map(stamp)\n return dispatch({ type: 'addMany', annotations }) ? annotations.map((a) => a.id) : []\n },\n update: (id, patch) => void dispatch({ type: 'update', id, patch, now: nowRef.current() }),\n remove: (id) => void dispatch({ type: 'remove', id, now: nowRef.current() }),\n setRedactionStatus: (ids, next) =>\n void dispatch({\n type: 'setRedactionStatus',\n ids,\n status: next,\n now: nowRef.current(),\n by: author,\n }),\n reply: (id, body) => {\n const t = nowRef.current()\n void dispatch({\n type: 'reply',\n id,\n reply: { id: idRef.current(), author, createdAt: t, body },\n now: t,\n })\n },\n resolve: (id, resolved) =>\n void dispatch({ type: 'resolve', id, resolved, now: nowRef.current() }),\n undo: () => {\n if (!readOnly) commit(historyUndo(historyRef.current))\n },\n redo: () => {\n if (!readOnly) commit(historyRedo(historyRef.current))\n },\n canUndo: !readOnly && historyCanUndo(history),\n canRedo: !readOnly && historyCanRedo(history),\n flush: save,\n }\n }, [\n present,\n history,\n status,\n error,\n saving,\n dirty,\n offline,\n readOnly,\n author,\n tool,\n settings,\n selectedId,\n stamp,\n dispatch,\n commit,\n save,\n ])\n\n return controller\n}\n"],
5
+ "mappings": "AAaA,SAAS,aAAa,WAAW,SAAS,QAAQ,gBAAgB;AAClE;AAAA,EACE;AAAA,OAMK;AACP,SAAS,mBAAmB;AAC5B,SAAS,kBAAyD;AAClE;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX,WAAW;AAAA,EACX;AAAA,EACA,QAAQ;AAAA,EACR,QAAQ;AAAA,OAGH;AACP,SAAS,mCAAyD;AAE3D,MAAM,cAAc;AAEpB,MAAM,WAAW;AAkBxB,MAAM,aAAa,OAAM,oBAAI,KAAK,GAAE,YAAY;AAChD,MAAM,YAAY,MAAM,WAAW,OAAO,WAAW;AAGrD,SAAS,cACP,SACA,MACA,QACc;AACd,QAAM,OAAO,CAAC,UACZ,UAAU,OAAO,SAAS,YAAY,EAAE,MAAM,MAAM,MAAM,OAAO,QAAQ,OAAO,CAAC;AACnF,SAAO;AAAA,IACL,SAAS,KAAK,QAAQ,OAAO;AAAA,IAC7B,MAAM,QAAQ,KAAK,IAAI,IAAI;AAAA,IAC3B,QAAQ,QAAQ,OAAO,IAAI,IAAI;AAAA,EACjC;AACF;AAEO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AA,MACvD;AAAA,MACA,MAAM,MAAM;AACV,YAAI,CAAC,SAAU,QAAO,YAAY,WAAW,OAAO,CAAC;AAAA,MACvD;AAAA,MACA,SAAS,CAAC,YAAY,eAAe,OAAO;AAAA,MAC5C,SAAS,CAAC,YAAY,eAAe,OAAO;AAAA,MAC5C,OAAO;AAAA,IACT;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -3,7 +3,7 @@ import { getUserDisplayName } from "../users/user-display.js";
3
3
  import { arbiQueryKeys } from "../hooks.js";
4
4
  import { useAssistantName } from "../host/assistant-copy.js";
5
5
  import { findConversation, isConversationShared } from "../conversation-list.js";
6
- import { allConversationThreads } from "./conversation-cache.js";
6
+ import { allConversationThreads, getThreadsQueryKey } from "./conversation-cache.js";
7
7
  import {
8
8
  extractMentions,
9
9
  linkMentions
@@ -33,6 +33,15 @@ function cachedMentionCandidates(queryClient, workspaceId, currentUserId, assist
33
33
  const aliases = assistantLabels(assistantName).slice(1).map((label) => ({ id: "assistant", kind: "assistant", label }));
34
34
  return [...buildMentionCandidates(users, currentUserId, assistantName), ...aliases];
35
35
  }
36
+ async function cacheAssistantMode(queryClient, conversationId, mode) {
37
+ const queryKey = getThreadsQueryKey(conversationId);
38
+ await queryClient.cancelQueries({ queryKey });
39
+ queryClient.setQueryData(
40
+ queryKey,
41
+ (old) => old ? { ...old, assistant_mode: mode } : old
42
+ );
43
+ void queryClient.invalidateQueries({ queryKey });
44
+ }
36
45
  function cachedAssistantMode(queryClient, conversationId, newMode) {
37
46
  if (!conversationId) return newMode;
38
47
  const threads = queryClient.getQueriesData(allConversationThreads).map(([, data]) => data).find((data) => data?.conversation_ext_id === conversationId);
@@ -50,6 +59,7 @@ export {
50
59
  ASSISTANT_MENTION_LABEL,
51
60
  assistantLabels,
52
61
  buildMentionCandidates,
62
+ cacheAssistantMode,
53
63
  cachedAssistantMode,
54
64
  cachedMentionCandidates,
55
65
  isCommentToPeople,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/chat/conversation-mentions.ts"],
4
- "sourcesContent": ["/**\n * Who can be @mentioned in a conversation, which mode it is in, and how a message is routed: to\n * ARBI (a turn) or to the people in the thread (a comment). The send path reads the caches here, so\n * it routes exactly as the composer shows.\n */\n\nimport { useCallback } from 'react'\nimport type { QueryClient } from '@tanstack/react-query'\nimport type { components } from '@arbidocs/client'\nimport { getUserDisplayName } from '../users/user-display'\nimport { arbiQueryKeys } from '../hooks'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { findConversation, isConversationShared } from '../conversation-list'\nimport { allConversationThreads } from './conversation-cache'\nimport {\n extractMentions,\n linkMentions,\n type MentionCandidate,\n type MessageMentionRef,\n} from './mentions'\n\ntype WorkspaceUser = components['schemas']['WorkspaceUserResponse']\ntype ThreadsResponse = components['schemas']['ThreadsResponse']\n\n/** When the assistant answers in a conversation: every message, or only when @mentioned. */\nexport type AssistantMode = components['schemas']['AssistantMode']\n\n/**\n * What the assistant is called in the composer when the host names it nothing else\n * (`ArbiHostConfig.assistantName`). The server stores this label with every assistant mention.\n */\nexport const ASSISTANT_MENTION_LABEL = 'ARBI'\n\n/**\n * Every name the assistant answers to: the host's, and \"ARBI\" (the server's stored label, and what\n * people may still type out of habit under a host's own name).\n */\nexport function assistantLabels(assistantName: string = ASSISTANT_MENTION_LABEL): string[] {\n return assistantName.toLowerCase() === ASSISTANT_MENTION_LABEL.toLowerCase()\n ? [assistantName]\n : [assistantName, ASSISTANT_MENTION_LABEL]\n}\n\n/**\n * `linkMentions` on this site: a mention of the assistant typed with the host's name for it is a\n * chip as well as one under the server's stored label (earlier `@ARBI` mentions).\n */\nexport function useLinkMentions(): (\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined\n) => string {\n const assistantName = useAssistantName()\n return useCallback(\n (content, mentions) => linkMentions(content, mentions, [assistantName]),\n [assistantName]\n )\n}\n\n/**\n * The mention candidates for a workspace: the assistant first (as `assistantName`), then every\n * human member except the current user (agents are not mentionable). People's labels use the\n * server's display-name rule so the inserted `@<label>` matches what the server stores.\n */\nexport function buildMentionCandidates(\n users: ReadonlyArray<WorkspaceUser>,\n currentUserId: string | null | undefined,\n assistantName: string = ASSISTANT_MENTION_LABEL\n): MentionCandidate[] {\n const people = users\n .filter((wu) => !wu.agent_ext_id && wu.user.external_id !== currentUserId)\n .map<MentionCandidate>((wu) => ({\n id: wu.user.external_id,\n kind: 'user',\n label: getUserDisplayName(wu.user),\n description: wu.user.email,\n }))\n .sort((a, b) => a.label.localeCompare(b.label))\n return [{ id: 'assistant', kind: 'assistant', label: assistantName }, ...people]\n}\n\n/**\n * A workspace's mention candidates for routing a send, from the cached member list: the menu's,\n * plus the assistant under \"ARBI\" when the host names it otherwise, so a typed `@ARBI` still\n * reaches it (the menu offers only the host's name).\n */\nexport function cachedMentionCandidates(\n queryClient: QueryClient,\n workspaceId: string | null | undefined,\n currentUserId: string | null | undefined,\n assistantName: string = ASSISTANT_MENTION_LABEL\n): MentionCandidate[] {\n const users =\n (workspaceId &&\n queryClient.getQueryData<WorkspaceUser[]>(arbiQueryKeys.workspaceUsers(workspaceId))) ||\n []\n const aliases = assistantLabels(assistantName)\n .slice(1)\n .map<MentionCandidate>((label) => ({ id: 'assistant', kind: 'assistant', label }))\n return [...buildMentionCandidates(users, currentUserId, assistantName), ...aliases]\n}\n\n/**\n * The assistant mode of a conversation from whatever is cached: its threads response (always\n * present once it is open, even when it is not in the cached list, e.g. a thread someone just\n * shared by mentioning you), else its list row. A conversation not created yet uses `newMode`, the\n * mode chosen in the composer.\n */\nexport function cachedAssistantMode(\n queryClient: QueryClient,\n conversationId: string | null | undefined,\n newMode: AssistantMode\n): AssistantMode {\n if (!conversationId) return newMode\n const threads = queryClient\n .getQueriesData<ThreadsResponse>(allConversationThreads)\n .map(([, data]) => data)\n .find((data) => data?.conversation_ext_id === conversationId)\n if (threads?.assistant_mode) return threads.assistant_mode\n return findConversation(queryClient, conversationId)?.assistant_mode ?? 'always'\n}\n\n/**\n * Whether a message is a comment to people rather than a prompt for ARBI. The one rule for\n * routing a message: an @mention of ARBI always addresses ARBI. Otherwise it's a comment in a\n * shared thread, when it @mentions a person, or in a `mentioned`-mode thread (ARBI only on\n * @mention), solo or not: the mode the composer's toggle shows is the one the send follows, and a\n * group chat never calls ARBI unasked because this user's cached list doesn't show it shared yet.\n */\nexport function isCommentToPeople(\n queryClient: QueryClient,\n conversationId: string | null | undefined,\n content: string,\n candidates: ReadonlyArray<MentionCandidate>\n): boolean {\n const mentioned = extractMentions(content, candidates)\n if (mentioned.some((c) => c.kind === 'assistant')) return false\n if (isConversationShared(queryClient, conversationId)) return true\n if (mentioned.some((c) => c.kind === 'user')) return true\n return (\n !!conversationId && cachedAssistantMode(queryClient, conversationId, 'always') === 'mentioned'\n )\n}\n"],
5
- "mappings": "AAMA,SAAS,mBAAmB;AAG5B,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AACjC,SAAS,kBAAkB,4BAA4B;AACvD,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAYA,MAAM,0BAA0B;AAMhC,SAAS,gBAAgB,gBAAwB,yBAAmC;AACzF,SAAO,cAAc,YAAY,MAAM,wBAAwB,YAAY,IACvE,CAAC,aAAa,IACd,CAAC,eAAe,uBAAuB;AAC7C;AAMO,SAAS,kBAGJ;AACV,QAAM,gBAAgB,iBAAiB;AACvC,SAAO;AAAA,IACL,CAAC,SAAS,aAAa,aAAa,SAAS,UAAU,CAAC,aAAa,CAAC;AAAA,IACtE,CAAC,aAAa;AAAA,EAChB;AACF;AAOO,SAAS,uBACd,OACA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K,CAAC,MAAM,EAAE,SAAS,MAAM,EAAG,QAAO;AACrD,SACE,CAAC,CAAC,kBAAkB,oBAAoB,aAAa,gBAAgB,QAAQ,MAAM;AAEvF;",
4
+ "sourcesContent": ["/**\n * Who can be @mentioned in a conversation, which mode it is in, and how a message is routed: to\n * ARBI (a turn) or to the people in the thread (a comment). The send path reads the caches here, so\n * it routes exactly as the composer shows.\n */\n\nimport { useCallback } from 'react'\nimport type { QueryClient } from '@tanstack/react-query'\nimport type { components } from '@arbidocs/client'\nimport { getUserDisplayName } from '../users/user-display'\nimport { arbiQueryKeys } from '../hooks'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { findConversation, isConversationShared } from '../conversation-list'\nimport { allConversationThreads, getThreadsQueryKey } from './conversation-cache'\nimport {\n extractMentions,\n linkMentions,\n type MentionCandidate,\n type MessageMentionRef,\n} from './mentions'\n\ntype WorkspaceUser = components['schemas']['WorkspaceUserResponse']\ntype ThreadsResponse = components['schemas']['ThreadsResponse']\n\n/** When the assistant answers in a conversation: every message, or only when @mentioned. */\nexport type AssistantMode = components['schemas']['AssistantMode']\n\n/**\n * What the assistant is called in the composer when the host names it nothing else\n * (`ArbiHostConfig.assistantName`). The server stores this label with every assistant mention.\n */\nexport const ASSISTANT_MENTION_LABEL = 'ARBI'\n\n/**\n * Every name the assistant answers to: the host's, and \"ARBI\" (the server's stored label, and what\n * people may still type out of habit under a host's own name).\n */\nexport function assistantLabels(assistantName: string = ASSISTANT_MENTION_LABEL): string[] {\n return assistantName.toLowerCase() === ASSISTANT_MENTION_LABEL.toLowerCase()\n ? [assistantName]\n : [assistantName, ASSISTANT_MENTION_LABEL]\n}\n\n/**\n * `linkMentions` on this site: a mention of the assistant typed with the host's name for it is a\n * chip as well as one under the server's stored label (earlier `@ARBI` mentions).\n */\nexport function useLinkMentions(): (\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined\n) => string {\n const assistantName = useAssistantName()\n return useCallback(\n (content, mentions) => linkMentions(content, mentions, [assistantName]),\n [assistantName]\n )\n}\n\n/**\n * The mention candidates for a workspace: the assistant first (as `assistantName`), then every\n * human member except the current user (agents are not mentionable). People's labels use the\n * server's display-name rule so the inserted `@<label>` matches what the server stores.\n */\nexport function buildMentionCandidates(\n users: ReadonlyArray<WorkspaceUser>,\n currentUserId: string | null | undefined,\n assistantName: string = ASSISTANT_MENTION_LABEL\n): MentionCandidate[] {\n const people = users\n .filter((wu) => !wu.agent_ext_id && wu.user.external_id !== currentUserId)\n .map<MentionCandidate>((wu) => ({\n id: wu.user.external_id,\n kind: 'user',\n label: getUserDisplayName(wu.user),\n description: wu.user.email,\n }))\n .sort((a, b) => a.label.localeCompare(b.label))\n return [{ id: 'assistant', kind: 'assistant', label: assistantName }, ...people]\n}\n\n/**\n * A workspace's mention candidates for routing a send, from the cached member list: the menu's,\n * plus the assistant under \"ARBI\" when the host names it otherwise, so a typed `@ARBI` still\n * reaches it (the menu offers only the host's name).\n */\nexport function cachedMentionCandidates(\n queryClient: QueryClient,\n workspaceId: string | null | undefined,\n currentUserId: string | null | undefined,\n assistantName: string = ASSISTANT_MENTION_LABEL\n): MentionCandidate[] {\n const users =\n (workspaceId &&\n queryClient.getQueryData<WorkspaceUser[]>(arbiQueryKeys.workspaceUsers(workspaceId))) ||\n []\n const aliases = assistantLabels(assistantName)\n .slice(1)\n .map<MentionCandidate>((label) => ({ id: 'assistant', kind: 'assistant', label }))\n return [...buildMentionCandidates(users, currentUserId, assistantName), ...aliases]\n}\n\n/**\n * The assistant mode of a conversation from whatever is cached: its threads response (always\n * present once it is open, even when it is not in the cached list, e.g. a thread someone just\n * shared by mentioning you), else its list row. A conversation not created yet uses `newMode`, the\n * mode chosen in the composer.\n */\n/**\n * Record a mode the server just accepted in the conversation's cached threads. A read of them sent before the\n * change would answer with the old mode and undo it: it is cancelled first, and the threads read again.\n */\nexport async function cacheAssistantMode(\n queryClient: QueryClient,\n conversationId: string,\n mode: AssistantMode\n): Promise<void> {\n const queryKey = getThreadsQueryKey(conversationId)\n await queryClient.cancelQueries({ queryKey })\n queryClient.setQueryData<ThreadsResponse>(queryKey, (old) =>\n old ? { ...old, assistant_mode: mode } : old\n )\n void queryClient.invalidateQueries({ queryKey })\n}\n\nexport function cachedAssistantMode(\n queryClient: QueryClient,\n conversationId: string | null | undefined,\n newMode: AssistantMode\n): AssistantMode {\n if (!conversationId) return newMode\n const threads = queryClient\n .getQueriesData<ThreadsResponse>(allConversationThreads)\n .map(([, data]) => data)\n .find((data) => data?.conversation_ext_id === conversationId)\n if (threads?.assistant_mode) return threads.assistant_mode\n return findConversation(queryClient, conversationId)?.assistant_mode ?? 'always'\n}\n\n/**\n * Whether a message is a comment to people rather than a prompt for ARBI. The one rule for\n * routing a message: an @mention of ARBI always addresses ARBI. Otherwise it's a comment in a\n * shared thread, when it @mentions a person, or in a `mentioned`-mode thread (ARBI only on\n * @mention), solo or not: the mode the composer's toggle shows is the one the send follows, and a\n * group chat never calls ARBI unasked because this user's cached list doesn't show it shared yet.\n */\nexport function isCommentToPeople(\n queryClient: QueryClient,\n conversationId: string | null | undefined,\n content: string,\n candidates: ReadonlyArray<MentionCandidate>\n): boolean {\n const mentioned = extractMentions(content, candidates)\n if (mentioned.some((c) => c.kind === 'assistant')) return false\n if (isConversationShared(queryClient, conversationId)) return true\n if (mentioned.some((c) => c.kind === 'user')) return true\n return (\n !!conversationId && cachedAssistantMode(queryClient, conversationId, 'always') === 'mentioned'\n )\n}\n"],
5
+ "mappings": "AAMA,SAAS,mBAAmB;AAG5B,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AACjC,SAAS,kBAAkB,4BAA4B;AACvD,SAAS,wBAAwB,0BAA0B;AAC3D;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAYA,MAAM,0BAA0B;AAMhC,SAAS,gBAAgB,gBAAwB,yBAAmC;AACzF,SAAO,cAAc,YAAY,MAAM,wBAAwB,YAAY,IACvE,CAAC,aAAa,IACd,CAAC,eAA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,SACe;AACf,MAAI,CAAC,eAAgB,QAAO;AAC5B,QAAM,UAAU,YACb,eAAgC,sBAAsB,EACtD,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,IAAI,EACtB,KAAK,CAAC,SAAS,MAAM,wBAAwB,cAAc;AAC9D,MAAI,SAAS,eAAgB,QAAO,QAAQ;AAC5C,SAAO,iBAAiB,aAAa,cAAc,GAAG,kBAAkB;AAC1E;AASO,SAAS,kBACd,aACA,gBACA,SACA,YACS;AACT,QAAM,YAAY,gBAAgB,SAAS,UAAU;AACrD,MAAI,UAAU,KAAK,CAAC,MAAM,EAAE,SAAS,WAAW,EAAG,QAAO;AAC1D,MAAI,qBAAqB,aAAa,cAAc,EAAG,QAAO;AAC9D,MAAI,UAAU,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,EAAG,QAAO;AACrD,SACE,CAAC,CAAC,kBAAkB,oBAAoB,aAAa,gBAAgB,QAAQ,MAAM;AAEvF;",
6
6
  "names": []
7
7
  }
@@ -7,8 +7,8 @@ import { refreshDocuments, useDocuments } from "../documents/documents-data.js";
7
7
  import { removeConversationFromLists } from "../conversation-list.js";
8
8
  import { useArbiSessionState, useArbiSessionStore } from "../session/index.js";
9
9
  import { toChatCitations } from "./citations.js";
10
- import { getThreadsQueryKey } from "./conversation-cache.js";
11
10
  import {
11
+ cacheAssistantMode,
12
12
  cachedAssistantMode,
13
13
  cachedMentionCandidates,
14
14
  isCommentToPeople
@@ -295,11 +295,7 @@ function useConversation(options = {}) {
295
295
  setHistoryError(null);
296
296
  try {
297
297
  await arbi.conversations.setAssistantMode(conversationId, mode);
298
- queryClient.setQueryData(
299
- getThreadsQueryKey(conversationId),
300
- (old) => old ? { ...old, assistant_mode: mode } : old
301
- );
302
- void queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) });
298
+ await cacheAssistantMode(queryClient, conversationId, mode);
303
299
  void (agentId ? agentHistory.refetch() : ordinaryHistory.refetch());
304
300
  } catch (e) {
305
301
  setHistoryError(messageOf(e, "The assistant mode could not be changed."));