Skip to content

Commit ca1fffc

Browse files
lseongjooclaude
andcommitted
Apply cross-review fixes and add a full-app review build
- Pin editor actions (revert, close, playback) to the document they were issued for, keep manual drafts visible as tabs, and surface arrivals. - Report every draft outcome with a structured status (editor_full, invalid, upgrade_required, unconfirmed) and distinguish busy from full. - Show blocked receipt, peer identity, and shared instruction in the connection area; retry pairing when enabling receive. - Treat an unreadable preset override as unreadable instead of falling back to built-ins; write instruction files 0600. - Target macOS 14.0 for all variants, pick a usable SDK without Xcode, and stage installs so a failed swap restores the previous app. - Add `./build.sh review`: the whole app with isolated identity, data, and sockets, without Services or global hotkeys. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent d6b2417 commit ca1fffc

14 files changed

Lines changed: 458 additions & 105 deletions

‎Helpers/AgentCatalogMCP.swift‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ import Foundation
9999
}
100100
let status = pairingStatus()
101101
if status == "ready" || status == "instruction_required" {
102-
reportReceipt(id, "instruction_required"); continue
102+
reportReceipt(id, "instruction_required", shareable: status == "ready"); continue
103103
}
104104
guard status == "receiving_only" else {
105105
tool(id, describe(status), failed: true); continue
@@ -142,24 +142,42 @@ import Foundation
142142
let keys = Set(args.keys)
143143
guard keys == required || keys == required.union(["speech_text"]),
144144
let retry = args["idempotency_key"] as? String,
145-
(1...128).contains(retry.utf8.count), retry.range(of: "^[A-Za-z0-9._-]+$", options: .regularExpression) != nil,
145+
// Byte check identical to the app's, so a key cannot pass here and fail there.
146+
(1...128).contains(retry.utf8.count),
147+
retry.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0)
148+
|| (97...122).contains($0) || $0 == 45 || $0 == 46 || $0 == 95 }),
146149
let display = args["display_text"] as? String, AgentBytes.textValid(display) else { return false }
147150
return args["speech_text"].map { ($0 as? String).map(AgentBytes.textValid) == true } ?? true
148151
}
149152

