Repository navigation
Expand file tree
/
Copy pathBlipView.qml
More file actions
3479 lines (3331 loc) · 160 KB
/
Copy pathBlipView.qml
File metadata and controls
3479 lines (3331 loc) · 160 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 QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Quickshell
import Quickshell.Io
import QtQuick.Effects
import qs.Commons
import qs.Ui
// Blip panel — threads, then an iMessage-style conversation with a compose box.
//
// list → every thread, newest first, unread marked
// conversation → bubbles: mine blue on the right, theirs grey on the left,
// grouped by sender with one timestamp per run, day dividers,
// compose box pinned at the bottom. Esc goes back.
//
// Reads its thread list from the host widget so there is exactly one poller.
// Bubble decoration (grouping, day labels, times) is computed in thread.ts,
// where it is unit-tested; this file only renders.
FocusScope {
id: root
// ---- host contract (docs/app-design-review.md) ----------------------
property var hostWidget: null
/** Qt format strings, owned by the host widget (see BarWidget). Empty when no host is
* attached or the host has none, which thread.ts and Qt both read as "use the defaults". */
readonly property string timeFormat: (hostWidget && hostWidget.timeFormat) || ""
readonly property string dateFormat: (hostWidget && hostWidget.dateFormat) || ""
readonly property string dateFormatWithYear: (hostWidget && hostWidget.dateFormatWithYear) || ""
/** The surface hosting this view is showing (popout: opened; window:
* visible). Gates reads, reloads, and autofocus — a hidden surface must
* never mark anything read. */
property bool surfaceOpen: false
// The window may be visible but unfocused / on another workspace: it still
// renders and refreshes, but must not mark conversations read (war room #25).
property bool readActive: true
property color foreground: Color.foreground
property color urgent: Color.urgent
/** The theme's font, injected by whichever surface hosts this view. */
property string themeFont: Style.font.family
/**
* The font Messages actually uses, when this machine has it.
*
* Omarchy resolves its family to JetBrainsMono system-wide, so every label
* here was monospace — the loudest remaining difference from Messages, more
* than any spacing. Apple ships SF Pro Text with Messages; a machine themed
* to look like a Mac usually already has it, and Qt.fontFamilies() says so
* for certain rather than guessing (asking for a missing family silently
* yields a default sans, which would be a worse wrong answer than the
* theme font).
* Order: SF Pro if the machine has it, then Inter — which is OFL-licensed,
* ships in Arch's `extra`, and was drawn for exactly this job — then the
* theme font, so nothing changes for anyone who has installed neither.
* `ui_font=theme` in bridge.conf opts out.
*
* Blip will never SHIP a font: SF Pro is Apple's and its licence forbids
* redistribution, which is why blip-setup installs Inter and only points at
* Apple's own download for SF Pro.
*/
readonly property string messagesFont: {
var want = ["SF Pro Text", "SF Pro Display", "SF Pro", "Inter"]
var have = Qt.fontFamilies()
for (var i = 0; i < want.length; i++) if (have.indexOf(want[i]) >= 0) return want[i]
return ""
}
readonly property bool themeFontForced: !!hostWidget && hostWidget.uiFontTheme === true
readonly property string fontFamily:
(messagesFont !== "" && !themeFontForced) ? messagesFont : themeFont
// `ui_font_size=N` in bridge.conf: N is bubble text in px. Unset (0) keeps
// Omarchy's tokens. Caption/body keep the same ratios as Style.font.
readonly property int uiFontSizePx: {
if (!hostWidget) return 0
var n = hostWidget.uiFontSize
return (typeof n === "number" && n > 0) ? n : 0
}
readonly property real uiFontScale: {
if (uiFontSizePx <= 0) return 1
var small = Style.font.bodySmall
return small > 0 ? uiFontSizePx / small : 1
}
readonly property int fontCaption: Math.max(1, Math.round(Style.font.caption * uiFontScale))
readonly property int fontBodySmall: Math.max(1, Math.round(Style.font.bodySmall * uiFontScale))
readonly property int fontBody: Math.max(1, Math.round(Style.font.body * uiFontScale))
readonly property color dim: Qt.darker(foreground, 1.45)
/** An editor owns the keyboard — the host's key catcher must stand down. */
readonly property bool editorActive:
composeField.activeFocus || searchField.activeFocus || newField.activeFocus || bubbleFocused
readonly property alias composeEditor: composeField
readonly property real contentHeightHint: listContent.implicitHeight
/** The view wants keyboard navigation focus back (list mode). */
signal navigationFocusRequested()
// Foreground and background follow the Omarchy theme (Color.* is the live
// theme singleton and hot-reloads on switch). The ACCENT does not: it is
// iMessage blue, always. Bubbles followed the theme accent until 2.3.3, and
// on the themes where that accent is red "my" messages read as errors;
// Fred, 2026-09-04: "Yes make the bubbles blue too" — blue bubbles are the
// look, not a theme preference. White text on that blue, as Messages does.
readonly property color accent: "#0a84ff"
readonly property color cyan: accent // legacy name; accents/links
readonly property color okColor: accent
readonly property color mineFill: accent
readonly property color mineText: "#ffffff"
readonly property color theirsFill: Qt.rgba(foreground.r, foreground.g, foreground.b, 0.14)
readonly property color theirsText: foreground
// Links inside a bubble take the bubble's readable text color instead of
// Qt's default theme blue, which is illegible on the accent fill.
function richMessageHtml(html, linkColor) {
var color = String(linkColor || "").toLowerCase()
if (!/^#[0-9a-f]{6}$/.test(color)) color = "#ffffff"
return String(html || "").replace(
/<a href=/g,
'<a style="color: ' + color + '; text-decoration: underline;" href='
)
}
readonly property string home: Quickshell.env("HOME")
readonly property string threadScript:
decodeURIComponent(Qt.resolvedUrl("thread.ts").toString().replace(/^file:\/\//, ""))
readonly property string fetchScript:
decodeURIComponent(Qt.resolvedUrl("fetch.ts").toString().replace(/^file:\/\//, ""))
readonly property string pasteScript:
decodeURIComponent(Qt.resolvedUrl("paste.ts").toString().replace(/^file:\/\//, ""))
readonly property string previewScript:
decodeURIComponent(Qt.resolvedUrl("linkpreview.ts").toString().replace(/^file:\/\//, ""))
readonly property string sendFileScript:
decodeURIComponent(Qt.resolvedUrl("send-file.ts").toString().replace(/^file:\/\//, ""))
readonly property string searchScript:
decodeURIComponent(Qt.resolvedUrl("search.ts").toString().replace(/^file:\/\//, ""))
readonly property string contactScript:
decodeURIComponent(Qt.resolvedUrl("contact-search.ts").toString().replace(/^file:\/\//, ""))
// ---- new-conversation state (`n` opens, Esc closes)
property bool newMode: false
property var newResults: []
property string newNote: ""
property int newCursor: 0
property string newQueryRan: ""
// ---- search state (list view only; `/` opens, Esc closes)
property bool searching: false
property var searchResults: []
property string searchNote: ""
property int searchCursor: 0
property string searchQueryRan: ""
// Results replace the thread list only once a search has actually produced
// something to show — focusing the box alone must not blank the list.
readonly property bool searchShowing:
searching && (searchResults.length > 0 || searchNote !== "")
// Fetched attachments: id → file:// url; "" = fetch failed (chip shows ⚠).
// The cache under ~/.cache/blip/att is global, so results never go stale on
// a thread switch — no ownership tracking needed, unlike thread loads.
property var attFiles: ({})
// attachment id → {pixelRatio, pixelWidth, pixelHeight} from fetch.ts, so
// Retina media can draw at its intended logical size (a 144-DPI screenshot
// is a 2x image, not a wall of pixels).
property var attMetrics: ({})
property var fetchQueue: []
property string fetchingId: ""
// Compose draft attachment (one per message in v1).
property string draftPath: ""
property string draftLabel: ""
// What the in-flight file send / paste belong to, so late completions
// can't clobber a NEWER draft or land in a DIFFERENT conversation.
property string sendDraftPath: ""
property string pasteChat: ""
readonly property var threads: hostWidget ? hostWidget.threads : []
readonly property var pinnedThreads: root.threads.filter(function(t) { return t.pinned === true })
readonly property var unpinnedThreads: root.threads.filter(function(t) { return t.pinned !== true })
readonly property bool online: hostWidget ? hostWidget.online : false
readonly property int unread: hostWidget ? hostWidget.unread : 0
/** The plugin's version, from the host (manifest.json). "" hides the tag. */
readonly property string version: hostWidget && hostWidget.version ? String(hostWidget.version) : ""
// ---- share sheet (right-click a link in a bubble, or a link card)
property string shareUrl: "" // "" = closed
property string shareQr: "" // file:// of the rendered QR, "" while rendering
readonly property string shareDir: Quickshell.env("XDG_RUNTIME_DIR") + "/blip"
/** Open the share sheet for one http(s) URL. Anything else is ignored. The
* URL is message content: it reaches qrencode and the LocalSend temp file
* on STDIN, never argv (CLAUDE.md: message text never rides argv). */
property var shareUrls: [] // the links the sheet was opened on
property int shareIndex: 0 // which of them it shows; ←/→ and ‹ › step
property int shareCursor: 0 // highlighted action (mouse and keys agree)
property real shareKeysFrom: 0 // Enter and digits act from this time on
/** Open the sheet on one URL or a list (a message's links, first showing).
* `auto`: it opened by itself — a link you sent, a link that arrived, IPC.
* The sheet is the warning either way (host, full URL, a button that says
* what Enter does), but for 700 ms after an auto sheet appears Enter and
* digits still belong to the draft, so a link landing as Enter is pressed
* to send is never opened by it. False when nothing in `u` is http(s). */
function openShare(u, auto) {
var urls = (Array.isArray(u) ? u : [u]).map(function(x) { return String(x || "") })
.filter(function(x) { return /^https?:\/\//i.test(x) })
if (urls.length === 0) return false
shareUrls = urls
shareIndex = 0
shareCursor = 0
shareKeysFrom = Date.now() + (auto === true ? 700 : 0)
shareQr = ""
showShareUrl(urls[0])
return true
}
function shareStep(d) {
var n = shareUrls.length
if (n < 2) return
shareIndex = (shareIndex + d + n) % n
showShareUrl(shareUrls[shareIndex])
}
/** The QR for `u`. The box keeps the previous code until this one is
* written, so stepping swaps the image instead of re-flowing the card. */
function showShareUrl(u) {
shareUrl = u
// A sheet opened over a still-rendering one: the old job's exit would have
// published ITS result under the new outFile (Astra A#8). Kill it; the
// non-zero exit keeps its result out. Stepping between links re-runs this,
// so it matters more here than it did for one link.
if (qrProc.running) qrProc.running = false
var out = shareDir + "/qr-" + Date.now() + ".png"
qrProc.outFile = out
qrProc.command = ["sh", "-c", 'mkdir -p "$1" && chmod 700 "$1" && umask 077 && exec qrencode -o "$2" -s 6 -m 2 -l M', "blip", shareDir, out]
qrProc.stdinEnabled = true
qrProc.running = true
qrProc.write(u)
qrProc.stdinEnabled = false
}
function closeShare() { shareUrl = ""; shareQr = ""; shareUrls = [] }
/** First http(s) URL in a string, or "" — mirrors collector.firstUrl. */
function firstUrl(t) {
var m = /https?:\/\/[^\s<>"']+/i.exec(String(t || ""))
return m ? m[0].replace(/[.,;:!?)\]}'"]+$/, "") : ""
}
/** Every link in a message, in order, exactly as linkify() anchors them
* (same pattern, same trailing-punctuation rule, www. gets https://). */
function allUrls(t) {
var re = /\bhttps?:\/\/[^\s<>"']+|\bwww\.[^\s<>"']+\.[^\s<>"']+/gi, out = [], m
while ((m = re.exec(String(t || ""))) !== null) {
var u = m[0].replace(/[.,;:!?\]]+$/, "")
while (u.endsWith(")") && u.split("(").length < u.split(")").length) u = u.slice(0, -1)
u = u.replace(/[.,;:!?\]]+$/, "")
if (/^www\./i.test(u)) u = "https://" + u
if (out.indexOf(u) < 0) out.push(u)
}
return out
}
/** IPC `share <url>` (host gates it behind automation=on), and the host's
* arriving-link path, which hands over every link of the message. */
function shareLink(u) {
return openShare(u, true) ? "share sheet" : "not an http(s) url"
}
/** The full app window. The host owns creation (Quickshell never re-maps a
* hidden FloatingWindow), so this asks the widget, exactly like SUPER+M.
* The popout closes behind it — the same order the bar's own double-click
* uses, and leaving both up put the same conversation on screen twice. */
function openApp() {
closeShare()
if (!hostWidget) return
if (typeof hostWidget.showApp === "function") hostWidget.showApp()
}
/** The sheet's keys: Esc closes, ←/→ step links, ↑/↓ move the highlight,
* Enter takes it, 1/2/3 pick directly. Anything else falls through to the
* field (a sheet over a draft never blocks typing); see openShare for
* the grace on an auto sheet. True when the key was the sheet's. */
function shareKey(key) {
if (shareUrl === "") return false
var acts = [shareOpen, shareCopy, shareSend]
if (key === Qt.Key_Escape) { closeShare(); return true }
// ←/→ are the sheet's only when there is something to step through; a
// draft keeps its caret keys otherwise.
if ((key === Qt.Key_Left || key === Qt.Key_Right) && shareUrls.length > 1) { shareStep(key === Qt.Key_Right ? 1 : -1); return true }
if (key === Qt.Key_Up || key === Qt.Key_Down) { shareCursor = Math.max(0, Math.min(2, shareCursor + (key === Qt.Key_Down ? 1 : -1))); return true }
if (Date.now() < shareKeysFrom) return false
if (key === Qt.Key_Return || key === Qt.Key_Enter) { acts[shareCursor](); return true }
if (key >= Qt.Key_1 && key <= Qt.Key_3) { acts[key - Qt.Key_1](); return true }
return false
}
function shareOpen() { var u = shareUrl; closeShare(); openLink(u) }
function shareCopy() { var u = shareUrl; closeShare(); copyText(u) }
/** Omarchy's share sheet. Same path as `omarchy-menu-share clipboard`: the
* text lands in a temp .txt and LocalSend's device picker takes it from
* there (the official headless CLI sends files, not text). */
function shareSend() {
var u = shareUrl; closeShare()
var f = shareDir + "/share-" + Date.now() + ".txt"
sendShareProc.command = ["sh", "-c", 'mkdir -p "$1" && chmod 700 "$1" && umask 077 && cat > "$2" && exec systemd-run --user --quiet --collect localsend --headless send "$2"', "blip", shareDir, f]
sendShareProc.stdinEnabled = true
sendShareProc.running = true
sendShareProc.write(u)
sendShareProc.stdinEnabled = false
note = "sent to LocalSend"
noteTimer.restart()
}
Process {
id: qrProc
property string outFile: ""
onExited: function(code) { if (code === 0 && root.shareUrl !== "") root.shareQr = "file://" + outFile }
}
Process { id: sendShareProc }
// ---- view state
property var active: null // selected thread object, null = list view
property var bubbles: [] // decorated messages for `active` (see thread.ts)
property bool loading: false
// A conversation is READ only after a snapshot of it actually rendered.
// `rendered` is false from openThread until bubbles land; a failed load
// (timeout, bad JSON) leaves it false, so a later refresh cannot mark the
// conversation read unseen (Astra A#2). `seenTs` is the newest ts IN that
// snapshot — what the eye saw — and is what every read mark carries; the
// sidebar's last_ts can be newer than anything on screen (Astra A#3).
property bool rendered: false
property string seenTs: ""
property string note: "" // transient status line (send result, errors)
property int cursor: -1 // keyboard row selection in list view
// Chat of the cursor row, so every row answers "am I the cursor?" with one
// string compare instead of an O(n) scan of threads per row per keypress.
readonly property string cursorChat: cursor >= 0 && cursor < threads.length ? String(threads[cursor].chat) : ""
// The row drawing the keyboard cursor right now — a thread row, pinned tile,
// search hit or contact hit registers itself when its hasCursor turns true,
// so the move functions never translate indexes between the four models.
// A destroyed row reads back as null (guarded QObject property).
property Item cursorRow: null
// The cursor is kept while the search field holds focus (Esc and Down
// return to it), but a row must not LOOK selected while typing happens
// elsewhere — Up from the top and a click in the field both got here.
readonly property bool cursorShown: !searchField.activeFocus
// The bubble the arrows have selected in a conversation (-1 = none) and the
// delegate drawing it — registered by the row itself, like cursorRow. The
// selection is a TARGET for actions (copy, open, reply), not a scroll state.
property int bubbleCursor: -1
property Item bubbleCursorItem: null
onBubblesChanged: clearBubbleCursor() // a reload renumbers the rows
property bool pinToBottom: false // scroll to the newest bubble once layout settles
property bool bubbleFocused: false // a bubble's TextEdit has focus (text selection in progress)
property string threadRunningChat: "" // chat owned by the current threadProc
property string bubblesJson: "" // last rendered bubbles, for no-op reload detection
property bool firstLoad: true // first load of the open thread pins to bottom
property string pendingThreadChat: "" // latest chat requested while it runs
property string sendChat: "" // immutable context for the current send
property string sendText: ""
property string sendStamp: "" // local "YYYY-MM-DD HH:mm:ss" the current send was typed at
// Text sends queue instead of refusing while one is on the wire; each gets
// its bubble the instant Enter is pressed (see pendingSends).
property var sendQueue: []
// Sends the Mac has not written a row for yet, {chat, text, ts}. Every
// thread reload carries them to thread.ts (--pending-stdin, never argv),
// which keeps their bubbles until the real row lands. Memory only.
property var pendingSends: []
property int reloadTries: 0 // post-send reloads still waiting for the row
property string reloadChat: ""
function avatarInitials(thread) {
var n = String(thread.name || "")
if (/^[+0-9]/.test(n) || n === "") return "#"
var parts = n.trim().split(/\s+/).filter(function(p) { return p.length > 0 })
if (parts.length === 0) return "#"
return (parts[0][0] + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase()
}
readonly property bool inThread: active !== null
// last_ts of the open conversation as of its last load — the push watcher
// refreshes the thread list, and when OUR thread advances, the bubbles
// reload themselves. The guard makes unchanged refreshes free.
property string activeLastTs: ""
onThreadsChanged: {
// LIST view: a rebuilt Repeater collapses contentHeight for a frame and
// StopAtBounds clamps contentY to 0 — the reader's place in a long list
// was lost on every genuine refresh. Restore it once layout settles.
if (!inThread && surfaceOpen) {
var y = threadFlick.contentY
if (y > 0) Qt.callLater(function() {
if (!root.inThread)
threadFlick.contentY = Math.max(0, Math.min(y, threadFlick.contentHeight - threadFlick.height))
})
return
}
// `opened` too, not just inThread: a CLOSED panel still holds `active`,
// and reloading a hidden thread marks it read without it ever being
// seen (Codex HIGH, 1.1.0 review).
if (!inThread || !surfaceOpen) return
for (var i = 0; i < threads.length; i++) {
var t = threads[i]
if (String(t.chat) !== String(active.chat)) continue
if (String(t.last_ts) !== activeLastTs) {
activeLastTs = String(t.last_ts)
active = t // fresher name/guid too (a group can BECOME sendable)
// The push ping usually started this exact load already — don't
// stack a second one behind it.
var busyHere = (threadProc.running && threadRunningChat === String(t.chat))
|| pendingThreadChat === String(t.chat)
if (!busyHere) {
if (!flick.stick) { pushPending = true } // reading history — defer
else {
pinToBottom = true
requestThreadLoad(String(t.chat))
}
}
}
return
}
}
// Same rule as collector.isGroupChat(): anything that is not a phone/email.
function isGroupId(c) { c = String(c || ""); return c !== "" && !/^\+?[0-9]{5,}$/.test(c) && c.indexOf("@") < 0 }
readonly property bool activeIsGroup: inThread && isGroupId(active.chat)
/**
* DMs send --to the chat id (a phone/email). Groups send --chat-id with the
* full AppleScript GUID ("any;+;<id>") that `imsg groups` supplies; a group
* whose GUID is not cached yet stays read-only rather than guess. Never the
* handle: a group's handle is whichever member spoke last, and sending to it
* would DM that one person while the panel shows the group.
*/
function isSendable(t) {
if (!t) return false
var c = String(t.chat || "")
if (isGroupId(c)) return /^[A-Za-z]+;[+-];.+$/.test(String(t.guid || ""))
return /^\+?[0-9]{5,}$/.test(c) || c.indexOf("@") > 0
}
// Unsent compose text per chat id. It lives on the host (BarWidget.draftCache)
// so the panel and the app window share it, and in memory only: message text
// never lands on disk. Written in place: nothing binds to the map, so there
// is no copy to make and no change to signal.
readonly property var drafts: hostWidget ? hostWidget.draftCache : ({})
/** Back to the list view, scrolled to top — the host calls this on open. */
function resetToList() {
closeShare() // the sheet belongs to the link you were looking at
active = null
bubbles = []
note = ""
cursor = -1
loading = false
pendingThreadChat = ""
composeField.text = ""
searching = false
searchResults = []
searchNote = ""
searchField.text = ""
newMode = false
newResults = []
newNote = ""
newField.text = ""
// Deep fetch for a real thread list. Does NOT clear dots: like iMessage,
// a thread stays marked until that conversation is opened.
if (hostWidget) hostWidget.refresh(true, false)
Qt.callLater(function() { threadFlick.contentY = 0 })
}
function back() {
closeShare() // ditto: navigating away dismisses the sheet
active = null
bubbles = []
note = ""
loading = false
pendingThreadChat = ""
composeField.text = ""
clearDraft() // a queued file must never survive into another thread
pinToBottom = false
// Top of the list for a mouse user; the cursor row for a keyboard user.
Qt.callLater(function() {
threadFlick.contentY = 0
scrollCursorIntoView()
root.navigationFocusRequested()
})
}
function openThread(t) {
if (!t) return
// A sheet opened over the PREVIOUS conversation (an arriving link opens it
// by itself) otherwise floats over this one, offering a QR for a link that
// is no longer on screen. Found by driving the live panel, 2026-09-07.
closeShare()
active = t
activeLastTs = String(t.last_ts || "")
bubbles = []
bubblesJson = ""
rendered = false
seenTs = ""
firstLoad = true
pushPending = false
note = ""
loading = true
composeField.text = drafts[String(t.chat)] || "" // this conversation's unsent text
10BC8
div> composeField.cursorPosition = composeField.length
clearDraft() // a queued file must never survive into another thread
requestThreadLoad(String(t.chat))
Qt.callLater(function() { composeField.forceActiveFocus() })
}
function requestThreadLoad(chat) {
pendingThreadChat = String(chat || "")
if (!threadProc.running) startNextThreadLoad()
}
function startNextThreadLoad() {
if (threadProc.running || pendingThreadChat === "") return
threadRunningChat = pendingThreadChat
pendingThreadChat = ""
var pending = root.pendingSends.filter(function(p) { return p.chat === threadRunningChat })
threadProc.command = ["bun", root.threadScript, threadRunningChat, "80",
"--time-format", root.timeFormat,
"--date-format", root.dateFormat,
"--date-format-with-year", root.dateFormatWithYear]
.concat(pending.length ? ["--pending-stdin"] : [])
if (pending.length) {
// In-flight sends ride stdin (message text never in argv) so their
// bubbles survive the reload until the Mac has the row.
threadProc.stdinEnabled = true
threadProc.running = true
threadProc.write(JSON.stringify(pending))
threadProc.stdinEnabled = false
} else {
threadProc.running = true
}
}
/** IPC test hook: drive the exact user send path minus the keyboard.
* Keystroke injection (wtype) proved non-deterministic — a virtual
* keyboard's events can land on whatever surface Hyprland favors. */
/** Clear every badge/dot locally. Read state never goes back to iMessage. */
/** Move the conversation by dy pixels — the wheel and the keys share this,
* so the bottom-stick (which gates the deferred push reload) behaves the
* same whichever way the reader moves. */
function scrollConversation(dy) {
var max = Math.max(0, flick.contentHeight - flick.height)
flick.contentY = Math.max(0, Math.min(max, flick.contentY + dy))
flick.stick = flick.contentY >= max - 4
}
/** Up/Down in an empty compose field walk the bubbles, newest first, and
* keep the selected one in view. Down past the newest drops the selection
* and re-sticks to the bottom, so the conversation follows new messages
* again — the reader is back where they started. */
function moveBubbleCursor(dy) {
var n = bubbles.length
if (n === 0) return
if (bubbleCursor < 0) {
if (dy > 0) return
bubbleCursor = n - 1
} else if (dy > 0 && bubbleCursor >= n - 1) {
leaveBubbles()
return
} else {
bubbleCursor = Math.max(0, bubbleCursor + dy)
}
revealBubbleCursor()
}
/** PgUp/PgDn walk the bubbles a screen at a time, and unlike the arrows
* they work with text in the compose field (they move no caret). PgUp
* selects the topmost visible bubble; already there, it pages up first.
* PgDn mirrors it with the bottommost, and past the newest leaves. */
function pageBubbles(dy) {
if (bubbles.length === 0) return
var edge = edgeVisibleBubble(dy)
if (edge === bubbleCursor && bubbleCursorItem) {
if (dy > 0 && edge === bubbles.length - 1) { leaveBubbles(); return }
// Page so the selected row lands at the OPPOSITE edge — a screen with
// one row of overlap, the way a pager turns a page.
var it = bubbleCursorItem, margin = Style.space(6)
scrollConversation(dy < 0 ? it.y + it.height + margin - flick.height - flick.contentY
: it.y - margin - flick.contentY)
edge = edgeVisibleBubble(dy)
}
if (edge < 0) return
bubbleCursor = edge
revealBubbleCursor()
}
/** Index of the topmost (dy < 0) or bottommost (dy > 0) bubble that is
* WHOLLY inside the viewport — a sliver of the neighbour above the
* selection must not count, or the next PgUp steps one row instead of
* paging. Falls back to a partly visible row (a picture taller than the
* view); -1 when nothing is laid out yet. */
function edgeVisibleBubble(dy) {
var top = flick.contentY, bottom = top + flick.height
var n = bubbleRepeater.count, partial = -1
for (var k = 0; k < n; k++) {
var i = dy < 0 ? k : n - 1 - k
var it = bubbleRepeater.itemAt(i)
if (!it || it.y >= bottom || it.y + it.height <= top) continue
if (partial < 0) partial = i
if (dy < 0 ? it.y >= top - 1 : it.y + it.height <= bottom + 1) return i
}
return partial
}
function revealBubbleCursor() {
var it = bubbleCursorItem // set synchronously by the row's hasCursor binding
if (!it) return
var margin = Style.space(6)
if (it.y < flick.contentY + margin)
scrollConversation(it.y - margin - flick.contentY)
else if (it.y + it.height > flick.contentY + flick.height - margin)
scrollConversation(it.y + it.height + margin - flick.height - flick.contentY)
}
function clearBubbleCursor() { bubbleCursor = -1; bubbleCursorItem = null }
/** Out of the selection and back where reading started: newest at the
* bottom, stick re-armed. Down past the newest and Esc both land here. */
function leaveBubbles() {
clearBubbleCursor()
scrollConversation(flick.contentHeight)
}
function selectedBubble() {
return bubbleCursor >= 0 && bubbleCursor < bubbles.length ? bubbles[bubbleCursor] : null
}
/** Enter on the selected bubble: its first attachment, else its link card,
* else the first URL in its text — the same handlers a click reaches. */
function openBubble(b) {
if (b.attachments && b.attachments.length > 0) { openAttachment(b.attachments[0]); return }
// A link goes to the share sheet, not straight to the browser: the sheet
// shows the host and the URL and makes opening a deliberate second step.
var urls = allUrls(b.text)
if (b.link && b.link.url && urls.indexOf(String(b.link.url)) < 0) urls.unshift(String(b.link.url))
openShare(urls, false)
}
/** Ctrl+C on the selected bubble: its text, or — for a bubble that is only
* a picture — the first image attachment, as an image. */
function copyBubble(b) {
var t = String(b.text || "")
if (t !== "") { copyText(t); return }
var atts = b.attachments || []
for (var i = 0; i < atts.length; i++) {
if (isImageMime(atts[i].mime)) { copyAttachment(atts[i]); return }
}
}
/** Ctrl+R: quote the selected bubble into the compose field. iMessage's
* inline reply is not reachable through the bridge (no message GUID leaves
* the Mac and AppleScript has no reply-to), so this is a plain "> quote". */
function quoteBubble(b) {
composeField.text = "> " + String(b.text || "").replace(/\s+/g, " ").slice(0, 200) + "\n"
composeField.cursorPosition = composeField.length
leaveBubbles()
}
function markAllRead() {
if (!root.hostWidget || root.unread === 0) return
root.hostWidget.markAllRead()
}
/** Chip icon for an attachment's mime type. */
function attachmentIcon(mime) {
var m = String(mime || "")
if (m.indexOf("image/") === 0) return "📷"
if (m.indexOf("video/") === 0) return "🎬"
if (m.indexOf("audio/") === 0) return "🎤"
if (m === "application/pdf") return "📄"
return "📎"
}
/** "❤️👍" — the emoji string for a bubble's tapback pill. */
function tapbackRow(list) {
var s = ""
for (var i = 0; i < (list || []).length; i++) s += list[i].emoji
return s
}
// ---------------------------------------------------- attachment fetching
function isImageMime(m) { return String(m || "").indexOf("image/") === 0 }
function linkHost(u) { var m = /^https?:\/\/([^/?#]+)/i.exec(String(u || "")); return (m ? m[1] : String(u || "")).replace(/^www\./, "").toLowerCase() }
/** Only http(s) ever reaches xdg-open from a card (thread.ts filters too). */
function openLink(u) {
u = String(u || "")
if (!/^https?:\/\//i.test(u)) return
// Open, then FOCUS the default browser's window: Omarchy sets
// focus_on_activate=false (no focus stealing), so a new tab in an existing
// browser on another workspace is invisible — "clicking links does
// nothing" (Fred, 2.1.4). The class is derived from the default handler's
// .desktop name (brave-browser, firefox, chromium, google-chrome…).
Quickshell.execDetached(["sh", "-c",
'xdg-open "$1" >/dev/null 2>&1; b=$(xdg-settings get default-web-browser 2>/dev/null | sed "s/[.]desktop$//" | tr "[:upper:]" "[:lower:]"); [ -n "$b" ] || exit 0; ' +
'for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do a=$(hyprctl clients -j 2>/dev/null | jq -r --arg b "$b" "$2"); ' +
'[ -n "$a" ] && { hyprctl dispatch "hl.dsp.focus({ window = \\"address:$a\\" })" >/dev/null 2>&1; exit 0; }; sleep 0.2; done',
"blip", u,
// the jq filter travels as $2 so no quote ever nests inside this QML string
'[.[] | select(((.class // "") | ascii_downcase | contains($b)) or ((.initialClass // "") | ascii_downcase | contains($b)))] | sort_by(.focusHistoryID) | .[0].address // empty'])
}
// ---------------------------------------------------- contact photos
// Sidebar avatars: `imsg avatar <handle>` via avatar.ts (7-day cache, negative
// markers). One request in flight; rows ask on creation; groups never ask.
readonly property string avatarScript: fetchScript.replace(/fetch\.ts$/, "avatar.ts")
// ---- link previews for URLs Messages never decorated
// Apple builds an LPLinkMetadata balloon for some links and not others (on
// this Mac: 7 of 27). linkpreview.ts fetches the page's own Open Graph card
// for the rest, so a bare URL still shows its picture and title.
property var linkCards: ({}) // url → {title,summary,image,host}, null = none
property var previewQueue: []
function requestPreview(url) {
url = String(url || "")
if (url === "" || !/^https?:\/\//i.test(url)) return
if (linkCards[url] !== undefined || previewQueue.indexOf(url) >= 0) return
previewQueue.push(url)
pumpPreview()
}
function pumpPreview() {
if (previewProc.running || previewQueue.length === 0) return
previewProc.url = previewQueue.shift()
// The URL is message content: stdin, never argv (Astra #6).
previewProc.command = ["bun", root.previewScript, "--stdin"]
previewProc.stdinEnabled = true
previewProc.running = true
previewProc.write(previewProc.url)
previewProc.stdinEnabled = false
}
Process {
id: previewProc
property string url: ""
stdout: StdioCollector {
onStreamFinished: {
var card = null
try {
var d = JSON.parse(text.trim())
if (d.ok === true) card = { title: String(d.title || ""), summary: String(d.summary || ""),
image: String(d.image || ""), url: String(d.url || previewProc.url) }
} catch (e) {}
var m = Object.assign({}, root.linkCards)
m[previewProc.url] = card
root.linkCards = m
root.pumpPreview()
}
}
onExited: Qt.callLater(root.pumpPreview)
}
property var avatarFiles: ({}) // handle → file:// url, "" = no photo
property var avatarQueue: []
function requestAvatar(handle) {
handle = String(handle || "")
if (handle === "") return // groups are welcome: avatar.ts asks for the group's own photo
if (avatarFiles[handle] !== undefined || avatarQueue.indexOf(handle) >= 0) return
avatarQueue.push(handle)
pumpAvatar()
}
// Letters stick in avatarFiles as "". Opening the panel/window again drops
// those and re-asks, so a photo set a minute ago is not stuck until tomorrow.
function retryBareAvatars() {
var m = Object.assign({}, root.avatarFiles)
var keys = []
for (var k in m) {
if (m[k] === "") { keys.push(k); delete m[k] }
}
if (keys.length === 0) return
root.avatarFiles = m
for (var i = 0; i < keys.length; i++) root.requestAvatar(keys[i])
}
onSurfaceOpenChanged: if (surfaceOpen) root.retryBareAvatars()
function pumpAvatar() {
if (avatarProc.running || avatarQueue.length === 0) return
avatarProc.handle = avatarQueue.shift()
// --retry skips the 24h "no photo" marker so a picture set after the
// first ask (a new group photo, a Contacts card) shows up this session.
avatarProc.command = ["bun", root.avatarScript, "--retry", avatarProc.handle]
avatarProc.running = true
}
Process {
id: avatarProc
property string handle: ""
stdout: StdioCollector {
onStreamFinished: {
var url = ""
try { var d = JSON.parse(text.trim()); if (d.ok === true) url = String(d.url || "") } catch (e) {}
var m = Object.assign({}, root.avatarFiles)
m[avatarProc.handle] = url
root.avatarFiles = m
root.pumpAvatar()
}
}
onExited: Qt.callLater(root.pumpAvatar)
}
/** Only media/documents are handed to xdg-open. Anything a sender could
* make executable (scripts, .desktop, unknown blobs) is saved and named,
* never launched (Codex audit #10). */
function openableMime(m) {
m = String(m || "")
return m.indexOf("image/") === 0 || m.indexOf("video/") === 0 || m.indexOf("audio/") === 0 ||
m === "application/pdf" || m === "text/plain" || m === "text/vcard" || m === "text/calendar"
}
/** action: "" = just cache it, "open" = xdg-open when it lands, "copy" =
* put it on the clipboard when it lands. */
function enqueueFetch(att, action, auto) {
var id = String(att.id || "")
if (id === "" || fetchingId === id) return
if (attFiles[id] !== undefined && !action) return
for (var i = 0; i < fetchQueue.length; i++) {
if (fetchQueue[i].id === id) {
if (action) fetchQueue[i].action = action
return
}
}
fetchQueue.push({ id: id, name: String(att.name || "file"),
mime: String(att.mime || ""), action: action || "",
auto: auto === true })
pumpFetch()
}
property string fetchJobAction: ""
property string fetchJobMime: ""
function pumpFetch() {
if (fetchProc.running || fetchQueue.length === 0) return
var job = fetchQueue.shift()
fetchingId = job.id
fetchJobAction = job.action
fetchJobMime = job.mime
// Auto-pulls carry a hard transfer cap: claimed metadata is not the limit.
fetchProc.command = ["bun", root.fetchScript, job.id, job.name, job.mime, job.auto ? "5242880" : ""]
fetchProc.running = true
}
/** Images ≤ 5 MB in the open conversation fetch themselves (Fred's call —
* it's what makes the panel feel like Messages, and cached hits are free). */
/** Source-size ceiling for an auto-fetch. Bigger than any photo a phone
* produces, small enough that a raw camera dump is still a click. */
readonly property int autoFetchMaxSource: 32 * 1024 * 1024
function autoFetchImages() {
if (!inThread) return
for (var i = 0; i < bubbles.length; i++) {
var atts = bubbles[i].attachments || []
for (var j = 0; j < atts.length; j++) {
// Bytes must be KNOWN — null/0 must not slip through and auto-pull
// something the click-path 100 MB ceiling would allow. The SOURCE cap
// is generous because the Mac resamples an auto-fetch to 1600 px
// before sending: the old 5 MB gate was measured against the source,
// while sips turns a 5.07 MB HEIC into a 7.80 MB JPEG, so full-size
// iPhone photos were rejected at both ends and simply never appeared.
var b = atts[j].bytes
if (isImageMime(atts[j].mime) && typeof b === "number" && b > 0 && b <= root.autoFetchMaxSource)
enqueueFetch(atts[j], "", true)
}
// link-card preview PNGs are small; the auto-fetch transfer cap bounds them
var l = bubbles[i].link
if (l && l.image_id) enqueueFetch({ id: String(l.image_id), name: "preview.png", mime: "image/png", bytes: 0 }, "", true)
}
}
/** Chip/image click: fetch-then-open. ALWAYS round-trips fetch.ts, even
* when attFiles already has a url — the LRU may have evicted the file
* since (Codex finding #5); a cache hit is instant anyway. */
function openAttachment(att) {
var id = String(att.id || "")
if (id === "") return
if (attFiles[id] === "") { // failed marker — clear it so a retry runs
var m = Object.assign({}, attFiles); delete m[id]; attFiles = m
}
enqueueFetch(att, "open")
}
/** Ctrl+C on an image bubble: fetch-then-clipboard, the same round trip as
* a click, ending in wl-copy with the image's own MIME type. */
function copyAttachment(att) {
if (String(att.id || "") === "") return
enqueueFetch(att, "copy")
}
// ------------------------------------------------------ compose attachment
function setDraft(path) {
var p = String(path || "")
if (p === "") return
draftPath = p
var parts = p.split("/")
draftLabel = parts[parts.length - 1] || "file"
Qt.callLater(function() { composeField.forceActiveFocus() })
}
function clearDraft() {
draftPath = ""
draftLabel = ""
}
function startPaste() {
if (pasteProc.running || !inThread) return
pasteChat = String(active.chat)
pasteProc.command = ["bun", root.pasteScript]
pasteProc.running = true
}
// ------------------------------------------------- new conversation
function startNew() {
if (inThread && !splitView) return // split view: the list pane is right there
exitSearch()
threadFlick.contentY = 0 // the field sits above the rows
newMode = true
newResults = []
newNote = ""
newCursor = 0
newQueryRan = ""
Qt.callLater(function() {
newField.forceActiveFocus()
newField.selectAll()
})
}
/** Down in an empty search or new-message field: back to the list, cursor
* on the first row — the list is showing its top, so that is where the eye
* is. Esc keeps the old cursor instead. */
function listFromTop() {
if (newMode) exitNew()
else exitSearch()
cursor = 0
}
function exitNew() {
newMode = false
newResults = []
newNote = ""
newCursor = 0
newQueryRan = ""
newField.text = ""
newField.focus = false
root.navigationFocusRequested()
// The field pushed the list to the top; bring the cursor row back once
// the rows have been rebuilt and laid out.
Qt.callLater(scrollCursorIntoView)
}
// Same identity discipline as message search: a stale completion must
// never surface Alice's results under Bob's query (Codex HIGH, 1.2.0).
property int contactSeq: 0
property string contactPending: ""
function threadRecencyJson() {
var rec = {}
for (var i = 0; i < threads.length; i++) {
var t = threads[i]
var ts = String(t.last_ts || "")
if (ts === "") continue
if (t.handle) rec[String(t.handle)] = ts
if (t.chat) rec[String(t.chat)] = ts
}
return JSON.stringify(rec)
}
function newFieldQuery() {
var d = String(newField.displayText || "")
var t = String(newField.text || "")
return (d !== "" ? d : t).trim()
}
function scheduleContactSearch() {
if (!newMode) return
if (newFieldQuery() === "") {
newSearchTimer.stop()
contactSeq++ // an in-flight answer must not repopulate an emptied field (Astra A#5)
newResults = []
newNote = ""
newQueryRan = ""
newCursor = 0
return
}
if (newFieldQuery() !== newQueryRan) contactSeq++
newNote = "searching…"
newSearchTimer.restart()
}
function runContactSearch() {
var q = newFieldQuery()
if (q === "") return
// Bump the generation NOW so the in-flight (older) result is rejected,
// never shown as clickable rows under the newer query (Codex audit #5).
if (contactProc.running) { contactSeq++; contactPending = q; return }
contactSeq++
// The previous query's rows are not answers to THIS query: clear them so
// nothing stale is clickable — or Enter-able, since acceptNewField gates on
// newQueryRan, which is about to become q (Astra A#5).
if (q !== newQueryRan) { newResults = []; newCursor = 0 }
newQueryRan = q
newNote = "searching…"
// The recency map names every conversation you have. argv is world-readable
// through `ps`, so it goes on stdin — the same rule message text follows.
contactProc.command = ["bun", root.contactScript, q, "--recency-stdin"]
contactProc.stdinEnabled = true
contactProc.running = true
contactProc.write(root.threadRecencyJson())
contactProc.stdinEnabled = false
}
function acceptNewField() {
var q = newFieldQuery()
if (q !== "" && q === newQueryRan && newResults.length > 0) {
var i = Math.max(0, Math.min(newCursor, newResults.length - 1))
openContact(newResults[i])
return
}
runContactSearch()
}
function moveNewCursor(dy) {
if (newResults.length === 0 || dy === 0) return
// Up from the first hit brings the field (which already has focus) back
// into view, as moveCursor does for the thread list.
if (dy < 0 && newCursor <= 0) { threadFlick.contentY = 0; return }
newCursor = Math.max(0, Math.min(newResults.length - 1, newCursor + dy))
scrollCursorIntoView()
}
/** Start (or resume) a DM with a picked handle. An existing thread is
* reused so history shows; otherwise a synthetic DM thread — sendable,
* because DMs only need --to <handle>. */
function openContact(hit) {
newMode = false
for (var i = 0; i < threads.length; i++) {
if (String(threads[i].chat) === String(hit.handle)) { openThread(threads[i]); return }
}
openThread({ chat: hit.handle, guid: "", name: hit.name, handle: hit.handle,