fsanyoto commited on
Commit
98370b2
·
verified ·
1 Parent(s): 8145bee

Prune files not in the deploy set (stale build context)

Browse files
web/src/customer-grid/GridChat.tsx DELETED
@@ -1,484 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / GridChat.tsx — the docked chat for ANY database view (W37-T40, R2, R10, C6).
3
- //
4
- // Owner items 10 and 11 are ONE feature (ruling R2): the chat IS the builder. This is its shell —
5
- // the conversation surface every later ticket in the lane hangs a power off. T42 gives it the
6
- // schema to answer from, T43 the view controls, and T45 the confirmed record edit.
7
- //
8
- // ⛔⛔ IT REACHES INTO NOTHING. Contract C6: every action is a callback the host supplies, and
9
- // EVERY PROP IS REQUIRED. An optional prop is how a panel ships mounted-but-inert — the feature is
10
- // whole, the gate is green, and the one line that would have passed the callback was never
11
- // written. This repo shipped five of those in a single wave. A required prop makes the omission a
12
- // compile error in the mounting file, which is where a person can see it.
13
- //
14
- // ⚠ THE SHAPE IS THE ONE THIS PRODUCT ALREADY HAS, not a third chat look. `AutomationChat` and
15
- // `AssistantPage` both render a centred opening while the transcript is empty, then a log with the
16
- // SAME composer moved to the foot; `FieldAgentChat` reuses the same composer classes rather than
17
- // drawing a second one. Copying that is not laziness, it is the reason the owner cannot tell which
18
- // surface was built by whom.
19
- //
20
- // ⚠ NO `import.meta.env` ANYWHERE IN THIS FILE'S GRAPH, and the constraint is load-bearing rather
21
- // than stylistic: the gate renders this component from a CommonJS build, and `import.meta` cannot
22
- // be required from one. `AutomationChat`'s own header records that exact crash. The imports below
23
- // are `react` + `./gridChat` + the stylesheet, and nothing else.
24
- // ---------------------------------------------------------------------------
25
-
26
- import { useCallback, useEffect, useRef, useState } from "react";
27
-
28
- import {
29
- answered,
30
- asked,
31
- composerHint,
32
- editSummary,
33
- emptyChat,
34
- failed,
35
- isBusy,
36
- noted,
37
- proposedEdits,
38
- readIntent,
39
- wrote,
40
- } from "./gridChat";
41
- import type {
42
- GridChatAnswer,
43
- GridChatEdit,
44
- GridChatField,
45
- GridChatState,
46
- GridChatTurn,
47
- } from "./gridChat";
48
- import "./gridChat.css";
49
-
50
- // ⭐ RE-EXPORTED SO THE MOUNTING FILE TAKES ONE IMPORT. The types live in `gridChat.ts` (they have
51
- // to: the state machine is typed by them and that module must stay React-free), but a host that
52
- // had to import the component from here and its types from there would be one refactor away from
53
- // the two drifting. Published to C in mailbox E-4 as a single import line.
54
- export type {
55
- GridChatAnswer,
56
- GridChatEdit,
57
- GridChatField,
58
- GridChatState,
59
- GridChatTurn,
60
- };
61
-
62
- /**
63
- * What the host asks the chat to do about the view. ⚠ DELIBERATELY NARROW: this is the vocabulary
64
- * `assistant build_view` already speaks, minus what it cannot express. There is no `rhs` in that
65
- * tool schema, so a field-versus-field condition is not sayable
66
- * [[assistant-build-view-is-a-subset]] — W37-T43 has to SAY it cannot rather than fail quietly.
67
- */
68
- export interface GridChatViewSpec {
69
- /**
70
- * ⚠ RESERVED AND DELIBERATELY NOT POPULATED BY `readIntent` YET. The panel understands
71
- * sort/group/colour from a sentence; a real FILTER needs the condition vocabulary the host owns,
72
- * so this is the slot C fills rather than a field the panel quietly leaves empty. Named here so
73
- * it reads as a contract with a known gap instead of a channel nobody noticed was dead
74
- * [[flag-shipped-without-its-writer]].
75
- */
76
- filter?: unknown;
77
- sortBy?: string;
78
- groupBy?: string;
79
- colorBy?: string;
80
- }
81
-
82
- export interface GridChatProps {
83
- /** The host owns the toggle. The panel never closes itself except through `onClose`. */
84
- open: boolean;
85
- onClose: () => void;
86
- /** What this chat is reading, in the person's words. Appears in the header and the placeholder. */
87
- databaseLabel: string;
88
- /** The columns the chat may reason about. The host decides; the chat never discovers. */
89
- schema: GridChatField[];
90
- rowCount: number;
91
- /**
92
- * ⛔ R10's BOUND, EXPRESSED AS AN AFFORDANCE. `false` means the edit power is not OFFERED, not
93
- * that it is offered and then refused. The chat is not a privilege escalation: a caller whose
94
- * own permissions would refuse the write must not be invited to compose one
95
- * [[permitted-is-not-answerable]].
96
- */
97
- canEdit: boolean;
98
- /**
99
- * ⭐ D-668 (W52-T09): whether "Undo view" is a real affordance for THIS host. `onUndoView` is
100
- * still required below (a caller with nothing to undo names that with a stub, same as the
101
- * chat's other unopened doors), but a host with no saved-view concept at all - the Sheet has
102
- * ONE view kind and no history to put back (wave-49 R2) - must say so explicitly rather than
103
- * offer a button that always does nothing. Named, not inferred from `canEdit`: view undo and
104
- * cell-write permission are different questions, and a viewer who may not write may still be
105
- * allowed to undo a view.
106
- */
107
- canUndoView: boolean;
108
- /** (a) answer a question about this database. */
109
- onDescribe: (question: string) => Promise<GridChatAnswer>;
110
- /** (b) change filter, sort, group or colour on the ACTIVE view. */
111
- onApplyView: (spec: GridChatViewSpec) => void;
112
- /** (b, undo half) put the view back the way it was. Offered only when `canUndoView` is true. */
113
- onUndoView: () => void;
114
- /** (d) write the cells the person just confirmed. ⛔ Reached only from the confirm control. */
115
- onWriteCells: (edits: GridChatEdit[]) => Promise<void>;
116
- }
117
-
118
- /** The send mark. ⛔ The Assistant's own path, point for point: a second arrow drawn slightly
119
- * differently is precisely how two surfaces stop looking like one product. */
120
- function SendMark() {
121
- return (
122
- <svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true" fill="none">
123
- <path d="M8 13V3.6M4 7.4 8 3.4l4 4" stroke="currentColor" strokeWidth="1.5"
124
- strokeLinecap="round" strokeLinejoin="round" />
125
- </svg>
126
- );
127
- }
128
-
129
- export default function GridChat(props: GridChatProps) {
130
- const {
131
- open, onClose, databaseLabel, schema, rowCount, canEdit, canUndoView,
132
- onDescribe, onApplyView, onUndoView, onWriteCells,
133
- } = props;
134
-
135
- const [state, setState] = useState<GridChatState>(emptyChat);
136
- const [draft, setDraft] = useState("");
137
- const [writing, setWriting] = useState(false);
138
- const logRef = useRef<HTMLDivElement | null>(null);
139
- const busy = isBusy(state);
140
-
141
- // The transcript follows the newest turn. Guarded on the ref because the log is not rendered at
142
- // all while the conversation is empty (see the opening below).
143
- useEffect(() => {
144
- const log = logRef.current;
145
- if (log) log.scrollTop = log.scrollHeight;
146
- }, [state.turns.length, busy]);
147
-
148
- const send = useCallback(() => {
149
- const said = draft.trim();
150
- if (!said || busy) return;
151
- setState((s) => asked(s, said));
152
- setDraft("");
153
-
154
- // ⭐⭐ W37-T42/T43/T44 — READ THE SENTENCE BEFORE SPENDING ANYTHING ON IT.
155
- // ⛔ THE REFUSAL BRANCH IS THE POINT OF T42 AND IT COSTS NOTHING. D-339's defect is an agent
156
- // that cannot read the database answering from words alone and inventing a number. The panel
157
- // HOLDS the schema, so a question naming a field this database does not have is answered here,
158
- // truthfully, without a model call that could only guess.
159
- const intent = readIntent(schema, databaseLabel, said);
160
- if (intent.refusal) {
161
- setState((s) => answered(s, said, { text: intent.refusal!, unanswerable: true }));
162
- return;
163
- }
164
- // ⚠ ...and a question the panel already knows the answer to is not a paid round trip either.
165
- if (intent.localAnswer) {
166
- setState((s) => answered(s, said, { text: intent.localAnswer! }));
167
- return;
168
- }
169
- if (intent.kind === "view") {
170
- // T43: the VIEW changes through the host's callback (C6), and what could NOT be expressed is
171
- // named rather than dropped [[assistant-build-view-is-a-subset]].
172
- if (intent.view) onApplyView(intent.view);
173
- const applied = intent.view
174
- ? "The view has been changed. Ask again or press Undo to put it back."
175
- : "I could not tell which field you meant, so the view is unchanged.";
176
- setState((s) => answered(s, said, {
177
- text: intent.cannot ? `${applied} ${intent.cannot}` : applied,
178
- }));
179
- return;
180
- }
181
-
182
- void (async () => {
183
- try {
184
- const answer = await onDescribe(said);
185
- // ⛔ THE PROPOSAL BRANCH IS HERE AND NOT IN THE HOST. A host that returned edits and also
186
- // wrote them would make the confirm cosmetic; the panel decides that edits mean "show the
187
- // person first", so there is exactly one place that decision can be got wrong.
188
- // ⚠ NO CAST. `GridChatAnswer.edits` is a declared part of the contract now, so the host
189
- // reads the same channel this line does; it used to be an `as` and the two could drift.
190
- const edits = answer?.edits;
191
- setState((s) => (canEdit && Array.isArray(edits) && edits.length
192
- ? proposedEdits(s, said, answer.text, edits)
193
- : answered(s, said, answer)));
194
- } catch (err) {
195
- const sentence = err instanceof Error ? err.message : "";
196
- setState((s) => failed(s, said, sentence));
197
- }
198
- })();
199
- }, [draft, busy, canEdit, onDescribe, onApplyView, schema, databaseLabel]);
200
-
201
- const confirmWrite = useCallback((edits: GridChatEdit[]) => {
202
- if (writing) return;
203
- setWriting(true);
204
- void (async () => {
205
- try {
206
- await onWriteCells(edits);
207
- // ⛔ `wrote` rather than `noted`: the note it appends CARRIES THE INVERSE, built from the
208
- // `before` values the person confirmed. An undo assembled after the write would have
209
- // nothing left to read [[capture-the-inverse-before-the-write]].
210
- setState((s) => wrote(s, edits));
211
- } catch (err) {
212
- const sentence = err instanceof Error && err.message
213
- ? err.message
214
- : "That write was refused, so nothing changed.";
215
- setState((s) => noted(s, sentence));
216
- } finally {
217
- setWriting(false);
218
- }
219
- })();
220
- }, [onWriteCells, writing]);
221
-
222
- if (!open) return null;
223
- return (
224
- <GridChatView
225
- state={state}
226
- draft={draft}
227
- writing={writing}
228
- databaseLabel={databaseLabel}
229
- schema={schema}
230
- rowCount={rowCount}
231
- canEdit={canEdit}
232
- canUndoView={canUndoView}
233
- logRef={logRef}
234
- onClose={onClose}
235
- onDraft={setDraft}
236
- onSend={send}
237
- onUndoView={onUndoView}
238
- onConfirmWrite={confirmWrite}
239
- onDeclineWrite={() => setState((s) => noted(s, "Nothing was written."))}
240
- />
241
- );
242
- }
243
-
244
- /**
245
- * ⭐⭐ THE PRESENTATIONAL HALF, AND IT IS SPLIT OUT FOR A REASON A GATE CAN USE.
246
- *
247
- * `<GridChat>` owns the state; this owns the pixels and takes the state as a prop. That split is
248
- * what makes T40's `done-when` observable at all: the only renderer available in this repo is
249
- * `react-dom/server`, which fires no events and runs no effects, so a gate can never DRIVE a
250
- * stateful component into its in-flight or error state. It can render THIS one into any state it
251
- * likes, because the state is an argument.
252
- *
253
- * ⛔ THE HOST NEVER IMPORTS THIS. `GridChat` is the default export and the contract C6 describes;
254
- * every prop on it is required, and nothing here weakens that. Splitting the render out is the
255
- * opposite of an optional prop: it adds a seam for the gate without adding a way for a mount to
256
- * be silently inert.
257
- */
258
- export function GridChatView(props: {
259
- state: GridChatState;
260
- draft: string;
261
- writing: boolean;
262
- databaseLabel: string;
263
- schema: GridChatField[];
264
- rowCount: number;
265
- canEdit: boolean;
266
- /** D-668 (W52-T09): whether "Undo view" renders at all. See `GridChatProps`'s own note. */
267
- canUndoView: boolean;
268
- // ⚠ Typed exactly as `useRef<HTMLDivElement | null>(null)` produces it, and OPTIONAL only
269
- // here: a server render has no DOM to scroll, so the gate omits it. The stateful shell
270
- // above always passes one.
271
- logRef?: React.Ref<HTMLDivElement>;
272
- onClose: () => void;
273
- onDraft: (text: string) => void;
274
- onSend: () => void;
275
- onUndoView: () => void;
276
- onConfirmWrite: (edits: GridChatEdit[]) => void;
277
- onDeclineWrite: () => void;
278
- }) {
279
- const {
280
- state, draft, writing, databaseLabel, schema, rowCount, canEdit, canUndoView, logRef,
281
- onClose, onDraft, onSend, onUndoView, onConfirmWrite, onDeclineWrite,
282
- } = props;
283
- const busy = isBusy(state);
284
- const hint = composerHint(databaseLabel, canEdit);
285
-
286
- const composer = (
287
- <div className="cg-chat-composer">
288
- <textarea
289
- className="cg-chat-input"
290
- value={draft}
291
- rows={2}
292
- placeholder={hint}
293
- aria-label={hint}
294
- disabled={busy}
295
- onChange={(e) => onDraft(e.target.value)}
296
- onKeyDown={(e) => {
297
- if (e.key === "Enter" && !e.shiftKey) {
298
- e.preventDefault();
299
- onSend();
300
- }
301
- }}
302
- />
303
- <div className="cg-chat-composer-foot">
304
- {/* ⚠ THE SCOPE LINE, NOT A DISCLAIMER. It says what the chat is reading, which is the one
305
- thing a person cannot tell by looking at a docked panel. */}
306
- <span className="cg-chat-scope">
307
- {rowCount === 1 ? "1 record" : `${rowCount} records`}
308
- {schema.length ? `, ${schema.length === 1 ? "1 field" : `${schema.length} fields`}` : ""}
309
- </span>
310
- <span className="cg-chat-spacer" />
311
- {/* ⭐ W37-T43's "and the change is undoable", as a control rather than a promise. It sits
312
- beside Send because that is where the person is after asking for a view change, and it
313
- calls the host's own undo so there is one place a view can be put back.
314
- ⛔ D-668 (W52-T09): GATED ON `canUndoView`, NOT ALWAYS RENDERED. A host with no
315
- saved-view concept - the Sheet has ONE view kind and no history to put back
316
- (wave-49 R2) - has nothing for this to undo, and a button that always does nothing is
317
- the defect, not a feature this host merely lacks. */}
318
- {canUndoView && (
319
- <button
320
- type="button"
321
- className="cg-chat-ghost"
322
- onClick={onUndoView}
323
- title="Put the view back the way it was"
324
- >
325
- Undo view
326
- </button>
327
- )}
328
- <button
329
- type="button"
330
- className="cg-chat-send"
331
- onClick={onSend}
332
- disabled={busy || draft.trim() === ""}
333
- aria-label="Send"
334
- title="Send"
335
- >
336
- <SendMark />
337
- </button>
338
- </div>
339
- </div>
340
- );
341
-
342
- return (
343
- <aside className="cg-chat" aria-label={`Chat about ${databaseLabel}`}>
344
- <header className="cg-chat-head">
345
- <span className="cg-chat-title">{databaseLabel}</span>
346
- <button
347
- type="button"
348
- className="cg-chat-close"
349
- onClick={onClose}
350
- aria-label="Close the chat"
351
- title="Close the chat"
352
- >
353
- <svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true" fill="none">
354
- <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
355
- strokeLinecap="round" />
356
- </svg>
357
- </button>
358
- </header>
359
-
360
- {/* ⛔ THE LOG IS NOT RENDERED AT ALL WHEN EMPTY, and `hidden` would be the bug. `.cg-chat-log`
361
- sets `display: flex`, and an author rule beats the user-agent `[hidden] { display: none }`
362
- whatever its specificity. `hidden` would take the log out of the accessibility tree and
363
- leave it PAINTED: an empty flex band shoving the centred opening off centre. That exact
364
- defect was found and written down one wave ago in `AutomationChat`, and it is invisible to
365
- any assertion that reads markup as text [[ui-invisible-to-assertions]]. */}
366
- {state.turns.length ? (
367
- <div className="cg-chat-log" ref={logRef}>
368
- {state.turns.map((turn, i) => (
369
- <div className="cg-chat-turn" key={i}>
370
- <div
371
- className={
372
- "cg-chat-msg " +
373
- (turn.error ? "is-error" : turn.who === "you" ? "is-you"
374
- : turn.who === "note" ? "is-note" : "is-assistant")
375
- }
376
- >
377
- {turn.text}
378
- </div>
379
-
380
- {/* ⭐ UNDO, OFFERED FROM THE TRANSCRIPT. R10 says the person confirms before a write;
381
- this is the other half of taking them seriously. A confirmed write they did not
382
- mean stays reversible in the place they are already looking, rather than behind a
383
- toast that faded while they read the result.
384
- ⛔ IT ROUTES THROUGH THE SAME `onWriteCells` the original went through, so the
385
- undo passes the caller's permission wall exactly as the write did. An undo with
386
- its own door would be a second write path, and the one nobody tested. */}
387
- {canEdit && turn.undo?.length ? (
388
- <div className="cg-chat-undo">
389
- <button
390
- type="button"
391
- className="cg-chat-ghost"
392
- disabled={writing}
393
- onClick={() => onConfirmWrite(turn.undo || [])}
394
- >
395
- Put it back
396
- </button>
397
- </div>
398
- ) : null}
399
-
400
- {/* ⛔⛔ R10 ON SCREEN: EXACTLY WHAT WILL BE WRITTEN, BEFORE ANYTHING IS. Not a count,
401
- not a summary of a summary. The person sees the record, the field, the old value
402
- and the new one, and nothing reaches `onWriteCells` until they press Write. */}
403
- {/* ⛔⛔ `canEdit` IS CHECKED HERE, IN THE VIEW, AND NOT ONLY WHERE THE PROPOSAL IS
404
- BUILT. The stateful shell already refuses to build a proposal for a caller who
405
- may not write, so this looked redundant and was left out of the first draft; the
406
- gate caught it. The wall has to sit where the CONTROL is drawn, because the view
407
- renders whatever state it is handed and a second caller, a replayed transcript or
408
- a permission that changed mid-session would otherwise paint a Write button for
409
- somebody the store is going to refuse [[permitted-is-not-answerable]]. A wall
410
- that depends on its caller's discipline is not a wall. */}
411
- {canEdit && turn.edits?.length ? (
412
- <div className="cg-chat-edits">
413
- <p className="cg-chat-edits-head">{editSummary(turn.edits)}</p>
414
- <table className="cg-chat-edits-table">
415
- <thead>
416
- <tr><th>Record</th><th>Field</th><th>Now</th><th>Would become</th></tr>
417
- </thead>
418
- <tbody>
419
- {turn.edits.map((edit, j) => (
420
- <tr key={j}>
421
- <td>{edit.rowLabel || edit.rowId}</td>
422
- <td>{edit.fieldLabel || edit.field}</td>
423
- <td className="cg-chat-before">{edit.before || "empty"}</td>
424
- <td className="cg-chat-after">{edit.after || "empty"}</td>
425
- </tr>
426
- ))}
427
- </tbody>
428
- </table>
429
- <div className="cg-chat-edits-act">
430
- <button
431
- type="button"
432
- className="cg-chat-ghost"
433
- disabled={writing}
434
- onClick={onDeclineWrite}
435
- >
436
- Leave it
437
- </button>
438
- <button
439
- type="button"
440
- className="cg-chat-go"
441
- disabled={writing}
442
- onClick={() => onConfirmWrite(turn.edits || [])}
443
- >
444
- {writing ? "Writing" : "Write these"}
445
- </button>
446
- </div>
447
- </div>
448
- ) : null}
449
- </div>
450
- ))}
451
-
452
- {/* ⚠ `.lp-spin` is the ONE loading mark in this application. A second spinner vocabulary
453
- in a new surface is how an app stops having one. */}
454
- {busy ? (
455
- <div className="cg-chat-pending" role="status">
456
- <span className="lp-spin" aria-hidden="true" />
457
- Reading {databaseLabel}
458
- </div>
459
- ) : null}
460
- </div>
461
- ) : null}
462
-
463
- {/* The centred opening, exactly the shape `AssistantPage` and `AutomationChat` already use.
464
- ⚠ NO DECORATIVE MARK: the reference image has a soft dot ring, and neither of this
465
- product's two existing chat surfaces does. A mark on the third one is the difference the
466
- owner would notice. */}
467
- {state.turns.length ? null : (
468
- <div className="cg-chat-opening">
469
- <h2 className="cg-chat-opening-h">How can I help?</h2>
470
- <p className="cg-chat-opening-p">
471
- {canEdit
472
- ? "Ask about the records in front of you, change what the view shows, or say what to change. Nothing is written until you confirm it."
473
- : "Ask about the records in front of you, or change what the view shows."}
474
- </p>
475
- {composer}
476
- </div>
477
- )}
478
-
479
- {/* ⚠ ONE composer const, rendered in exactly one place at a time. Two on screen at once is
480
- the defect this pattern exists to make impossible. */}
481
- {state.turns.length ? <div className="cg-chat-foot">{composer}</div> : null}
482
- </aside>
483
- );
484
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/gridChat.css DELETED
@@ -1,294 +0,0 @@
1
- /* customer-grid/gridChat.css — the docked chat panel (W37-T40, contract C8).
2
- *
3
- * ⛔ MODULE-LOCAL BY CONTRACT, not by preference. C8 hands `index.css` (12k+ lines) to lane A
4
- * alone this wave, and every other lane adds styles in its own per-surface sheet imported by its
5
- * own component. The precedent already exists next door in `navExtras.css`.
6
- * ⚠ Colours come from the design tokens (navy #1F4E78 + gold #C8A24B, DESIGN.md), never from fresh
7
- * hexes: a surface that invents its own palette is the thing the constitution exists to prevent.
8
- * Only the tokens this file actually uses are named.
9
- * ⛔⛔ NO FALLBACK LITERAL INSIDE A `font:` SHORTHAND, and this sheet shipped ten of them before
10
- * `web_ui` said so (lane A, mailbox A-47). A fallback there is a SECOND SOURCE OF TRUTH for a size
11
- * that silently becomes THE size the day the token is renamed, and `index.css` always loads, so it
12
- * can never actually fire. Sizes are therefore `var(--lp-fs-xs)` bare; colours keep their fallback
13
- * because a missing colour is a legibility failure rather than a silent wrong number.
14
- * ⚠ NO EMOJIS AND NO ALL-CAPS CHROME (DESIGN.md). */
15
-
16
- .cg-chat {
17
- display: flex;
18
- flex-direction: column;
19
- height: 100%;
20
- min-height: 0;
21
- /* ⚠ A FLOOR AND A CEILING, NOT A FIXED WIDTH. The host docks this beside a grid whose columns
22
- are the reason the person is here; a panel that cannot give width back squeezes the thing it
23
- is talking about. Below the floor the transcript stops being readable, so the floor is real. */
24
- min-width: 280px;
25
- max-width: 420px;
26
- flex: 0 0 340px;
27
- background: var(--lp-surface, #ffffff);
28
- border-left: 1px solid var(--lp-border, #e4e7ec);
29
- }
30
-
31
- /* Below 1024px a docked panel and a grid cannot both be usable, so the panel takes the surface.
32
- ⚠ It does NOT hide itself: hiding would leave the host's toggle saying "open" with nothing on
33
- screen, which is a worse failure than a full-width panel the person can close. */
34
- @media (max-width: 1024px) {
35
- .cg-chat { flex: 1 1 auto; max-width: none; border-left: 0; }
36
- }
37
-
38
- .cg-chat-head {
39
- display: flex;
40
- align-items: center;
41
- gap: 8px;
42
- padding: 10px 12px;
43
- border-bottom: 1px solid var(--lp-border, #e4e7ec);
44
- background: var(--lp-surface, #ffffff);
45
- }
46
-
47
- .cg-chat-title {
48
- font: 600 var(--lp-fs-xs)/1.4 Inter, system-ui, sans-serif;
49
- color: var(--lp-text, #1d2939);
50
- /* The database name can be long and the header is narrow. Truncating beats wrapping into a
51
- two-line header that shifts the whole panel down. */
52
- overflow: hidden;
53
- text-overflow: ellipsis;
54
- white-space: nowrap;
55
- flex: 1 1 auto;
56
- min-width: 0;
57
- }
58
-
59
- .cg-chat-close {
60
- display: inline-flex;
61
- align-items: center;
62
- justify-content: center;
63
- width: 24px;
64
- height: 24px;
65
- border: 0;
66
- border-radius: 6px;
67
- background: transparent;
68
- color: var(--lp-text-muted, #667085);
69
- cursor: pointer;
70
- }
71
- .cg-chat-close:hover { background: var(--lp-surface-sunken, #f2f4f7); color: var(--lp-text, #1d2939); }
72
-
73
- /* ── the transcript ─────────────────────────────────────────────────────── */
74
-
75
- .cg-chat-log {
76
- display: flex;
77
- flex-direction: column;
78
- gap: 10px;
79
- flex: 1 1 auto;
80
- min-height: 0;
81
- overflow-y: auto;
82
- padding: 14px 12px;
83
- }
84
-
85
- .cg-chat-turn { display: flex; flex-direction: column; gap: 6px; }
86
-
87
- .cg-chat-msg {
88
- max-width: 92%;
89
- padding: 8px 10px;
90
- border-radius: 10px;
91
- font: 400 var(--lp-fs-xs)/1.55 Inter, system-ui, sans-serif;
92
- white-space: pre-wrap;
93
- /* ⚠ A pasted column name or an id has no spaces to break on and would otherwise push the panel
94
- wider than its own max-width. */
95
- overflow-wrap: anywhere;
96
- }
97
-
98
- .cg-chat-msg.is-you {
99
- align-self: flex-end;
100
- background: var(--lp-navy, #1f4e78);
101
- color: #ffffff;
102
- }
103
- .cg-chat-msg.is-assistant {
104
- align-self: flex-start;
105
- background: var(--lp-surface-sunken, #f2f4f7);
106
- color: var(--lp-text, #1d2939);
107
- }
108
- /* ⚠ The panel talking about ITSELF (a write landed, a proposal was declined) is neither side of
109
- the conversation, so it is centred and quiet rather than dressed as an answer. */
110
- .cg-chat-msg.is-note {
111
- align-self: center;
112
- max-width: 100%;
113
- background: transparent;
114
- color: var(--lp-text-muted, #667085);
115
- font-size: var(--lp-fs-2xs, 11px);
116
- text-align: center;
117
- padding: 2px 4px;
118
- }
119
- /* ⛔ An error is a KIND OF TURN, in the transcript where it can be re-read while the person
120
- rephrases. Not a toast that has already faded by then. */
121
- .cg-chat-msg.is-error {
122
- align-self: flex-start;
123
- background: #fef3f2;
124
- color: #b42318;
125
- border: 1px solid #fecdca;
126
- }
127
-
128
- .cg-chat-pending {
129
- display: flex;
130
- align-items: center;
131
- gap: 8px;
132
- padding: 2px 2px 4px;
133
- font: 400 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif;
134
- color: var(--lp-text-muted, #667085);
135
- }
136
-
137
- /* ── the write confirm (R10) ────────────────────────────────────────────── */
138
-
139
- .cg-chat-edits {
140
- border: 1px solid var(--lp-border, #e4e7ec);
141
- border-radius: 10px;
142
- background: var(--lp-surface, #ffffff);
143
- padding: 10px;
144
- }
145
-
146
- .cg-chat-edits-head {
147
- margin: 0 0 8px;
148
- font: 600 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif;
149
- color: var(--lp-text, #1d2939);
150
- }
151
-
152
- .cg-chat-edits-table {
153
- width: 100%;
154
- border-collapse: collapse;
155
- font: 400 var(--lp-fs-3xs)/1.45 Inter, system-ui, sans-serif;
156
- /* A proposal can name more cells than fit; it scrolls rather than being clipped, because a
157
- confirm the person cannot fully read is not a confirm. */
158
- display: block;
159
- max-height: 220px;
160
- overflow: auto;
161
- }
162
- .cg-chat-edits-table th {
163
- text-align: left;
164
- font-weight: 600;
165
- color: var(--lp-text-muted, #667085);
166
- padding: 0 8px 4px 0;
167
- position: sticky;
168
- top: 0;
169
- background: var(--lp-surface, #ffffff);
170
- }
171
- .cg-chat-edits-table td {
172
- padding: 3px 8px 3px 0;
173
- color: var(--lp-text, #1d2939);
174
- border-top: 1px solid var(--lp-border, #e4e7ec);
175
- vertical-align: top;
176
- overflow-wrap: anywhere;
177
- }
178
- /* ⚠ The two values are told apart by WEIGHT and colour, never by colour alone: a red/green pair
179
- is unreadable to a substantial minority of people, and this is a confirm before a write. */
180
- .cg-chat-before { color: var(--lp-text-muted, #667085); text-decoration: line-through; }
181
- .cg-chat-after { color: var(--lp-navy, #1f4e78); font-weight: 600; }
182
-
183
- /* ⚠ Centred under the note it belongs to, and quiet: an undo control that shouted would read as
184
- a warning that something went wrong, when what happened is exactly what the person confirmed. */
185
- .cg-chat-undo { display: flex; justify-content: center; margin-top: 2px; }
186
-
187
- .cg-chat-edits-act {
188
- display: flex;
189
- justify-content: flex-end;
190
- gap: 8px;
191
- margin-top: 10px;
192
- }
193
-
194
- .cg-chat-ghost,
195
- .cg-chat-go {
196
- border-radius: 7px;
197
- padding: 5px 12px;
198
- font: 500 var(--lp-fs-2xs)/1.2 Inter, system-ui, sans-serif;
199
- cursor: pointer;
200
- }
201
- .cg-chat-ghost {
202
- border: 1px solid var(--lp-border, #e4e7ec);
203
- background: var(--lp-surface, #ffffff);
204
- color: var(--lp-text, #1d2939);
205
- }
206
- .cg-chat-go {
207
- border: 1px solid var(--lp-navy, #1f4e78);
208
- background: var(--lp-navy, #1f4e78);
209
- color: #ffffff;
210
- }
211
- .cg-chat-ghost:disabled,
212
- .cg-chat-go:disabled { opacity: 0.55; cursor: default; }
213
-
214
- /* ── the opening and the composer ───────────────────────────────────────── */
215
-
216
- .cg-chat-opening {
217
- display: flex;
218
- flex-direction: column;
219
- justify-content: center;
220
- flex: 1 1 auto;
221
- min-height: 0;
222
- gap: 10px;
223
- padding: 16px 12px;
224
- text-align: center;
225
- }
226
-
227
- .cg-chat-opening-h {
228
- margin: 0;
229
- font: 600 var(--lp-fs-lg)/1.3 Inter, system-ui, sans-serif;
230
- color: var(--lp-text, #1d2939);
231
- }
232
-
233
- .cg-chat-opening-p {
234
- margin: 0 0 6px;
235
- font: 400 var(--lp-fs-2xs)/1.55 Inter, system-ui, sans-serif;
236
- color: var(--lp-text-muted, #667085);
237
- }
238
-
239
- .cg-chat-foot { padding: 10px 12px 12px; border-top: 1px solid var(--lp-border, #e4e7ec); }
240
-
241
- .cg-chat-composer {
242
- border: 1px solid var(--lp-border, #e4e7ec);
243
- border-radius: 12px;
244
- background: var(--lp-surface, #ffffff);
245
- padding: 8px;
246
- text-align: left;
247
- }
248
- .cg-chat-composer:focus-within { border-color: var(--lp-navy, #1f4e78); }
249
-
250
- .cg-chat-input {
251
- width: 100%;
252
- border: 0;
253
- outline: 0;
254
- resize: none;
255
- background: transparent;
256
- color: var(--lp-text, #1d2939);
257
- font: 400 var(--lp-fs-xs)/1.5 Inter, system-ui, sans-serif;
258
- }
259
- .cg-chat-input::placeholder { color: var(--lp-text-muted, #667085); }
260
- .cg-chat-input:disabled { color: var(--lp-text-muted, #667085); }
261
-
262
- /* ⚠ The foot row sits INSIDE the composer's border, which is the shape `cg-agent-composer-foot`
263
- already established. A second card outline under the input would read as two controls. */
264
- .cg-chat-composer-foot {
265
- display: flex;
266
- align-items: center;
267
- gap: 8px;
268
- margin-top: 6px;
269
- }
270
-
271
- .cg-chat-scope {
272
- font: 400 var(--lp-fs-3xs)/1.3 Inter, system-ui, sans-serif;
273
- color: var(--lp-text-muted, #667085);
274
- }
275
-
276
- .cg-chat-spacer { flex: 1 1 auto; }
277
-
278
- .cg-chat-send {
279
- display: inline-flex;
280
- align-items: center;
281
- justify-content: center;
282
- width: 26px;
283
- height: 26px;
284
- border: 0;
285
- border-radius: 50%;
286
- background: var(--lp-navy, #1f4e78);
287
- color: #ffffff;
288
- cursor: pointer;
289
- }
290
- .cg-chat-send:disabled {
291
- background: var(--lp-surface-sunken, #f2f4f7);
292
- color: var(--lp-text-muted, #667085);
293
- cursor: default;
294
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/gridChat.ts DELETED
@@ -1,424 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / gridChat.ts — the chat panel's state, as pure functions (W37-T40, R2, C6).
3
- //
4
- // ⭐⭐ WHY THE STATE LIVES HERE AND NOT IN THE COMPONENT. `<GridChat>` has to demonstrate three
5
- // things its `done-when` names: a message history, an in-flight state and an error state. If those
6
- // transitions live in `useState` callbacks inside the .tsx, the only way to assert on them is to
7
- // render React and match emitted markup — which pins the compiler's output rather than the
8
- // behaviour, and goes red on a refactor that changed nothing a person can see. Here they are plain
9
- // functions over a plain object, so the gate checks the STATE MACHINE without React in the process
10
- // at all, and the render only has to prove the three states paint.
11
- //
12
- // ⛔⛔ NOTHING IN THIS FILE TALKS TO THE NETWORK, THE GRID, OR THE STORE — contract C6, and it is
13
- // structural rather than a promise. There is no `fetch` here and no import of anything that has
14
- // one: every action the chat can take arrives as a callback the host supplies. That is what lets
15
- // the host WALL the chat by simply not passing a power, instead of the chat asking permission and
16
- // being told no [[permitted-is-not-answerable]].
17
- //
18
- // ⚠ NO EM DASH OR EN DASH IN ANY STRING THAT REACHES A SCREEN (standing rule 2). The sentences
19
- // below are user-facing copy, and `web_prose` cannot see a wrapped JSX sentence, so the discipline
20
- // is on the author. Commas, colons and full stops carry the same weight and are not AI slop.
21
- // ---------------------------------------------------------------------------
22
-
23
- /** One column the chat is allowed to know about. The host decides what goes in this list. */
24
- export interface GridChatField {
25
- key: string;
26
- label: string;
27
- type: string;
28
- }
29
-
30
- /**
31
- * What a host callback hands back for a question.
32
- *
33
- * ⛔ `text` IS REQUIRED AND `unanswerable` IS THE HONEST OUT. D-339's lesson is that an agent
34
- * which cannot read the database answers from words alone and invents a number; a host that cannot
35
- * answer must be able to SAY so rather than return an empty string the panel renders as silence.
36
- */
37
- export interface GridChatAnswer {
38
- text: string;
39
- /** Set when the question named something this database does not have. Rendered as an answer,
40
- * not as a failure: the person asked a reasonable question about the wrong column. */
41
- unanswerable?: boolean;
42
- /**
43
- * ⭐⭐ R10's PROPOSAL CHANNEL, DECLARED RATHER THAN CAST. The panel reads this to decide that an
44
- * answer is a proposed WRITE and must be shown for confirmation instead of rendered as prose.
45
- *
46
- * ⛔ IT WAS A CAST FIRST, AND THAT WAS THE BUG-IN-WAITING. `GridChat` read
47
- * `(answer as {edits?: ...}).edits` while this interface said nothing about it, so the contract
48
- * lived in one file and the reader in another. The host reads the PUBLISHED type; a host that
49
- * never sees `edits` never sends `edits`, the whole confirm path is dead on arrival, and nothing
50
- * anywhere fails [[flag-shipped-without-its-writer]]. Typing it is the difference between a
51
- * channel and a coincidence.
52
- * ⚠ Its presence is a PROPOSAL, never an instruction: nothing is written until the person
53
- * confirms, and a caller with `canEdit:false` is not shown the control at all.
54
- */
55
- edits?: GridChatEdit[];
56
- }
57
-
58
- /** One cell the chat proposes to write. R10: the person sees `before` and `after` before anything. */
59
- export interface GridChatEdit {
60
- rowId: string;
61
- rowLabel: string;
62
- field: string;
63
- fieldLabel: string;
64
- before: string;
65
- after: string;
66
- }
67
-
68
- /** Who said it. `note` is the panel talking about itself (a confirm outcome, a cancelled write). */
69
- export type GridChatWho = "you" | "assistant" | "note";
70
-
71
- /**
72
- * One turn. ⚠ `error` is a KIND OF TURN rather than a banner, and that is deliberate: a failed
73
- * question is part of the conversation a person is having. They will rephrase and try again, and a
74
- * toast that has already faded cannot be re-read while they do. `AutomationChat` made the same
75
- * call for the same reason; two chat surfaces disagreeing about where failure lives is how one
76
- * product stops looking like one product.
77
- */
78
- export interface GridChatTurn {
79
- who: GridChatWho;
80
- text: string;
81
- error?: boolean;
82
- /** Present only on a turn that is proposing writes. The panel renders the before/after list. */
83
- edits?: GridChatEdit[];
84
- /**
85
- * ⭐⭐ THE INVERSE OF A WRITE THAT ALREADY HAPPENED, CARRIED ON THE NOTE THAT REPORTS IT.
86
- *
87
- * ⛔ IT IS BUILT FROM THE PROPOSAL, BEFORE THE WRITE, NOT READ BACK AFTER IT
88
- * [[capture-the-inverse-before-the-write]]. Once the cells are written the old values are gone
89
- * from the store, so an undo assembled afterwards can only re-read what it just wrote and undo
90
- * nothing. Every `GridChatEdit` already carries `before` because the person had to SEE it in
91
- * order to confirm, which means the inverse costs nothing extra and cannot be stale.
92
- */
93
- undo?: GridChatEdit[];
94
- }
95
-
96
- /**
97
- * The whole panel state.
98
- *
99
- * ⭐ `pending` IS THE IN-FLIGHT STATE AND IT IS THE QUESTION ITSELF, not a boolean. A boolean can
100
- * go stale against the transcript: two rapid sends with `busy: true` leave no record of which
101
- * question is actually outstanding, and the answer lands under whichever turn happens to be last.
102
- * Holding the text means the panel can always say what it is waiting on, and `answered()` can
103
- * refuse an answer that arrived after the person moved on.
104
- */
105
- export interface GridChatState {
106
- turns: GridChatTurn[];
107
- pending: string | null;
108
- }
109
-
110
- export function emptyChat(): GridChatState {
111
- return { turns: [], pending: null };
112
- }
113
-
114
- export function isBusy(state: GridChatState): boolean {
115
- return state.pending !== null;
116
- }
117
-
118
- /**
119
- * The person sent something. Returns the new state, or the SAME state when there is nothing to
120
- * send or a question is already outstanding.
121
- *
122
- * ⛔ ONE QUESTION AT A TIME, AND THE REFUSAL IS SILENT BY DESIGN. The composer disables its own
123
- * send button while `pending`, so a second send can only arrive from a key repeat or a double
124
- * click. Answering that with an error turn would put a scolding message in a transcript the person
125
- * did not mean to write in. Returning the same object also lets the caller skip the re-render.
126
- */
127
- export function asked(state: GridChatState, said: string): GridChatState {
128
- const text = String(said || "").trim();
129
- if (!text || state.pending !== null) return state;
130
- return { turns: [...state.turns, { who: "you", text }], pending: text };
131
- }
132
-
133
- /**
134
- * A host callback answered. `forQuestion` is the text `asked()` returned in `pending`.
135
- *
136
- * ⛔ AN ANSWER TO A QUESTION NOBODY IS WAITING ON IS DROPPED. A slow first answer that lands after
137
- * the person cancelled and asked something else would otherwise be appended under the new question
138
- * and read as its answer. Checking the text is enough here because `asked()` refuses to start a
139
- * second question while one is outstanding, so at most one can ever be in flight.
140
- */
141
- export function answered(
142
- state: GridChatState,
143
- forQuestion: string,
144
- answer: GridChatAnswer,
145
- ): GridChatState {
146
- if (state.pending === null || state.pending !== forQuestion) return state;
147
- const said = String(answer?.text || "").trim();
148
- return {
149
- turns: [...state.turns, {
150
- who: "assistant",
151
- // ⚠ An empty answer is a defect in the host, not a blank bubble for the reader to interpret.
152
- text: said || "That came back empty, so there is nothing to show. Try asking again.",
153
- error: !said,
154
- }],
155
- pending: null,
156
- };
157
- }
158
-
159
- /**
160
- * A host callback failed. `sentence` is what the person reads.
161
- *
162
- * ⛔ THE SENTENCE IS THE PRODUCT. `HTTP 402` on a screen tells a reader nothing they can do, and
163
- * the owner has quoted a raw status back at us twice. A caller with nothing better than an
164
- * exception name passes nothing and gets the fallback below, which at least says what happened and
165
- * what to do next.
166
- */
167
- export function failed(
168
- state: GridChatState,
169
- forQuestion: string,
170
- sentence?: string,
171
- ): GridChatState {
172
- if (state.pending === null || state.pending !== forQuestion) return state;
173
- const said = String(sentence || "").trim();
174
- return {
175
- turns: [...state.turns, {
176
- who: "assistant",
177
- text: said || "That did not go through. Nothing was changed, so it is safe to try again.",
178
- error: true,
179
- }],
180
- pending: null,
181
- };
182
- }
183
-
184
- /** The panel telling the person what it just did. Never in flight, never an error. */
185
- export function noted(state: GridChatState, text: string): GridChatState {
186
- const said = String(text || "").trim();
187
- if (!said) return state;
188
- return { ...state, turns: [...state.turns, { who: "note", text: said }] };
189
- }
190
-
191
- /**
192
- * The assistant is proposing cell writes and wants a confirm (R10).
193
- *
194
- * ⭐ THE PROPOSAL IS A TURN, not a modal. A modal would cover the transcript the person needs in
195
- * order to judge the proposal, and it would vanish on a mis-click taking the reasoning with it.
196
- * ⛔ NOTHING IS WRITTEN BY THIS FUNCTION. It appends a turn carrying the before/after list; the
197
- * host's `onWriteCells` is reached only from the confirm control, which is W37-T45's half.
198
- */
199
- export function proposedEdits(
200
- state: GridChatState,
201
- forQuestion: string,
202
- text: string,
203
- edits: GridChatEdit[],
204
- ): GridChatState {
205
- if (state.pending === null || state.pending !== forQuestion) return state;
206
- const rows = (edits || []).filter((e) => e && e.rowId && e.field);
207
- if (!rows.length) return answered(state, forQuestion, { text });
208
- return {
209
- turns: [...state.turns, {
210
- who: "assistant",
211
- text: String(text || "").trim() || "Here is exactly what this would write.",
212
- edits: rows,
213
- }],
214
- pending: null,
215
- };
216
- }
217
-
218
- /**
219
- * The inverse of a set of edits: what would put every cell back.
220
- *
221
- * ⛔ CALL THIS BEFORE THE WRITE, NOT AFTER. It reads `before`, which only exists on the proposal
222
- * the person confirmed; after the write the store holds `after` and there is nothing left to
223
- * invert from [[capture-the-inverse-before-the-write]].
224
- * ⚠ `rowLabel` and `fieldLabel` are carried through unchanged, so an undo confirm reads in the
225
- * same words the original proposal did rather than in keys.
226
- */
227
- export function invertEdits(edits: GridChatEdit[]): GridChatEdit[] {
228
- return (edits || [])
229
- .filter((e) => e && e.rowId && e.field)
230
- .map((e) => ({ ...e, before: e.after, after: e.before }));
231
- }
232
-
233
- /**
234
- * A confirmed write landed. The note it appends CARRIES ITS OWN INVERSE, so undo is offered from
235
- * the transcript rather than from a toast that has already gone.
236
- */
237
- export function wrote(state: GridChatState, edits: GridChatEdit[]): GridChatState {
238
- const rows = (edits || []).filter((e) => e && e.rowId && e.field);
239
- if (!rows.length) return state;
240
- return {
241
- ...state,
242
- turns: [...state.turns, {
243
- who: "note",
244
- text: `Written. ${editSummary(rows)}`,
245
- undo: invertEdits(rows),
246
- }],
247
- };
248
- }
249
-
250
- /**
251
- * The one-line summary a confirm control shows beside the before/after list.
252
- *
253
- * ⚠ It counts CELLS and RECORDS separately because they are different risks: twenty cells on one
254
- * record is a correction, one cell on twenty records is a sweep. A single "20 changes" hides which
255
- * of those the person is about to approve.
256
- */
257
- export function editSummary(edits: GridChatEdit[]): string {
258
- const rows = (edits || []).filter((e) => e && e.rowId && e.field);
259
- if (!rows.length) return "Nothing to write.";
260
- const records = new Set(rows.map((e) => e.rowId)).size;
261
- const cellWord = rows.length === 1 ? "cell" : "cells";
262
- const recordWord = records === 1 ? "record" : "records";
263
- return `${rows.length} ${cellWord} on ${records} ${recordWord}.`;
264
- }
265
-
266
- /**
267
- * What the composer invites the person to type.
268
- *
269
- * ⚠ IT NAMES THE DATABASE. A chat docked beside a grid is ambiguous about what it is reading the
270
- * moment a person has two tabs open, and the fix is one word in the placeholder rather than a
271
- * second header line.
272
- */
273
- export function composerHint(databaseLabel: string, canEdit: boolean): string {
274
- const where = String(databaseLabel || "").trim() || "this database";
275
- return canEdit
276
- ? `Ask about ${where}, or say what to change`
277
- : `Ask about ${where}`;
278
- }
279
-
280
- // ═══════════════════════════════════════════════════════════════════════════════════════════
281
- // ⭐⭐ THE INTENT LAYER (W37-T42 · T43 · T44) — WHAT THE CHAT KNOWS WITHOUT SPENDING ANYTHING
282
- //
283
- // ⛔⛔ ITS JOB IS TO REFUSE HONESTLY BEFORE A MODEL CALL, NOT TO BE CLEVER. D-339's lesson is that
284
- // an agent which cannot read the database answers from WORDS ALONE and invents a number; the fix
285
- // is not a better guess, it is knowing what this database actually has and saying so when the
286
- // question names something it does not. The panel holds the schema, so that answer costs nothing
287
- // and cannot be wrong in the direction that matters.
288
- // ⚠ EVERYTHING HERE IS PURE AND LOCAL. Anything that needs a model, a query or a write goes out
289
- // through a host callback (C6). This layer only decides WHICH callback, and catches the questions
290
- // that should never reach one.
291
- // ═══════════════════════════════════════════════════════════════════════════════════════════
292
-
293
- /** What the panel decided a sentence was asking for. */
294
- export type GridChatIntentKind = "schema" | "view" | "ask";
295
-
296
- export interface GridChatIntent {
297
- kind: GridChatIntentKind;
298
- /** A complete answer the panel can give with NO model call. Present only when it truly can. */
299
- localAnswer?: string;
300
- /** Set when the sentence names something this database does not have. */
301
- refusal?: string;
302
- /** For `view`: what the panel understood, in the vocabulary the host's callback takes. */
303
- view?: { sortBy?: string; groupBy?: string; colorBy?: string };
304
- /** For `view`: what was asked for and CANNOT be expressed, named rather than dropped. */
305
- cannot?: string;
306
- }
307
-
308
- const norm = (s: string) => String(s || "").toLowerCase().trim();
309
-
310
- /**
311
- * Which known fields a sentence mentions, by label or by key.
312
- *
313
- * ⚠ LABEL FIRST AND LONGEST FIRST. A person types the label they can see ("Sales rep"), not the
314
- * key (`agent_id`), and matching short keys first would let a field called `n` match the word "in".
315
- */
316
- export function fieldsNamed(schema: GridChatField[], said: string): GridChatField[] {
317
- const text = norm(said);
318
- if (!text) return [];
319
- return (schema || [])
320
- .filter((f) => f && (f.label || f.key))
321
- .slice()
322
- .sort((a, b) => (b.label || b.key).length - (a.label || a.key).length)
323
- .filter((f) => {
324
- const label = norm(f.label);
325
- const key = norm(f.key);
326
- return (label.length > 2 && text.includes(label))
327
- || (key.length > 2 && text.includes(key));
328
- });
329
- }
330
-
331
- /**
332
- * A quoted name that this database does not have, if the sentence contains one.
333
- *
334
- * ⛔ ONLY QUOTED NAMES, DELIBERATELY. Guessing that any capitalised phrase is a column would refuse
335
- * perfectly good questions ("how many are in New York?"), and a refusal that fires on a real
336
- * question is worse than a model call that answers it. Quotes are the one place a person has said
337
- * "this is a name" out loud, so the panel can be certain enough to answer instead of asking.
338
- * ⚠ This is the D-339 half the panel can do alone. Everything unquoted still goes to the host,
339
- * which knows the data and can say `unanswerable` with better information than a regex has.
340
- */
341
- export function unknownFieldNamed(schema: GridChatField[], said: string): string | null {
342
- const quoted = String(said || "").match(/"[^"]{1,60}"|'[^']{1,60}'/g) || [];
343
- const known = new Set((schema || []).flatMap((f) => [norm(f.label), norm(f.key)]));
344
- for (const raw of quoted) {
345
- const typed = raw.slice(1, -1).trim();
346
- // ⛔ COMPARE LOWERCASED, RETURN AS TYPED, AND THE FIRST DRAFT DID NOT. It returned the
347
- // normalised form, so somebody who wrote "Supplier Rep" was told there is no field called
348
- // "supplier rep" — their own words handed back mangled, which reads as the system having
349
- // misheard them rather than as an honest answer. Matching is case-insensitive because a person
350
- // should not have to match a label's capitalisation; the MESSAGE quotes them exactly.
351
- if (typed && !known.has(norm(typed))) return typed;
352
- }
353
- return null;
354
- }
355
-
356
- /** The plain-language field list, for a question the panel can answer with no model call at all. */
357
- export function schemaSentence(schema: GridChatField[], databaseLabel: string): string {
358
- const where = String(databaseLabel || "").trim() || "this database";
359
- const names = (schema || []).map((f) => f.label || f.key).filter(Boolean);
360
- if (!names.length) return where + " has no fields the chat can see.";
361
- const word = names.length === 1 ? "field" : "fields";
362
- return where + " has " + names.length + " " + word + ": " + names.join(", ") + ".";
363
- }
364
-
365
- /** Sentences that are asking what is here, rather than asking about the data. */
366
- const SCHEMA_WORDS = ["what fields", "which fields", "what columns", "which columns",
367
- "list the fields", "list the columns", "what can you see"];
368
- /** Sentences asking for the VIEW to change rather than for an answer. */
369
- const VIEW_WORDS = ["sort by", "sorted by", "group by", "grouped by", "colour by", "color by",
370
- "show me only", "filter"];
371
-
372
- /**
373
- * Read a sentence. ⛔ THE ORDER IS THE POLICY: refuse first, answer locally second, route third.
374
- *
375
- * ⚠ A DELIBERATELY SHALLOW READER. It is not trying to understand the question, because the host's
376
- * model does that. It is trying to catch the two cases where going to the model is WRONG: a name
377
- * this database does not have (which would come back as an invented number), and a question the
378
- * panel already knows the answer to (which would be a paid round trip for a list it is holding).
379
- */
380
- export function readIntent(
381
- schema: GridChatField[],
382
- databaseLabel: string,
383
- said: string,
384
- ): GridChatIntent {
385
- const text = norm(said);
386
- const where = String(databaseLabel || "").trim() || "this database";
387
- const missing = unknownFieldNamed(schema, said);
388
- if (missing) {
389
- const names = (schema || []).map((f) => f.label || f.key).filter(Boolean);
390
- return {
391
- kind: "ask",
392
- refusal: 'There is no field called "' + missing + '" in ' + where + ". "
393
- + (names.length
394
- ? "The fields here are: " + names.join(", ") + "."
395
- : "This database has no fields the chat can see."),
396
- };
397
- }
398
- if (SCHEMA_WORDS.some((w) => text.includes(w)))
399
- return { kind: "schema", localAnswer: schemaSentence(schema, databaseLabel) };
400
-
401
- if (VIEW_WORDS.some((w) => text.includes(w))) {
402
- const named = fieldsNamed(schema, said);
403
- const view: { sortBy?: string; groupBy?: string; colorBy?: string } = {};
404
- if (named.length) {
405
- if (text.includes("group")) view.groupBy = named[0].key;
406
- else if (text.includes("colour") || text.includes("color")) view.colorBy = named[0].key;
407
- else if (text.includes("sort")) view.sortBy = named[0].key;
408
- }
409
- // ⛔ WHAT IT CANNOT SAY, SAID OUT LOUD. `assistant build_view` has no `rhs` in its tool schema,
410
- // so a condition comparing one field to another is not expressible anywhere in this product
411
- // [[assistant-build-view-is-a-subset]]. Dropping it silently would leave a person looking at a
412
- // view that quietly ignored half their sentence, which is the failure this note exists to stop.
413
- const fieldVsField = named.length >= 2 && /\b(than|versus|vs\.?|compared to)\b/.test(text);
414
- return {
415
- kind: "view",
416
- view: Object.keys(view).length ? view : undefined,
417
- cannot: fieldVsField
418
- ? "This build cannot compare one field against another in a view filter, so that part was "
419
- + "left out. Everything else was applied."
420
- : undefined,
421
- };
422
- }
423
- return { kind: "ask" };
424
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/inbox/InboxPage.tsx DELETED
@@ -1,595 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // inbox/InboxPage.tsx — WAVE 32 · T20 (owner item 16, ruling R7, contract C3).
3
- //
4
- // Owner, item 16: *"Alerts becomes an Inbox that looks like email."* R7: it is a
5
- // FULL MODULE and the pop-up pane is deleted — the bell navigates here, there is
6
- // no dropdown.
7
- //
8
- // So this is a LIST + a READING PANE, which is the only structural thing an email
9
- // client actually is. The pane it replaces was a 520px drawer with one column, and
10
- // that shape is why the feature never read like mail: a drawer has no room for a
11
- // subject line above a body, so subject and body were one field, and a
12
- // notification could only ever be a sentence with no sender.
13
- //
14
- // ⛔ NOT A REGISTRY MODULE — a CHROME route, like Home and Connectors. Every
15
- // provisioned tenant carries a restricted `modules` list (`['analyst','automation']`
16
- // on all three), and a registry key outside it is silently OMITTED from the rail.
17
- // Registering Inbox would make it invisible in every tenant while every gate stayed
18
- // green. `alerts` was already chrome; Inbox inherits the right shape. The MOUNT is
19
- // A's (`shell/Shell.tsx`, W32-T04); this file only exports the surface.
20
- //
21
- // ⚠ STYLING REUSES THE `.alerts-*` RULES ON PURPOSE. They are the same feature's
22
- // classes, they already exist, and `src/index.css` is in no lane's fence this wave
23
- // (D-186's shape, second occurrence). Page-frame geometry that has no class yet is
24
- // inline rather than invented: a class name with no rule behind it looks identical
25
- // to a rule that failed to load.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useCallback, useEffect, useMemo, useState } from "react";
29
- import {
30
- deleteAlert,
31
- fetchAlerts,
32
- fetchInbox,
33
- markRead,
34
- runAlert,
35
- } from "../alerts/alertsApi";
36
- import {
37
- NOTIF_KIND_AUTOMATION,
38
- applyRead,
39
- canMarkAll,
40
- paneView,
41
- stampText,
42
- } from "../alerts/alertsModel";
43
- import type { Alert, Inbox, Notification, NotificationTarget } from "../alerts/alertsModel";
44
- import type { InboxSections } from "./inboxModel";
45
- import {
46
- UNOPENABLE_NOTE,
47
- canOpen,
48
- inboxSections,
49
- previewOf,
50
- routeForTarget,
51
- senderOf,
52
- subjectOf,
53
- targetOf,
54
- } from "./inboxModel";
55
- import { BellIcon } from "../ui/icons";
56
- // ⭐ WAVE 27 C5, CARRIED FORWARD — the ONE generated loop mark, consumed rather than redrawn.
57
- // ⛔ It is here because W32-T21 DELETES `AlertsPane`, and a rename ticket must not quietly drop a
58
- // shipped visual: an automation row wore this mark, and losing it in the move would be a silent
59
- // regression behind a green gate. ⛔ NOT A STATUS DOT (W26 R14 deleted the whole status
60
- // vocabulary from the automation module) and never a hand-copied path — `shell/Brand.tsx`'s own
61
- // header records a redrawn copy silently painting LAST WAVE'S BRAND while a comment claimed parity.
62
- import { Mark } from "../shell/Brand";
63
- import { API_V1, CREDENTIALS } from "../apiContract";
64
-
65
- async function fetchRouteTasks(): Promise<Notification[]> {
66
- try {
67
- const response = await fetch(`${API_V1}/notifications`, { credentials: CREDENTIALS });
68
- const body = await response.json();
69
- if (!response.ok || !Array.isArray(body?.items)) return [];
70
- return body.items.filter((item: Record<string, unknown>) => item?.kind === "route_task").map((item: Record<string, unknown>) => {
71
- const rawTarget = item.target && typeof item.target === "object" ? item.target as Record<string, unknown> : {};
72
- const routeId = String(rawTarget.routeId ?? item.routeId ?? "");
73
- const application = typeof rawTarget.application === "string" ? rawTarget.application.trim() : "";
74
- return ({
75
- id: String(item.id), alertId: "", viewId: "", topic: "customer", rowId: routeId,
76
- label: `Route ${String(item.subject ?? "task")} · ${String(item.routeDate ?? "Date not set")} · ${String(item.assignee ?? "Unassigned")}`,
77
- alertLabel: String(item.subject ?? "Route task"), subject: String(item.subject ?? "Route task"), sender: String(item.source ?? "Loopable Routes"),
78
- at: String(item.at ?? item.routeDate ?? ""), read: item.read === true, kind: "route_task",
79
- target: routeId ? { module: "customer_data", id: routeId, tab: "map", ...(application ? { application } : {}) } : undefined,
80
- }); });
81
- } catch { return []; }
82
- }
83
-
84
- /** The page frame. `.shell-home`'s geometry, without borrowing Home's class name for a
85
- * surface that is not Home — the rule is six declarations and copying them is cheaper than
86
- * a shared class two modules would then have to agree about. */
87
- const PAGE: React.CSSProperties = {
88
- height: "100%",
89
- overflow: "hidden",
90
- padding: "34px 44px 28px",
91
- boxSizing: "border-box",
92
- background: "var(--lp-wash)",
93
- display: "flex",
94
- flexDirection: "column",
95
- };
96
-
97
- const SPLIT: React.CSSProperties = {
98
- flex: "1 1 auto",
99
- minHeight: 0,
100
- display: "flex",
101
- gap: 20,
102
- alignItems: "stretch",
103
- };
104
-
105
- const CARD: React.CSSProperties = {
106
- background: "var(--lp-surface)",
107
- border: "1px solid var(--lp-line)",
108
- borderRadius: "var(--lp-r-lg)",
109
- overflow: "auto",
110
- minHeight: 0,
111
- };
112
-
113
- function actionLabelOf(notification: Notification): string {
114
- const destination = routeForTarget(targetOf(notification));
115
- if (destination?.surface === "automation") return "Open the agent";
116
- if (destination?.surface === "map") return "Open the map";
117
- if (destination?.surface === "database" && destination.key.startsWith("app?"))
118
- return "Open the App";
119
- return "Open the database";
120
- }
121
-
122
- export default function InboxPage({
123
- onOpenTarget,
124
- onInbox,
125
- onToast,
126
- seed,
127
- }: {
128
- /**
129
- * ⛔ REQUIRED, NOT OPTIONAL, and this is the lesson written into a type rather than a comment.
130
- * An optional callback the frame forgot to pass degrades to "clicking an Inbox item does
131
- * nothing" — indistinguishable from "the feature was never built", and red in no gate. A
132
- * required prop fails `tsc` the moment it is unmounted. `AlertsPane` carried the same rule on
133
- * `onOpenAutomation` and `seed`; C3 carries it forward as the wave's cross-fence contract.
134
- *
135
- * The FRAME owns routing — it holds the router and knows which module surfaces exist. This
136
- * module owns the QUESTION (`inboxModel.routeForTarget` turns a wire target into a surface +
137
- * what it needs) so the frame's dispatcher is a switch over two literals rather than a second
138
- * copy of the topic→route table.
139
- */
140
- onOpenTarget: (t: NotificationTarget) => void;
141
- /** Hand the freshly-read inbox back so the rail badge and this module agree. */
142
- onInbox: (inbox: Inbox) => void;
143
- onToast: (message: string) => void;
144
- /**
145
- * ⛔ REQUIRED, for the reason `onOpenTarget` is (W31-T23's shipped bug, kept as a type). The
146
- * frame has ALREADY fetched this — it is what paints the rail badge the user just clicked — so
147
- * the module opens knowing the account's count, and "Mark all read" is live from the first
148
- * frame and stays live if this module's own read fails.
149
- */
150
- seed: Inbox;
151
- }) {
152
- const [inbox, setInbox] = useState<Inbox>(seed);
153
- const [alerts, setAlerts] = useState<Alert[]>([]);
154
- const [error, setError] = useState("");
155
- const [busy, setBusy] = useState(false);
156
- const [selectedId, setSelectedId] = useState("");
157
- /**
158
- * ⭐⭐ W33-T28 — the ids read during THIS visit, held in their section so a clicked row does not
159
- * move out from under the cursor. See `inboxModel.inboxSections`' note for the defect.
160
- * ⚠ A ref-like `useState` initialiser, not state: mutating it must not itself re-render, and it
161
- * never needs to — `setRead` already triggers the render that reads it.
162
- */
163
- const [held] = useState<Set<string>>(() => new Set<string>());
164
- /** ⛔ THE STATE THE PANE DID NOT HAVE (W31-T23). Without it "no rows yet" and "no rows, ever"
165
- * are the same value, so an in-flight read — 3,280 ms live on tenant #0 — printed a confident
166
- * "Nothing new." over an inbox nobody had looked at yet. */
167
- const [phase, setPhase] = useState<"pending" | "ready" | "error">("pending");
168
-
169
- const publish = useCallback(
170
- (next: Inbox) => {
171
- setInbox(next);
172
- onInbox(next);
173
- },
174
- [onInbox]
175
- );
176
-
177
- const load = useCallback(async () => {
178
- const [inboxRes, alertRes, routeTasks] = await Promise.all([fetchInbox(), fetchAlerts(), fetchRouteTasks()]);
179
- if (inboxRes.ok) {
180
- const correctedRouteIds = new Set(routeTasks.map((item) => item.id));
181
- publish({ ...inboxRes.value, items: [
182
- ...routeTasks,
183
- ...inboxRes.value.items.filter((item) => !correctedRouteIds.has(item.id)),
184
- ] });
185
- setError("");
186
- setPhase("ready");
187
- } else {
188
- // ⚠ THE SEEDED INBOX SURVIVES A FAILED READ. Blanking it would take the count — and with it
189
- // the Mark-all control — away from a reader who can see the badge. The failure is REPORTED
190
- // and nothing the frame already knew is discarded.
191
- setError(inboxRes.message);
192
- setPhase("error");
193
- }
194
- if (alertRes.ok) setAlerts(alertRes.value);
195
- }, [publish]);
196
-
197
- useEffect(() => {
198
- void load();
199
- }, [load]);
200
-
201
- const sections = useMemo(() => inboxSections(inbox.items, held), [inbox.items, held]);
202
- const rowCount = sections.unread.length + sections.read.length;
203
- const view = paneView(phase, rowCount, seed.unread);
204
- const selected = useMemo(
205
- () => inbox.items.find((n) => n.id === selectedId) ?? null,
206
- [inbox.items, selectedId]
207
- );
208
-
209
- const setRead = useCallback(
210
- (n: Notification, read: boolean) => {
211
- if (n.read === read) return;
212
- // Optimistic, with the server's own convention (`ids`, `read`) sent explicitly — and
213
- // reverted OUT LOUD if refused, because a badge that silently disagrees with the list is
214
- // how a reader learns to stop trusting it.
215
- const before = inbox;
216
- publish(applyRead(inbox, [n.id], read));
217
- void markRead([n.id], read).then((r) => {
218
- if (!r.ok) {
219
- publish(before);
220
- onToast(r.message);
221
- }
222
- });
223
- },
224
- [inbox, publish, onToast]
225
- );
226
-
227
- const markAll = useCallback(() => {
228
- const before = inbox;
229
- // `applyRead(…, null, true)` zeroes the count from the ITEMS, which is right here because the
230
- // request below clears the whole ACCOUNT (`ids: null`) — 0 is what the server is about to
231
- // make true. The revert on failure is what keeps it honest.
232
- publish({ ...applyRead(inbox, null, true), unread: 0 });
233
- void markRead(null, true).then((r) => {
234
- if (!r.ok) {
235
- publish(before);
236
- onToast(r.message);
237
- }
238
- });
239
- }, [inbox, publish, onToast]);
240
-
241
- /**
242
- * ⭐ SELECTING IS READING. Opening a mail item marks it read — that is what the metaphor
243
- * promises, and a reader who has to press a second button to clear a badge they have plainly
244
- * seen concludes the badge is decorative.
245
- *
246
- * ⛔ IT DOES NOT NAVIGATE. Item 19 (T29) is the separate act: the reading pane offers "Open …",
247
- * which is where `onOpenTarget` fires. The old pane conflated them, so there was no way to READ
248
- * a notification without leaving the surface you were reading it on.
249
- */
250
- const select = useCallback(
251
- (n: Notification) => {
252
- setSelectedId(n.id);
253
- // ⭐ W33-T28 — remember it BEFORE the flag flips, so the row keeps its place in the list
254
- // for the rest of this visit. Only on SELECT: an explicit "mark read" on the row's own
255
- // toggle is a deliberate act of filing, and that one should move.
256
- if (!n.read) held.add(n.id);
257
- setRead(n, true);
258
- },
259
- [held, setRead]
260
- );
261
-
262
- const open = useCallback(
263
- (n: Notification) => {
264
- const t = targetOf(n);
265
- if (!t) return onToast(UNOPENABLE_NOTE);
266
- setRead(n, true);
267
- onOpenTarget(t);
268
- },
269
- [onOpenTarget, onToast, setRead]
270
- );
271
-
272
- const runAlertNow = useCallback(
273
- (a: Alert) => {
274
- setBusy(true);
275
- void runAlert(a.id).then((r) => {
276
- setBusy(false);
277
- if (!r.ok) return onToast(r.message);
278
- const v = r.value as { new?: unknown[]; skipped?: string };
279
- onToast(
280
- v?.skipped
281
- ? `Skipped: ${v.skipped}`
282
- : `${(v?.new ?? []).length} new since the last check.`
283
- );
284
- void load();
285
- });
286
- },
287
- [load, onToast]
288
- );
289
-
290
- const deleteAlertNow = useCallback(
291
- (a: Alert) => {
292
- setBusy(true);
293
- void deleteAlert(a.id).then((r) => {
294
- setBusy(false);
295
- if (!r.ok) return onToast(r.message);
296
- setAlerts((cur) => cur.filter((x) => x.id !== a.id));
297
- void load();
298
- });
299
- },
300
- [load, onToast]
301
- );
302
-
303
- return (
304
- <InboxSurface
305
- alerts={alerts}
306
- error={error}
307
- busy={busy}
308
- view={view}
309
- sections={sections}
310
- selected={selected}
311
- selectedId={selectedId}
312
- now={inbox.now}
313
- onSelect={select}
314
- onOpen={open}
315
- onSetRead={setRead}
316
- onMarkAll={markAll}
317
- onRunAlert={runAlertNow}
318
- onDeleteAlert={deleteAlertNow}
319
- canMarkAllNow={canMarkAll(inbox.unread, busy)}
320
- />
321
- );
322
- }
323
-
324
- /**
325
- * ⭐ THE SURFACE, WITH NO FETCH IN IT — every value arrives as a prop.
326
- *
327
- * ⛔ SPLIT FOR ONE REASON, AND IT IS THE `done-when`: *"observed by a person"*. `InboxPage` reads
328
- * on mount, and `renderToStaticMarkup` never runs an effect — so a shot of the page can only ever
329
- * photograph its spinner. `_inbox_shot.tsx` renders THIS with rows that came through the real
330
- * server derivation (`routes_alerts.inbox_view`), so what a reviewer looks at is the shipped
331
- * markup over the shipped payload rather than a picture of a fixture. It is the same division
332
- * `connectors/_conn_shot.tsx` already relies on.
333
- */
334
- export function InboxSurface({
335
- alerts,
336
- error,
337
- busy,
338
- view,
339
- sections,
340
- selected,
341
- selectedId,
342
- now,
343
- onSelect,
344
- onOpen,
345
- onSetRead,
346
- onMarkAll,
347
- onRunAlert,
348
- onDeleteAlert,
349
- canMarkAllNow,
350
- }: {
351
- alerts: Alert[];
352
- error: string;
353
- busy: boolean;
354
- view: ReturnType<typeof paneView>;
355
- sections: InboxSections;
356
- selected: Notification | null;
357
- selectedId: string;
358
- /** ⭐ W33-T28 / D-208 — the SERVER's clock, so `stampText` can be mail-shaped without ever
359
- * reading the browser's. Absent (an older payload) degrades to the absolute stamp. */
360
- now?: string;
361
- onSelect: (n: Notification) => void;
362
- onOpen: (n: Notification) => void;
363
- onSetRead: (n: Notification, read: boolean) => void;
364
- onMarkAll: () => void;
365
- onRunAlert: (a: Alert) => void;
366
- onDeleteAlert: (a: Alert) => void;
367
- canMarkAllNow: boolean;
368
- }) {
369
- const row = (n: Notification) => {
370
- const preview = previewOf(n);
371
- return (
372
- <li key={n.id} className={"alerts-row" + (n.read ? "" : " is-unread")}>
373
- <button
374
- type="button"
375
- className="alerts-row-main"
376
- aria-current={n.id === selectedId ? "true" : undefined}
377
- style={n.id === selectedId ? { background: "var(--lp-wash)" } : undefined}
378
- onClick={() => onSelect(n)}
379
- title={subjectOf(n)}
380
- >
381
- {/* THE SUBJECT, on its own line and first — the header this feature never had. */}
382
- <span className="alerts-row-label">
383
- {n.kind === NOTIF_KIND_AUTOMATION ? (
384
- // ⚠ INSIDE the label span, not beside it. `.alerts-row-main` is a flex COLUMN, so a
385
- // sibling here becomes a third ROW stacked above the text
386
- // ([[wrong-parent-not-broken-control]]); inline, it sits on the line it annotates
387
- // and rides the same ellipsis.
388
- <span className="alerts-row-mark">
389
- <Mark size={12} />
390
- </span>
391
- ) : null}
392
- {subjectOf(n)}
393
- </span>
394
- <span className="alerts-row-meta">
395
- {/* ⭐⭐ W33-T28 — THE SENDER, where mail puts one. This position held
396
- `kindLabel(n.kind)` — "Alert" / "Automation" / "Shared with you" — a CATEGORY
397
- standing in for a who, which is why the row never read like mail however it was
398
- laid out. The kind is still legible: it decides the fallback name and the mark
399
- above. */}
400
- {senderOf(n)}
401
- {preview ? ` · ${preview}` : ""}
402
- {" · "}
403
- {/* ⭐⭐ W33-T28 / D-208 — MAIL-SHAPED: `09:41` today, `Aug 12` beyond, the year only
404
- when it differs. It was `2026-08-13 09:41` — a database stamp in a surface asked
405
- to look like email. ⛔ `now` is the SERVER's clock, carried on the payload: still
406
- never re-derived, still no browser Date, because `at` is UTC-with-offset (D-18)
407
- precisely so every reader sees the same instant, and asking a local clock "is
408
- this today?" is how a tenant a day ahead gets told an event happened tomorrow. */}
409
- {stampText(n.at, now)}
410
- </span>
411
- </button>
412
- <button
413
- type="button"
414
- className="alerts-row-toggle"
415
- aria-label={n.read ? `Mark ${subjectOf(n)} unread` : `Mark ${subjectOf(n)} read`}
416
- title={n.read ? "Mark unread" : "Mark read"}
417
- onClick={() => onSetRead(n, !n.read)}
418
- >
419
- {/* The ACTION, not the state: "Read" beside an unread row reads as a label for the
420
- row itself. */}
421
- {n.read ? "Mark unread" : "Mark read"}
422
- </button>
423
- </li>
424
- );
425
- };
426
-
427
- return (
428
- <div className="inbox-page" style={PAGE}>
429
- <header className="alerts-head" style={{ padding: "0 0 14px" }}>
430
- <h2>
431
- <BellIcon size={18} className="alerts-bell" /> Inbox
432
- </h2>
433
- <button
434
- type="button"
435
- className="alerts-markall"
436
- // ⭐⭐ W31-T23 (R6), KEPT: the question is about the ACCOUNT, so it is asked of the
437
- // count the frame already holds. `inbox.unread === 0` was this surface's OWN state —
438
- // zero until its fetch landed and zero for ever if it failed — so the one verb that
439
- // clears the badge was disabled in exactly the two situations the owner reported.
440
- disabled={!canMarkAllNow}
441
- onClick={onMarkAll}
442
- >
443
- Mark all read
444
- </button>
445
- </header>
446
-
447
- {error ? <p className="shell-newdb-err">{error}</p> : null}
448
-
449
- <div style={SPLIT}>
450
- <div style={{ ...CARD, flex: "1 1 42%", padding: "4px 16px 16px" }}>
451
- {view === "pending" ? (
452
- /* R6: the mark, never the word. `verify_icons` asserts this product ships no load
453
- TEXT — and the sentence that used to occupy this space was worse than a word, it
454
- was an ANSWER ("Nothing new.") to a question nobody had asked yet. */
455
- <p className="alerts-empty" aria-busy="true">
456
- <span className="lp-spin" role="status" aria-label="Loading the inbox" />
457
- </p>
458
- ) : view === "error" ? (
459
- <p className="alerts-empty">
460
- Notifications could not be loaded.
461
- </p>
462
- ) : view === "empty" ? (
463
- <p className="alerts-empty">
464
- Nothing new.
465
- </p>
466
- ) : (
467
- <>
468
- {/* ⛔ THE UNREAD HEADING RENDERS AT ZERO TOO. Hiding it would make "I have read
469
- everything" and "the unread half failed to render" the same picture. */}
470
- <h3 className="home-section-title" style={{ margin: "14px 0 6px" }}>
471
- Unread{sections.unread.length ? ` (${sections.unread.length})` : ""}
472
- </h3>
473
- {sections.unread.length ? (
474
- <ul className="alerts-list">{sections.unread.map(row)}</ul>
475
- ) : (
476
- <p className="alerts-empty" style={{ margin: "4px 0 10px" }}>
477
- Nothing unread.
478
- </p>
479
- )}
480
- {sections.read.length ? (
481
- <>
482
- <h3 className="home-section-title" style={{ margin: "18px 0 6px" }}>
483
- Earlier
484
- </h3>
485
- <ul className="alerts-list">{sections.read.map(row)}</ul>
486
- </>
487
- ) : null}
488
- </>
489
- )}
490
-
491
- {alerts.length > 0 ? (
492
- <section className="alerts-watching">
493
- <h3 className="home-section-title">Watching</h3>
494
- {alerts.map((a) => (
495
- <div key={a.id} className="alerts-watch-row">
496
- <span className="alerts-watch-label">{a.label}</span>
497
- <span className="alerts-watch-meta">
498
- {/* The remembered set's SIZE, which is what "no news" means here: an alert
499
- with 40 matches and nothing new is working. */}
500
- {a.matched.toLocaleString()} matched
501
- {a.lastError ? ` · ${a.lastError}` : ""}
502
- </span>
503
- <button
504
- type="button"
505
- className="alerts-watch-run"
506
- disabled={busy}
507
- onClick={() => onRunAlert(a)}
508
- >
509
- Check now
510
- </button>
511
- <button
512
- type="button"
513
- className="alerts-watch-del"
514
- disabled={busy}
515
- aria-label={`Delete the alert ${a.label}`}
516
- onClick={() => onDeleteAlert(a)}
517
- >
518
- Delete
519
- </button>
520
- </div>
521
- ))}
522
- </section>
523
- ) : null}
524
- </div>
525
-
526
- {/* THE READING PANE. Always present, so the layout does not jump when a row is picked —
527
- and so the surface reads as mail before anything is selected. */}
528
- <div className="inbox-detail" style={{ ...CARD, flex: "1 1 58%", padding: "20px 24px" }}>
529
- {selected === null ? (
530
- <p className="alerts-empty">Select a notification to read it.</p>
531
- ) : (
532
- <>
533
- <h3
534
- style={{
535
- margin: "0 0 6px",
536
- fontSize: "var(--lp-fs-sm)",
537
- fontWeight: 650,
538
- color: "var(--lp-ink)",
539
- }}
540
- >
541
- {subjectOf(selected)}
542
- </h3>
543
- <p className="alerts-row-meta" style={{ margin: "0 0 16px" }}>
544
- {/* ⭐⭐ W33-T28 / D-208 — THE SECOND CALL SITE, and it is the one that would have
545
- made the fix look like a bug. The row above renders `09:41`; this pane sits
546
- directly below it, and left on the old formatting it would have printed
547
- `2026-08-13 09:41` for the SAME notification, on the same screen, at the same
548
- moment. A half-applied format is more confusing than the format it replaced.
549
- ⚠ `senderOf`, not `kindLabel`, for the same reason as the row: mail puts a WHO
550
- here, and the kind is already legible from the mark. */}
551
- {senderOf(selected)} · {stampText(selected.at, now)}
552
- </p>
553
- {previewOf(selected) ? (
554
- <p
555
- style={{
556
- margin: "0 0 18px",
557
- fontSize: "var(--lp-fs-xs)",
558
- lineHeight: 1.55,
559
- color: "var(--lp-ink)",
560
- }}
561
- >
562
- {previewOf(selected)}
563
- </p>
564
- ) : null}
565
- {canOpen(selected) ? (
566
- <button
567
- type="button"
568
- className="login-submit"
569
- onClick={() => onOpen(selected)}
570
- >
571
- {actionLabelOf(selected)}
572
- </button>
573
- ) : (
574
- /* ⛔ SAID ON THE ITEM, NOT ON THE CLICK. The pane raised this as a toast AFTER
575
- the reader pressed a button that looked live — "you pressed this and were
576
- told off" rather than "this is unavailable". */
577
- <p className="alerts-empty" style={{ margin: 0 }}>
578
- {UNOPENABLE_NOTE}
579
- </p>
580
- )}
581
- <button
582
- type="button"
583
- className="alerts-row-toggle"
584
- style={{ marginLeft: 10 }}
585
- onClick={() => onSetRead(selected, !selected.read)}
586
- >
587
- {selected.read ? "Mark unread" : "Mark read"}
588
- </button>
589
- </>
590
- )}
591
- </div>
592
- </div>
593
- </div>
594
- );
595
- }