Skip to content

Commit f719c17

Browse files
committed
Add conversation context, model catalog and performance diagnostics
Preserve pending TTS work: bounded explanation history and context-aware result caching, provider conversation adapters, dynamic ElevenLabs model capabilities, input and memory diagnostics, offline tests, and the existing native HUD drag surface.
1 parent 4da9d5d commit f719c17

31 files changed

Lines changed: 1108 additions & 83 deletions

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,10 @@ Codebasic-TTS/
290290
└── Sidecar/ # 로컬 Qwen3-TTS(MLX) FastAPI 사이드카
291291
```
292292

293+
## 진단 문서
294+
295+
[메모리 및 입력 지연 진단](docs/performance-diagnostics.md)
296+
293297
## 후원 💖
294298

295299
Codebasic TTS는 무료·오픈소스(MIT)로, 꾸준한 유지보수와 기능 개발로 계속 발전합니다.

‎Sources/App/AntigravityPlan.swift‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ enum AntigravityPlan {
6767
process.standardError = FileHandle.nullDevice
6868
try Task.checkCancellation()
6969
try process.run()
70+
MemoryDiagnostics.sample("agy.process.started", details: "childPID=\(process.processIdentifier)")
71+
defer { MemoryDiagnostics.sample("agy.scope.end", details: "childPID=\(process.processIdentifier) running=\(process.isRunning)") }
7072
let deadline = Date().addingTimeInterval(timeout)
7173
while process.isRunning {
7274
try Task.checkCancellation()
@@ -113,18 +115,20 @@ enum AntigravityPlan {
113115
return response
114116
}
115117
static func stream(prompt: String, model: String, images: [Data], executable: URL? = AntigravityPlan.executable,
116-
home: URL = AntigravityPlan.home) -> AsyncThrowingStream<String, Error> {
118+
home: URL = AntigravityPlan.home, conversation: ExplanationConversation? = nil) -> AsyncThrowingStream<String, Error> {
117119
AsyncThrowingStream { continuation in
118120
let task = Task { @MainActor in
121+
let activityID = MemoryDiagnostics.begin("AntigravityPlan.generation")
122+
defer { MemoryDiagnostics.end(activityID) }
119123
do {
120124
// The documented stream input protocol supports text blocks only.
121-
guard images.isEmpty else { throw connectionError("Antigravity CLI의 자동 연결은 텍스트 입력만 지원합니다. 이미지 인식에는 API 키 연결을 선택하세요.") }
125+
guard images.isEmpty && conversation?.hasImages != true else { throw connectionError("Antigravity CLI의 자동 연결은 텍스트 입력만 지원합니다. 이미지 인식에는 API 키 연결을 선택하세요.") }
122126
var args = ["--input-format", "stream-json", "--output-format", "stream-json",
123127
"--disable-slash-commands", "--print-timeout", "3m"]
124128
// Migrate the former Gemini auto sentinel to the CLI's default selection.
125129
if !model.isEmpty && model != "auto" { args += ["--model", model] }
126130
var decoder = AntigravityDeltaDecoder()
127-
let (data, code) = try await run(arguments: args, input: inputData(prompt), executable: executable, home: home) { bytes in
131+
let (data, code) = try await run(arguments: args, input: inputData(conversation?.transcript ?? prompt), executable: executable, home: home) { bytes in
128132
for delta in try decoder.append(bytes) { continuation.yield(delta) }
129133
}
130134
let response = try decodeResponse(data, exitCode: code)
@@ -161,6 +165,8 @@ enum AntigravityPlan {
161165
busy = true
162166
status = "Google 계정 확인 중…"
163167
task = Task { [weak self] in
168+
let activityID = MemoryDiagnostics.begin("AntigravityPlan.connectionCheck")
169+
defer { MemoryDiagnostics.end(activityID) }
164170
guard let self else { return }
165171
do {
166172
do {

‎Sources/App/AppState.swift‎

Lines changed: 121 additions & 32 deletions
Large diffs are not rendered by default.

‎Sources/App/CodexPlan.swift‎

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,17 @@ func connectionError(_ message: String) -> NSError {
1010
/// A dedicated home avoids importing the user's project tools, MCP servers or API configuration.
1111
@MainActor
1212
final class CodexPlanRPC {
13+
private let diagnosticID = MemoryDiagnostics.begin("codexRPC.instance")
14+
deinit { MemoryDiagnostics.end(diagnosticID) }
15+
private func updateMemoryMetrics() {
16+
MemoryDiagnostics.update(diagnosticID, values: ["rpcBufferBytes": buffer.count, "rpcPending": pending.count])
17+
}
1318
private let process = Process()
1419
private let input = Pipe()
1520
private let output = Pipe()
16-
private var buffer = Data()
21+
private var buffer = Data() { didSet { updateMemoryMetrics() } }
1722
private var nextID = 0
18-
private var pending: [Int: CheckedContinuation<[String: Any], Error>] = [:]
23+
private var pending: [Int: CheckedContinuation<[String: Any], Error>] = [:] { didSet { updateMemoryMetrics() } }
1924
var notification: ((String, [String: Any]) -> Void)?
2025
var disconnected: (() -> Void)?
2126
private var closed = false
@@ -45,18 +50,21 @@ final class CodexPlanRPC {
4550
output.fileHandleForReading.readabilityHandler = { [weak self] handle in
4651
let data = handle.availableData
4752
Task { @MainActor in
53+
let activityID = MemoryDiagnostics.begin("CodexPlan.rpcRead")
54+
defer { MemoryDiagnostics.end(activityID) }
4855
guard let self else { return }
4956
if data.isEmpty { self.stop(); return }
5057
self.receive(data)
5158
}
5259
}
5360
process.terminationHandler = { [weak self] _ in Task { @MainActor in self?.stop() } }
5461
try process.run()
62+
MemoryDiagnostics.sample("codex.process.started", details: "childPID=\(process.processIdentifier)")
5563
}
5664

57-
func initialize() async throws {
65+
func initialize(experimental: Bool = false) async throws {
5866
_ = try await request("initialize", ["clientInfo": ["name": "codebasic_tts", "version": "1.0"],
59-
"capabilities": ["experimentalApi": false]])
67+
"capabilities": ["experimentalApi": experimental]])
6068
try send(["method": "initialized", "params": [:]])
6169
}
6270

@@ -69,6 +77,8 @@ final class CodexPlanRPC {
6977
do { try send(["id": id, "method": method, "params": params]) }
7078
catch { pending.removeValue(forKey: id)?.resume(throwing: error) }
7179
Task { [weak self] in
80+
let activityID = MemoryDiagnostics.begin("CodexPlan.rpcDeadline")
81+
defer { MemoryDiagnostics.end(activityID) }
7282
try? await Task.sleep(for: .seconds(30))
7383
self?.pending.removeValue(forKey: id)?.resume(throwing: connectionError("연결 응답 시간이 초과되었습니다."))
7484
}
@@ -111,6 +121,7 @@ final class CodexPlanRPC {
111121
func stop() {
112122
guard !closed else { return }
113123
closed = true
124+
MemoryDiagnostics.sample("codex.stop.requested", details: "childPID=\(process.processIdentifier) running=\(process.isRunning)")
114125
notification = nil
115126
output.fileHandleForReading.readabilityHandler = nil
116127
try? input.fileHandleForWriting.close()
@@ -136,6 +147,8 @@ final class CodexPlanLogin: ObservableObject {
136147
busy = true
137148
status = "로그인 준비 중…"
138149
loginTask = Task {
150+
let activityID = MemoryDiagnostics.begin("CodexPlan.login")
151+
defer { MemoryDiagnostics.end(activityID) }
139152
do {
140153
try Task.checkCancellation()
141154
let client = try CodexPlanRPC()
@@ -159,6 +172,8 @@ final class CodexPlanLogin: ObservableObject {
159172
guard NSWorkspace.shared.open(url) else { throw connectionError("로그인 브라우저를 열 수 없습니다.") }
160173
status = "브라우저에서 ChatGPT 로그인을 완료하세요."
161174
timeout = Task { [weak self] in
175+
let activityID = MemoryDiagnostics.begin("CodexPlan.loginDeadline")
176+
defer { MemoryDiagnostics.end(activityID) }
162177
do { try await Task.sleep(for: .seconds(180)) } catch { return }
163178
self?.cancel()
164179
self?.status = "로그인 시간이 초과되었습니다. 다시 시도하세요."
@@ -191,35 +206,45 @@ enum CodexPlan {
191206
return models
192207
}
193208

194-
static func stream(prompt: String, model: String, images: [Data], reasoning: ReasoningLevel) -> AsyncThrowingStream<String, Error> {
209+
static func stream(prompt: String, model: String, images: [Data], reasoning: ReasoningLevel,
210+
conversation: ExplanationConversation? = nil, executable: URL? = nil, home: URL? = nil) -> AsyncThrowingStream<String, Error> {
195211
AsyncThrowingStream { continuation in
196212
let task = Task { @MainActor in
213+
let activityID = MemoryDiagnostics.begin("CodexPlan.generation")
214+
defer { MemoryDiagnostics.end(activityID) }
197215
var rpc: CodexPlanRPC?
198216
do {
199217
try Task.checkCancellation()
200-
let client = try CodexPlanRPC()
218+
let client = try CodexPlanRPC(executable: executable, home: home)
201219
rpc = client
202220
defer { client.stop() }
203-
try await client.initialize()
221+
try await client.initialize(experimental: conversation != nil)
204222
_ = try await client.requirePlan()
205223
try Task.checkCancellation()
206224
let thread = try await client.request("thread/start", ["ephemeral": true, "model": model,
207225
"modelProvider": "openai", "sandbox": "read-only", "approvalPolicy": "never",
208-
"baseInstructions": "Return only the requested text. Do not use tools, access files, or perform actions.",
226+
"baseInstructions": "Return only the requested text. Do not use tools, access files, or perform actions."
227+
+ (conversation.map { "\n\n" + $0.system } ?? ""),
209228
"config": ["features.shell_tool": false, "features.apply_patch_freeform": false,
210229
"features.code_mode": false, "web_search": "disabled"]])
211230
guard let info = thread["thread"] as? [String: Any], let id = info["id"] as? String else {
212231
throw connectionError("생성 세션을 시작하지 못했습니다.")
213232
}
233+
if let conversation, !conversation.codexHistoryItems.isEmpty {
234+
_ = try await client.request("thread/injectItems", ["threadId": id, "items": conversation.codexHistoryItems])
235+
}
214236
let (events, eventContinuation) = AsyncStream<(String, [String: Any])>.makeStream()
215237
client.notification = { eventContinuation.yield(($0, $1)) }
216238
client.disconnected = { eventContinuation.finish() }
217-
var input: [[String: Any]] = [["type": "text", "text": prompt, "text_elements": []]]
218-
input += images.map { ["type": "image", "url": "data:image/png;base64,\($0.base64EncodedString())"] }
239+
let current = conversation?.messages.last
240+
var input: [[String: Any]] = [["type": "text", "text": current?.text ?? prompt, "text_elements": []]]
241+
input += (current?.images ?? images).map { ["type": "image", "url": "data:image/png;base64,\($0.base64EncodedString())"] }
219242
var params: [String: Any] = ["threadId": id, "input": input]
220243
if !reasoning.isProviderDefault { params["effort"] = reasoning.rawValue }
221244
_ = try await client.request("turn/start", params)
222245
let deadline = Task { @MainActor in
246+
let activityID = MemoryDiagnostics.begin("CodexPlan.generationDeadline")
247+
defer { MemoryDiagnostics.end(activityID) }
223248
do { try await Task.sleep(for: .seconds(180)) } catch { return }
224249
eventContinuation.finish()
225250
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import Foundation
2+
3+
/// Public model metadata only; never stores account credentials.
4+
struct ElevenModel: Codable, Identifiable, Equatable {
5+
let id: String
6+
let name: String
7+
let canDoTextToSpeech: Bool
8+
let languages: [Language]
9+
let canUseStyle: Bool?
10+
let canUseSpeakerBoost: Bool?
11+
struct Language: Codable, Equatable {
12+
let languageId: String
13+
enum CodingKeys: String, CodingKey { case languageId = "language_id" }
14+
}
15+
enum CodingKeys: String, CodingKey {
16+
case canUseStyle = "can_use_style", canUseSpeakerBoost = "can_use_speaker_boost"
17+
case id = "model_id", name, canDoTextToSpeech = "can_do_text_to_speech", languages
18+
}
19+
20+
init(from decoder: Decoder) throws {
21+
let values = try decoder.container(keyedBy: CodingKeys.self)
22+
id = try values.decode(String.self, forKey: .id)
23+
name = try values.decodeIfPresent(String.self, forKey: .name) ?? id
24+
canDoTextToSpeech = try values.decodeIfPresent(Bool.self, forKey: .canDoTextToSpeech) ?? false
25+
languages = try values.decodeIfPresent([Language].self, forKey: .languages) ?? []
26+
canUseStyle = try values.decodeIfPresent(Bool.self, forKey: .canUseStyle)
27+
canUseSpeakerBoost = try values.decodeIfPresent(Bool.self, forKey: .canUseSpeakerBoost)
28+
}
29+
30+
func voiceSettingsJSON(stability: Double, similarityBoost: Double, style: Double,
31+
useSpeakerBoost: Bool) -> [String: Any] {
32+
var json: [String: Any] = ["stability": stability, "similarity_boost": similarityBoost]
33+
if canUseStyle == true { json["style"] = style }
34+
if canUseSpeakerBoost == true { json["use_speaker_boost"] = useSpeakerBoost }
35+
return json
36+
}
37+
}
38+
39+
enum ElevenModelCatalog {
40+
static func koreanTTS(from data: Data) throws -> [ElevenModel] {
41+
let models = try JSONDecoder().decode([ElevenModel].self, from: data)
42+
var seen = Set<String>()
43+
let result = models.filter {
44+
$0.canDoTextToSpeech && !$0.id.isEmpty &&
45+
$0.languages.contains { $0.languageId == "ko" } && seen.insert($0.id).inserted
46+
}
47+
guard !result.isEmpty else {
48+
throw NSError(domain: "ElevenLabsModels", code: 0,
49+
userInfo: [NSLocalizedDescriptionKey: "한국어 음성 합성 모델이 반환되지 않았습니다."])
50+
}
51+
return result
52+
}
53+
54+
static func fetch(apiKey: String) async throws -> [ElevenModel] {
55+
var request = URLRequest(url: URL(string: "https://api.elevenlabs.io/v1/models")!)
56+
request.timeoutInterval = 30
57+
request.setValue(apiKey, forHTTPHeaderField: "xi-api-key")
58+
let (data, response) = try await URLSession.shared.data(for: request)
59+
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
60+
let status = (response as? HTTPURLResponse)?.statusCode ?? -1
61+
// Do not expose arbitrary response bodies (or authentication details) in the UI.
62+
throw NSError(domain: "ElevenLabsModels", code: status,
63+
userInfo: [NSLocalizedDescriptionKey: "모델 조회 실패 (HTTP \(status))"])
64+
}
65+
return try koreanTTS(from: data)
66+
}
67+
68+
static func load(from url: URL) -> [ElevenModel] {
69+
guard let data = try? Data(contentsOf: url), let models = try? koreanTTS(from: data) else { return [] }
70+
return models
71+
}
72+
73+
static func save(_ models: [ElevenModel], to url: URL) throws {
74+
let data = try JSONEncoder().encode(models)
75+
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
76+
try data.write(to: url, options: .atomic)
77+
}
78+
}

0 commit comments

Comments
 (0)