@reticlehq/computer 0.0.0-stage → 3.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +237 -2
  4. package/bin/attach.mjs +333 -0
  5. package/dist/attach.d.ts +105 -0
  6. package/dist/attach.js +234 -0
  7. package/dist/channels.d.ts +42 -0
  8. package/dist/channels.js +46 -0
  9. package/dist/computer-realm.d.ts +54 -0
  10. package/dist/computer-realm.js +487 -0
  11. package/dist/doctor.d.ts +32 -0
  12. package/dist/doctor.js +42 -0
  13. package/dist/driver.d.ts +227 -0
  14. package/dist/driver.js +73 -0
  15. package/dist/effect.d.ts +60 -0
  16. package/dist/effect.js +158 -0
  17. package/dist/files.d.ts +16 -0
  18. package/dist/files.js +40 -0
  19. package/dist/hud/port.d.ts +44 -0
  20. package/dist/hud/port.js +6 -0
  21. package/dist/index.d.ts +34 -0
  22. package/dist/index.js +22 -0
  23. package/dist/lines.d.ts +34 -0
  24. package/dist/lines.js +80 -0
  25. package/dist/mac/from-ax.d.ts +27 -0
  26. package/dist/mac/from-ax.js +275 -0
  27. package/dist/mac/mac-driver.d.ts +42 -0
  28. package/dist/mac/mac-driver.js +355 -0
  29. package/dist/mac/mac-hud.d.ts +10 -0
  30. package/dist/mac/mac-hud.js +142 -0
  31. package/dist/peer/act-effect.d.ts +9 -0
  32. package/dist/peer/act-effect.js +13 -0
  33. package/dist/peer/commands.d.ts +87 -0
  34. package/dist/peer/commands.js +811 -0
  35. package/dist/peer/form.d.ts +62 -0
  36. package/dist/peer/form.js +103 -0
  37. package/dist/peer/link-switch.d.ts +12 -0
  38. package/dist/peer/link-switch.js +38 -0
  39. package/dist/peer/peer.d.ts +43 -0
  40. package/dist/peer/peer.js +216 -0
  41. package/dist/peer/pointer.d.ts +97 -0
  42. package/dist/peer/pointer.js +289 -0
  43. package/dist/peer/scroll.d.ts +12 -0
  44. package/dist/peer/scroll.js +157 -0
  45. package/dist/peer/seen.d.ts +18 -0
  46. package/dist/peer/seen.js +61 -0
  47. package/dist/peer/select.d.ts +27 -0
  48. package/dist/peer/select.js +78 -0
  49. package/dist/peer/window.d.ts +25 -0
  50. package/dist/peer/window.js +111 -0
  51. package/dist/ui-node.d.ts +93 -0
  52. package/dist/ui-node.js +192 -0
  53. package/dist/win/helper-launch.d.ts +16 -0
  54. package/dist/win/helper-launch.js +57 -0
  55. package/native/linux/Dockerfile +22 -0
  56. package/native/linux/reticle-atspi.py +933 -0
  57. package/native/linux/sandbox.mjs +127 -0
  58. package/native/mac/build/reticle-ax +0 -0
  59. package/native/mac/build/reticle-hud +0 -0
  60. package/native/mac/hud.swift +749 -0
  61. package/native/mac/reticle-ax.swift +1786 -0
  62. package/native/win/reticle-uia.ps1 +620 -0
  63. package/package.json +65 -3