150-
static func reportReceipt(_ id: Any, _ status: String?) {
153+
/// Every outcome carries a machine-readable status, and each failure names a
154+
/// recovery the agent or the user can actually perform in the reported state.
155+
static func reportReceipt(_ id: Any, _ status: String?, shareable: Bool? = nil) {
156+
let app = "\(TTSRuntime.displayName) → Agent (에이전트)"
157+
func fail(_ code: String, _ message: String) { tool(id, message, failed: true, extra: ["status": code]) }
151158
switch status {
152159
case "accepted": tool(id, "Received in the app’s editor. Not played.", extra: ["status": "accepted"])
153160
case "duplicate": tool(id, "Already received. Nothing new was opened or played.", extra: ["status": "duplicate"])
154-
case "conflict": tool(id, "Retry key already used for different content.", failed: true)
155-
case "busy": tool(id, "Open documents have reached their limit. Close a tab and retry with the same key.", failed: true, extra: ["status": "busy"])
161+
case "conflict": fail("conflict", "Retry key already used for different content. Use a new key for new content.")
162+
case "busy": fail("busy", "Open documents have reached their limit. Ask the user to close a tab in \(app), then retry with the same key.")
163+
case "editor_full":
164+
fail("editor_full", "The text open in the app is too large to keep beside a new draft. Ask the user to shorten or move it in \(app), then retry with the same key.")
156165
case "session_limit":
157-
tool(id, "This helper session has reached its draft-key limit. Ask the user to disconnect and enable a new session.", failed: true, extra: ["status": "session_limit"])
158-
case "rate_limited": tool(id, "This session’s receipt rate limit was reached.", failed: true)
166+
fail("session_limit", "This helper session has reached its draft-key limit. Ask the user to disconnect and enable a new session.")
167+
case "rate_limited": fail("rate_limited", "This session’s receipt rate limit was reached. Wait a minute, then retry with the same key.")
159168
case "instruction_required":
160-
tool(id, "A saved instruction is selected. Read the current selection and send with submit_explanation_draft, or ask the user to clear the selection.", failed: true, extra: ["status": "instruction_required"])
161-
case "unproven": tool(id, "Instruction selection, revision, or proof is no longer valid. Read the selected saved instruction again and retry.", failed: true, extra: ["status": "unproven"])
162-
default: tool(id, "Receipt not confirmed. Check TTS agent status and retry with the same key.", failed: true)
169+
switch shareable {
170+
case true?:
171+
fail("instruction_required", "A saved instruction is selected. Read it with get_tts_instructions and send with submit_explanation_draft, or ask the user to clear the selection.")
172+
case false?:
173+
fail("instruction_required", "A saved instruction is selected but is not being shared, so it cannot be read. Ask the user to select it again or clear the selection in \(app).")
174+
case nil:
175+
fail("instruction_required", "A saved instruction is selected. Check tts_agent_status: when it is ready, read the instruction and use submit_explanation_draft; otherwise ask the user to select it again or clear the selection in \(app).")
176+
}
177+
case "unproven": fail("unproven", "Instruction selection, revision, or proof is no longer valid. Check tts_agent_status, read the selected saved instruction again, and retry.")
178+
case "invalid": fail("invalid", "The app rejected the draft arguments. Check the key and text limits; retrying unchanged will not help.")
179+
case "upgrade_required": fail("upgrade_required", "The running app and this helper are different versions. Use the helper bundled with the running app.")
180+
default: fail("unconfirmed", "Receipt not confirmed. Check tts_agent_status and retry with the same key.")
163181
}
164182
}
165183

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ macOS용 TTS 앱: **텍스트 읽기, 에이전트 지시 관리, 받은 대본
2525

2626
| | |
2727
|---|---|
28-
| 플랫폼 | macOS 13.0+ (Apple Silicon 최적화, Intel 미검증) |
28+
| 플랫폼 | macOS 14.0+ (Apple Silicon 최적화, Intel 미검증) |
2929
| 요구사항 | 릴리스 앱은 Xcode 불필요. 기존 플랜 연결은 Codex CLI 또는 Antigravity CLI, 로컬 음성은 Qwen3-TTS 서버 필요 |
3030
| 라이선스 | MIT |
3131
| 다운로드 | [Releases](../../releases/latest) 에서 `Codebasic-TTS.app.zip` |

‎Resources/Info.plist‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
<key>CFBundleIconFile</key>
2020
<string>AppIcon</string>
2121
<key>LSMinimumSystemVersion</key>
22-
<string>13.0</string>
22+
<string>14.0</string>
2323

2424
<!-- macOS Services registration. NSMessage maps to the selector
2525
readSelectedText:userData:error: in ServiceProvider.swift. -->

‎Sources/App/AgentSessionController.swift‎

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import Foundation
1313

1414
var message: String {
1515
switch self {
16-
case .notSelected: return "아직 공유하지 않음 · 지시문을 선택하세요."
16+
case .notSelected: return "공유하는 지시 없음 · 대본은 지시 없이 받습니다."
1717
case .waitingForHelper: return "선택됨 · 에이전트 연결을 켜면 공유됩니다."
1818
case .active: return "선택한 지시 공유 중"
1919
case .canceled: return "지시 공유를 취소했습니다."
@@ -30,7 +30,8 @@ import Foundation
3030

3131
var isProblem: Bool {
3232
switch self {
33-
case .legacySharing, .catalogUnavailable, .invalidInstruction, .pairingUnavailable, .instructionGrantFailed, .draftGrantFailed: return true
33+
case .expired, .changed, .legacySharing, .catalogUnavailable, .invalidInstruction, .pairingUnavailable,
34+
.instructionGrantFailed, .draftGrantFailed: return true
3435
default: return false
3536
}
3637
}
@@ -70,6 +71,14 @@ import Foundation
7071
private(set) var selectionDiagnostics: [SelectionStatus] = []
7172
@Published private(set) var waitingForReceiveHelper = false
7273
@Published private(set) var instructionScope: String?
74+
/// Why the last submission from the agent was not opened, in the user's terms.
75+
@Published private(set) var receiptNotice: String?
76+
/// False for an ad-hoc signed build, where a helper can never be verified.
77+
private(set) lazy var pairingSupported = AgentPeerSigning.ownLeaf() != nil && bundledHelper() != nil
78+
79+
/// Receipt is on, but a chosen instruction is not being shared, so every
80+
/// submission is refused until the user picks it again or clears it.
81+
var receiptBlockedBySelection: Bool { receiving && instructionScope != nil && shared == nil }
7382
private var pendingReceive: ReceiveRequest?
7483
private var pendingReceiveTask: Task<Void, Never>?
7584
private var pendingSelection: PendingSelection?
@@ -219,6 +228,7 @@ import Foundation
219228
private func clearSelection() {
220229
cancelPending()
221230
stopShare()
231+
receiptNotice = nil
222232
}
223233

224234
private func cancelPending() {
@@ -272,10 +282,12 @@ import Foundation
272282
status = ""
273283
shareSocket = socket
274284
shared = snapshot
275-
shareTask = Task { [weak self] in
285+
shareTask = Task { [weak self, weak socket] in
276286
do { try await ContinuousClock().sleep(until: deadline) } catch { return }
277-
self?.clearSelection()
278-
self?.note(.expired)
287+
// A later share owns the state by now if this one was already replaced.
288+
guard let self, let socket, self.shareSocket === socket else { return }
289+
self.clearSelection()
290+
self.note(.expired)
279291
}
280292
return true
281293
}
@@ -284,10 +296,13 @@ import Foundation
284296
@discardableResult
285297
func enableReceive(current: @escaping @MainActor (String) -> AgentInstructionSnapshot?,
286298
workspace: ExplanationDraftWorkspace) -> Bool {
287-
guard !receiving, pendingReceive == nil, pairingSocket != nil else {
288-
if pairingSocket == nil { status = "MCP 연결을 시작할 수 없습니다." }
299+
// startPairing() leaves the specific reason in `status`; keep it visible.
300+
if pairingSocket == nil, !startPairing() {
301+
if status.isEmpty { status = "MCP 연결을 시작할 수 없습니다." }
289302
return false
290303
}
304+
guard !receiving, pendingReceive == nil else { return false }
305+
if let stale = pair, LocalInstructionPeer.current(pid: stale.peer.pid) != stale.peer { disconnect() }
291306
let deadline = ContinuousClock.now.advanced(by: selectionWaiting)
292307
let request = ReceiveRequest(current: current, workspace: workspace, deadline: deadline)
293308
pendingReceive = request
@@ -329,6 +344,7 @@ import Foundation
329344
instructionScope = nil
330345
note(.notSelected)
331346
status = ""
347+
receiptNotice = nil
332348
}
333349

334350
private func cancelPendingReceive() {
@@ -384,6 +400,9 @@ import Foundation
384400
// This is enforced here, not just by a potentially stale MCP tool status.
385401
// A selected-but-not-yet-shareable request also cannot fall back generically.
386402
guard self.instructionScope == nil, self.shared == nil, self.pendingSelection == nil else {
403+
self.receiptNotice = self.shared != nil
404+
? "에이전트가 지시를 읽지 않고 대본을 보내 받지 않았습니다."
405+
: "선택한 지시가 공유되고 있지 않아 대본을 받지 않았습니다. 지시를 다시 선택하거나 ‘사용 안 함’으로 바꾸세요."
387406
response.set("instruction_required"); return
388407
}
389408
origin = nil
@@ -398,12 +417,24 @@ import Foundation
398417
response.set(previous == fingerprint ? "duplicate" : "conflict"); return
399418
}
400419
guard self.receiptKeys.count < Self.maxReceiptKeys else { response.set("session_limit"); return }
401-
guard workspace.canReceiveDocument() else { response.set("busy"); return }
402-
guard self.rate.canAccept() else { response.set("rate_limited"); return }
420+
switch workspace.receiveBlock() {
421+
case .documents:
422+
self.receiptNotice = "열린 대본이 \(ExplanationDraftWorkspace.maxDocuments)개라 새 대본을 받지 않았습니다. 탭을 닫으면 에이전트가 다시 보낼 수 있습니다."
423+
response.set("busy"); return
424+
case .bytes:
425+
self.receiptNotice = "열어 둔 글이 너무 커서 새 대본을 받지 않았습니다. 글을 줄이거나 다른 곳에 옮긴 뒤 다시 받으세요."
426+
response.set("editor_full"); return
427+
case nil: break
428+
}
429+
guard self.rate.canAccept() else {
430+
self.receiptNotice = "대본이 너무 자주 와서 잠시 받지 않았습니다."
431+
response.set("rate_limited"); return
432+
}
403433
let result = workspace.receiveDocument(draft)
404434
if result == .accepted {
405435
self.receiptKeys[clientKey] = fingerprint
406436
self.rate.mark()
437+
self.receiptNotice = nil
407438
}
408439
response.set(result.rawValue)
409440
}
@@ -422,11 +453,13 @@ import Foundation
422453
workspace.setReceiver(pair.peer.pid)
423454
receiptTask = Task { [weak self, weak workspace] in
424455
do { try await ContinuousClock().sleep(until: deadline) } catch { return }
425-
self?.stopReceipt(workspace: workspace)
426-
self?.clearSelection()
427-
self?.instructionScope = nil
428-
self?.note(.notSelected)
429-
self?.status = "대본 수신 연결이 만료되었습니다."
456+
// Turning receipt off and on again starts a new deadline this timer does not own.
457+
guard let self, self.receiveDeadline == deadline else { return }
458+
self.stopReceipt(workspace: workspace)
459+
self.clearSelection()
460+
self.instructionScope = nil
461+
self.note(.notSelected)
462+
self.status = "대본 수신 연결이 만료되었습니다."
430463
}
431464
receiptWorkspace = workspace
432465
return true
@@ -440,6 +473,8 @@ import Foundation
440473
clearSelection()
441474
instructionScope = nil
442475
note(.notSelected)
476+
// Receipt widens to unlinked drafts here, so say so where the user is looking.
477+
if receiving { status = "선택한 지시가 삭제되어 이제 지시 없이 대본을 받습니다." }
443478
return
444479
}
445480
if shared?.selector == selector || pendingSelection?.snapshot.selector == selector {
@@ -475,6 +510,7 @@ import Foundation
475510
receiptKeys.removeAll()
476511
pair = nil
477512
status = ""
513+
receiptNotice = nil
478514
note(.notSelected)
479515
}
480516

‎Sources/App/AppDelegate.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
2525
AppDelegate.shared = self
2626

2727
setUpMainMenu()
28-
if !TTSRuntime.isPreview {
28+
if TTSRuntime.registersSystemIntegration {
2929
registerServices()
3030
registerHotKeys()
3131
}

‎Sources/App/AppState.swift‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,14 @@ final class AppState: ObservableObject {
9494
let agentAccess = AgentSessionController()
9595
private static let agentPresetURL = URL(fileURLWithPath: Secrets.appSupportDir)
9696
.appendingPathComponent("agent-preset-instructions-v1.json")
97-
@Published private(set) var agentPresetInstructions = (try? AgentPresetInstructions.read(at: AppState.agentPresetURL)) ?? [:]
97+
private static let storedPresets = Result { try AgentPresetInstructions.read(at: agentPresetURL) }
98+
@Published private(set) var agentPresetInstructions = (try? AppState.storedPresets.get()) ?? [:]
99+
/// A damaged override file is not the same as "never customized": the saved text
100+
/// is unknown, so built-in instructions are not shared until a save succeeds.
101+
@Published private(set) var agentPresetUnreadable: Bool = {
102+
if case .failure = AppState.storedPresets { return true }
103+
return false
104+
}()
98105

99106
func saveAgentPresetInstruction(_ selector: String, expected: UUID, text: String) throws {
100107
guard LocalInstructionProfile.Name(rawValue: selector) != nil,
@@ -103,6 +110,7 @@ final class AppState: ObservableObject {
103110
expectedOverride: agentPresetInstructions[selector],
104111
at: Self.agentPresetURL)
105112
agentPresetInstructions = saved
113+
agentPresetUnreadable = false
106114
invalidatePreset(selector)
107115
}
108116

@@ -111,6 +119,7 @@ final class AppState: ObservableObject {
111119

112120
func agentSnapshot(_ selector: String) -> AgentInstructionSnapshot? {
113121
if let builtin = LocalInstructionProfile.Name(rawValue: selector) {
122+
guard !agentPresetUnreadable else { return nil }
114123
let text = agentPresetInstructions[selector] ?? instructionText(builtin)
115124
if let old = presetSnapshots[selector], AgentBytes.same(old.text, text) { return old }
116125
let snapshot = AgentInstructionSnapshot(selector: selector, generation: UUID(), text: text)
@@ -145,9 +154,9 @@ final class AppState: ObservableObject {
145154

146155
/// The external agent has already done the text work. Only the current
147156
/// voice engine may be used, and only on this explicit editor action.
148-
func playExplanationDraft(displayOnly: Bool = false) {
157+
func playExplanationDraft(displayOnly: Bool = false, expectedDocumentID: String? = nil) {
149158
guard !TTSRuntime.isPreview, !isBusy, !explaining, !normalizing,
150-
let input = explanationDrafts.playback(displayOnly: displayOnly),
159+
let input = explanationDrafts.playback(displayOnly: displayOnly, expectedDocumentID: expectedDocumentID),
151160
AgentBytes.safeForSpeech(input.speech) else { return }
152161
playbackMode = .explain
153162
synthesize(input.speech, displayText: input.display, preserveLiteral: true)

‎Sources/Core/AgentInstructionEditing.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ enum AgentPresetInstructions {
7171
let payload = try JSONEncoder().encode(current)
7272
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
7373
try payload.write(to: url, options: .atomic)
74+
// Instruction text is private to this account, like the catalog beside it.
75+
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
7476
return current
7577
}
7678
}

0 commit comments

Comments
 (0)