-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathextraction.go
More file actions
2209 lines (2010 loc) · 60.5 KB
/
extraction.go
File metadata and controls
2209 lines (2010 loc) · 60.5 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
// Copyright 2026 Phillip Cloud
// Licensed under the Apache License, Version 2.0
package app
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cpcloud/micasa/internal/data"
"github.com/cpcloud/micasa/internal/extract"
"github.com/cpcloud/micasa/internal/llm"
"github.com/cpcloud/micasa/internal/locale"
)
// --- Extraction step types ---
type extractionStep int
const (
stepText extractionStep = iota
stepExtract
stepLLM
numExtractionSteps
)
const tableDocuments = data.TableDocuments
var nextExtractionID atomic.Uint64
type stepStatus int
const (
stepPending stepStatus = iota
stepRunning
stepDone
stepFailed
stepSkipped
)
// extractionStepInfo tracks the state of a single extraction step.
type extractionStepInfo struct {
Status stepStatus
Detail string // tool/model identifier (e.g. "pdf", "qwen3:0.6b")
Metric string // measurement (e.g. "68 chars")
Logs []string
Elapsed time.Duration
Started time.Time
}
// extractionLogState holds the state of the extraction progress overlay.
type extractionLogState struct {
ID uint64
DocID uint
Filename string
Steps [numExtractionSteps]extractionStepInfo
Spinner spinner.Model
Viewport viewport.Model
Visible bool
Done bool
HasError bool
ctx context.Context
CancelFn context.CancelFunc
llmCancelFn context.CancelFunc // cancels the LLM timeout context
// Text sources accumulated during extraction, passed to LLM prompt.
sources []extract.TextSource
extractedText string // best available text for DB storage/display
// Async extraction results pending persistence (nil until produced).
pendingText string // text from async extraction
pendingData []byte // structured data from async extraction
// LLM token accumulator for JSON parsing on completion.
llmAccum strings.Builder
// Carried between steps.
fileData []byte
mime string
extractors []extract.Extractor
// Per-tool image acquisition state (non-nil during acquisition phase).
acquireTools []extract.AcquireToolState
docPages int // total PDF pages when capped (0 = all pages processed)
extractedPages int // pages actually processed
// Channel references for the waitFor loop pattern.
extractCh <-chan extract.ExtractProgress
llmCh <-chan llm.StreamChunk
markdownRenderer
// Which steps are active (skipped steps are simply not shown).
hasText bool
hasExtract bool
hasLLM bool
// Pending results held until user accepts.
operations []extract.Operation // validated operations (not yet executed)
shadowDB *extract.ShadowDB // staged operations for cross-reference resolution
accepted bool // true once user accepted results
pendingDoc *data.Document // deferred creation: unpersisted document (magic-add)
// Cursor and expand/collapse state for exploring output.
cursor int // index into activeSteps()
toolCursor int // -1 = parent header, 0..N-1 = child tool line
cursorManual bool // true after j/k; disables auto-follow
expanded map[extractionStep]bool // manual expand/collapse overrides
// Explore mode: read-only table navigation for proposed operations.
exploring bool // true when in table explore mode
previewGroups []previewTableGroup // cached grouped operations
previewTab int // active tab in explore mode
previewRow int // row cursor within active tab
previewCol int // column cursor within active tab
// LLM ping state: ping runs concurrently with earlier steps.
llmPingDone bool // true once ping completed (success or fail)
llmPingErr error // non-nil if LLM was unreachable
// Model picker: inline model selection before rerunning LLM step.
modelPicker *modelCompleter // non-nil when picker is showing
modelFilter string // current filter text for fuzzy matching
}
// cancelLLMTimeout releases the LLM inference timeout context if set.
func (ex *extractionLogState) cancelLLMTimeout() {
if ex.llmCancelFn != nil {
ex.llmCancelFn()
ex.llmCancelFn = nil
}
}
// closeShadowDB closes and nils the shadow DB if present.
func (ex *extractionLogState) closeShadowDB() {
if ex.shadowDB != nil {
_ = ex.shadowDB.Close()
ex.shadowDB = nil
}
}
// activeSteps returns the ordered list of steps that are shown.
func (ex *extractionLogState) activeSteps() []extractionStep {
var steps []extractionStep
if ex.hasText {
steps = append(steps, stepText)
}
if ex.hasExtract {
steps = append(steps, stepExtract)
}
if ex.hasLLM {
steps = append(steps, stepLLM)
}
return steps
}
// cursorStep returns the step at the current cursor position.
func (ex *extractionLogState) cursorStep() extractionStep {
active := ex.activeSteps()
if ex.cursor >= 0 && ex.cursor < len(active) {
return active[ex.cursor]
}
return stepText
}
// stepDefaultExpanded returns the default expanded state for a step before
// any user toggle. Running and failed steps auto-expand so the cursor
// tracks progress. The ext/ocr step stays collapsed by default while
// running since the parent header shows combined progress. Once done,
// only the LLM step stays expanded (streaming output); text and ext
// steps collapse their log content by default.
func (ex *extractionLogState) stepDefaultExpanded(si extractionStep) bool {
info := ex.Steps[si]
if info.Status == stepRunning || info.Status == stepFailed || info.Status == stepSkipped {
// Ext with tools: collapsed by default while running since
// the parent header shows the combined percentage.
if si == stepExtract && len(ex.acquireTools) > 0 && info.Status == stepRunning {
return false
}
return true
}
return si == stepLLM && info.Status == stepDone
}
// stepExpanded returns whether a step is currently expanded, accounting
// for both the default and any user toggle.
func (ex *extractionLogState) stepExpanded(si extractionStep) bool {
if toggled, ok := ex.expanded[si]; ok {
return toggled
}
return ex.stepDefaultExpanded(si)
}
// advanceCursor moves the cursor to the latest settled (done/failed/skipped)
// step. In manual mode (after user presses j/k) this is a no-op.
func (ex *extractionLogState) advanceCursor() {
if ex.cursorManual {
return
}
active := ex.activeSteps()
for i := len(active) - 1; i >= 0; i-- {
s := ex.Steps[active[i]].Status
if s == stepDone || s == stepFailed || s == stepSkipped {
ex.cursor = i
ex.toolCursor = -1
return
}
}
}
// --- Messages ---
// extractionProgressMsg delivers a single async extraction progress update.
type extractionProgressMsg struct {
ID uint64
Progress extract.ExtractProgress
}
// extractionLLMStartedMsg delivers the LLM stream channel.
type extractionLLMStartedMsg struct {
ID uint64
Ch <-chan llm.StreamChunk
}
// extractionLLMChunkMsg delivers a single LLM token.
type extractionLLMChunkMsg struct {
ID uint64
Content string
Done bool
Err error
}
// extractionLLMPingMsg delivers the result of a background LLM ping.
type extractionLLMPingMsg struct {
ID uint64
Err error // nil = reachable, non-nil = unreachable
}
// --- Overlay lifecycle ---
// startExtractionOverlay opens the extraction progress overlay and kicks off
// the first applicable step. Returns nil if no async steps are needed.
func (m *Model) startExtractionOverlay(
docID uint,
filename string,
fileData []byte,
mime string,
extractedText string,
) tea.Cmd {
needsExtract := extract.NeedsOCR(m.ex.extractors, mime)
needsLLM := m.extractionLLMClient() != nil
if !needsExtract && !needsLLM {
return nil
}
sp := spinner.New(spinner.WithSpinner(spinner.Dot))
sp.Style = appStyles.AccentText()
//nolint:gosec // cancel stored in ex.CancelFn, called on extraction close
ctx, cancel := context.WithCancel(
context.Background(),
)
// Text extraction only applies to PDFs and text files; skip for images.
hasText := !extract.IsImageMIME(mime)
// Build initial text source from already-extracted text.
var sources []extract.TextSource
if hasText && strings.TrimSpace(extractedText) != "" {
var tool, desc string
switch {
case mime == extract.MIMEApplicationPDF:
tool = "pdftotext"
desc = "Digital text extracted directly from the PDF."
case strings.HasPrefix(mime, "text/"):
tool = "plaintext"
desc = "Plain text content."
default:
tool = mime
}
sources = append(sources, extract.TextSource{
Tool: tool,
Desc: desc,
Text: extractedText,
})
}
state := &extractionLogState{
ID: nextExtractionID.Add(1),
DocID: docID,
Filename: filename,
Spinner: sp,
Visible: true,
ctx: ctx,
CancelFn: cancel,
sources: sources,
extractedText: extractedText,
fileData: fileData,
mime: mime,
extractors: m.ex.extractors,
hasText: hasText,
hasExtract: needsExtract,
hasLLM: needsLLM,
toolCursor: -1,
expanded: make(map[extractionStep]bool),
}
if hasText {
nChars := len(strings.TrimSpace(extractedText))
var textTool string
switch {
case mime == extract.MIMEApplicationPDF:
textTool = "pdf"
case strings.HasPrefix(mime, "text/"):
textTool = "plaintext"
default:
textTool = mime
}
textStep := extractionStepInfo{
Status: stepDone,
Detail: textTool,
Metric: fmt.Sprintf("%d chars", nChars),
}
if nChars > 0 {
textStep.Logs = strings.Split(extractedText, "\n")
}
state.Steps[stepText] = textStep
}
// Background any existing foreground extraction instead of cancelling.
if m.ex.extraction != nil {
m.backgroundExtraction()
}
m.ex.extraction = state
var cmd tea.Cmd
if needsExtract {
state.Steps[stepExtract].Status = stepRunning
state.Steps[stepExtract].Started = time.Now()
cmd = asyncExtractCmd(ctx, state)
// Ping LLM concurrently so we know before OCR finishes whether
// the LLM endpoint is reachable.
if needsLLM {
return tea.Batch(cmd, m.llmPingCmd(state), state.Spinner.Tick)
}
} else if needsLLM {
state.Steps[stepLLM].Status = stepRunning
state.Steps[stepLLM].Started = time.Now()
state.Steps[stepLLM].Detail = m.extractionModelLabel()
cmd = m.llmExtractCmd(ctx, state)
}
return tea.Batch(cmd, state.Spinner.Tick)
}
// findExtraction returns the extraction with the given ID, checking the
// foreground extraction first, then scanning bgExtractions.
func (m *Model) findExtraction(id uint64) *extractionLogState {
if m.ex.extraction != nil && m.ex.extraction.ID == id {
return m.ex.extraction
}
for _, ex := range m.ex.bgExtractions {
if ex.ID == id {
return ex
}
}
return nil
}
// isBgExtraction returns true when the given extraction is in bgExtractions.
func (m *Model) isBgExtraction(ex *extractionLogState) bool {
for _, bg := range m.ex.bgExtractions {
if bg == ex {
return true
}
}
return false
}
// cancelExtraction cancels any in-flight extraction and clears state.
func (m *Model) cancelExtraction() {
if m.ex.extraction == nil {
return
}
m.ex.extraction.cancelLLMTimeout()
if m.ex.extraction.CancelFn != nil {
m.ex.extraction.CancelFn()
}
m.ex.extraction.closeShadowDB()
m.ex.extraction = nil
}
// interruptExtraction cancels the running step but keeps the overlay open so
// the user can inspect partial results, rerun, or dismiss with ESC.
func (m *Model) interruptExtraction() {
ex := m.ex.extraction
if ex == nil || ex.Done {
return
}
ex.cancelLLMTimeout()
if ex.CancelFn != nil {
ex.CancelFn()
}
for i := range ex.Steps {
if ex.Steps[i].Status == stepRunning {
ex.Steps[i].Status = stepFailed
ex.Steps[i].Elapsed = time.Since(ex.Steps[i].Started)
ex.Steps[i].Logs = append(ex.Steps[i].Logs, "interrupted")
}
}
ex.Done = true
ex.HasError = true
ex.advanceCursor()
}
// cancelAllExtractions cancels the foreground and all background extractions.
func (m *Model) cancelAllExtractions() {
m.cancelExtraction()
for _, ex := range m.ex.bgExtractions {
ex.cancelLLMTimeout()
if ex.CancelFn != nil {
ex.CancelFn()
}
ex.closeShadowDB()
}
m.ex.bgExtractions = nil
}
// backgroundExtraction moves the foreground extraction to bgExtractions.
func (m *Model) backgroundExtraction() {
if m.ex.extraction == nil {
return
}
m.ex.extraction.Visible = false
m.ex.bgExtractions = append(m.ex.bgExtractions, m.ex.extraction)
m.ex.extraction = nil
}
// foregroundExtraction brings the most recent bg extraction to the foreground.
func (m *Model) foregroundExtraction() {
n := len(m.ex.bgExtractions)
if n == 0 {
return
}
// If there's already a foreground extraction, background it first.
if m.ex.extraction != nil {
m.backgroundExtraction()
}
ex := m.ex.bgExtractions[n-1]
m.ex.bgExtractions = m.ex.bgExtractions[:n-1]
ex.Visible = true
m.ex.extraction = ex
}
// --- Async commands ---
// asyncExtractCmd starts the async extraction pipeline and returns the
// first progress message via waitForExtractProgress.
func asyncExtractCmd(ctx context.Context, state *extractionLogState) tea.Cmd {
ch := extract.ExtractWithProgress(
ctx, state.fileData, state.mime, state.extractors,
)
state.extractCh = ch
return waitForExtractProgress(state.ID, ch)
}
// waitForExtractProgress blocks until the next extraction progress update.
func waitForExtractProgress(id uint64, ch <-chan extract.ExtractProgress) tea.Cmd {
return waitForStream(ch, func(p extract.ExtractProgress) tea.Msg {
return extractionProgressMsg{ID: id, Progress: p}
}, extractionProgressMsg{ID: id, Progress: extract.ExtractProgress{Done: true}})
}
// llmPingCmd fires a background ping to the LLM endpoint. The result is
// delivered via extractionLLMPingMsg so the extraction can skip the LLM
// step early if the server is unreachable.
func (m *Model) llmPingCmd(state *extractionLogState) tea.Cmd {
client := m.extractionLLMClient()
if client == nil {
return nil
}
id := state.ID
return func() tea.Msg {
ctx, cancel := context.WithTimeout(context.Background(), llm.QuickOpTimeout)
defer cancel()
err := client.Ping(ctx)
return extractionLLMPingMsg{ID: id, Err: err}
}
}
// llmExtractCmd starts LLM document analysis with streaming.
func (m *Model) llmExtractCmd(ctx context.Context, ex *extractionLogState) tea.Cmd {
client := m.extractionLLMClient()
if client == nil {
return nil
}
schemaCtx := m.buildSchemaContext()
id := ex.ID
timeout := m.ex.llmInferenceTimeout
return func() tea.Msg {
llmCtx := ctx
if timeout > 0 {
var cancel context.CancelFunc
llmCtx, cancel = context.WithTimeout(ctx, timeout)
ex.llmCancelFn = cancel
}
messages := extract.BuildExtractionPrompt(extract.ExtractionPromptInput{
DocID: ex.DocID,
Filename: ex.Filename,
MIME: ex.mime,
SizeBytes: int64(len(ex.fileData)),
Schema: schemaCtx,
Sources: ex.sources,
SendTSV: m.ex.ocrTSV,
ConfThreshold: m.ex.ocrConfThreshold,
})
ch, err := client.ChatStream(
llmCtx,
messages,
llm.WithJSONSchema("extraction_operations", extract.OperationsSchema()),
)
if err != nil {
return extractionLLMChunkMsg{ID: id, Err: err, Done: true}
}
return extractionLLMStartedMsg{ID: id, Ch: ch}
}
}
// buildSchemaContext gathers DDL and entity rows for the extraction prompt.
func (m *Model) buildSchemaContext() extract.SchemaContext {
var ctx extract.SchemaContext
if m.store == nil {
return ctx
}
ddl, err := m.store.TableDDL(extract.ExtractionTables...)
if err == nil {
ctx.DDL = ddl
}
rows, err := m.store.EntityRows()
if err == nil {
ctx.Vendors = toExtractRows(rows.Vendors)
ctx.Projects = toExtractRows(rows.Projects)
ctx.Appliances = toExtractRows(rows.Appliances)
ctx.MaintenanceItems = toExtractRows(rows.MaintenanceItems)
ctx.MaintenanceCategories = toExtractRows(rows.MaintenanceCategories)
ctx.ProjectTypes = toExtractRows(rows.ProjectTypes)
}
return ctx
}
// toExtractRows converts data.EntityRow slices to extract.EntityRow slices.
func toExtractRows(rows []data.EntityRow) []extract.EntityRow {
if len(rows) == 0 {
return nil
}
out := make([]extract.EntityRow, len(rows))
for i, r := range rows {
out[i] = extract.EntityRow{ID: r.ID, Name: r.Name}
}
return out
}
// waitForLLMChunk blocks until the next LLM token.
func waitForLLMChunk(id uint64, ch <-chan llm.StreamChunk) tea.Cmd {
return waitForStream(ch, func(c llm.StreamChunk) tea.Msg {
return extractionLLMChunkMsg{ID: id, Content: c.Content, Done: c.Done, Err: c.Err}
}, extractionLLMChunkMsg{ID: id, Done: true})
}
// --- Message handlers ---
// handleExtractionProgress processes an async extraction progress update.
func (m *Model) handleExtractionProgress(msg extractionProgressMsg) tea.Cmd {
ex := m.findExtraction(msg.ID)
if ex == nil {
return nil
}
p := msg.Progress
step := &ex.Steps[stepExtract]
if p.Err != nil {
step.Status = stepFailed
step.Elapsed = time.Since(step.Started)
step.Logs = append(step.Logs, p.Err.Error())
ex.HasError = true
ex.advanceCursor()
// Extraction failed but LLM can still run on whatever text exists.
if cmd := m.maybeStartLLMStep(ex); cmd != nil {
return cmd
}
ex.Done = true
if m.isBgExtraction(ex) {
m.setStatusError(fmt.Sprintf("Extraction failed: %s", ex.Filename))
}
return nil
}
if !p.Done {
// Per-tool acquisition state update.
if len(p.AcquireTools) > 0 {
ex.acquireTools = p.AcquireTools
}
// OCR phase: page progress is shown in the tool line via
// renderPageRatio; detail stays simple for the header.
switch p.Phase {
case "extract":
step.Detail = fmt.Sprintf("page %d/%d", p.Page, p.Total)
ex.docPages = p.DocPages
ex.extractedPages = p.Total
}
return waitForExtractProgress(ex.ID, ex.extractCh)
}
// Extraction done.
step.Status = stepDone
step.Elapsed = time.Since(step.Started)
nChars := len(strings.TrimSpace(p.Text))
step.Detail = p.Tool
step.Metric = fmt.Sprintf("%d chars", nChars)
ex.docPages = p.DocPages
ex.extractedPages = p.Total
ex.advanceCursor()
// Store output as explorable logs.
if nChars > 0 {
step.Logs = strings.Split(p.Text, "\n")
}
// Add to LLM sources (prompt builder skips empty text).
ex.sources = append(ex.sources, extract.TextSource{
Tool: p.Tool,
Desc: p.Desc,
Text: p.Text,
Data: p.Data,
})
// Hold for persistence at accept time.
ex.pendingText = p.Text
ex.pendingData = p.Data
// If no text was extracted synchronously, use async result.
if nChars > 0 && ex.extractedText == "" {
ex.extractedText = p.Text
}
// Advance to LLM step if configured and reachable.
if cmd := m.maybeStartLLMStep(ex); cmd != nil {
return cmd
}
ex.Done = true
if m.isBgExtraction(ex) {
m.setStatusInfo(fmt.Sprintf("Extracted: %s", ex.Filename))
}
return nil
}
// maybeStartLLMStep attempts to advance to the LLM step. If the concurrent
// ping determined the LLM is unreachable, the step is marked skipped and nil
// is returned. Otherwise it starts the LLM streaming command.
func (m *Model) maybeStartLLMStep(ex *extractionLogState) tea.Cmd {
if !ex.hasLLM {
return nil
}
// Already marked skipped by the ping handler.
if ex.Steps[stepLLM].Status == stepSkipped {
return nil
}
client := m.extractionLLMClient()
if client == nil {
return nil
}
ex.Steps[stepLLM].Status = stepRunning
ex.Steps[stepLLM].Started = time.Now()
ex.Steps[stepLLM].Detail = m.extractionModelLabel()
return m.llmExtractCmd(ex.ctx, ex)
}
// handleExtractionLLMPing processes the background LLM ping result.
func (m *Model) handleExtractionLLMPing(msg extractionLLMPingMsg) tea.Cmd {
ex := m.findExtraction(msg.ID)
if ex == nil {
return nil
}
ex.llmPingDone = true
ex.llmPingErr = msg.Err
if msg.Err != nil {
// Mark LLM as skipped immediately so the strikethrough renders
// in real time, even while earlier steps are still running.
ex.Steps[stepLLM].Status = stepSkipped
ex.Steps[stepLLM].Detail = m.extractionModelLabel()
ex.Steps[stepLLM].Logs = append(ex.Steps[stepLLM].Logs, msg.Err.Error())
// If extraction already finished, the pipeline is done.
if ex.Steps[stepExtract].Status == stepDone || ex.Steps[stepExtract].Status == stepFailed {
ex.Done = true
ex.advanceCursor()
if m.isBgExtraction(ex) {
m.setStatusInfo(fmt.Sprintf("Extracted: %s (LLM skipped)", ex.Filename))
}
}
}
return nil
}
// handleExtractionLLMStarted stores the LLM stream channel and starts reading.
func (m *Model) handleExtractionLLMStarted(msg extractionLLMStartedMsg) tea.Cmd {
ex := m.findExtraction(msg.ID)
if ex == nil {
return nil
}
ex.llmCh = msg.Ch
return waitForLLMChunk(ex.ID, msg.Ch)
}
// handleExtractionLLMChunk processes a single LLM token.
func (m *Model) handleExtractionLLMChunk(msg extractionLLMChunkMsg) tea.Cmd {
ex := m.findExtraction(msg.ID)
if ex == nil {
return nil
}
step := &ex.Steps[stepLLM]
if msg.Err != nil {
ex.cancelLLMTimeout()
step.Status = stepFailed
step.Elapsed = time.Since(step.Started)
errMsg := msg.Err.Error()
if errors.Is(msg.Err, context.DeadlineExceeded) {
errMsg = fmt.Sprintf(
"timed out after %s -- increase extraction.llm_timeout in config",
step.Elapsed.Truncate(time.Second),
)
}
step.Logs = append(step.Logs, errMsg)
ex.HasError = true
ex.Done = true
ex.advanceCursor()
if m.isBgExtraction(ex) {
m.setStatusError(fmt.Sprintf("Extraction failed: %s", ex.Filename))
}
return nil
}
if msg.Content != "" {
ex.llmAccum.WriteString(msg.Content)
step.Logs = strings.Split(ex.llmAccum.String(), "\n")
}
if msg.Done {
ex.cancelLLMTimeout()
step.Elapsed = time.Since(step.Started)
// Parse and validate operations; hold for accept.
response := ex.llmAccum.String()
ops, err := extract.ParseOperations(response)
if err != nil {
step.Status = stepFailed
step.Logs = append(step.Logs, "parse error: "+err.Error())
ex.HasError = true
} else if err := extract.ValidateOperations(ops, extract.ExtractionAllowedOps); err != nil {
step.Status = stepFailed
step.Logs = append(step.Logs, "validation error: "+err.Error())
ex.HasError = true
} else if sdb, err := extract.NewShadowDB(m.store); err != nil {
step.Status = stepFailed
step.Logs = append(step.Logs, "shadow db: "+err.Error())
ex.HasError = true
} else if err := sdb.Stage(ops); err != nil {
step.Status = stepFailed
step.Logs = append(step.Logs, "stage ops: "+err.Error())
ex.HasError = true
} else {
step.Status = stepDone
ex.operations = ops
ex.shadowDB = sdb
}
step.Metric = fmt.Sprintf("%d ops", len(ex.operations))
ex.Done = true
ex.advanceCursor()
if m.isBgExtraction(ex) {
if ex.HasError {
m.setStatusError(fmt.Sprintf("Extraction failed: %s", ex.Filename))
} else {
m.setStatusInfo(fmt.Sprintf("Extracted: %s", ex.Filename))
}
}
return nil
}
// More tokens coming.
return waitForLLMChunk(ex.ID, ex.llmCh)
}
// applyStringField sets *dst to the string value at data[key] if present.
func applyStringField(data map[string]any, key string, dst *string) {
if v, ok := data[key]; ok {
if s, ok := v.(string); ok {
*dst = s
}
}
}
// acceptExtraction persists all pending results and closes the overlay.
// Works regardless of whether LLM ran, failed, or was skipped.
func (m *Model) acceptExtraction() {
ex := m.ex.extraction
if ex == nil || !ex.Done || ex.accepted {
return
}
if ex.pendingDoc != nil {
if err := m.acceptDeferredExtraction(); err != nil {
m.setStatusError(err.Error())
return
}
} else {
if err := m.acceptExistingExtraction(); err != nil {
m.setStatusError(err.Error())
return
}
}
ex.accepted = true
m.ex.extraction = nil
}
// acceptDeferredExtraction creates the deferred document, applying any
// LLM-produced document fields, then dispatches remaining operations.
func (m *Model) acceptDeferredExtraction() error {
ex := m.ex.extraction
doc := ex.pendingDoc
// Apply fields from "create documents" operations to the pending doc.
for _, op := range ex.operations {
if op.Table == tableDocuments {
applyStringField(op.Data, "title", &doc.Title)
applyStringField(op.Data, "notes", &doc.Notes)
applyStringField(op.Data, "entity_kind", &doc.EntityKind)
if v, ok := op.Data["entity_id"]; ok {
if n := extract.ParseUint(v); n > 0 {
doc.EntityID = n
}
}
}
}
// Apply async extraction results to the document before creating.
if ex.pendingText != "" {
doc.ExtractedText = ex.pendingText
}
if len(ex.pendingData) > 0 {
doc.ExtractData = ex.pendingData
}
if err := m.store.CreateDocument(doc); err != nil {
return fmt.Errorf("create document: %w", err)
}
// Commit non-document operations via shadow DB (vendors, quotes, etc.).
var nonDocOps []extract.Operation
for _, op := range ex.operations {
if op.Table != tableDocuments {
nonDocOps = append(nonDocOps, op)
}
}
if err := m.commitShadowOperations(ex, nonDocOps); err != nil {
return fmt.Errorf("dispatch operations: %w", err)
}
m.reloadAfterMutation()
return nil
}
// acceptExistingExtraction persists extraction text and dispatches operations
// for an already-saved document.
func (m *Model) acceptExistingExtraction() error {
ex := m.ex.extraction
// Persist async extraction results.
if ex.pendingText != "" || len(ex.pendingData) > 0 {
if m.store != nil {
if err := m.store.UpdateDocumentExtraction(
ex.DocID, ex.pendingText, ex.pendingData,
); err != nil {
return fmt.Errorf("save extraction: %w", err)
}
}
}
// Commit validated operations via shadow DB.
if err := m.commitShadowOperations(ex, ex.operations); err != nil {
return fmt.Errorf("dispatch operations: %w", err)
}
return nil
}
// commitShadowOperations commits staged operations through the shadow DB,
// remapping cross-referenced IDs to real database IDs.
func (m *Model) commitShadowOperations(ex *extractionLogState, ops []extract.Operation) error {
if m.store == nil || len(ops) == 0 {
return nil
}
if ex.shadowDB == nil {
return fmt.Errorf("no shadow DB: operations were not staged")
}
err := ex.shadowDB.Commit(m.store, ops)
ex.closeShadowDB()
if err != nil {
return err
}
m.reloadAfterMutation()
return nil
}
// toggleExtractionTSV flips the ocrTSV setting and reruns the LLM step
// so the user can compare extraction quality with and without spatial layout.
func (m *Model) toggleExtractionTSV() tea.Cmd {
m.ex.ocrTSV = !m.ex.ocrTSV
if m.ex.ocrTSV {
m.setStatusInfo("layout on")
} else {
m.setStatusInfo("layout off")
}
return m.rerunLLMExtraction()
}
// rerunLLMExtraction resets the LLM step and re-runs it.
func (m *Model) rerunLLMExtraction() tea.Cmd {
ex := m.ex.extraction
if ex == nil || !ex.hasLLM {
return nil
}
// Cancel any previous LLM timeout before restarting.
ex.cancelLLMTimeout()
// Replace a cancelled context so the rerun has a live one.
if ex.ctx.Err() != nil {
ctx, cancel := context.WithCancel( //nolint:gosec // cancel stored in ex.CancelFn, called on extraction close
context.Background(),
)
ex.ctx = ctx
ex.CancelFn = cancel
}
// Reset LLM state (including any prior ping failure).
ex.llmAccum.Reset()
ex.llmPingDone = false
ex.llmPingErr = nil
ex.operations = nil
ex.closeShadowDB()
ex.previewGroups = nil
ex.exploring = false
ex.Steps[stepLLM] = extractionStepInfo{
Status: stepRunning,
Started: time.Now(),
Detail: m.extractionModelLabel(),
}
ex.Done = false
ex.HasError = false
delete(ex.expanded, stepLLM)
// Re-check other steps for errors (they stay as-is).
for _, si := range ex.activeSteps() {
if si != stepLLM && ex.Steps[si].Status == stepFailed {
ex.HasError = true
}
}
// Position cursor on the LLM step being rerun.
active := ex.activeSteps()
for i, s := range active {
if s == stepLLM {
ex.cursor = i
break
}
}
return tea.Batch(m.llmExtractCmd(ex.ctx, ex), ex.Spinner.Tick)
}
// --- Keyboard handler ---
// handleExtractionKey processes keys when the extraction overlay is visible.