@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
swift 293 lines 14.3 KB
Raw
1 import UniformTypeIdentifiers
2 import UIKit
3
4 func check(_ passed: Bool, _ message: String) {
5 if !passed {
6 FileHandle.standardError.write(Data((message + "\n").utf8))
7 exit(1)
8 }
9 }
10
11 extension T3ComposerEditorView {
12 var editor: UITextView { textView }
13 var text: String { textView.serializedText() }
14 func chip(at location: Int) -> NSTextAttachment? {
15 textView.textStorage.attribute(.attachment, at: location, effectiveRange: nil) as? NSTextAttachment
16 }
17 }
18
19 func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false, tokensJson: String = "[]") -> String {
20 let payload: [String: Any] = [
21 "value": value,
22 "selection": NSNull(),
23 "tokensJson": tokensJson,
24 "mostRecentEventCount": revision,
25 "isNativeEcho": isNativeEcho,
26 "resetGeneration": resetGeneration,
27 ]
28 return String(data: try! JSONSerialization.data(withJSONObject: payload), encoding: .utf8)!
29 }
30
31 func replace(_ view: T3ComposerEditorView, _ target: String, with replacement: String) {
32 let editor = view.editor
33 let location = (editor.text as NSString).range(of: target).location
34 let start = editor.position(from: editor.beginningOfDocument, offset: location)!
35 let end = editor.position(from: start, offset: (target as NSString).length)!
36 editor.replace(editor.textRange(from: start, to: end)!, withText: replacement)
37 }
38
39 func mention(_ label: String, at start: Int, source: String = "@README.md") -> String {
40 #"[{"type":"mention","source":"\#(source)","label":"\#(label)","start":\#(start),"end":\#(start + source.utf16.count)}]"#
41 }
42
43 func makeEditor(_ value: String, tokensJson: String = "[]") -> T3ComposerEditorView {
44 let view = T3ComposerEditorView()
45 view.frame = CGRect(x: 0, y: 0, width: 320, height: 200)
46 view.setControlledDocumentJson(document(value, revision: 0, tokensJson: tokensJson))
47 check(view.text == value, "Initial controlled value was not applied")
48 return view
49 }
50
51 // A send clears the draft after an autocorrection the parent had not received yet.
52 do {
53 let view = makeEditor("hello wrold")
54 replace(view, "wrold", with: "world")
55 let corrected = view.onComposerChange.payloads.last
56 check(corrected?["value"] as? String == "hello world", "Autocorrection did not emit a change")
57 check(corrected?["eventCount"] as? Int == 1, "Autocorrection did not advance the native revision")
58 view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 1))
59 check(view.text == "", "Send clear lost to an autocorrection the parent had not seen: \(view.text)")
60 check(corrected?["resetGeneration"] as? Int == 0, "Pre-clear native event must carry the old reset generation")
61 view.editor.insertText("n")
62 let typed = view.onComposerChange.payloads.last
63 check(typed?["value"] as? String == "n", "Typing after the clear did not start from empty")
64 check(typed?["resetGeneration"] as? Int == 1, "Typing after the clear must carry the new reset generation")
65 check(typed?["eventCount"] as? Int == 1, "Typing after the clear must follow the parent's revision")
66 }
67
68 // An attachment-only send can reset an empty JS draft before a native keystroke is delivered.
69 do {
70 let view = makeEditor("")
71 view.editor.insertText("x")
72 view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 1, isNativeEcho: true))
73 check(view.text == "", "An echo-marked reset retained an undelivered keystroke: \(view.text)")
74 view.editor.insertText("n")
75 check(view.text == "n", "Typing after an echo-marked reset restored the previous keystroke")
76 view.setControlledDocumentJson(document("", revision: 1, resetGeneration: 1, isNativeEcho: true))
77 check(view.text == "n", "An ordinary mismatched echo overwrote newer native typing")
78 }
79
80 // Moving the editor to another draft can lower the parent's reset generation; that payload stays ordinary.
81 do {
82 let view = makeEditor("draft a")
83 view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 2))
84 view.setControlledDocumentJson(document("draft b", revision: 0, resetGeneration: 1))
85 check(view.text == "draft b", "A lower reset generation was rejected")
86 view.editor.insertText("!")
87 check(
88 view.onComposerChange.payloads.last?["resetGeneration"] as? Int == 2,
89 "A lower reset generation rewound the editor's"
90 )
91 }
92
93 // Without a reset, a payload behind the native revision still loses to newer typing.
94 do {
95 let view = makeEditor("ab")
96 view.editor.selectedRange = NSRange(location: 2, length: 0)
97 view.editor.insertText("c")
98 view.setControlledDocumentJson(document("ab", revision: 0))
99 check(view.text == "abc", "A stale controlled value overwrote newer native typing")
100 }
101
102 // A send clear during an IME composition must not come back when the composition commits.
103 do {
104 let view = makeEditor("hello ")
105 view.editor.selectedRange = NSRange(location: 6, length: 0)
106 view.editor.setMarkedText("wor", selectedRange: NSRange(location: 3, length: 0))
107 check(view.editor.markedTextRange != nil, "Harness could not start a composition")
108 let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
109 view.setControlledDocumentJson(document("", revision: revision, resetGeneration: 1))
110 view.editor.unmarkText()
111 check(view.text == "", "Send clear lost to a committed composition: \(view.text)")
112 check(
113 !view.onComposerChange.payloads.contains { ($0["value"] as? String)?.contains("hello") == true && ($0["resetGeneration"] as? Int) == 1 },
114 "Committed composition republished the sent draft"
115 )
116 }
117
118 // An echo that only shifts a chip keeps the rendered text; moving or relabeling the chip redraws it.
119 do {
120 let draft = "hi! @README.md @README.md"
121 let view = makeEditor("hi @README.md @README.md", tokensJson: mention("README.md", at: 3))
122 let rendered = view.chip(at: 3)
123 check(rendered != nil, "Harness could not render the chip")
124 view.editor.selectedRange = NSRange(location: 2, length: 0)
125 view.editor.insertText("!")
126 let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
127 view.setControlledDocumentJson(document(draft, revision: revision, isNativeEcho: true, tokensJson: mention("README.md", at: 4)))
128 check(view.chip(at: 4) === rendered, "An echo that only moved a chip replaced the text")
129 view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 4)))
130 check((view.chip(at: 4) as? ComposerTextAttachment)?.label == "Readme", "A relabeled chip was not redrawn")
131 view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 15)))
132 check(view.chip(at: 4) == nil && view.chip(at: 15) != nil, "A chip moved to another copy of its source stayed on the old one")
133 }
134
135 // A chip source that changes only in Unicode normalization is rebuilt from the new text.
136 do {
137 let view = makeEditor("@\u{00E9}", tokensJson: mention("e", at: 0, source: "@\u{00E9}"))
138 view.setControlledDocumentJson(document("@e\u{0301}", revision: 0, tokensJson: mention("e", at: 0, source: "@e\u{0301}")))
139 check(view.text.utf16.elementsEqual("@e\u{0301}".utf16), "A renormalized chip source kept the old text")
140 }
141
142 // The placeholder label is hidden from VoiceOver, so the text view must carry it.
143 do {
144 let view = makeEditor("")
145 view.setPlaceholder("Ask anything")
146 check(view.editor.accessibilityLabel == "Ask anything", "VoiceOver label: \(String(describing: view.editor.accessibilityLabel))")
147 }
148
149 // Cutting a chip is undoable: Undo restores the chip and tells the parent, Redo removes it again.
150 // The parent echoes each edit with its re-derived chips; those echoes must not rebuild the text.
151 do {
152 let view = makeEditor("hi @README.md ok", tokensJson: mention("README.md", at: 3))
153 func echo() {
154 let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
155 let chips = view.text.contains("@README.md") ? mention("README.md", at: 3) : "[]"
156 view.setControlledDocumentJson(document(view.text, revision: revision, isNativeEcho: true, tokensJson: chips))
157 }
158 view.editor.selectedRange = NSRange(location: 3, length: 2)
159 view.editor.cut(nil)
160 check(view.text == "hi ok", "Cut left the selection behind: \(view.text)")
161 check(view.onComposerChange.payloads.last?["value"] as? String == "hi ok", "Cut did not emit the new value")
162 echo()
163 view.editor.undoManager?.undo()
164 check(view.text == "hi @README.md ok", "Undo did not restore the cut text: \(view.text)")
165 let restored = view.chip(at: 3)
166 check(restored is ComposerTextAttachment, "Undo did not restore the cut chip")
167 check(view.onComposerChange.payloads.last?["value"] as? String == "hi @README.md ok", "Undo did not emit the restored value")
168 echo()
169 check(view.chip(at: 3) === restored, "The parent's echo of the restored chip rebuilt the text and dropped Redo")
170 view.editor.undoManager?.redo()
171 check(view.text == "hi ok", "Redo did not cut again: \(view.text)")
172 }
173
174 print("composer editor tests passed")
175
176 private let dropEditor = ComposerTextView()
177 private let image = UIGraphicsImageRenderer(size: CGSize(width: 8, height: 8)).image { context in
178 UIColor.red.setFill()
179 context.fill(CGRect(x: 0, y: 0, width: 8, height: 8))
180 }
181 private let imageProvider = NSItemProvider(object: image)
182 private let pngProvider = NSItemProvider(item: image.pngData()! as NSData, typeIdentifier: UTType.png.identifier)
183 private let textProvider = NSItemProvider(object: "plain text" as NSString)
184 private let fileProvider = NSItemProvider(item: Data("file".utf8) as NSData, typeIdentifier: UTType.data.identifier)
185
186 check(dropEditor.canPaste([imageProvider]), "An image drag must reach the composer's UITextDropDelegate")
187 check(dropEditor.canPaste([pngProvider]), "A PNG representation must reach the image drop handler")
188 check(dropEditor.canPaste([imageProvider, pngProvider]), "A multi-image drag must be accepted")
189
190 private let defaultEditor = UITextView()
191 for providers in [[textProvider], [], [fileProvider], [imageProvider, textProvider], [imageProvider, fileProvider]] {
192 check(dropEditor.canPaste(providers) == defaultEditor.canPaste(providers), "Non-image-only sessions must retain UIKit behavior")
193 }
194
195 dropEditor.isReadOnly = true
196 check(!dropEditor.canPaste([imageProvider]), "A read-only composer must reject image drops")
197 dropEditor.isReadOnly = false
198 dropEditor.isEditable = false
199 check(!dropEditor.canPaste([imageProvider]), "A noneditable composer must reject image drops")
200 dropEditor.isEditable = true
201 check(dropEditor.canPaste([imageProvider]), "An unlocked composer must accept image drops again")
202 print("Composer image-drop eligibility checks passed")
203
204 private final class ImmediateImageProvider: NSItemProvider {
205 let image: UIImage
206 private(set) var loadCount = 0
207
208 init(image: UIImage) {
209 self.image = image
210 super.init()
211 registerObject(image, visibility: .all)
212 }
213
214 override func loadObject(
215 ofClass aClass: NSItemProviderReading.Type,
216 completionHandler: @escaping @Sendable (NSItemProviderReading?, Error?) -> Void
217 ) -> Progress {
218 loadCount += 1
219 completionHandler(image, nil)
220 return Progress(totalUnitCount: 1)
221 }
222 }
223
224 private let pasteEditor = ComposerTextView()
225 private let pasteProvider = ImmediateImageProvider(image: image)
226 private var pastedImages: [[String]] = []
227 pasteEditor.text = "Keep this draft"
228 pasteEditor.onPasteImages = { pastedImages.append($0) }
229 pasteEditor.paste(itemProviders: [pasteProvider])
230
231 for readOnly in [true, false] {
232 let lockedEditor = ComposerTextView()
233 let provider = ImmediateImageProvider(image: image)
234 lockedEditor.isReadOnly = readOnly
235 lockedEditor.isEditable = readOnly
236 lockedEditor.paste(itemProviders: [provider])
237 check(provider.loadCount == 0, "Locked inputs must not load pasted image providers")
238 }
239
240 func interceptedPaste(_ items: [String]) -> String? {
241 let savedItems = UIPasteboard.general.items
242 defer { UIPasteboard.general.items = savedItems }
243 let editor = ComposerTextView()
244 editor.textPasteThresholdBytes = 32 * 1024
245 var intercepted: String?
246 editor.onPasteText = { text, _ in intercepted = text }
247 UIPasteboard.general.items = items.map { [UTType.utf8PlainText.identifier: $0] }
248 editor.paste(nil)
249 return intercepted
250 }
251 let halfA = String(repeating: "A", count: 20_000)
252 let halfB = String(repeating: "B", count: 20_000)
253 check(interceptedPaste([halfA, halfB]) == halfA + halfB, "Text items that together reach the threshold must fold")
254
255 // Two-frame animated GIF: a mixed paste keeps the GIF's original bytes and the still image's PNG, in order.
256 private let gifBytes = Data(base64Encoded: "R0lGODlhAQABAIEAAP8AAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAAIBAABBAQAIfkEAAoAAAAsAAAAAAEAAQCBAP8AAAAAAAAAAAAACAQAAQQEADs=")!
257 private let gifProvider = NSItemProvider()
258 gifProvider.registerDataRepresentation(forTypeIdentifier: UTType.gif.identifier, visibility: .all) { completion in
259 completion(gifBytes, nil)
260 return nil
261 }
262 private let gifEditor = ComposerTextView()
263 gifEditor.onPasteImages = { urls in
264 let files = urls.compactMap(URL.init(string:))
265 let contents = files.compactMap { try? Data(contentsOf: $0) }
266 files.forEach { try? FileManager.default.removeItem(at: $0) }
267 check(files.map(\.pathExtension) == ["gif", "png"], "A mixed paste must keep each image's format, in order: \(urls)")
268 check(contents.first == gifBytes, "A pasted animated GIF must keep its original bytes")
269 check(contents.count == 2 && contents[1] == image.pngData(), "The still image beside a GIF must still attach as PNG")
270 print("Composer GIF-paste checks passed")
271 exit(0)
272 }
273
274 // Inline provider completion places the attachment callback before this main-queue check.
275 DispatchQueue.main.async {
276 check(pastedImages.count == 1, "An accepted provider-based paste must emit exactly one attachment batch")
277 check(pastedImages[0].count == 1, "One pasted image must produce one attachment")
278 guard let url = URL(string: pastedImages[0][0]),
279 let data = try? Data(contentsOf: url),
280 let decoded = UIImage(data: data) else {
281 check(false, "Provider-based paste must create a readable image file")
282 return
283 }
284 try? FileManager.default.removeItem(at: url)
285 check(decoded.cgImage?.width == image.cgImage?.width &&
286 decoded.cgImage?.height == image.cgImage?.height && data == image.pngData(),
287 "The attachment must contain the pasted image's pixels")
288 check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text")
289 print("Composer provider-paste checks passed")
290 check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path")
291 gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)])
292 }
293 dispatchMain()