Repository navigation
Expand file tree
/
Copy pathAppState.swift
More file actions
1686 lines (1556 loc) · 88.4 KB
/
Copy pathAppState.swift
File metadata and controls
1686 lines (1556 loc) · 88.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
import Foundation
import Combine
import CryptoKit
import AppKit
/// 용어 → 발음 한 쌍. 대본(정규화) LLM에 few-shot 사전으로 주입되어 코드 명칭·
/// 고유명사 발음을 일관되게 만든다. settings.json의 "glossary"에 저장된다.
struct GlossaryEntry: Codable, Equatable, Identifiable {
var id: UUID = UUID()
var term: String
var pronunciation: String
var note: String = ""
}
/// Single source of truth for the UI and the speak path. Holds connection,
/// settings, history, and runs synthesis (cache-first) + playback.
@MainActor
final class AppState: ObservableObject {
/// The TTS-engine seam: each engine declares its capabilities so the settings
/// UI renders the right controls without hardcoding ElevenLabs. A new engine =
/// a new case + these descriptors + its own settings sub-section. The engine's
/// concrete tuning (e.g. ElevenVoiceSettings) stays its own typed value so the
/// cache key / persistence are untouched.
enum BackendKind: String, CaseIterable, Identifiable {
case elevenlabs, local
var id: String { rawValue }
var label: String { self == .elevenlabs ? "ElevenLabs (클라우드)" : "로컬 Qwen3 (sidecar)" }
/// Engine needs an API key + a connection step.
var requiresAPIKey: Bool { self == .elevenlabs }
/// Engine exposes a fetchable voice list (else the voice is entered/fixed).
var hasVoiceList: Bool { self == .elevenlabs }
/// Engine reaches a local sidecar at a configurable base URL.
var usesLocalSidecar: Bool { self == .local }
}
// Connection
@Published var keyPresent: Bool = Secrets.elevenLabsKey != nil
@Published var backendKind: BackendKind = .elevenlabs
@Published var voices: [ElevenVoice] = []
@Published var connectionStatus = ""
@Published private(set) var elevenModels: [ElevenModel] = []
@Published private(set) var modelStatus = ""
@Published private(set) var refreshingModels = false
private static var modelCatalogURL: URL {
URL(fileURLWithPath: Secrets.appSupportDir).appendingPathComponent("eleven_models.json")
}
// Settings
@Published var voiceId = "Yp1WZJMrN7OSdP8PG9sm" // 성주 (cloned)
@Published var voiceName = "성주"
@Published var modelId = "eleven_flash_v2_5"
@Published var voiceSettings = ElevenVoiceSettings()
@Published var useCache = true
@Published var localBaseURL = "http://127.0.0.1:8765"
// TTS-friendly text normalization (LLM endpoints: dynamic, user-managed).
// An endpoint = baseURL + API key (own <id>.key file) + apiStyle; the legacy
// gemini/zai/ollama fields were migrated into 3 seeded endpoints on first
// run (seedEndpoints) and the old settings keys are read as seed data only.
@Published var endpoints: [CustomEndpoint] = []
@Published private var endpointModels: [String: [String]] = [:] // endpoint id → live models.list
@Published private(set) var endpointStatus: [String: String] = [:] // endpoint id → 연결 확인 status
@Published var normalizeEnabled = false
@Published var normalizePrompt = TextNormalizer.defaultInstruction
@Published var normalizing = false
@Published var scriptHint = "" // 대본 단계 (원문→대본) 추가 지시
/// 대본 few-shot 용어 발음 사전 (glossary). 대본(정규화) 단계에만 프롬프트에
/// 주입된다 — 해설 단계는 코드 해설이라 제외.
@Published var glossary: [GlossaryEntry] = []
/// glossary 키가 settings.json에 아직 없을 때만 심는 기본 예시
/// (defaultInstruction의 예시 활용). 빈 배열 저장은 "전부 삭제"로 존중됨.
static let seedGlossary: [GlossaryEntry] = [
GlossaryEntry(term: "np", pronunciation: "넘파이"),
GlossaryEntry(term: "pd", pronunciation: "판다스"),
GlossaryEntry(term: "sklearn", pronunciation: "싸이킷런"),
GlossaryEntry(term: "plt", pronunciation: "매트플롯립"),
GlossaryEntry(term: "tf", pronunciation: "텐서플로우"),
]
private var scriptBuiltFrom = "" // (원본 ∥ 지시) the 대본 was built from
/// True when 원본 or 추가 지시 changed after the 대본 was generated. Suppressed
/// while generating — scriptText fills before scriptBuiltFrom is stamped.
var scriptStale: Bool {
!normalizing
&& !scriptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
&& scriptBuiltFrom != (inputText + "\u{1F}" + scriptHint)
}
// Commentary (코드 → 해설). Shares the endpoint pool above, but the explain
// model is SEPARATE from the script model — they can differ.
@Published var codeText = "" // source code (해설 panel, top)
@Published var explanationText = "" // generated commentary (해설 panel, bottom)
@Published var explaining = false
@Published var explainPrompt = CodeExplanation.defaultInstruction
@Published var explainHint = "" // 해설 단계 (코드→해설) 추가 지시
@Published var explainAutoPlay = true // 단축키/Services 해설: 생성 직후 바로 재생(끄면 검토 후 수동 재생)
/// Set by AppDelegate: bring the management window forward so a review-only
/// 해설 (explainAutoPlay == false) is visible to read/check before playing.
var onRequestReview: (() -> Void)?
@Published var explainTemperature: Double = 0.4 // 해설 LLM 생성 매개변수
@Published var scriptTemperature: Double = 0.2 // 대본 LLM 생성 매개변수
/// 역할별 reasoning(thinking) 수준 — 공급자별 파라미터로 변환해 요청에 실린다
/// (ReasoningLevel 참고). 엔드포인트별이 아닌 역할별로 단순하게.
@Published var explainReasoningLevel: ReasoningLevel = .medium // 해설 (+single-stage 해설)
@Published var scriptReasoningLevel: ReasoningLevel = .medium // 대본 정규화
@Published var visionReasoningLevel: ReasoningLevel = .medium // 스크린샷 전사 (비전)
@Published var codeImages: [Data] = [] { didSet { logMemory("images.changed") } } // pasted code screenshots (PNG); needs a vision model
var hasImages: Bool { !codeImages.isEmpty }
private var explanationHistory = ExplanationHistory()
@Published var lastExplainedCode = "" // baseline snapshot for "이어서 해설" (incremental)
@Published var lastSegment = "" // the most recently produced commentary (full or appended delta)
var canContinueExplain: Bool {
!lastExplainedCode.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
var hasLastSegment: Bool {
!lastSegment.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
@Published var selectedTab = 0 // RootView TabView selection
// Per-role endpoint reference + model memory. A role points at an endpoint
// (id) and remembers the model last picked for it; an unset role model
// inherits the endpoint's defaultModel (구 zaiModel 폴백의 일반화).
@Published var explainEndpointID = ""
@Published var scriptEndpointID = ""
@Published var visionEndpointID = ""
@Published var visionOverridden = false // false = vision follows the 해설 model
@Published var explainRoleModels: [String: String] = [:] // endpoint id → model
@Published var scriptRoleModels: [String: String] = [:]
@Published var visionRoleModels: [String: String] = [:]
// MARK: Endpoint resolution
func endpoint(byID id: String) -> CustomEndpoint? {
endpoints.first { $0.id.uuidString == id }
}
/// Only ENABLED endpoints resolve for generation/pickers; a disabled one
/// behaves like a missing one.
func activeEndpoint(byID id: String) -> CustomEndpoint? {
endpoints.first { $0.id.uuidString == id && $0.isEnabled }
}
func endpointKey(_ e: CustomEndpoint) -> String {
Secrets.endpointKey(e.id) ?? ""
}
/// A role's model on `e`: its own remembered pick, or the endpoint's 기본
/// 모델 when unset. Every LLM call must go through this — a raw empty role
/// field would be sent to the API as `"model": ""`.
func roleModel(_ role: [String: String], _ e: CustomEndpoint) -> String {
let m = role[e.id.uuidString] ?? ""
return m.isEmpty ? e.defaultModel : m
}
/// True when the 기본 모델 is usable: unset, in the fetched list, or not yet
/// checkable (no list). Drives the per-endpoint SettingsView warning.
func endpointDefaultModelValid(_ e: CustomEndpoint) -> Bool {
let ms = endpointModels[e.id.uuidString] ?? []
return e.defaultModel.isEmpty || ms.isEmpty || ms.contains(e.defaultModel)
}
/// Effective endpoint/model per role (role's own memory → endpoint default).
var scriptModel: String {
guard let e = activeEndpoint(byID: scriptEndpointID) else { return "" }
return roleModel(scriptRoleModels, e)
}
var explainModel: String {
guard let e = activeEndpoint(byID: explainEndpointID) else { return "" }
return roleModel(explainRoleModels, e)
}
var visionEndpointEff: CustomEndpoint? {
visionOverridden ? activeEndpoint(byID: visionEndpointID) : activeEndpoint(byID: explainEndpointID)
}
var visionModelEff: String {
if !visionOverridden { return explainModel }
guard let e = activeEndpoint(byID: visionEndpointID) else { return "" }
return roleModel(visionRoleModels, e)
}
/// A pick in a model selector: an (endpoint, model) pair. Identity carries
/// the endpoint so models from different endpoints never collide.
struct LLMChoice: Hashable, Identifiable {
let endpointID: String
let endpointName: String
let model: String
var id: String { endpointID + "\u{1F}" + model }
var label: String { "\(model) · \(endpointName)" }
}
/// Well-known model names for a style, used ONLY to pick a sensible 기본 모델
/// out of a freshly fetched list (see refreshEndpointModels) — never shown as
/// a standalone picker entry, since these names are provider-specific and an
/// arbitrary OpenAI-호환 endpoint (내 vLLM 등) does not serve them.
func preferredModels(_ e: CustomEndpoint) -> [String] {
if e.usesPlan { return [] }
switch e.apiStyle {
case .anthropic: return []
case .gemini: return GeminiNormalizer.models
case .openAICompatible: return e.resolvedProvider == .openAI ? ["gpt-4.1-mini", "gpt-4.1", "gpt-4o"] : ZAINormalizer.fallbackModels
case .ollama: return []
}
}
/// All models from enabled endpoints. Before a successful models.list the
/// only model we can honestly offer is the endpoint's own 기본 모델 — that
/// also makes a keyless/offline endpoint selectable once the user types one.
var connectedModels: [LLMChoice] {
let started = ProcessInfo.processInfo.systemUptime
defer { InputDiagnostics.shared.recordWork("connectedModels", since: started) }
var out: [LLMChoice] = []
for e in endpoints where e.isEnabled {
let fetched = endpointModels[e.id.uuidString] ?? []
let ms = fetched.isEmpty ? (e.defaultModel.isEmpty ? [] : [e.defaultModel]) : fetched
out += ms.map { LLMChoice(endpointID: e.id.uuidString, endpointName: e.name, model: $0) }
}
return out
}
func models(for endpoint: CustomEndpoint) -> [String] {
guard let stored = self.endpoint(byID: endpoint.id.uuidString), stored.cacheIdentity == endpoint.cacheIdentity else { return [] }
return endpointModels[endpoint.id.uuidString] ?? []
}
func refreshAllModels() {
for e in endpoints where e.isEnabled { refreshEndpointModels(e) }
}
func refreshAllModelsIfNeeded() {
for e in endpoints
where e.isEnabled && (endpointModels[e.id.uuidString] ?? []).isEmpty {
// Fetching a keyed endpoint without a key just errors — wait for the key.
if !e.usesPlan && (e.apiStyle == .gemini || e.apiStyle == .anthropic) && endpointKey(e).isEmpty { continue }
refreshEndpointModels(e)
}
}
// Runtime
enum Phase: Equatable { case idle, synthesizing, playing, paused }
@Published var phase: Phase = .idle
/// High-frequency playback values (progress/chunkProgress/chunkSeconds) live on
/// a SEPARATE ObservableObject so the 10 Hz tick doesn't invalidate every view
/// observing AppState. Only PlayerOverlay observes this. See PlaybackTelemetry.
let telemetry = PlaybackTelemetry()
/// What the current playback is — shown in the HUD instead of the script text.
enum PlaybackMode { case tts, explain
var label: String { self == .tts ? "TTS" : "해설" }
var icon: String { self == .tts ? "speaker.wave.2.fill" : "text.book.closed.fill" }
}
@Published var playbackMode: PlaybackMode = .tts
// HUD subtitles: show the paragraph being read (toggle per mode).
@Published var subtitleTTS = true
@Published var subtitleExplain = true
@Published var subtitleFontSize: Double = 17 // points; adjustable from the HUD (A-/A+)
static let subtitleFontRange: ClosedRange<Double> = 11...48
// HUD placement. The HUD follows the focused app per command: at trigger time
// we capture which screen the command happened on, and the HUD shows there
// (so in a lecture it lands on the screen the learners see). The user can drag
// it; its position is remembered per screen so each monitor keeps its own spot.
var hudTargetScreenID: CGDirectDisplayID? // screen the current command targets
var hudPositions: [CGDirectDisplayID: CGPoint] = [:] // bottom-left offset within each screen's visibleFrame
@Published var spokenChunks: [String] = [] // the spoken (대본) paragraph chunks — drives crawlFraction
@Published var subtitleText = "" // the human-readable subtitle source (원본/해설), shown as the crawl
@Published var chunkSentenceTimes: [[Double]] = [] // exact sentence start times per chunk (ElevenLabs); [] = estimate
var showSubtitle: Bool { playbackMode == .tts ? subtitleTTS : subtitleExplain }
// MARK: - Continuous crawl (teleprompter over the WHOLE script)
/// One subtitle sentence. The subtitle is the human-readable source
/// (`subtitleText`: 원본/해설), NOT the spoken 대본, so it never has to align with
/// the audio chunking — the crawl position is driven by overall progress.
struct CrawlLine: Identifiable {
let id: Int // global order (0-based)
let text: String
}
/// Memoized sentence split of the current subtitle. `TextSplitter.sentences`
/// is an O(N) char scan; the crawl reads it every 0.1s frame (and used to
/// re-split once PER line for the current-line test), so recomputing it per
/// frame stalls the main thread and janks the subtitle + typing. Recompute
/// only when `subtitleText` actually changes.
private var sentenceCacheKey: String?
private var sentenceCache: [String] = []
private var subtitleSentences: [String] {
if sentenceCacheKey != subtitleText {
sentenceCacheKey = subtitleText
sentenceCache = TextSplitter.sentences(subtitleText)
}
return sentenceCache
}
/// The full subtitle text split into sentences, flattened in reading order.
var crawlLines: [CrawlLine] {
subtitleSentences.enumerated().map { CrawlLine(id: $0.offset, text: $0.element) }
}
/// Which subtitle sentence is being read now — overall audio progress
/// (`crawlFraction`) mapped onto the subtitle text by length.
var currentCrawlLineID: Int {
TextSplitter.sentenceIndex(at: crawlFraction, in: subtitleSentences)
}
func isCurrentLine(_ line: CrawlLine) -> Bool { line.id == currentCrawlLineID }
/// How far through the WHOLE playback the audio is (0…1), weighted by spoken
/// chunk length (chars) so it tracks the voice smoothly via chunkProgress —
/// QueuePlayer.progress is chunk-equal-weighted, which lurches per paragraph.
var crawlFraction: Double {
CrawlLayout.fraction(chunkLengths: spokenChunks.map { Double(max(1, $0.count)) },
chunkIndex: chunkIndex, chunkProgress: telemetry.chunkProgress)
}
/// Map ElevenLabs per-character start times to one start time per sentence
/// of `text`. Returns [] if the alignment doesn't line up (→ estimate).
private func sentenceStartTimes(text: String, charStarts: [Double]) -> [Double] {
let chars = Array(text)
guard charStarts.count == chars.count else { return [] }
let sentences = TextSplitter.sentences(text)
var times: [Double] = []
var offset = 0
for s in sentences {
while offset < chars.count, chars[offset].isWhitespace { offset += 1 }
times.append(offset < charStarts.count ? charStarts[offset] : (times.last ?? 0))
offset += s.count
}
return times.count == sentences.count ? times : []
}
@Published var currentText = "" // text being spoken (overlay label)
@Published var inputText = "" // original (top panel / source text)
@Published var scriptText = "" // TTS-friendly script actually sent to the engine (bottom panel)
@Published var chunkIndex = 0 // 1-based chunk being played
@Published var chunkCount = 0
@Published var statusText = ""
@Published var maxChunkChars = TextSplitter.defaultMaxChars
@Published private(set) var historyRevision = 0 // bumped on any history change → view reloads
@Published private(set) var backlog: [BacklogEntry] = []
var isBusy: Bool { phase != .idle }
private let cache = CacheStore()
private let normCache = NormalizationCache()
private let backlogStore = BacklogStore()
private let player = QueuePlayer()
private var task: Task<Void, Never>? // audio synthesis/playback
private var explainTask: Task<Void, Never>? // long-lived 해설 LLM stream
private var scriptTask: Task<Void, Never>? // long-lived 대본 정규화 stream
private var memoryTimer: Timer?
private var activeMemoryOperations = 0
private var memoryOperationSequence = 0
func logMemory(_ event: String) {
let imageBytes = codeImages.reduce(0) { $0 + $1.count }
let backlogBytes = backlog.reduce(0) { total, entry in
total + (entry.images ?? []).reduce(0) { $0 + $1.count }
}
MemoryDiagnostics.sample(event, details:
"images=\(codeImages.count) imageBytes=\(imageBytes) backlogImageBytes=\(backlogBytes) activeGenerations=\(activeMemoryOperations) subtitleUTF8=\(subtitleText.utf8.count) cachedSentences=\(sentenceCache.count) subtitleVisible=\(showSubtitle) phase=\(phase) playbackTimer=\(timer != nil) normEntries=\(normCache.count) normTextBytes=\(normCache.textBytes) backlogEntries=\(backlog.count) spokenChunks=\(spokenChunks.count) timingValues=\(chunkSentenceTimes.reduce(0) { $0 + $1.count }) textUTF8=\([inputText, scriptText, codeText, explanationText].reduce(0) { $0 + $1.utf8.count }) endpoints=\(endpoints.count) models=\(endpointModels.values.reduce(0) { $0 + $1.count }) windows=\(NSApp.windows.count) visibleWindows=\(NSApp.windows.filter { $0.isVisible }.count) urlCacheBytes=\(URLCache.shared.currentMemoryUsage) \(player.memorySummary)")
}
private func beginMemoryOperation(_ name: String) -> Int {
memoryOperationSequence += 1
activeMemoryOperations += 1
logMemory("\(name).begin.\(memoryOperationSequence)")
return memoryOperationSequence
}
private func endMemoryOperation(_ name: String, _ id: Int) {
activeMemoryOperations -= 1
logMemory("\(name).end.\(id)")
}
private var timer: Timer?
init() {
loadSettings()
elevenModels = ElevenModelCatalog.load(from: Self.modelCatalogURL)
backlog = backlogStore.entries
player.onFinish = { [weak self] in self?.finish() }
InputDiagnostics.shared.start()
logMemory("startup")
memoryTimer = Timer.scheduledTimer(withTimeInterval: 15, repeats: true) { [weak self] timer in
guard let self else { timer.invalidate(); return }
MainActor.assumeIsolated {
self.logMemory("periodic")
InputDiagnostics.shared.flush()
}
}
memoryTimer?.tolerance = 3
}
// MARK: - Backlog (flag a generation case for later analysis)
enum IssueStage { case explain, script }
/// Capture the current stage's full context (input + prompt + hint + output)
/// into the backlog, tagged for later filtering/analysis.
func recordIssue(_ stage: IssueStage, note: String = "", tags: [String] = ["이슈"]) {
let cleanTags = tags.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
let finalTags = cleanTags.isEmpty ? ["이슈"] : cleanTags
let e: BacklogEntry
switch stage {
case .explain:
guard !explanationText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
statusText = "기록할 해설이 없습니다"; return
}
e = BacklogEntry(id: UUID().uuidString, createdAt: Date(), tags: finalTags, note: note,
stage: "해설", provider: endpoint(byID: explainEndpointID)?.name ?? "-",
model: explainModel,
prompt: explainPrompt, hint: explainHint, input: codeText, output: explanationText,
images: codeImages.isEmpty ? nil : codeImages)
case .script:
guard !scriptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
statusText = "기록할 대본이 없습니다"; return
}
e = BacklogEntry(id: UUID().uuidString, createdAt: Date(), tags: finalTags, note: note,
stage: "대본", provider: endpoint(byID: scriptEndpointID)?.name ?? "-",
model: scriptModel,
prompt: normalizePrompt, hint: scriptHint, input: inputText, output: scriptText,
images: nil)
}
backlogStore.add(e); backlog = backlogStore.entries
statusText = "백로그에 기록됨 (\(stage == .explain ? "해설" : "대본"))"
}
func updateBacklog(_ e: BacklogEntry) { backlogStore.update(e); backlog = backlogStore.entries }
func deleteBacklog(_ id: String) { backlogStore.delete(id); backlog = backlogStore.entries }
func clearBacklog() { backlogStore.clear(); backlog = backlogStore.entries }
func exportBacklog(_ items: [BacklogEntry]) -> URL? { backlogStore.export(items) }
var backlogTags: [String] { backlogStore.allTags }
private func finish() {
defer { logMemory("playback.finished") }
stopTimer()
phase = .idle; telemetry.reset(); statusText = ""; chunkIndex = 0; chunkCount = 0
}
// MARK: - Transport (overlay controls)
func togglePause() {
switch phase {
case .playing: player.pause(); phase = .paused; stopTimer()
case .paused: player.resume(); phase = .playing; startTimer()
default: break
}
}
private func startTimer() {
stopTimer()
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in
MainActor.assumeIsolated { self?.tick() }
}
}
private func stopTimer() { timer?.invalidate(); timer = nil }
private func tick() {
telemetry.progress = player.progress
telemetry.chunkProgress = player.chunkFraction
telemetry.chunkSeconds = player.chunkSeconds
// Only assign chunkIndex when the paragraph actually turns — it lives on
// AppState (read by GenerateView/overlay), so a 10 Hz same-value write would
// needlessly fire AppState.objectWillChange and re-render the whole window.
let ci = min(max(1, player.finishedCount + 1), max(1, chunkCount))
if ci != chunkIndex { chunkIndex = ci }
}
var backendIdentity: String { backendKind == .elevenlabs ? "elevenlabs" : "qwen3-local" }
var settingsHash: String { backendKind == .elevenlabs ? voiceSettings.hash : "" }
var audioExt: String { backendKind == .elevenlabs ? "mp3" : "wav" }
private func makeBackend() -> TTSBackend? {
switch backendKind {
case .elevenlabs:
guard let key = Secrets.elevenLabsKey else { return nil }
return ElevenLabsBackend(apiKey: key, settings: voiceSettings, models: elevenModels)
case .local:
return Qwen3MLXBackend(identity: backendIdentity,
baseURL: URL(string: localBaseURL) ?? URL(string: "http://127.0.0.1:8765")!)
}
}
// MARK: - Synthesize (paragraph chunks, cache-first, queued playback)
/// `displayText` is the human-readable source to show as the subtitle (원문 for
/// TTS, 해설 prose for commentary) while `text` is what's actually synthesized
/// (the 대본). When omitted, the subtitle is the spoken text.
func synthesize(_ text: String, displayText: String? = nil) {
// cleanInput both sides: collapse the stray line breaks a web selection or
// an LLM 대본 carries (esp. math/markdown), so paragraph chunking is by
// blank lines — otherwise the spoken and display chunk counts diverge and
// the subtitle falls back to the 대본.
let t = TextSplitter.cleanInput(text)
guard !t.isEmpty else { return }
let chunks = TextSplitter.paragraphs(t, maxChars: maxChunkChars)
guard !chunks.isEmpty else { return }
cancelActiveWork() // supersede any prior command (LLM/synthesis/playback)
currentText = t // overlay label (the spoken text); do NOT touch inputText
spokenChunks = chunks // spoken 대본 chunks (drive crawlFraction)
// Subtitle is the human-readable source, decoupled from the audio chunking
// — so it's always the 원본/해설, never the 대본, regardless of how the LLM
// reformatted paragraphs (web-selected math, etc.).
subtitleText = TextSplitter.cleanInput(displayText ?? t)
chunkSentenceTimes = Array(repeating: [], count: chunks.count)
telemetry.reset()
player.start(expected: chunks.count)
chunkCount = chunks.count; chunkIndex = 0
let ident = backendIdentity, vid = voiceId, mid = modelId, sHash = settingsHash
let vName = voiceName, ext = audioExt
let voice = VoiceConfig(voiceId: vid, modelId: mid, settingsHash: sHash)
task = Task { [weak self] in
let activityID = MemoryDiagnostics.begin("AppState.audioPipeline")
defer { MemoryDiagnostics.end(activityID) }
guard let self else { return }
var backend: TTSBackend?
var startedPlaying = false // ⏳ only before the first audio plays
do {
for (ci, chunk) in chunks.enumerated() {
try Task.checkCancellation()
let key = CacheStore.key(text: chunk, backend: ident,
voiceId: vid, modelId: mid, settingsHash: sHash)
var url: URL?
if self.useCache, let u = self.cache.fileURL(forKey: key) {
self.cache.touch(key); url = u // cache hit: skip synthesizing state
self.chunkSentenceTimes[ci] = self.cache.times(forKey: key) ?? []
} else {
// "synthesizing" only while waiting for the FIRST chunk
if !startedPlaying {
self.phase = .synthesizing
if self.statusText.isEmpty { self.statusText = "합성 중…" }
}
if backend == nil { backend = self.makeBackend() }
guard let b = backend else {
self.phase = .idle; self.statusText = "키/백엔드 미설정"; return
}
var data = Data()
var times: [Double] = []
if let timed = try await b.synthesizeTimed(segment: chunk, voice: voice) {
try Task.checkCancellation()
data = timed.data
times = self.sentenceStartTimes(text: chunk, charStarts: timed.charStarts)
} else {
for try await c in b.stream(segment: chunk, voice: voice) {
try Task.checkCancellation(); data.append(c)
}
}
MemoryDiagnostics.sample("audio.ready", details: "audioBytes=\(data.count) timingValues=\(times.count)")
self.chunkSentenceTimes[ci] = times
if self.useCache {
let e = self.cache.save(key: key, text: chunk, backend: ident, voiceId: vid,
voiceName: vName, modelId: mid, ext: ext, data: data)
self.cache.saveTimes(key: key, times)
url = self.cache.audioURL(e)
} else {
let tmp = FileManager.default.temporaryDirectory
.appendingPathComponent("\(key).\(ext)")
try? data.write(to: tmp); url = tmp
}
}
if let url {
self.player.enqueue(url)
if !startedPlaying {
startedPlaying = true
self.phase = .playing; self.statusText = "재생 중…"; self.startTimer()
}
}
}
self.historyRevision += 1
} catch is CancellationError {
self.finish()
} catch {
// Tear playback down like finish() (stop the timer + player) but keep
// the error message. Without stopTimer() a mid-playback synthesis
// error left the 10 Hz timer running forever, growing memory at idle.
self.stopTimer()
self.player.stop()
self.phase = .idle; self.telemetry.reset()
self.chunkIndex = 0; self.chunkCount = 0
self.statusText = "오류: \(error.localizedDescription)"
}
}
}
/// Build the script normalizer from the 대본 role's endpoint, branching on
/// its apiStyle — the HTTP implementations (LLM.*) are reused as-is.
private func makeNormalizer(instruction: String) -> Normalizing? {
guard let e = activeEndpoint(byID: scriptEndpointID) else { return nil }
let model = roleModel(scriptRoleModels, e)
// A role with no pick AND an endpoint with no 기본 모델 would post
// `"model": ""` — refuse instead of letting the server 400.
guard !model.isEmpty else { return nil }
return EndpointGenerator(endpoint: e, apiKey: endpointKey(e), model: model,
instruction: instruction, temperature: scriptTemperature, reasoningLevel: scriptReasoningLevel)
}
/// few-shot 용어 발음 사전 섹션. term 순(알파벳/가나다)으로 정렬해 결정적
/// 프롬프트를 유지하고, 용어·발음이 빈 행은 건너뛴다. 사전이 비면 "".
private func glossaryBlock() -> String {
let entries = glossary
.map { GlossaryEntry(id: $0.id,
term: $0.term.trimmingCharacters(in: .whitespaces),
pronunciation: $0.pronunciation.trimmingCharacters(in: .whitespaces),
note: $0.note) }
.filter { !$0.term.isEmpty && !$0.pronunciation.isEmpty }
.sorted { $0.term.localizedCaseInsensitiveCompare($1.term) == .orderedAscending }
guard !entries.isEmpty else { return "" }
let table = entries.map { "\($0.term) → \($0.pronunciation)" }.joined(separator: "\n")
return "[용어 발음 사전 — 반드시 이 표기대로 변환]\n\(table)\n"
+ "위 사전에 있는 표기는 아래 일반 규칙(영어는 그대로 둠 등)보다 우선한다."
+ " 사전에 없는 표기는 아래 규칙을 따른다."
}
/// Normalize instruction with the optional per-run 대본 hint folded in. The
/// hint goes FIRST as highest-priority: appended after the base rules, the
/// base "영어는 그대로 둠 / 의미 보존" rules drown it out (verified w/ gemma —
/// top placement is followed, trailing placement is ignored).
/// 용어 발음 사전도 같은 이유로 base rules **앞**에 둔다: 사전은 "영어는 그대로
/// 둠" 규칙과 정면으로 충돌하므로(np → 넘파이) 뒤에 붙이면 무시된다.
/// 우선순위는 추가 지시 > 사전 > 기본 규칙 — 사전에 없는 표기는 기본 규칙이 맡는다.
private func scriptInstruction() -> String {
let h = scriptHint.trimmingCharacters(in: .whitespacesAndNewlines)
var parts: [String] = []
if !h.isEmpty {
parts.append("[가장 중요한 지시 — 아래 규칙과 충돌하면 이 지시를 최우선으로 따른다]\n\(h)")
}
let g = glossaryBlock()
if !g.isEmpty { parts.append(g) }
parts.append(normalizePrompt)
return parts.joined(separator: "\n\n")
}
// MARK: - Endpoint management (settings UI)
/// Register a new endpoint; its key (if any) goes to its own <id>.key file.
func addEndpoint(name: String, baseURL: String, style: CustomEndpoint.APIStyle,
apiKey: String, defaultModel: String = "", isEnabled: Bool = true,
provider: CustomEndpoint.Provider? = nil, connection: CustomEndpoint.Connection? = nil) {
var e = CustomEndpoint(name: name, baseURL: baseURL, apiStyle: style)
e.isEnabled = isEnabled
e.provider = provider
e.connection = connection
e.name = e.name.isEmpty ? style.label : e.name
let k = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
if !k.isEmpty { Secrets.writeEndpointKey(e.id, k) }
e.defaultModel = defaultModel.trimmingCharacters(in: .whitespacesAndNewlines)
endpoints.append(e)
// First endpoint ever → point the roles at it so a fresh setup works.
if e.isEnabled && (endpoints.filter { $0.isEnabled }.count == 1)
&& !endpoints.contains(where: { $0.id.uuidString == explainEndpointID && $0.isEnabled }) {
explainEndpointID = e.id.uuidString
if !visionOverridden { visionEndpointID = e.id.uuidString }
if scriptEndpointID.isEmpty || !endpoints.contains(where: { $0.id.uuidString == scriptEndpointID && $0.isEnabled }) {
scriptEndpointID = e.id.uuidString
}
}
saveSettings()
refreshEndpointModels(e)
}
func updateEndpoint(_ endpoint: CustomEndpoint) {
guard let index = endpoints.firstIndex(where: { $0.id == endpoint.id }) else { return }
let old = endpoints[index]
if old.connectionMethod != endpoint.connectionMethod || old.apiStyle != endpoint.apiStyle || old.baseURL != endpoint.baseURL {
let id = endpoint.id.uuidString
endpointModels[id] = nil
endpointStatus[id] = nil
explainRoleModels[id] = nil
scriptRoleModels[id] = nil
visionRoleModels[id] = nil
}
endpoints[index] = endpoint
saveSettings()
}
func deleteEndpoint(_ id: UUID) {
endpoints.removeAll { $0.id == id }
endpointModels[id.uuidString] = nil
endpointStatus[id.uuidString] = nil
explainRoleModels[id.uuidString] = nil
scriptRoleModels[id.uuidString] = nil
visionRoleModels[id.uuidString] = nil
// Any role still pointing at the deleted endpoint falls back to the
// first remaining enabled one (or the first remaining at all).
let fallback = endpoints.first(where: { $0.isEnabled })?.id.uuidString
?? endpoints.first?.id.uuidString ?? ""
if explainEndpointID == id.uuidString { explainEndpointID = fallback }
if scriptEndpointID == id.uuidString { scriptEndpointID = fallback }
if visionEndpointID == id.uuidString {
// The vision OVERRIDE pointed here. Retargeting it silently would
// pin vision to an endpoint the user never chose, so drop back to
// 해설 추종 (the documented default) instead.
visionEndpointID = fallback
visionOverridden = false
}
saveSettings()
}
func saveEndpointKey(_ id: UUID, _ key: String) {
let k = key.trimmingCharacters(in: .whitespacesAndNewlines)
Secrets.writeEndpointKey(id, k)
guard let e = endpoint(byID: id.uuidString) else { return }
if !k.isEmpty || e.apiStyle != .gemini { refreshEndpointModels(e) }
}
/// Fetch the endpoint's live models.list (openAI=`GET /models`,
/// gemini=`GET /models`, ollama=`GET /api/tags`) and swap it into the picker.
/// Reuses the existing per-style helpers — no new network code.
func refreshEndpointModels(_ endpoint: CustomEndpoint) {
let e = endpoint
let id = e.id.uuidString
if !e.usesPlan && (e.apiStyle == .gemini || e.apiStyle == .anthropic) && endpointKey(e).isEmpty {
endpointStatus[id] = "키 없음"
return
}
endpointStatus[id] = "확인 중…"
// Read the endpoint's URL/key HERE, on the main actor, exactly as the old
// refreshGemini/ZAIModels did — reading them through `self?` inside the
// Task would send an UNAUTHENTICATED request if self had gone away.
let base = e.baseURL
let key = endpointKey(e)
Task { [weak self] in
let activityID = MemoryDiagnostics.begin("AppState.modelRefresh")
defer { MemoryDiagnostics.end(activityID) }
do {
let ms: [String]
if e.usesPlan {
if e.resolvedProvider == .google {
ms = try await AntigravityPlan.models()
} else {
guard e.resolvedProvider == .openAI else { throw connectionError("이 공급자의 플랜 연결은 지원하지 않습니다.") }
ms = try await CodexPlan.models()
}
} else { switch e.apiStyle {
case .anthropic:
ms = try await AnthropicAPI.models(baseURL: base, key: key)
case .openAICompatible:
ms = try await ZAI.models(baseURL: base, apiKey: key)
case .gemini:
ms = try await Gemini.models(baseURL: base, apiKey: key)
case .ollama:
ms = try await Ollama.models(baseURL: URL(string: base) ?? URL(string: "http://localhost:11434")!)
}
}
guard let self, self.endpoints.contains(where: { $0 == e }) else { return }
self.endpointModels[id] = ms
// 기본 모델 미지정: 목록에서 채운다 (선호 모델이 목록에 있으면 그것, 없으면 첫 항목).
if let idx = self.endpoints.firstIndex(where: { $0.id == e.id }), (self.endpoints[idx].defaultModel.isEmpty || (e.usesPlan && e.resolvedProvider == .google && self.endpoints[idx].defaultModel == "auto")) {
let fallback = self.preferredModels(e).first(where: { ms.contains($0) }) ?? ms.first ?? ""
if !fallback.isEmpty {
self.endpoints[idx].defaultModel = fallback
self.saveSettings()
}
}
var status = "연결됨 · 모델 \(ms.count)개"
if !self.endpointDefaultModelValid(e) {
let dm = self.endpoint(byID: id)?.defaultModel ?? ""
status += " · ⚠️ 기본 모델 ‘\(dm)’이 목록에 없음"
}
self.endpointStatus[id] = status
} catch {
guard let self, self.endpoints.contains(where: { $0 == e }) else { return }
self.endpointStatus[id] = "연결 실패: \(error.localizedDescription)"
}
}
}
// MARK: - Commentary (코드 → 해설)
private func makeExplainer() -> EndpointGenerator? {
guard let e = activeEndpoint(byID: explainEndpointID) else { return nil }
let model = roleModel(explainRoleModels, e)
guard !model.isEmpty else { return nil } // never post `"model": ""`
return EndpointGenerator(endpoint: e, apiKey: endpointKey(e), model: model,
instruction: explainPrompt, temperature: explainTemperature, reasoningLevel: explainReasoningLevel)
}
/// Stable digest of the attached screenshots, for caching the transcription.
private func imagesDigest(_ imgs: [Data]) -> String {
var h = SHA256()
for d in imgs { h.update(data: d) }
return h.finalize().map { String(format: "%02x", $0) }.joined()
}
/// Stage 1 of image-explain: the VISION model transcribes the screenshot(s) to
/// text (the code + any relevant screen content). Cached by image digest so a
/// re-run skips the vision call. The text then feeds the normal explain stage.
private func transcribeImages(_ imgs: [Data]) async -> String? {
let memoryID = beginMemoryOperation("vision")
defer { endMemoryOperation("vision", memoryID) }
guard let visionProv = visionEndpointEff else {
statusText = "비전 엔드포인트 없음 (설정에서 엔드포인트를 확인하세요)"
return nil
}
let visionModel = visionModelEff
guard !visionModel.isEmpty else {
statusText = "\(visionProv.name) 비전 모델 미설정 (기본 모델을 지정하세요)"
return nil
}
let tkey = NormalizationCache.key(text: imagesDigest(imgs),
provider: "vision:" + visionProv.cacheIdentity,
model: visionModel,
prompt: "transcribe" + visionReasoningLevel.cacheSuffix)
if let cached = normCache.script(forKey: tkey) { return cached }
let prompt = """
이미지를 텍스트로 옮기는 작업입니다. 여러 장이 첨부될 수 있으며, 서로 보완하는 자료(코드 화면 + 필기
메모·그림 + 책/교재 페이지 등)일 수 있으니 모든 이미지를 빠짐없이 반영하세요. 반드시 아래 세 섹션으로 나눠 출력하세요.
[코드]
보이는 코드를 들여쓰기·줄바꿈 그대로 옮겨 적습니다. 코드가 아닌 화면 요소(파일명·출력·오류 등)는 짧게 덧붙입니다.
[강조 표시]
사용자가 손으로 그린 강조(박스·화살표·동그라미·밑줄·색칠·필기 메모 등)를 빠짐없이 적습니다. 각 강조가
어떤 코드/변수/요소를 가리키는지, 적힌 메모 내용, 그리고 무엇을 비교·대조하거나 왜 강조했는지를 구체적으로
설명합니다. 예: "x1, x2 컬럼을 빨간 박스로, label 컬럼을 초록 박스로 묶고 'label ∈ {0,1}', 'y ∈ float'라고 적어
분류(라벨)와 회귀(연속값 y)의 차이를 대조함". 손으로 그린 강조가 전혀 없으면 정확히 "없음"이라고만 적습니다.
[참고 자료]
코드가 아닌 설명 자료(책/교재 페이지, 개념 그림, 긴 설명 텍스트 등)가 있으면, 코드 이해에 도움이 되는 핵심
내용을 요약해 적습니다(관련 개념·기법·용어·정의 등). 없으면 정확히 "없음".
해설·설명 문장은 쓰지 말고 위 세 섹션 형식으로만 출력합니다.
"""
let stream = EndpointGenerator(endpoint: visionProv, apiKey: endpointKey(visionProv), model: visionModel,
instruction: "", temperature: 0, reasoningLevel: visionReasoningLevel)
.generate(prompt, images: imgs)
var acc = ""
do {
for try await delta in stream { try Task.checkCancellation(); acc += delta }
} catch is CancellationError {
return nil
} catch {
statusText = "이미지 인식 오류: \(error.localizedDescription)"; return nil
}
let out = acc.trimmingCharacters(in: .whitespacesAndNewlines)
guard !out.isEmpty else { return nil }
// Non-vision models (e.g. gemma4) silently reply "이미지가 없다" instead of
// erroring — catch that so we don't explain a refusal as if it were code.
let refusal = ["이미지가 첨부", "이미지를 첨부", "이미지가 없", "이미지가 보이지", "첨부되지 않",
"no image", "can't see", "cannot see", "don't see"]
if out.count < 400, refusal.contains(where: { out.contains($0) }) {
statusText = "비전 모델이 이미지를 못 읽었습니다 — 비전 모델을 gemma3 등 비전 지원 모델로 바꾸세요"
return nil
}
normCache.put(key: tkey, script: out)
return out
}
// Public entry points (sync): manage the single long-lived `explainTask`,
// serialized so a new run waits for the previous to fully unwind (no two
// writers racing into `explanationText`). The streaming workers below stream
// deltas straight into `explanationText` and finalize (strip + cache) at end.
func generateExplanation(force: Bool = false) {
cancelActiveWork()
explainTask = Task { [weak self] in _ = await self?.runExplain(force: force) }
}
func continueExplanation(force: Bool = false) {
cancelActiveWork()
explainTask = Task { [weak self] in _ = await self?.runContinue(force: force) }
}
/// Stream a full 해설 (코드→해설) into `explanationText`. Returns the finalized
/// text, or nil on failure/cancel. Code is sent verbatim (no cleanInput).
@discardableResult
private func runExplain(force: Bool) async -> String? {
let memoryID = beginMemoryOperation("explain")
defer { endMemoryOperation("explain", memoryID) }
let typed = codeText.trimmingCharacters(in: .whitespacesAndNewlines)
let imgs = codeImages
let hint = explainHint
guard !typed.isEmpty || !imgs.isEmpty else { explanationText = ""; return nil }
guard let explainer = makeExplainer(), let ep = activeEndpoint(byID: explainEndpointID) else {
statusText = "해설 생성 불가 — 엔드포인트·모델·API 키 중 하나가 미설정입니다 (설정 확인)"
return nil
}
explaining = true
defer { explaining = false }
// If a screenshot is attached AND the vision model is the same as the 해설
// model, that model can both read the image and explain in ONE call — skip
// the transcribe stage (less loss, faster). Otherwise: vision transcribes,
// then the text model explains.
let singleStage = !imgs.isEmpty
&& visionEndpointEff?.id == ep.id && visionModelEff == explainer.model
var code = typed
if !imgs.isEmpty && !singleStage {
statusText = "이미지에서 코드 추출 중…"
guard let transcribed = await transcribeImages(imgs) else {
if statusText.isEmpty { statusText = "이미지 인식 실패" }
return nil
}
code = typed.isEmpty ? transcribed : typed + "\n\n" + transcribed
} else if singleStage {
code = typed.isEmpty
? CodeExplanation.imageOnlyInput
: typed
}
guard !code.isEmpty else { statusText = "해설 생성 실패 (빈 입력)"; return nil }
guard !Task.isCancelled else { return nil }
let user = ConversationMessage(role: .user, text: CodeExplanation.conversationInput(code, hint: hint),
images: singleStage ? imgs : [])
let sourceID = NormalizationCache.key(text: typed, provider: "explain-source", model: "", prompt: imagesDigest(imgs))
let request = explanationHistory.prepare(system: CodeExplanation.conversationSystem(explainer.instruction),
user: user, sourceID: sourceID)
// Include the EXACT selected conversation and all generation settings. Old stateless keys never collide.
let nk = request.conversation.resultCacheKey(endpointIdentity: ep.cacheIdentity, model: explainer.model,
temperature: explainer.temperature, reasoning: explainer.reasoningLevel.rawValue)
if !force, let cached = normCache.script(forKey: nk) {
guard !Task.isCancelled, explanationHistory.commit(request, output: cached) else { return nil }
explanationText = cached; lastExplainedCode = code; lastSegment = cached; return cached
}
explanationText = ""
statusText = "해설 생성 중…"
var acc = ""
do {
let stream = explainer.generate("", conversation: request.conversation)
for try await delta in stream {
try Task.checkCancellation()
acc += delta
explanationText = acc // live (raw markdown shows until finalize)
}
} catch is CancellationError {
return nil
} catch {
statusText = "해설 오류: \(error.localizedDescription)"
return nil
}
guard !Task.isCancelled else { return nil } // superseded just as the stream ended
let out = CodeExplanation.stripMarkdown(acc)
guard !out.isEmpty else { statusText = "해설 생성 실패 (빈 응답)"; return nil }
guard explanationHistory.commit(request, output: out) else { return nil }
normCache.put(key: nk, script: out)
explanationText = out // finalize (stripped)
lastExplainedCode = code // baseline for "이어서 해설"
lastSegment = out
statusText = ""
return out
}
/// Stream only the added/changed part (이어서 해설), appending to the running
/// narration. First run (no baseline) falls back to a full explain. On the
/// "변경 없음" sentinel or cancel, rolls the streamed text back to the original.
@discardableResult
private func runContinue(force: Bool) async -> String? {
let memoryID = beginMemoryOperation("continue")
defer { endMemoryOperation("continue", memoryID) }
let current = codeText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !current.isEmpty else { return nil }
guard canContinueExplain else { return await runExplain(force: force) }
guard let explainer = makeExplainer(), let ep = activeEndpoint(byID: explainEndpointID) else {
statusText = "해설 생성 불가 — 엔드포인트·모델·API 키 중 하나가 미설정입니다 (설정 확인)"
return nil
}
let prompt = explainer.continuationPrompt(previous: lastExplainedCode, current: current, hint: explainHint)
let nk = CodeExplanation.continuationCacheKey(prompt: prompt, endpointIdentity: ep.cacheIdentity,
model: explainer.model, temperature: explainer.temperature,
reasoning: explainer.reasoningLevel)
if !force, let cached = normCache.script(forKey: nk) {
applyContinuation(cached, newBaseline: current); return cached
}
explaining = true
defer { explaining = false }
let original = explanationText
let base = original.isEmpty ? "" : original + "\n\n"
statusText = "이어서 해설 생성 중…"
var acc = ""
do {
for try await delta in explainer.generate(prompt) {
try Task.checkCancellation()
acc += delta
explanationText = base + acc
}
} catch is CancellationError {
explanationText = original // roll back the streamed text
return nil
} catch {
explanationText = original
statusText = "이어서 해설 오류: \(error.localizedDescription)"
return nil
}
let out = CodeExplanation.stripMarkdown(acc)
if out.isEmpty || out.hasPrefix(CodeExplanation.noChange) {
explanationText = original // nothing to add → restore
statusText = out.isEmpty ? "이어서 해설 실패 (빈 응답)" : "변경 없음 — 추가할 해설 없음"
lastExplainedCode = current // advance baseline anyway
return out
}
normCache.put(key: nk, script: out)
explanationText = base + out // finalize (stripped)
lastSegment = out
lastExplainedCode = current
statusText = "이어서 해설 추가됨"
return out
}