-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.svelte
More file actions
2308 lines (2200 loc) · 98.4 KB
/
Copy pathApp.svelte
File metadata and controls
2308 lines (2200 loc) · 98.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<script lang="ts">
import { onMount } from 'svelte';
import {
workspace,
type PromptTemplate,
type RecordSet,
type ResponseRecord,
type ResponseFlag,
type Row,
type HelpfulLink,
type SocialProfile, resolveWsUrl } from '@augment-it/workspace';
import ConfidencePill from '@augment-it/shared-ui/ConfidencePill.svelte';
import { MOCK_PACKS_FIXTURE } from './fixtures/mock-packs';
import ConnectorPalette from './ConnectorPalette.svelte';
import type { PaletteConnector, PalettePack } from './ConnectorPalette.svelte';
// Each remote owns its own workspace singleton + WebSocket — no `shared`
// federation block (see the 2026-05-21_03 changelog).
const TOKEN_KEY = 'augment-it:session-token';
const WS_URL = resolveWsUrl();
const FLAGS: ResponseFlag[] = ['good', 'partial', 'wrong', 'needs-rerun', 'needs-human'];
// Per-record palette pack roster — one chip per intent, default click walks
// the pack's preferred_connectors chain; long-press opens a connector menu.
// Source of truth for pack identity is services/social-search/src/packs.ts;
// short_label + accent live here so the UI renders without a round-trip.
// Migrated from the legacy two-row provider × pack grid 2026-06-03 per
// context-v/specs/Connector-Inventory-and-Per-Record-Palette.md.
const PACKS_META: PalettePack[] = [
{ pack_id: 'linkedin-pack', display_name: 'LinkedIn', intent: 'search.social.linkedin', short_label: 'in', accent: '#0a66c2', preferred_connectors: ['searxng', 'tavily', 'serpapi-google'] },
{ pack_id: 'x-pack', display_name: 'X / Twitter', intent: 'search.social.x', short_label: 'x', accent: '#1d9bf0', preferred_connectors: ['searxng', 'tavily', 'serpapi-google'] },
{ pack_id: 'bluesky-pack', display_name: 'Bluesky', intent: 'search.social.bluesky', short_label: 'bs', accent: '#1185fe', preferred_connectors: ['searxng', 'tavily', 'serpapi-google'] },
{ pack_id: 'youtube-pack', display_name: 'YouTube', intent: 'search.social.youtube', short_label: 'yt', accent: '#ff0000', preferred_connectors: ['searxng', 'tavily', 'serpapi-google'] },
{ pack_id: 'facebook-pack', display_name: 'Facebook', intent: 'search.social.facebook', short_label: 'f', accent: '#1877f2', preferred_connectors: ['searxng', 'tavily', 'serpapi-google'] },
{ pack_id: 'wikipedia-pack', display_name: 'Wikipedia', intent: 'fetch.wikipedia', short_label: 'wp', accent: '#888a8c', preferred_connectors: ['searxng', 'serpapi-google'] },
{ pack_id: 'instagram-pack', display_name: 'Instagram', intent: 'search.social.instagram', short_label: 'ig', accent: '#e1306c', preferred_connectors: ['searxng', 'tavily', 'serpapi-google'] },
];
// Inventory loaded once via connectors.inventory capability. Shared across
// every palette in the by-record view so N rows don't trigger N fetches.
// Empty during load; palette degrades to "no connectors available" cleanly.
let inventory = $state<PaletteConnector[]>([]);
// View modes — single-response stepper (the original UI, best for prompt
// responses where each row has one verbose response to read) OR by-record
// (groups all responses for a row into one card, best for pack responses
// where each row has N parallel results to triage quickly). Per the user's
// feedback in the 2026-05-25 pack smoke: stepping through 402 unflagged
// pack responses one-by-one was untenable; per-record collapses the same
// data into ~67 row-cards. Persisted so refresh sticks.
type ViewMode = 'single' | 'by-record' | 'content-reader';
const VIEW_MODE_KEY = 'augment-it:response-reviewer:view-mode';
function readViewMode(): ViewMode {
if (typeof localStorage === 'undefined') return 'single';
return (localStorage.getItem(VIEW_MODE_KEY) as ViewMode) ?? 'single';
}
let viewMode = $state<ViewMode>(readViewMode());
$effect(() => {
if (typeof localStorage !== 'undefined') localStorage.setItem(VIEW_MODE_KEY, viewMode);
});
let status = $state<'connecting' | 'open' | 'closed' | 'error' | 'auth_required'>('connecting');
let responses = $state<ResponseRecord[]>([]);
let promptsById = $state<Record<string, PromptTemplate>>({});
let recordSetsById = $state<Record<string, RecordSet>>({});
// By-record view needs to know each row's entity name (and other fields).
// Loaded lazily when entering by-record mode — see `loadRowsForByRecord`.
let rowsByRowId = $state<Record<string, Row>>({});
let rowBusyId = $state<string>(''); // shows the spinner on per-row triage clicks
let filter = $state<'all' | 'unflagged' | ResponseFlag>('all');
// Record-set scope filter — narrows the response list to one record set.
// Surfaced after the 2026-05-26 by-record diagnosis: response-store
// outlives row-store (responses survive when their parent record set
// is deleted), so without scoping the by-record view shows orphan
// responses with row_id headers (no entity name resolvable).
//
// Two-state model: a value + an isExplicit flag. isExplicit=false means
// "the user hasn't picked yet — feel free to auto-default." Only the
// click handlers (via setRecordSetFilter) mark it explicit + persist.
// The auto-default effect picks the largest non-orphan bucket once
// responses load, so a returning user sees their active dataset first
// and orphans drop out.
// v2 key — bumped 2026-05-26 when the storage semantics changed: the v1
// key was written on every reactive change (including the initial 'all'
// default), so it can't be used to distinguish "user picked all" from
// "code never ran auto-default." v2 is only written by explicit click
// handlers via setRecordSetFilter.
const RECORD_SET_FILTER_KEY = 'augment-it:response-reviewer:record-set-filter-v2';
const initialStoredRSF =
typeof localStorage !== 'undefined' ? localStorage.getItem(RECORD_SET_FILTER_KEY) : null;
let recordSetFilter = $state<string>(initialStoredRSF ?? 'all');
let recordSetFilterIsExplicit = $state<boolean>(initialStoredRSF !== null);
function setRecordSetFilter(value: string): void {
recordSetFilter = value;
recordSetFilterIsExplicit = true;
if (typeof localStorage !== 'undefined') {
localStorage.setItem(RECORD_SET_FILTER_KEY, value);
}
}
let index = $state(0);
let editText = $state('');
let busy = $state('');
let refreshing = $state(false);
let lastRefreshAt = $state<number | null>(null);
let editSavedAt = $state<number | null>(null);
let editDirty = $state(false);
let savingEdit = $state(false);
// helpful-links state — the current row's full record, fetched from row-store
// whenever the focused response changes. Links live in row.fields.helpful_links.
let currentRow = $state<Row | null>(null);
let newLinkUrl = $state('');
let newLinkNote = $state('');
let addingLink = $state(false);
let linkBusy = $state('');
const helpfulLinks = $derived.by(() => {
const raw = (currentRow?.fields as Record<string, unknown> | undefined)?.helpful_links;
return Array.isArray(raw) ? (raw as HelpfulLink[]) : [];
});
// editText is reset only when the *response_id* changes, so a background
// refresh (a flag landing, a new response) doesn't clobber an in-progress
// edit of the same response.
let editTextForId = '';
// Apply the record-set scope BEFORE the flag filter so flag-counts
// reflect what the user is currently focused on. '__orphan__' is the
// synthetic bucket for responses whose parent record set was deleted.
const scopedByRecordSet = $derived.by(() => {
if (recordSetFilter === 'all') return responses;
if (recordSetFilter === '__orphan__') {
return responses.filter((r) => !recordSetsById[r.record_set_id]);
}
return responses.filter((r) => r.record_set_id === recordSetFilter);
});
const filtered = $derived(
scopedByRecordSet.filter((r) => {
if (filter === 'all') return true;
if (filter === 'unflagged') return r.flag === null;
return r.flag === filter;
}),
);
const current = $derived(filtered[index] ?? null);
// Per-bucket counts for the FLAG chips — scoped to the active record set
// so the counts match what the user actually sees.
const counts = $derived.by(() => {
const c: Record<string, number> = {
all: scopedByRecordSet.length,
unflagged: 0,
good: 0,
partial: 0,
wrong: 0,
'needs-rerun': 0,
'needs-human': 0,
};
for (const r of scopedByRecordSet) {
if (r.flag === null) c.unflagged += 1;
else c[r.flag] = (c[r.flag] ?? 0) + 1;
}
return c;
});
// Per-record-set counts for the new record-set chip tier. Includes an
// 'orphan' bucket for responses whose record_set_id doesn't resolve to
// a known record set (parent set was deleted / archived after the
// response was recorded).
type RecordSetBucket = {
id: string; // record_set_id or '__orphan__'
label: string; // display label
count: number;
};
// Auto-default the record-set filter to the largest non-orphan bucket the
// first time responses load. Marks isExplicit=false so the user's later
// click on "all sets" or "(orphan)" sticks. Skips when the user has
// already picked something (recordSetFilterIsExplicit).
$effect(() => {
if (recordSetFilterIsExplicit) return;
if (responses.length === 0) return;
const tallies: Record<string, number> = {};
for (const r of responses) tallies[r.record_set_id] = (tallies[r.record_set_id] ?? 0) + 1;
let best: { id: string; count: number } | null = null;
for (const [id, n] of Object.entries(tallies)) {
if (!recordSetsById[id]) continue; // orphan — skip
if (!best || n > best.count) best = { id, count: n };
}
if (best && best.id !== recordSetFilter) recordSetFilter = best.id;
});
const recordSetBuckets = $derived.by<RecordSetBucket[]>(() => {
const counts: Record<string, number> = {};
for (const r of responses) counts[r.record_set_id] = (counts[r.record_set_id] ?? 0) + 1;
const buckets: RecordSetBucket[] = [];
let orphanCount = 0;
for (const [setId, n] of Object.entries(counts)) {
const rs = recordSetsById[setId];
if (rs) {
buckets.push({ id: setId, label: rs.name, count: n });
} else {
orphanCount += n;
}
}
buckets.sort((a, b) => b.count - a.count);
if (orphanCount > 0) {
buckets.push({ id: '__orphan__', label: 'orphan (parent set gone)', count: orphanCount });
}
return buckets;
});
const firedPrompt = $derived.by(() => {
const rb = current?.request_body as { messages?: { content?: unknown }[] } | undefined;
const content = rb?.messages?.[0]?.content;
return typeof content === 'string' ? content : '';
});
const promptName = $derived(
current ? (promptsById[current.prompt_id]?.name ?? current.prompt_id) : '',
);
const recordSetName = $derived(
current ? (recordSetsById[current.record_set_id]?.name ?? current.record_set_id) : '',
);
// Outcome-driven rendering for pack responses. Found responses render the
// existing editor + actions; the other four outcomes render thin rows in
// place of the editor. The candidate card (when structured !== null) sits
// above whatever body the outcome chose. See:
// context-v/blueprints/Packs-and-Bundles-Pattern.md §Bundle anatomy/§5
const isFound = $derived(current?.outcome === 'found');
let snippetExpanded = $state(false);
$effect(() => {
// collapse the snippet whenever the focused response changes
void current?.response_id;
snippetExpanded = false;
});
onMount(() => {
workspace.connect({
url: WS_URL,
getToken: () => localStorage.getItem(TOKEN_KEY),
saveToken: (t) => localStorage.setItem(TOKEN_KEY, t),
onStatus: (s) => (status = s),
});
void loadResponses();
void loadPrompts();
void loadRecordSets();
void loadInventory();
// Belt-and-suspenders: if the user closes the tab or hard-refreshes with
// an unsaved edit, fire one last best-effort autosave. (Browsers may not
// wait for the promise — the onblur autosave does the real work.)
const beforeUnload = () => { void flushEdit(); };
window.addEventListener('beforeunload', beforeUnload);
return () => window.removeEventListener('beforeunload', beforeUnload);
});
// refresh when a response is created, flagged, or deleted — seq-cursor dedup.
let lastSeq = -1;
$effect(() => {
const ev = workspace.events[workspace.events.length - 1];
if (!ev || ev.seq <= lastSeq) return;
lastSeq = ev.seq;
if (
ev.subject === 'response.created' ||
ev.subject === 'response.flagged' ||
ev.subject === 'response.deleted' ||
ev.subject === 'response.edited'
) {
void loadResponses();
}
// Refresh the current row whenever it gets updated (helpful_links changed
// here or elsewhere, or any other field write).
if (ev.subject === 'row.updated') {
const p = ev.payload as { row_id?: string };
if (p.row_id && p.row_id === current?.row_id) void loadCurrentRow();
}
});
// load the row record whenever the focused response changes
$effect(() => {
const c = current;
if (!c) {
currentRow = null;
return;
}
void loadCurrentRow();
});
async function loadCurrentRow() {
if (!current) return;
try {
const r = (await workspace.invoke('row.get', { row_id: current.row_id })) as { row: Row | null };
currentRow = r.row;
} catch (e) {
console.error('row.get', e);
}
}
async function addHelpfulLink() {
if (!current) return;
const url = newLinkUrl.trim();
if (!url) return;
addingLink = true;
linkBusy = '';
try {
const result = (await workspace.invoke('row.helpful_links.add', {
row_id: current.row_id,
url,
note: newLinkNote.trim(),
response_id: current.response_id,
})) as { row: Row };
currentRow = result.row;
newLinkUrl = '';
newLinkNote = '';
} catch (e) {
linkBusy = `add failed — ${e instanceof Error ? e.message : String(e)}`;
} finally {
addingLink = false;
}
}
async function removeHelpfulLink(link_id: string) {
if (!current) return;
try {
const result = (await workspace.invoke('row.helpful_links.remove', {
row_id: current.row_id,
link_id,
})) as { row: Row };
currentRow = result.row;
} catch (e) {
linkBusy = `remove failed — ${e instanceof Error ? e.message : String(e)}`;
}
}
function linkLabel(link: HelpfulLink): string {
if (link.label) return link.label;
try {
return new URL(link.url).hostname.replace(/^www\./, '');
} catch {
return link.url;
}
}
// keep the stepper index inside the filtered list
$effect(() => {
const len = filtered.length;
if (index >= len) index = Math.max(0, len - 1);
});
// load the editable copy when the focused response changes. Critically:
// if the OUTGOING response has unsaved edits, flush them to the server
// before swapping in the new response's text — stepping must never lose
// typed content.
$effect(() => {
const c = current;
if (!c) {
void flushEdit();
editText = '';
editTextForId = '';
return;
}
if (c.response_id !== editTextForId) {
// flush pending edits on the response we're leaving
void flushEdit();
editText = c.edited_text ?? c.response_text;
editTextForId = c.response_id;
editDirty = false;
editSavedAt = c.edited_at ? Date.parse(c.edited_at) : null;
}
});
// any non-trivial change marks the editor dirty; autosave fires on blur.
function onEditInput() {
if (!current) return;
const saved = current.edited_text ?? current.response_text;
editDirty = editText !== saved;
}
async function flushEdit(): Promise<void> {
// Use editTextForId, not current.response_id — current may already be
// pointing at the next response by the time this fires.
const targetId = editTextForId;
if (!targetId || !editDirty) return;
const pending = editText;
savingEdit = true;
try {
await workspace.invoke('response.set_text', {
response_id: targetId,
edited_text: pending,
});
// Only clear dirty if the editor is still on the same response;
// if the user kept typing on it in the meantime, leave dirty=true.
if (targetId === editTextForId && editText === pending) {
editDirty = false;
editSavedAt = Date.now();
}
} catch (e) {
console.error('response.set_text', e);
busy = `autosave failed — ${e instanceof Error ? e.message : String(e)}`;
} finally {
savingEdit = false;
}
}
// Detect `?fixture=mock-packs` once on mount. When set, prepend the mock
// pack-shaped responses to the live list so every outcome+confidence band
// is visible side-by-side. Mocks are NEVER persisted — clearing them is a
// refresh away (drop the query param). Spec:
// context-v/prompts/Response-Reviewer-Structured-Output-Extension.md
const fixtureMode =
typeof window !== 'undefined' &&
new URLSearchParams(window.location.search).get('fixture') === 'mock-packs';
async function loadResponses() {
try {
const r = (await workspace.invoke('response.list', {})) as { responses: ResponseRecord[] };
responses = fixtureMode ? [...MOCK_PACKS_FIXTURE, ...r.responses] : r.responses;
lastRefreshAt = Date.now();
} catch (e) {
console.error('response.list', e);
}
}
async function manualRefresh() {
refreshing = true;
try {
await Promise.all([loadResponses(), loadPrompts(), loadRecordSets()]);
if (viewMode === 'by-record' || viewMode === 'content-reader') await loadRowsForByRecord();
} finally {
refreshing = false;
}
}
// By-record view: load every row referenced by the currently-filtered
// responses so we can show the entity name + use row.fields for
// disambiguation. Batches per record_set_id via the existing row.list
// capability. Cheap enough for the foundation-dataset scale.
//
// Effect-cycle note: when this is invoked from a $effect, only the
// SYNCHRONOUS portion (up to the first `await`) participates in Svelte
// 5's reactive read-tracking. We therefore avoid reading `rowsByRowId`
// synchronously — otherwise the effect would (a) read rowsByRowId,
// (b) write rowsByRowId, and (c) re-fire on every write, infinite loop.
// The spread + assignment live after the first await, outside the
// tracking window.
async function loadRowsForByRecord() {
const setIds = new Set<string>();
for (const r of filtered) setIds.add(r.record_set_id);
if (setIds.size === 0) return;
const fresh: Record<string, Row> = {};
for (const record_set_id of setIds) {
try {
const r = (await workspace.invoke('row.list', { record_set_id })) as { rows: Row[] };
for (const row of r.rows) fresh[row.row_id] = row;
} catch (e) {
console.error('row.list (by-record)', record_set_id, e);
}
}
// Past the first await — outside the effect's sync tracking window.
// Reading rowsByRowId here does NOT register as a dep of the effect
// that called us, so writing it doesn't re-fire that effect.
rowsByRowId = { ...rowsByRowId, ...fresh };
}
// The columns we look in to find an entity's display name. In order — the
// user's foundation dataset puts the org in "Prospect / Organization";
// fallbacks cover common shapes seen across CSVs.
const NAME_COLUMNS = ['Prospect / Organization', 'name', 'organization', 'org', 'company', 'foundation', 'entity'];
// Returns BOTH the resolved column name + value so the by-record header
// can edit the same column we're displaying. When researching, the user
// often needs to correct the entity's name (e.g. "Accelerate the Future
// (ACH, GW Match)" → "Accelerate the Future") to make subsequent searches
// work — that edit writes back to the CSV-derived column via row.update.
function entityFieldFor(
row: Row | undefined,
): { field: string; value: string } | null {
if (!row) return null;
const fields = row.fields as Record<string, unknown>;
for (const c of NAME_COLUMNS) {
const v = fields[c];
if (typeof v === 'string' && v.trim().length > 0) {
return { field: c, value: v.trim() };
}
}
// Case-insensitive fallback — match the first field that smells like a
// name column. Avoids re-hunting on CSVs with different casing.
for (const k of Object.keys(fields)) {
if (NAME_COLUMNS.some((c) => k.toLowerCase() === c.toLowerCase())) {
const v = fields[k];
if (typeof v === 'string' && v.trim().length > 0) {
return { field: k, value: v.trim() };
}
}
}
return null;
}
// By-record grouping. Groups filtered responses by row_id, preserves
// recency order (newest response first), and ranks rows by entity name
// (alphabetical) so the user steps through "A → Z" rather than a random
// response-id order. `entity_field` is the row column the name came from
// — null when no candidate matched, in which case the header falls back
// to row_id and the name is read-only.
type RowGroup = {
row_id: string;
record_set_id: string;
entity_field: string | null;
entity_name: string;
responses: ResponseRecord[];
};
const byRecord = $derived.by<RowGroup[]>(() => {
const groups: Record<string, RowGroup> = {};
for (const r of filtered) {
if (!groups[r.row_id]) {
const ef = entityFieldFor(rowsByRowId[r.row_id]);
groups[r.row_id] = {
row_id: r.row_id,
record_set_id: r.record_set_id,
entity_field: ef?.field ?? null,
entity_name: ef?.value ?? '',
responses: [],
};
}
groups[r.row_id].responses.push(r);
}
return Object.values(groups).sort((a, b) => {
const an = a.entity_name || a.row_id;
const bn = b.entity_name || b.row_id;
return an.localeCompare(bn);
});
});
// Lazy-load rows whenever entering by-record mode and the response set
// grows (manual refresh refreshes too — see manualRefresh).
$effect(() => {
if (viewMode !== 'by-record' && viewMode !== 'content-reader') return;
// Touch the response list size so this re-fires when new responses
// arrive via the broadcast.
void responses.length;
void loadRowsForByRecord();
});
// In-flight URL drafts for the by-record view's inline URL inputs.
// Keyed by response_id. Falls back to structured.url for display when no
// local draft exists. Persisted to response-store on blur via
// response.set_structured. Cleared after a successful save so the
// refreshed response value takes over.
let urlDrafts = $state<Record<string, string>>({});
// Same shape for the display_name input — separate so the two fields
// can be edited independently and save independently.
let nameDrafts = $state<Record<string, string>>({});
// Per-row drafts for the entity-name column edit in the by-record header.
// Keyed by row_id (one entity-name per row, not per response).
let rowNameDrafts = $state<Record<string, string>>({});
async function saveUrlEdit(resp: ResponseRecord) {
// Two valid paths: a pack response with existing structured (edit
// correction) OR a pack response with structured: null (human supply
// for not_found/error/etc.). Non-pack responses don't have the
// structured surface at all, so skip.
if (!resp.pack_id) return;
const draft = urlDrafts[resp.response_id];
if (draft === undefined) return; // never edited
const next = draft.trim();
// Empty draft is a no-op — don't fire set_structured with an empty URL
// since the backend rejects (you'd just generate noise).
if (next.length === 0) return;
if (resp.structured && next === resp.structured.url) {
// No actual change — drop the draft so the input falls back to source.
delete urlDrafts[resp.response_id];
urlDrafts = { ...urlDrafts };
return;
}
try {
await workspace.invoke('response.set_structured', {
response_id: resp.response_id,
patch: { url: next },
});
// Refresh so the local response list picks up structured.url = draft.
// Then clear the draft so the input renders from the canonical source.
await loadResponses();
delete urlDrafts[resp.response_id];
urlDrafts = { ...urlDrafts };
} catch (e) {
console.error('response.set_structured', e);
}
}
// Save an edit to the row's entity-name CSV column (e.g. "Prospect /
// Organization"). When researching, the user often needs to correct the
// name to make subsequent searches work — that edit writes back to the
// row via row.update. After save we re-pull rows so the by-record header
// re-renders with the canonical value and every group's entity_name
// re-sorts alphabetically.
async function saveRowNameEdit(group: { row_id: string; record_set_id: string; entity_field: string | null; entity_name: string }) {
if (!group.entity_field) return;
const draft = rowNameDrafts[group.row_id];
if (draft === undefined) return;
const next = draft.trim();
if (next === group.entity_name) {
delete rowNameDrafts[group.row_id];
rowNameDrafts = { ...rowNameDrafts };
return;
}
if (next.length === 0) return; // refuse to blank the name
try {
await workspace.invoke('row.update', {
row_id: group.row_id,
fields: { [group.entity_field]: next },
});
// Re-fetch the row so rowsByRowId reflects the new value; the byRecord
// derived recomputes from there.
await loadRowsForByRecord();
delete rowNameDrafts[group.row_id];
rowNameDrafts = { ...rowNameDrafts };
} catch (e) {
console.error('row.update (entity-name)', e);
}
}
async function saveNameEdit(resp: ResponseRecord) {
if (!resp.pack_id || !resp.structured) return;
const draft = nameDrafts[resp.response_id];
if (draft === undefined) return;
const next = draft.trim();
if (next === resp.structured.display_name) {
delete nameDrafts[resp.response_id];
nameDrafts = { ...nameDrafts };
return;
}
try {
await workspace.invoke('response.set_structured', {
response_id: resp.response_id,
patch: { display_name: next },
});
await loadResponses();
delete nameDrafts[resp.response_id];
nameDrafts = { ...nameDrafts };
} catch (e) {
console.error('response.set_structured (display_name)', e);
}
}
// Per-(row × pack) in-flight state for the per-record palette chips. Keyed
// `${row_id}::${pack_id}` — one fire per pack per row at a time (a second
// click is a no-op until the first settles, by design — the user should
// wait for the result before re-firing through a different connector).
let packBusy = $state<Set<string>>(new Set());
const packBusyKey = (row_id: string, pack_id: string) =>
`${row_id}::${pack_id}`;
// Which packs already have a result accepted onto this record — from accepted
// responses in the group AND from profiles already written to row.socials
// (the latter survives across promotes/record sets). Drives the ✓ badge so
// the user can tell at a glance what's "not already accepted" and worth
// re-running. Re-running an accepted pack stays allowed — it's additive.
function acceptedPackIds(group: RowGroup): Set<string> {
const ids = new Set<string>();
for (const r of group.responses) {
if (r.accepted && r.pack_id) ids.add(r.pack_id);
}
const socials = (rowsByRowId[group.row_id]?.fields as Record<string, unknown> | undefined)?.socials;
if (Array.isArray(socials)) {
for (const s of socials as SocialProfile[]) if (s?.pack_id) ids.add(s.pack_id);
}
return ids;
}
// Run ONE pack against ONE record from the per-record palette. When
// `connector_id` is omitted (default click on a chip) the backend's
// existing chain-walk picks the head of the pack's preferred_connectors.
// When provided (chosen from the long-press connector menu), the
// explicit connector overrides the chain. Strictly ADDITIVE — produces
// a new candidate response for triage and NEVER writes to row.fields;
// only a human accept does that, so accepted data is never overridden.
//
// NOTE on the provider_override seam: the underlying pack.search.requested
// subject's args still use `provider_override: ProviderId`. We pass the
// chosen connector_id through that field — the legacy ProviderId union
// ('searxng' | 'tavily' | 'serpapi' | 'gdelt' | 'google-news-rss') now
// matches the new connector_ids 1:1 except for SerpApi (registry id
// 'serpapi-google' vs legacy 'serpapi'). We map at the boundary.
function connectorIdToProviderId(connector_id: string): string {
if (connector_id === 'serpapi-google') return 'serpapi';
return connector_id;
}
async function runPackOnRecord(group: RowGroup, pack_id: string, connector_id?: string) {
const entity_name = group.entity_name.trim();
if (entity_name.length === 0) return; // nothing to search on
const key = packBusyKey(group.row_id, pack_id);
if (packBusy.has(key)) return;
packBusy = new Set(packBusy).add(key);
try {
await workspace.invoke('pack.search', {
pack_id,
row_id: group.row_id,
record_set_id: group.record_set_id,
entity_name,
entity_name_field: group.entity_field ?? undefined,
provider_override: connector_id ? connectorIdToProviderId(connector_id) : undefined,
});
await loadResponses();
if (viewMode === 'by-record') await loadRowsForByRecord();
} catch (e) {
console.error('pack.search (by-record)', e);
} finally {
const next = new Set(packBusy);
next.delete(key);
packBusy = next;
}
}
// Per-row Set of busy pack_ids — derived from packBusy by stripping the
// row_id prefix. The palette consumes this for chip 'firing' state.
function busyForRow(row_id: string): Set<string> {
const out = new Set<string>();
const prefix = `${row_id}::`;
for (const key of packBusy) {
if (key.startsWith(prefix)) out.add(key.slice(prefix.length));
}
return out;
}
// Inline triage in by-record mode — bypass the per-cell editText
// machinery. Just flips the flag (and writes to row.socials on accept
// via the existing response.accept fork).
async function flagInline(response_id: string, f: ResponseFlag) {
rowBusyId = response_id;
try {
await workspace.invoke('response.flag', { response_id, flag: f });
await loadResponses();
} catch (e) {
console.error('response.flag (inline)', e);
} finally {
rowBusyId = '';
}
}
async function acceptInline(response_id: string) {
rowBusyId = response_id;
try {
await workspace.invoke('response.accept', { response_id });
await loadResponses();
} catch (e) {
console.error('response.accept (inline)', e);
} finally {
rowBusyId = '';
}
}
function formatAge(ts: number | null): string {
if (ts === null) return 'never';
const s = Math.floor((Date.now() - ts) / 1000);
if (s < 5) return 'just now';
if (s < 60) return `${s}s ago`;
return `${Math.floor(s / 60)}m ago`;
}
async function loadPrompts() {
try {
const r = (await workspace.invoke('prompt.list', {})) as { prompts: PromptTemplate[] };
const map: Record<string, PromptTemplate> = {};
for (const p of r.prompts) map[p.prompt_id] = p;
promptsById = map;
} catch (e) {
console.error('prompt.list', e);
}
}
// Connector inventory — loaded once on mount, fed into every ConnectorPalette
// so the per-record chips can resolve cost tiers, missing env vars, and
// available-for-this-intent connector lists without a fetch per row.
async function loadInventory() {
try {
const r = (await workspace.invoke('connectors.inventory', {})) as {
connectors: PaletteConnector[];
};
inventory = r.connectors ?? [];
} catch (e) {
// Non-fatal — palette degrades to "no connectors" / chips show needs-env
// for everything when the registry is unavailable.
console.warn('connectors.inventory unavailable', e);
inventory = [];
}
}
async function loadRecordSets() {
try {
const r = (await workspace.invoke('record_set.list', {})) as { record_sets: RecordSet[] };
const map: Record<string, RecordSet> = {};
for (const rs of r.record_sets) map[rs.record_set_id] = rs;
recordSetsById = map;
} catch (e) {
console.error('record_set.list', e);
}
}
function step(delta: number) {
index = Math.min(Math.max(index + delta, 0), Math.max(filtered.length - 1, 0));
}
async function flag(f: ResponseFlag) {
if (!current) return;
busy = 'flagging…';
try {
await workspace.invoke('response.flag', { response_id: current.response_id, flag: f });
await loadResponses();
busy = '';
} catch (e) {
busy = `flag failed — ${e instanceof Error ? e.message : String(e)}`;
}
}
async function accept() {
if (!current) return;
busy = 'accepting…';
try {
// Pass the current editor contents whenever they differ from what's
// saved on the response; the server side picks `value` over edited_text
// over response_text, so this always reflects the latest edit. (Also
// flushes any pending autosave by virtue of the explicit value.)
const savedText = current.edited_text ?? current.response_text;
const value = editText !== savedText ? editText : undefined;
await workspace.invoke('response.accept', {
response_id: current.response_id,
value,
});
editDirty = false;
editSavedAt = Date.now();
await loadResponses();
busy = 'accepted → value written to the row cell';
} catch (e) {
busy = `accept failed — ${e instanceof Error ? e.message : String(e)}`;
}
}
async function deleteCurrent() {
if (!current) return;
if (!window.confirm(`Delete this response? (It will not affect any cell value already accepted to a row.)`)) return;
busy = 'deleting…';
try {
await workspace.invoke('response.delete', { response_id: current.response_id });
await loadResponses();
busy = '';
} catch (e) {
busy = `delete failed — ${e instanceof Error ? e.message : String(e)}`;
}
}
async function clearVisible() {
if (filtered.length === 0) return;
const scopeLabel =
filter === 'all' ? `all ${filtered.length} responses` : `${filtered.length} "${filter}" responses`;
if (!window.confirm(`Clear ${scopeLabel}? This cannot be undone.`)) return;
busy = 'clearing…';
try {
// The store's delete_all takes a ResponseFilter; the UI filter has an
// extra 'unflagged' bucket that the store can't express directly, so
// we fall back to per-id deletes in that one case. Everything else maps
// to a single bulk call.
if (filter === 'unflagged') {
await Promise.all(
filtered.map((r) => workspace.invoke('response.delete', { response_id: r.response_id })),
);
} else if (filter === 'all') {
await workspace.invoke('response.delete_all', {});
} else {
await workspace.invoke('response.delete_all', { flag: filter });
}
index = 0;
await loadResponses();
busy = '';
} catch (e) {
busy = `clear failed — ${e instanceof Error ? e.message : String(e)}`;
}
}
function rerun() {
if (!current) return;
// hand the row back to request-reviewer (it listens for this event when
// mounted) and flag this response so the triage list reflects it.
window.dispatchEvent(
new CustomEvent('augment-it:review-request', {
detail: {
prompt_id: current.prompt_id,
record_set_id: current.record_set_id,
row_id: current.row_id,
},
}),
);
void flag('needs-rerun');
}
// ============================================================
// Content Reader (view mode 'content-reader')
// Per context-v/specs/Funder-Content-Corpus-Workflow.md.
// Implements Rules 5-8:
// Rule 5: per-item curation (edit title + tags, "+ add to corpus")
// Rule 6: hide already-in-corpus items from preview list
// Rule 7: show ALL rows of the active record set, including not-fired
// and invalid-URL rows, with clear affordances
// Rule 8: scope responses to latest fire_id per (row_id, pack_id);
// surface "last fired" timestamp per record
// ============================================================
// Content-shaped packs whose responses surface as previewable content.
// Must match services/content-ingest/src/handlers.ts CONTENT_PACK_IDS
// and services/social-search/src/entity-pulse/packs (which packs are
// wired to publish responses).
const CONTENT_PACK_IDS = new Set(['official-blog-pack']);
const CLIENT_ID = 'reach-edu';
type PreviewResult = {
response_id: string;
status: 'ready' | 'failed';
exact_url: string;
pack_id: string | null;
title?: string;
excerpt?: string;
fetched_at?: string;
extra_metadata?: Record<string, unknown>;
error?: string;
};
type CorpusEntry = {
corpus_path: string;
response_id: string | null;
record_id: string | null;
exact_url: string;
fetched_at: string;
title: string;
tags: string[];
};
let previewsByRowId = $state<Record<string, PreviewResult[]>>({});
let previewBusyRowId = $state<string>('');
let previewErrorByRowId = $state<Record<string, string>>({});
let corpusEntriesByRowId = $state<Record<string, CorpusEntry[]>>({});
let addingResponseId = $state<string>('');
let titleDraftsByResponseId = $state<Record<string, string>>({});
let tagDraftsByResponseId = $state<Record<string, string>>({});
// Active record set is what the user picked in the scope chip row.
// Defaults to the largest non-orphan bucket (an existing $effect handles
// this), but operator can switch.
const activeRecordSet = $derived.by(() => {
if (recordSetFilter === 'all' || recordSetFilter === '__orphan__') return null;
return recordSetsById[recordSetFilter] ?? null;
});
// Rule 8: latest fire_id per (row_id, pack_id). fire_ids are time-prefixed
// so lexicographic max == temporal max. Null fire_id is "older than any
// stamped fire" — only surfaces when no stamped fire exists for the pair.
type FireKey = string; // `${row_id}::${pack_id}`
const latestFireIdByRowPack = $derived.by<Map<FireKey, string | null>>(() => {
const out = new Map<FireKey, string | null>();
for (const r of responses) {
if (r.pack_id == null) continue;
const key: FireKey = `${r.row_id}::${r.pack_id}`;
const fid = (r as unknown as { fire_id?: string | null }).fire_id ?? null;
const cur = out.get(key);
if (cur === undefined) out.set(key, fid);
else if (fid != null && (cur == null || fid > cur)) out.set(key, fid);
}
return out;
});
function responseFireId(r: ResponseRecord): string | null {
return (r as unknown as { fire_id?: string | null }).fire_id ?? null;
}
// Rules 1+2 layered defense + Rule 8 fire scoping.
function rowHostnameFor(row_id: string): string | null {
const row = rowsByRowId[row_id];
const u = (row?.fields as Record<string, unknown> | undefined)?.url;
if (typeof u !== 'string') return null;
try { return new URL(u).hostname.replace(/^www\./, ''); } catch { return null; }
}
const NAVIGATION_PATTERNS = [
/\/page\/\d+\/?$/i, /\/p\/\d+\/?$/i,
/\/category\/[^/]+\/?$/i, /\/categories\/[^/]+\/?$/i,
/\/tag\/[^/]+\/?$/i, /\/tags\/[^/]+\/?$/i,
/\/topic\/[^/]+\/?$/i, /\/topics\/[^/]+\/?$/i,
/\/author\/[^/]+\/?$/i, /\/contributors\/[^/]+\/?$/i,
/\/archive\/?$/i, /\/archives\/?$/i,
/\/feed\/?$/i, /\/rss\/?$/i, /\/atom\.xml$/i, /\/index\.html?$/i,
/\/\d{4}\/?$/i, /\/\d{4}\/\d{1,2}\/?$/i,
];
function isNavigationUrl(url: string): boolean {
try {
const p = new URL(url).pathname;
for (const re of NAVIGATION_PATTERNS) if (re.test(p)) return true;
return false;
} catch { return true; }
}