@@ -0,0 +1,749 @@
1
+ // reticle-hud: what the person at the machine sees of the realm.
2
+ //
3
+ // - A pointer of the realm's own: an arrow, as a mouse has, in the colour of Reticle. It goes
4
+ // to the element the realm acts on, and a ring spreads from its tip when the realm acts. The
5
+ // pointer of the person does not move for an action in the background, so without this
6
+ // nothing on the screen says where the realm is.
7
+ // - The HUD, as in a browser. At rest it is one circle with the mark and a ring in the colour
8
+ // of the state. A press opens it: a panel with the mark and the name, a row with the dot of
9
+ // the state, the action that runs, and the buttons to pause and to stop, the last actions with
10
+ // what each one did, and a toolbar under it. The same parts, in the same places, as in a browser.
11
+ //
12
+ // The program draws and reports. It never reads an application and never acts on one.
13
+ //
14
+ // One line of JSON on standard input for each thing to show:
15
+ // {"t":"app","name":"Notes"}
16
+ // {"t":"move","x":120,"y":300} the middle of the element, in points from the top left
17
+ // {"t":"act","text":"press button \"Save\""}
18
+ // {"t":"effect","text":"2 changes","kind":"ok"} kind: ok | none | refused
19
+ // {"t":"glow","x":80,"y":80,"w":450,"h":320} a ring round the window the realm works in
20
+ // {"t":"hide"} the pointer goes away
21
+ // {"t":"turn","state":"ended","tone":"ask","text":"Type the 2FA code"} the person's turn
22
+ // One line on standard output when the person presses a button: {"paused":true} or false for
23
+ // the pause, {"stopped":true} for the stop, and {"done":true} at the end of their turn. After a
24
+ // stop the realm leaves the application.
25
+ // The program ends when standard input closes.
26
+ import AppKit
27
+
28
+ func hex(_ value: UInt32, _ alpha: CGFloat = 1) -> NSColor {
29
+ NSColor(
30
+ srgbRed: CGFloat((value >> 16) & 0xff) / 255, green: CGFloat((value >> 8) & 0xff) / 255,
31
+ blue: CGFloat(value & 0xff) / 255, alpha: alpha)
32
+ }
33
+
34
+ /// The design values, in one place. They are the tokens of the HUD in the browser
35
+ /// (`presenter-design-tokens.ts`, `presenter-shell-styles.ts`): the same ground, text, brand
36
+ /// colour, state colours, radii, sizes and motion.
37
+ enum Token {
38
+ static let ground = hex(0x0b0b0c)
39
+ static let surface = hex(0x151417, 0.9)
40
+ static let hover = hex(0xffffff, 0.12)
41
+ static let border = hex(0x3a3941)
42
+ static let text = hex(0xf5f3ef)
43
+ static let muted = hex(0xa6a29a)
44
+ static let faint = hex(0x8b867d)
45
+ static let brand = hex(0xf0872e)
46
+ static let active = hex(0x3b82f6)
47
+ static let idle = hex(0xeab308)
48
+ static let ended = hex(0xef4444)
49
+ /// The body of the pointer: near black, so the moving edge in the two colours stands out.
50
+ static let pointerFill = hex(0x0b0b0c)
51
+ /// The width of the moving edge of the pointer, and the time of one turn of its colours.
52
+ static let pointerEdge: CGFloat = 2.2
53
+ static let pointerTurn = 2.0
54
+ static let radiusLarge: CGFloat = 14
55
+ static let space1: CGFloat = 4
56
+ static let space2: CGFloat = 8
57
+ static let space3: CGFloat = 12
58
+ static let edge: CGFloat = 20
59
+ static let extraSmall = NSFont.systemFont(ofSize: 11, weight: .regular)
60
+ static let small = NSFont.systemFont(ofSize: 12, weight: .regular)
61
+ static let base = NSFont.systemFont(ofSize: 13, weight: .semibold)
62
+ static let dockWidth: CGFloat = 320
63
+ static let toolbarHeight: CGFloat = 44
64
+ static let control: CGFloat = 36
65
+ static let rowHeight: CGFloat = 34
66
+ static let rows = 4
67
+ static let fab: CGFloat = 44
68
+ static let headerHeight: CGFloat = 40
69
+ static let statusHeight: CGFloat = 38
70
+ static let square: CGFloat = 26
71
+ static let radiusSmall: CGFloat = 6
72
+ static let wash = 0.18
73
+ /// The glide of the pointer to a target when the realm gives no time for it.
74
+ static let glide = 0.12
75
+ static let ease = CAMediaTimingFunction(controlPoints: 0.22, 1, 0.36, 1)
76
+ static let ripple = 0.45
77
+ static let glowDepth = 22
78
+ static let glowIn = 0.25
79
+ static let glowRest = 1.4
80
+ static let pointerBox: CGFloat = 64
81
+ /// The tip of the arrow, from the top left of its box: the ring spreads from here.
82
+ static let tip = NSPoint(x: 20, y: 20)
83
+ }
84
+
85
+ /// The arrow of a mouse: a black body with an edge that goes from orange to blue, and the colours
86
+ /// move round the edge all the time, so a person sees at once which pointer is Reticle's. A ring
87
+ /// spreads from its tip when the realm acts, as the ripple does in a browser.
88
+ final class ArrowView: NSView {
89
+ var ring: CGFloat = 0 { didSet { needsDisplay = true } }
90
+ var ringColor = Token.text
91
+ /// Where the colours of the edge are in their turn, 0 to 1.
92
+ var turn: CGFloat = 0
93
+ var turning: Timer?
94
+ override var isFlipped: Bool { true }
95
+
96
+ override func viewDidMoveToWindow() {
97
+ super.viewDidMoveToWindow()
98
+ turning?.invalidate()
99
+ let started = Date()
100
+ turning = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] _ in
101
+ // Drawn again only while the pointer can be seen: a hidden pointer costs nothing.
102
+ guard let self, (self.window?.alphaValue ?? 0) > 0 else { return }
103
+ self.turn = CGFloat(Date().timeIntervalSince(started) / Token.pointerTurn)
104
+ .truncatingRemainder(dividingBy: 1)
105
+ self.needsDisplay = true
106
+ }
107
+ }
108
+ override func draw(_ dirtyRect: NSRect) {
109
+ let tip = Token.tip
110
+ if ring > 0 {
111
+ let reach = 6 + ring * 18
112
+ ringColor.withAlphaComponent(0.55 * (1 - ring)).setStroke()
113
+ let circle = NSBezierPath(
114
+ ovalIn: NSRect(x: tip.x - reach, y: tip.y - reach, width: reach * 2, height: reach * 2))
115
+ circle.lineWidth = 2
116
+ circle.stroke()
117
+ }
118
+ // The outline of a pointer: the tip, down the left edge, the notch, the tail, and back.
119
+ let shape: [(CGFloat, CGFloat)] = [
120
+ (0, 0), (0, 21), (5.6, 16), (9.4, 24.6), (13, 23), (9.2, 14.6), (16.4, 14.6),
121
+ ]
122
+ let arrow = NSBezierPath()
123
+ let outline = CGMutablePath()
124
+ for (index, point) in shape.enumerated() {
125
+ let at = NSPoint(x: tip.x + point.0, y: tip.y + point.1)
126
+ if index == 0 {
127
+ arrow.move(to: at)
128
+ outline.move(to: at)
129
+ } else {
130
+ arrow.line(to: at)
131
+ outline.addLine(to: at)
132
+ }
133
+ }
134
+ arrow.close()
135
+ outline.closeSubpath()
136
+ NSGraphicsContext.saveGraphicsState()
137
+ let shadow = NSShadow()
138
+ shadow.shadowColor = NSColor.black.withAlphaComponent(0.45)
139
+ shadow.shadowBlurRadius = 5
140
+ shadow.shadowOffset = NSSize(width: 0, height: -2)
141
+ shadow.set()
142
+ Token.pointerFill.setFill()
143
+ arrow.fill()
144
+ NSGraphicsContext.restoreGraphicsState()
145
+ // The edge: the outline as a band, filled with orange to blue to orange at an angle that
146
+ // turns, so the colours run round the pointer.
147
+ guard let context = NSGraphicsContext.current?.cgContext,
148
+ let gradient = NSGradient(colors: [Token.brand, Token.active, Token.brand])
149
+ else { return }
150
+ let edge = outline.copy(
151
+ strokingWithWidth: Token.pointerEdge, lineCap: .round, lineJoin: .round, miterLimit: 10)
152
+ NSGraphicsContext.saveGraphicsState()
153
+ context.addPath(edge)
154
+ context.clip()
155
+ gradient.draw(in: arrow.bounds.insetBy(dx: -4, dy: -4), angle: turn * 360)
156
+ NSGraphicsContext.restoreGraphicsState()
157
+ }
158
+ }
159
+
160
+ /// The glow round the window the realm works in, as the glow at the edge of a page in a
161
+ /// browser: a thin ring and a soft light inside it, in the colour of the state.
162
+ final class GlowView: NSView {
163
+ var color = Token.active { didSet { needsDisplay = true } }
164
+ override func draw(_ dirtyRect: NSRect) {
165
+ let corner = Token.radiusLarge - 4
166
+ // The soft light: rings that fade toward the inside.
167
+ for step in 0..<Token.glowDepth {
168
+ let inset = CGFloat(step) + 1
169
+ let part = 1 - CGFloat(step) / CGFloat(Token.glowDepth)
170
+ color.withAlphaComponent(0.26 * part * part).setStroke()
171
+ let ring = NSBezierPath(
172
+ roundedRect: bounds.insetBy(dx: inset, dy: inset), xRadius: corner, yRadius: corner)
173
+ ring.lineWidth = 1
174
+ ring.stroke()
175
+ }
176
+ color.withAlphaComponent(0.7).setStroke()
177
+ let edge = NSBezierPath(
178
+ roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: corner, yRadius: corner)
179
+ edge.lineWidth = 2
180
+ edge.stroke()
181
+ }
182
+ }
183
+
184
+ /// A picture that is only a picture: a click goes through it to the button it lies on, and it is
185
+ /// no element of its own. The mark on the circle took the click of a person, and the circle did
186
+ /// not open.
187
+ final class Picture: NSImageView {
188
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
189
+ override func isAccessibilityElement() -> Bool { false }
190
+ }
191
+
192
+ /// A round button of the toolbar: clear, and lighter under the pointer.
193
+ final class RoundButton: NSButton {
194
+ override func updateTrackingAreas() {
195
+ trackingAreas.forEach(removeTrackingArea)
196
+ addTrackingArea(
197
+ NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeAlways], owner: self))
198
+ }
199
+ override func mouseEntered(with event: NSEvent) { layer?.backgroundColor = Token.hover.cgColor }
200
+ override func mouseExited(with event: NSEvent) { layer?.backgroundColor = NSColor.clear.cgColor }
201
+ }
202
+
203
+ /// An icon of the HUD, drawn as lines in the colour of the text.
204
+ func icon(_ size: CGFloat, _ draw: @escaping (NSBezierPath) -> Void, fill: Bool = false) -> NSImage {
205
+ NSImage(size: NSSize(width: size, height: size), flipped: false) { _ in
206
+ let path = NSBezierPath()
207
+ path.lineWidth = 1.5
208
+ path.lineCapStyle = .round
209
+ path.lineJoinStyle = .round
210
+ draw(path)
211
+ if fill {
212
+ Token.text.setFill()
213
+ path.fill()
214
+ } else {
215
+ Token.text.setStroke()
216
+ path.stroke()
217
+ }
218
+ return true
219
+ }
220
+ }
221
+
222
+ final class Hud: NSObject, NSApplicationDelegate {
223
+ var pointer: NSWindow!
224
+ let arrow = ArrowView(
225
+ frame: NSRect(x: 0, y: 0, width: Token.pointerBox, height: Token.pointerBox))
226
+ var glow: NSWindow!
227
+ let glowView = GlowView()
228
+ var glowRest: Timer?
229
+ var panel: NSPanel!
230
+ // At rest: the circle. Open: the panel and the toolbar.
231
+ let fabHolder = NSView()
232
+ let dockHolder = NSView()
233
+ var fab: RoundButton!
234
+ let card = NSView()
235
+ let wash = CAGradientLayer()
236
+ let dot = NSView()
237
+ let doing = NSTextField(labelWithString: "Ready")
238
+ let app = NSTextField(labelWithString: "")
239
+ var pause: RoundButton!
240
+ var stop: RoundButton!
241
+ var empty: [NSTextField] = []
242
+ var log: [(action: NSTextField, effect: NSTextField)] = []
243
+ var lines: [(action: String, effect: String, kind: String)] = []
244
+ var state = Token.idle
245
+ var open = false
246
+ var paused = false
247
+ var stopped = false
248
+ /// The agent asked the person for something (a 2FA code, a captcha): the Pause button is "Done".
249
+ var asking = false
250
+ var rippling: Timer?
251
+
252
+ /// The colour of the state: the realm acts, the realm waits or is paused, the action was refused.
253
+ func setState(_ color: NSColor) {
254
+ state = color
255
+ dot.layer?.backgroundColor = color.cgColor
256
+ fab.layer?.borderColor = color.withAlphaComponent(0.85).cgColor
257
+ fab.layer?.shadowColor = color.cgColor
258
+ card.layer?.borderColor = color.blended(withFraction: 0.6, of: Token.border)?.cgColor
259
+ wash.colors = [
260
+ (Token.ground.blended(withFraction: Token.wash, of: color) ?? Token.ground).cgColor,
261
+ Token.ground.cgColor,
262
+ ]
263
+ }
264
+
265
+ func text(_ field: NSTextField, _ font: NSFont, _ color: NSColor, _ frame: NSRect, in view: NSView) {
266
+ field.font = font
267
+ field.textColor = color
268
+ field.frame = frame
269
+ field.lineBreakMode = .byTruncatingTail
270
+ view.addSubview(field)
271
+ }
272
+
273
+ func round(_ title: String, _ image: NSImage, _ frame: NSRect, _ action: Selector, in view: NSView)
274
+ -> RoundButton
275
+ {
276
+ let button = RoundButton(title: "", target: self, action: action)
277
+ button.isBordered = false
278
+ button.wantsLayer = true
279
+ button.image = image
280
+ button.frame = frame
281
+ button.layer?.cornerRadius = min(frame.width, frame.height) / 2
282
+ button.setAccessibilityLabel(title)
283
+ view.addSubview(button)
284
+ return button
285
+ }
286
+
287
+ /// The place of the window: the corner at the bottom right, as in a browser. The circle and
288
+ /// the open HUD keep the same corner.
289
+ func place() {
290
+ let screen = NSScreen.main?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1200, height: 800)
291
+ let size = open ? dockHolder.frame.size : fabHolder.frame.size
292
+ let right = panel.frame.width > 0 ? panel.frame.maxX : screen.maxX - Token.edge
293
+ let bottom = panel.frame.height > 0 ? panel.frame.minY : screen.minY + Token.edge
294
+ panel.setFrame(
295
+ NSRect(x: right - size.width, y: bottom, width: size.width, height: size.height),
296
+ display: true)
297
+ fabHolder.isHidden = open
298
+ dockHolder.isHidden = !open
299
+ }
300
+
301
+ func applicationDidFinishLaunching(_ notification: Notification) {
302
+ // The pointer: over every window, and a click goes through it to what is under it.
303
+ pointer = NSWindow(
304
+ contentRect: arrow.frame, styleMask: [.borderless], backing: .buffered, defer: false)
305
+ pointer.isOpaque = false
306
+ pointer.backgroundColor = .clear
307
+ pointer.hasShadow = false
308
+ pointer.ignoresMouseEvents = true
309
+ pointer.level = .screenSaver
310
+ pointer.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle, .fullScreenAuxiliary]
311
+ pointer.contentView = arrow
312
+ pointer.alphaValue = 0
313
+
314
+ // The glow: a window with nothing in it but the ring, and a click goes through it.
315
+ glow = NSWindow(
316
+ contentRect: .zero, styleMask: [.borderless], backing: .buffered, defer: false)
317
+ glow.isOpaque = false
318
+ glow.backgroundColor = .clear
319
+ glow.hasShadow = false
320
+ glow.ignoresMouseEvents = true
321
+ glow.level = .floating
322
+ glow.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle, .fullScreenAuxiliary]
323
+ glow.contentView = glowView
324
+ glow.alphaValue = 0
325
+
326
+ // The HUD. It floats, it never takes the keyboard, and the person can move it.
327
+ panel = NSPanel(
328
+ contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered,
329
+ defer: false)
330
+ panel.isOpaque = false
331
+ panel.backgroundColor = .clear
332
+ panel.level = .floating
333
+ panel.isMovableByWindowBackground = true
334
+ panel.collectionBehavior = [.canJoinAllSpaces, .ignoresCycle, .fullScreenAuxiliary]
335
+ let root = NSView()
336
+ panel.contentView = root
337
+ root.addSubview(fabHolder)
338
+ root.addSubview(dockHolder)
339
+
340
+ // At rest: one circle, with room round it for its light.
341
+ let room: CGFloat = 12
342
+ fabHolder.frame = NSRect(x: 0, y: 0, width: Token.fab + room * 2, height: Token.fab + room * 2)
343
+ fab = round(
344
+ "Open Reticle", NSImage(), NSRect(x: room, y: room, width: Token.fab, height: Token.fab),
345
+ #selector(toggleOpen), in: fabHolder)
346
+ fab.layer?.backgroundColor = Token.ground.cgColor
347
+ fab.layer?.borderWidth = 1.5
348
+ fab.layer?.shadowOpacity = 0.75
349
+ fab.layer?.shadowRadius = 8
350
+ fab.layer?.shadowOffset = .zero
351
+ fab.layer?.masksToBounds = false
352
+ // The mark is a file beside the source of this program: the same paths as in the browser.
353
+ let markFile = URL(fileURLWithPath: CommandLine.arguments[0])
354
+ .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent(
355
+ "reticle-mark.svg")
356
+ let markImage = NSImage(contentsOf: markFile)
357
+ func mark(_ frame: NSRect, in view: NSView) {
358
+ let image = Picture(frame: frame)
359
+ image.image = markImage
360
+ image.imageScaling = .scaleProportionallyUpOrDown
361
+ view.addSubview(image)
362
+ }
363
+ mark(fab.bounds.insetBy(dx: 11, dy: 11), in: fab)
364
+
365
+ // Open: the card, and the toolbar under it.
366
+ let logHeight = CGFloat(Token.rows) * Token.rowHeight + Token.space2 * 2
367
+ let cardHeight = Token.headerHeight + Token.statusHeight + logHeight
368
+ dockHolder.frame = NSRect(
369
+ x: 0, y: 0, width: Token.dockWidth,
370
+ height: cardHeight + Token.space2 + Token.toolbarHeight)
371
+ card.frame = NSRect(
372
+ x: 0, y: Token.toolbarHeight + Token.space2, width: Token.dockWidth, height: cardHeight)
373
+ card.wantsLayer = true
374
+ card.layer?.cornerRadius = Token.radiusLarge
375
+ card.layer?.borderWidth = 1
376
+ card.layer?.masksToBounds = true
377
+ wash.frame = card.bounds
378
+ wash.startPoint = CGPoint(x: 0.5, y: 1)
379
+ wash.endPoint = CGPoint(x: 0.5, y: 0.35)
380
+ card.layer?.addSublayer(wash)
381
+ dockHolder.addSubview(card)
382
+
383
+ func rule(_ y: CGFloat) {
384
+ let line = NSView(frame: NSRect(x: 0, y: y, width: Token.dockWidth, height: 1))
385
+ line.wantsLayer = true
386
+ line.layer?.backgroundColor = Token.hover.cgColor
387
+ card.addSubview(line)
388
+ }
389
+
390
+ // The header: the mark, the name, the application, and the sign that closes the HUD.
391
+ let headerY = cardHeight - Token.headerHeight
392
+ mark(NSRect(x: Token.space3, y: headerY + 12, width: 16, height: 16), in: card)
393
+ text(
394
+ NSTextField(labelWithString: "Reticle"), Token.base, Token.text,
395
+ NSRect(x: 36, y: headerY + 11, width: 56, height: 18), in: card)
396
+ text(app, Token.small, Token.muted, NSRect(x: 92, y: headerY + 11, width: 170, height: 17), in: card)
397
+ _ = round(
398
+ "Hide",
399
+ icon(16) { path in
400
+ path.move(to: NSPoint(x: 3.5, y: 10))
401
+ path.line(to: NSPoint(x: 8, y: 5.5))
402
+ path.line(to: NSPoint(x: 12.5, y: 10))
403
+ },
404
+ NSRect(x: Token.dockWidth - 36, y: headerY + 7, width: Token.square, height: Token.square),
405
+ #selector(toggleOpen), in: card)
406
+ rule(headerY)
407
+
408
+ // The row of the state: the dot, the action that runs, and the two buttons.
409
+ let statusY = headerY - Token.statusHeight
410
+ dot.frame = NSRect(x: Token.space3, y: statusY + 15, width: 8, height: 8)
411
+ dot.wantsLayer = true
412
+ dot.layer?.cornerRadius = 4
413
+ card.addSubview(dot)
414
+ text(
415
+ doing, Token.small, Token.text,
416
+ NSRect(x: 28, y: statusY + 10, width: Token.dockWidth - 28 - 76, height: 17), in: card)
417
+ func square(_ title: String, _ image: NSImage, _ x: CGFloat, _ action: Selector) -> RoundButton {
418
+ let button = round(
419
+ title, image, NSRect(x: x, y: statusY + 6, width: Token.square, height: Token.square),
420
+ action, in: card)
421
+ button.layer?.cornerRadius = Token.radiusSmall
422
+ button.layer?.borderWidth = 1
423
+ button.layer?.borderColor = Token.hover.cgColor
424
+ return button
425
+ }
426
+ pause = square("Pause", NSImage(), Token.dockWidth - 68, #selector(togglePause))
427
+ stop = square(
428
+ "Stop",
429
+ icon(14) { path in
430
+ path.appendRoundedRect(NSRect(x: 3.5, y: 3.5, width: 7, height: 7), xRadius: 1.5, yRadius: 1.5)
431
+ }, Token.dockWidth - 36, #selector(pressStop))
432
+ setPauseSign()
433
+ rule(statusY)
434
+
435
+ // The last actions, the newest at the bottom, each with what it did. Before the first
436
+ // action: what this window is for, as the panel in a browser says it.
437
+ for row in 0..<Token.rows {
438
+ let y = Token.space2 + CGFloat(Token.rows - 1 - row) * Token.rowHeight
439
+ let action = NSTextField(labelWithString: "")
440
+ let effect = NSTextField(labelWithString: "")
441
+ text(
442
+ action, Token.small, Token.text,
443
+ NSRect(x: Token.space3, y: y + 15, width: Token.dockWidth - Token.space3 * 2, height: 16),
444
+ in: card)
445
+ text(
446
+ effect, Token.extraSmall, Token.muted,
447
+ NSRect(x: Token.space3, y: y + 1, width: Token.dockWidth - Token.space3 * 2, height: 14),
448
+ in: card)
449
+ log.append((action, effect))
450
+ }
451
+ for (index, words) in [
452
+ "Reticle works in this application from the outside.",
453
+ "Each action of your agent shows here, live,",
454
+ "with what it changed.",
455
+ ].enumerated() {
456
+ let line = NSTextField(labelWithString: words)
457
+ line.alignment = .center
458
+ text(
459
+ line, index == 0 ? Token.base : Token.small, index == 0 ? Token.text : Token.muted,
460
+ NSRect(
461
+ x: Token.space3, y: logHeight / 2 + 14 - CGFloat(index) * 20,
462
+ width: Token.dockWidth - Token.space3 * 2, height: 18),
463
+ in: card)
464
+ empty.append(line)
465
+ }
466
+
467
+ // The toolbar: a pill, as in a browser. It has the parts this HUD has: the log, and Hide.
468
+ let bar = NSView(
469
+ frame: NSRect(x: 0, y: 0, width: Token.dockWidth, height: Token.toolbarHeight))
470
+ bar.wantsLayer = true
471
+ bar.layer?.backgroundColor = Token.ground.cgColor
472
+ bar.layer?.cornerRadius = Token.toolbarHeight / 2
473
+ bar.layer?.borderWidth = 1
474
+ bar.layer?.borderColor = Token.border.cgColor
475
+ dockHolder.addSubview(bar)
476
+ func tab(_ title: String, _ image: NSImage, _ x: CGFloat, _ action: Selector?, active: Bool) {
477
+ let holder = NSView(frame: NSRect(x: x, y: 2, width: 64, height: Token.toolbarHeight - 4))
478
+ bar.addSubview(holder)
479
+ let button = round(
480
+ title, image, NSRect(x: 20, y: 16, width: 24, height: 22), action ?? #selector(noop),
481
+ in: holder)
482
+ button.layer?.cornerRadius = Token.radiusSmall
483
+ let name = NSTextField(labelWithString: title)
484
+ name.alignment = .center
485
+ text(
486
+ name, Token.extraSmall, active ? Token.text : Token.muted,
487
+ NSRect(x: 0, y: 4, width: 64, height: 13), in: holder)
488
+ if active {
489
+ let under = NSView(frame: NSRect(x: 24, y: 0, width: 16, height: 2))
490
+ under.wantsLayer = true
491
+ under.layer?.backgroundColor = Token.text.cgColor
492
+ under.layer?.cornerRadius = 1
493
+ holder.addSubview(under)
494
+ }
495
+ }
496
+ tab(
497
+ "Log",
498
+ icon(18) { path in
499
+ path.appendRoundedRect(NSRect(x: 2.5, y: 5, width: 13, height: 9.5), xRadius: 3, yRadius: 3)
500
+ path.move(to: NSPoint(x: 6, y: 5))
501
+ path.line(to: NSPoint(x: 5, y: 2.5))
502
+ path.line(to: NSPoint(x: 9, y: 5))
503
+ }, Token.space3, nil, active: true)
504
+ tab(
505
+ "Hide",
506
+ icon(18) { path in
507
+ path.move(to: NSPoint(x: 4.5, y: 4.5))
508
+ path.line(to: NSPoint(x: 13.5, y: 13.5))
509
+ path.move(to: NSPoint(x: 13.5, y: 4.5))
510
+ path.line(to: NSPoint(x: 4.5, y: 13.5))
511
+ }, Token.dockWidth - 64 - Token.space3, #selector(toggleOpen), active: false)
512
+
513
+ redraw()
514
+ setState(Token.idle)
515
+ place()
516
+ panel.orderFrontRegardless()
517
+
518
+ // One line of JSON for each thing to show. Read off the main thread; draw on it.
519
+ Thread.detachNewThread {
520
+ while let line = readLine() {
521
+ guard let data = line.data(using: .utf8),
522
+ let say = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
523
+ else { continue }
524
+ DispatchQueue.main.async { self.show(say) }
525
+ }
526
+ DispatchQueue.main.async { NSApp.terminate(nil) }
527
+ }
528
+ }
529
+
530
+ @objc func noop() {}
531
+
532
+ /// The circle opens the HUD, and the sign in the header or Hide in the toolbar closes it.
533
+ @objc func toggleOpen() {
534
+ open.toggle()
535
+ place()
536
+ }
537
+
538
+ /// The sign on the button: two bars to pause, a triangle to go on.
539
+ func setPauseSign() {
540
+ let isPaused = paused
541
+ pause.image = icon(14, { path in
542
+ if isPaused {
543
+ path.move(to: NSPoint(x: 4.5, y: 3))
544
+ path.line(to: NSPoint(x: 11, y: 7))
545
+ path.line(to: NSPoint(x: 4.5, y: 11))
546
+ path.close()
547
+ } else {
548
+ path.move(to: NSPoint(x: 5, y: 3.5))
549
+ path.line(to: NSPoint(x: 5, y: 10.5))
550
+ path.move(to: NSPoint(x: 9, y: 3.5))
551
+ path.line(to: NSPoint(x: 9, y: 10.5))
552
+ }
553
+ })
554
+ pause.setAccessibilityLabel(paused ? "Resume" : "Pause")
555
+ }
556
+
557
+ func redraw() {
558
+ let shown = Array(lines.suffix(Token.rows))
559
+ empty.forEach { $0.isHidden = !lines.isEmpty }
560
+ for (row, fields) in log.enumerated() {
561
+ let line = row < shown.count ? shown[row] : ("", "", "none")
562
+ let newest = row == shown.count - 1
563
+ fields.action.stringValue = line.0
564
+ fields.action.textColor = newest ? Token.text : Token.muted
565
+ fields.effect.stringValue = line.1
566
+ fields.effect.textColor =
567
+ line.2 == "refused" ? Token.ended : (line.2 == "ok" ? Token.text : Token.faint)
568
+ }
569
+ }
570
+
571
+ /// The person's turn, from the agent's `yield`: the question shows, and Pause becomes Done.
572
+ func ask(_ question: String) {
573
+ asking = true
574
+ if !open { toggleOpen() }
575
+ doing.stringValue = question.isEmpty ? "Your turn" : "Your turn: \(question)"
576
+ setState(Token.brand)
577
+ pause.action = #selector(pressDone)
578
+ pause.image = icon(14) { path in
579
+ path.move(to: NSPoint(x: 3, y: 7.5))
580
+ path.line(to: NSPoint(x: 6, y: 4.5))
581
+ path.line(to: NSPoint(x: 11, y: 10))
582
+ }
583
+ pause.setAccessibilityLabel("Done")
584
+ panel.orderFrontRegardless()
585
+ }
586
+
587
+ /// The end of the person's turn: Done becomes Pause again.
588
+ func endAsk() {
589
+ asking = false
590
+ pause.action = #selector(togglePause)
591
+ setPauseSign()
592
+ }
593
+
594
+ @objc func pressDone() {
595
+ guard asking, !stopped else { return }
596
+ endAsk()
597
+ doing.stringValue = "Done. The agent goes on."
598
+ setState(Token.idle)
599
+ print("{\"done\":true}")
600
+ fflush(stdout)
601
+ }
602
+
603
+ @objc func togglePause() {
604
+ guard !stopped else { return }
605
+ paused.toggle()
606
+ setPauseSign()
607
+ doing.stringValue = paused ? "Paused by you" : "Ready"
608
+ setState(Token.idle)
609
+ print(paused ? "{\"paused\":true}" : "{\"paused\":false}")
610
+ fflush(stdout)
611
+ }
612
+
613
+ @objc func pressStop() {
614
+ guard !stopped else { return }
615
+ stopped = true
616
+ stop.isEnabled = false
617
+ pause.isEnabled = false
618
+ doing.stringValue = "Stopped by you"
619
+ setState(Token.ended)
620
+ pointer.animator().alphaValue = 0
621
+ glow.animator().alphaValue = 0
622
+ print("{\"stopped\":true}")
623
+ fflush(stdout)
624
+ }
625
+
626
+ /// A ring that spreads from the tip of the pointer, once.
627
+ func ripple(_ color: NSColor) {
628
+ rippling?.invalidate()
629
+ arrow.ringColor = color
630
+ let started = Date()
631
+ rippling = Timer.scheduledTimer(withTimeInterval: 1.0 / 60, repeats: true) { timer in
632
+ let part = CGFloat(Date().timeIntervalSince(started) / Token.ripple)
633
+ self.arrow.ring = part >= 1 ? 0 : max(part, 0.01)
634
+ if part >= 1 { timer.invalidate() }
635
+ }
636
+ }
637
+
638
+ func show(_ say: [String: Any]) {
639
+ switch say["t"] as? String {
640
+ case "app":
641
+ app.stringValue = say["name"] as? String ?? ""
642
+ // While computer use is live, its pointer is on the desktop: it comes at the join, where
643
+ // the person's own pointer is, and it stays between actions until Stop or the end.
644
+ if pointer.alphaValue == 0, !stopped {
645
+ let at = NSEvent.mouseLocation
646
+ pointer.setFrameOrigin(
647
+ NSPoint(x: at.x - Token.tip.x, y: at.y - (Token.pointerBox - Token.tip.y)))
648
+ pointer.orderFrontRegardless()
649
+ pointer.animator().alphaValue = 1
650
+ }
651
+ case "move":
652
+ guard let x = say["x"] as? Double, let y = say["y"] as? Double else { return }
653
+ // The realm gives points from the top left. AppKit counts from the bottom left.
654
+ let top = NSScreen.screens.first?.frame.height ?? 0
655
+ let target = NSPoint(x: x, y: top - y)
656
+ // The HUD must not lie over what the realm acts on: the realm presses only what a person
657
+ // could press, and it would refuse a control that is under the HUD. So the HUD goes to the
658
+ // other side of the screen when the target is under it.
659
+ if panel.frame.insetBy(dx: -Token.space3, dy: -Token.space3).contains(target),
660
+ let screen = NSScreen.main?.visibleFrame
661
+ {
662
+ let left = panel.frame.midX > screen.midX
663
+ panel.setFrameOrigin(
664
+ NSPoint(
665
+ x: left ? screen.minX + Token.edge : screen.maxX - panel.frame.width - Token.edge,
666
+ y: panel.frame.origin.y))
667
+ }
668
+ // The tip of the arrow goes to the target.
669
+ let to = NSPoint(x: target.x - Token.tip.x, y: target.y - (Token.pointerBox - Token.tip.y))
670
+ pointer.orderFrontRegardless()
671
+ NSAnimationContext.runAnimationGroup { move in
672
+ // The realm says how long the way takes, and waits for it before it acts: longer for a
673
+ // longer way, as a hand. An older realm says nothing, and the glide is the short one.
674
+ let glide = (say["ms"] as? Double).map { $0 / 1000 } ?? Token.glide
675
+ move.duration = pointer.alphaValue > 0 ? glide : 0
676
+ move.timingFunction = Token.ease
677
+ // The frame, not the origin: AppKit animates the frame of a window, and an animated
678
+ // setFrameOrigin does nothing. A pointer that was on the screen stayed where it was.
679
+ pointer.animator().setFrame(NSRect(origin: to, size: pointer.frame.size), display: true)
680
+ pointer.animator().alphaValue = 1
681
+ }
682
+ case "glow":
683
+ guard !paused, !stopped, let x = say["x"] as? Double, let y = say["y"] as? Double,
684
+ let w = say["w"] as? Double, let h = say["h"] as? Double
685
+ else { return }
686
+ let top = NSScreen.screens.first?.frame.height ?? 0
687
+ glow.setFrame(NSRect(x: x, y: top - y - h, width: w, height: h), display: true)
688
+ glowView.color = Token.active
689
+ glow.orderFrontRegardless()
690
+ NSAnimationContext.runAnimationGroup { fade in
691
+ fade.duration = Token.glowIn
692
+ glow.animator().alphaValue = 1
693
+ }
694
+ glowRest?.invalidate()
695
+ case "act":
696
+ guard !paused, !stopped else { return }
697
+ let words = say["text"] as? String ?? ""
698
+ doing.stringValue = words
699
+ lines.append((words, "…", "none"))
700
+ redraw()
701
+ setState(Token.active)
702
+ ripple(Token.text)
703
+ case "effect":
704
+ guard !lines.isEmpty else { return }
705
+ let kind = say["kind"] as? String ?? "none"
706
+ lines[lines.count - 1].effect = say["text"] as? String ?? ""
707
+ lines[lines.count - 1].kind = kind
708
+ redraw()
709
+ setState(kind == "refused" ? Token.ended : Token.idle)
710
+ if kind == "refused" { ripple(Token.ended) }
711
+ // The glow says what the action did, and then goes: it lies over the application of the
712
+ // person, so it does not stay.
713
+ glowView.color = kind == "refused" ? Token.ended : Token.active
714
+ glowRest?.invalidate()
715
+ glowRest = Timer.scheduledTimer(withTimeInterval: Token.glowRest, repeats: false) { _ in
716
+ NSAnimationContext.runAnimationGroup { fade in
717
+ fade.duration = Token.glowIn * 2
718
+ self.glow.animator().alphaValue = 0
719
+ }
720
+ }
721
+ case "turn":
722
+ // The agent's `yield`. "ended" with the tone "ask": the person's turn. "ended" with another
723
+ // tone: the agent waits for the person's next message. "active": the agent works again.
724
+ let words = say["text"] as? String ?? ""
725
+ if say["state"] as? String == "ended", say["tone"] as? String == "ask" {
726
+ ask(words)
727
+ } else if say["state"] as? String == "ended" {
728
+ if asking { endAsk() }
729
+ doing.stringValue = words.isEmpty ? "The agent waits for you" : words
730
+ setState(Token.idle)
731
+ } else if asking {
732
+ endAsk()
733
+ setState(Token.active)
734
+ }
735
+ case "open":
736
+ // For a check, and for a person who wants the HUD open from the start.
737
+ if !open { toggleOpen() }
738
+ case "hide":
739
+ pointer.animator().alphaValue = 0
740
+ default: break
741
+ }
742
+ }
743
+ }
744
+
745
+ let application = NSApplication.shared
746
+ application.setActivationPolicy(.accessory)
747
+ let hud = Hud()
748
+ application.delegate = hud
749
+ application.run()