@aivin-labs/cli 1.0.11 → 1.0.21

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 (88) hide show
  1. package/README.md +325 -288
  2. package/bin/cli.mjs +163 -17
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +12 -0
  9. package/bin/lib/remote/browserTunnel.mjs +47 -8
  10. package/bin/lib/remote/callLedger.mjs +94 -14
  11. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  12. package/bin/lib/remote/client.mjs +1024 -808
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +2 -2
  15. package/bin/lib/remote/constants.mjs +261 -234
  16. package/bin/lib/remote/credentials.mjs +81 -4
  17. package/bin/lib/remote/daemonLock.mjs +57 -17
  18. package/bin/lib/remote/dailyBrowser.mjs +8 -2
  19. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  20. package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
  21. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  22. package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
  23. package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
  24. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  25. package/bin/lib/remote/desktop/index.mjs +58 -7
  26. package/bin/lib/remote/desktop/linux.mjs +1 -1
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
  28. package/bin/lib/remote/desktop/mac.mjs +2 -2
  29. package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
  30. package/bin/lib/remote/desktop/strings.mjs +28 -2
  31. package/bin/lib/remote/desktop/traySource.mjs +905 -527
  32. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  33. package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
  34. package/bin/lib/remote/deviceProfile.mjs +1 -0
  35. package/bin/lib/remote/docText.mjs +85 -0
  36. package/bin/lib/remote/fileIndexer.mjs +773 -399
  37. package/bin/lib/remote/folderRules.mjs +143 -0
  38. package/bin/lib/remote/gitSafe.mjs +31 -0
  39. package/bin/lib/remote/gui/index.mjs +170 -19
  40. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  41. package/bin/lib/remote/gui/windowsHost.mjs +12 -3
  42. package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
  43. package/bin/lib/remote/httpTransfer.mjs +64 -3
  44. package/bin/lib/remote/idempotency.mjs +49 -20
  45. package/bin/lib/remote/localPolicy.mjs +81 -9
  46. package/bin/lib/remote/mascot/ask.mjs +207 -42
  47. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
  49. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  50. package/bin/lib/remote/mascot/bot.mjs +54 -5
  51. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  52. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  53. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  54. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  55. package/bin/lib/remote/mascot/hostSource.mjs +331 -52
  56. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  57. package/bin/lib/remote/mascot/images.mjs +111 -0
  58. package/bin/lib/remote/mascot/index.mjs +663 -493
  59. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  60. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  61. package/bin/lib/remote/mascot/mood.mjs +57 -0
  62. package/bin/lib/remote/mascot/rigSource.mjs +648 -609
  63. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  64. package/bin/lib/remote/mascot/strings.mjs +456 -375
  65. package/bin/lib/remote/mascot/ui.mjs +27 -7
  66. package/bin/lib/remote/multiUser.mjs +7 -2
  67. package/bin/lib/remote/notify.mjs +4 -1
  68. package/bin/lib/remote/office/index.mjs +12 -6
  69. package/bin/lib/remote/osSearch.mjs +107 -0
  70. package/bin/lib/remote/processes.mjs +5 -2
  71. package/bin/lib/remote/sandbox.mjs +26 -0
  72. package/bin/lib/remote/secretPaths.mjs +21 -0
  73. package/bin/lib/remote/sqliteDb.mjs +51 -0
  74. package/bin/lib/remote/tokenRotation.mjs +28 -0
  75. package/bin/lib/remote/toolHandlers.mjs +852 -741
  76. package/bin/lib/remote/watchBatcher.mjs +56 -0
  77. package/bin/lib/remoteControl.mjs +26 -26
  78. package/bin/lib/selfUpdate.mjs +12 -2
  79. package/bin/lib/update/binarySwap.mjs +15 -1
  80. package/bin/lib/update/state.mjs +10 -0
  81. package/docs/AIVIN_MASCOT.md +14 -0
  82. package/docs/CLI.md +1545 -1484
  83. package/docs/media/aivin-ecosystem.jpg +0 -0
  84. package/docs/media/aivin-mascot-live.gif +0 -0
  85. package/docs/media/aivin-mascot-live.png +0 -0
  86. package/docs/media/aivin-remote-architecture.svg +102 -0
  87. package/package.json +75 -71
  88. package/docs/media/aivin-mascot-states.mp4 +0 -0
@@ -1,512 +1,658 @@
1
- /**
2
- * Ô hỏi của linh vật, phía cửa sổ (29/10/2026) — mã PowerShell chèn vào host.ps1 tại dấu `# @ASK_HOOK` (index.mjs ghép), dùng khung
3
- * XAML `Ask` / `ChatList` / `AskBox` / `MicBtn` (`MicIcon` / `SendIcon`) / `AskStatus` của hostSource.mjs.
4
- *
5
- * - Rê chuột vào bot → ô hỏi hiện ra (chưa nhận bàn phím); rời chuột ~0,6 s → ẩn, trừ khi đang dùng (đang gõ trong ô, đang ghi âm, đang
6
- * chờ trả lời — trả lời xong mà chuột không ở đó thì ẩn sau 8 s). Bấm bot / bấm vào ô → cửa sổ nhận bàn phím (bỏ WS_EX_NOACTIVATE + đưa lên
7
- * trước) để gõ; bấm ra ngoài / Esc / bấm bot lần nữa thì đóng, về không cướp focus. Chữ gõ dở vẫn giữ cho lần hiện sau. Chuột phải → nhật ký.
8
- * - Mỗi lúc một khung: ô hỏi đang mở thì việc bot làm trên máy không bật bong bóng (chỉ cập nhật chữ); ô đóng mà bot còn bận thì
9
- * bong bóng hiện lại bước mới nhất.
10
- * - Một nút ở góc dưới: ô trống = mic, có chữ = gửi. Enter / nút gửi → `{ t: 'ask', text, window }`. Mic = nói chuyện trực tiếp (realtime) với Aivin:
11
- * bấm → `{ t: 'voice_start', window }`, daemon mở phiên thoại trên BE rồi gửi `voice_begin { in_rate, out_rate }` → mở mic + loa (voiceSource.mjs,
12
- * âm thanh đi thẳng giữa C# và stdin/stdout). Đang nghe mà bấm → `voice_stop`; bot đang nói mà bấm → `voice_interrupt` (ngắt lời; có
13
- * khử tiếng vọng thì nói chen bằng giọng cũng được). BE cũ chưa có nói chuyện: `voice_begin { state: 'recording' }` — nói xong bấm mic để gửi.
14
- * Phím tắt (Ctrl+Alt+Space, bị chiếm thì Win+Alt+Space / Ctrl+Alt+V; hiện trong chú thích nút mic) ở đâu cũng = bấm mic. Trạng thái "đang nói" giữ tới khi loa im thật (BE báo xong sớm hơn loa phát hết); mặt bot theo
15
- * trạng thái nói chuyện (nghe / nghĩ / nói).
16
- * - `window` = `{ window: '0x..', title, process }` của cửa sổ chủ máy đang dùng ngay trước khi rê / bấm vào bot hay nhấn phím tắt (không tính
17
- * chính bot, thanh tác vụ, màn nền), hoặc null — để "cái này" trong câu hỏi trỏ đúng cửa sổ đó.
18
- * - Lệnh vào thêm: `chat { role, id, text, remove? }`, `chat_busy { busy }`, `ask_status { text }`, `voice_begin`, `voice_state { state }`
19
- * (listening | thinking | speaking), `voice_end { text? }`.
20
- * Giữ toàn ASCII (xem hostSource.mjs).
21
- */
22
- import { ASK_BTN, MASCOT_CENTER } from './hostSource.mjs';
23
-
24
- /**
25
- * Lựa chọn khi Aivin hỏi lại: mỗi thẻ tô một màu pastel nhạt (xoay vòng hồng → tím nhạt → xanh trời → xanh bạc hà, theo viền ô hỏi), không
26
- * viền, chữ xám đậm; rê chuột thì thẻ đậm lên nhẹ.
27
- */
28
- const CHOICE_CARDS = Object.freeze(['#FDF2F8', '#F5F3FF', '#EFF6FF', '#ECFDF5']);
29
- const CHOICE_INK = '#3B4256';
30
- const CHOICE_HOVER = '#0F1E1B4B';
31
- /** Viền chấm tròn / ô vuông đầu mỗi lựa chọn (chưa tích). */
32
- const CHOICE_MARK = '#9AA1B2';
33
- /**
34
- * Icon cuối lựa chọn: tên Lucide (như thẻ chọn trên Aivin; so khớp viết thường, bỏ dấu gạch) → mã ký tự Segoe MDL2 Assets. Tên không có ở
35
- * đây thì không vẽ icon; một emoji / ký hiệu ngắn thì vẽ nguyên.
36
- */
37
- const CHOICE_ICON_GLYPHS = Object.freeze({
38
- check: 'E73E', checkcircle: 'E930', x: 'E711', file: 'E8A5', filetext: 'E8A5', folder: 'E8B7', folderopen: 'E838', calendar: 'E787',
39
- clock: 'E823', mail: 'E715', send: 'E724', globe: 'E774', link: 'E71B', search: 'E721', settings: 'E713', user: 'E77B', users: 'E716',
40
- download: 'E896', upload: 'E898', image: 'EB9F', trash: 'E74D', trash2: 'E74D', pencil: 'E70F', edit: 'E70F', play: 'E768', pause: 'E769',
41
- star: 'E734', heart: 'EB51', phone: 'E717', lock: 'E72E', unlock: 'E785', alerttriangle: 'E7BA', trianglealert: 'E7BA', info: 'E946',
42
- home: 'E80F', refreshcw: 'E72C', copy: 'E8C8', save: 'E74E', monitor: 'E7F4', terminal: 'E756', code: 'E943', thumbsup: 'E8E1',
43
- thumbsdown: 'E8E0', arrowright: 'E72A', externallink: 'E8A7', mic: 'E720', camera: 'E722', printer: 'E749', share: 'E72D',
44
- });
45
-
46
- export const ASK_PS1 = String.raw`
47
- # ---- Ask box (askHostSource.mjs) ----
48
- Add-Type -TypeDefinition @'
49
- using System; using System.Runtime.InteropServices;
50
- namespace AivinMascotAsk {
51
- public static class Native {
52
- [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);
53
- [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr h);
54
- [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
55
- [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, IntPtr pid);
56
- [DllImport("user32.dll")] static extern bool AttachThreadInput(uint a, uint b, bool attach);
57
- [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
58
- [DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr h, int id, uint mods, uint vk);
59
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr h, System.Text.StringBuilder s, int n);
60
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, System.Text.StringBuilder s, int n);
61
- [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
62
- /** The window the person is using (not the bot, the taskbar or the desktop): { "0x..", title, pid }, or null. */
63
- public static string[] UserWindow() {
64
- IntPtr h = GetForegroundWindow(); if (h == IntPtr.Zero) return null;
65
- uint pid; GetWindowThreadProcessId(h, out pid);
66
- if (pid == (uint)System.Diagnostics.Process.GetCurrentProcess().Id) return null;
67
- var c = new System.Text.StringBuilder(256); GetClassName(h, c, 256);
68
- string cls = c.ToString(); if (cls == "Shell_TrayWnd" || cls == "Progman" || cls == "WorkerW") return null;
69
- var t = new System.Text.StringBuilder(512); GetWindowText(h, t, 512);
70
- return new string[] { "0x" + h.ToInt64().ToString("x"), t.ToString(), pid.ToString() };
71
- }
72
- /** The user just clicked the bot: take keyboard focus (Windows refuses SetForegroundWindow from a background window otherwise). */
73
- public static bool TakeFocus(IntPtr h) {
74
- uint fg = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero), me = GetCurrentThreadId();
75
- bool attached = fg != 0 && fg != me && AttachThreadInput(fg, me, true);
76
- try { BringWindowToTop(h); return SetForegroundWindow(h); }
77
- finally { if (attached) AttachThreadInput(fg, me, false); }
78
- }
79
- }
80
- }
81
- '@
82
- (E 'AskHint').Text = $T.ask_hint; (E 'MicBtn').ToolTip = $T.ask_mic
83
- # "New chat" on the activity panel: the daemon opens a new chat on the server and sends chat_clear; the ask box opens for the first line.
84
- (E 'NewChatText').Text = $T.new_chat; (E 'NewChatBtn').ToolTip = $T.new_chat_tip
85
- (E 'NewChatBtn').Add_Click({ Send @{ t = 'new_chat' }; OpenAsk })
86
-
87
- function AskShow($name) {
88
- $script:bubbleTimer.Stop(); (E 'Bubble').Visibility = 'Collapsed'; (E 'Bubble').Opacity = 0
89
- $el = E $name; $el.Visibility = 'Visible'; $w.FindResource('PanelIn').Begin($el)
90
- }
91
- function AskHide($name) {
92
- $el = E $name; if ($el.Visibility -ne 'Visible') { return }
93
- # The ask box may be shown again while it is still fading out: then the finished fade must not collapse it.
94
- $sb = $w.FindResource('PanelOut').Clone(); $sb.Add_Completed({ if ($name -ne 'Ask' -or -not $script:askOpen) { (E $name).Visibility = 'Collapsed' } }.GetNewClosure()); $sb.Begin($el)
95
- }
96
- function SetActivatable($on) {
97
- if (-not $script:hwnd) { return }
98
- $ex = [AivinMascot.Native]::GetWindowLong($script:hwnd, -20)
99
- $ex = if ($on) { $ex -band (-bnot 0x08000000) } else { $ex -bor 0x08000000 }
100
- [void][AivinMascot.Native]::SetWindowLong($script:hwnd, -20, $ex)
101
- }
102
- function AskStatus($text) {
103
- $el = E 'AskStatus'; $el.Text = [string]$text; $el.Visibility = if ($text) { 'Visible' } else { 'Collapsed' }
104
- }
105
- $script:askOpen = $false; $script:askFocused = $false
106
- # The window the person was on right before reaching for the bot: sent with each question / talk so "this" means that window.
107
- $script:askTarget = $null
108
- function NoteTarget {
109
- $i = $null; try { $i = [AivinMascotAsk.Native]::UserWindow() } catch { }
110
- if (-not $i) { return }
111
- $p = ''; try { $p = (Get-Process -Id ([int]$i[2]) -ErrorAction Stop).ProcessName } catch { }
112
- $script:askTarget = @{ window = $i[0]; title = $i[1]; process = $p }
113
- }
114
- function PeekAsk {
115
- NoteTarget
116
- if ($script:askOpen) { return }
117
- $script:askOpen = $true; AskShow 'Ask'; $w.FindResource('AskGlow').Begin($w, $true)
118
- }
119
- function OpenAsk {
120
- NoteTarget; AskHide 'Panel'; PeekAsk
121
- $script:askFocused = $true; SetActivatable $true; $ok = [AivinMascotAsk.Native]::TakeFocus($script:hwnd); [void]$w.Activate(); Dbg "ask focus=$ok"
122
- [void](E 'AskBox').Focus(); [void][Windows.Input.Keyboard]::Focus((E 'AskBox'))
123
- }
124
- function CloseAsk {
125
- $script:askHideTimer.Stop()
126
- if (-not $script:askOpen) { return }
127
- if ($script:voiceLive) { StopVoice }
128
- $script:askOpen = $false; $script:askFocused = $false
129
- AskHide 'Ask'; SetActivatable $false; $w.FindResource('AskGlow').Stop($w)
130
- }
131
- function MascotClick { if ($script:askFocused) { CloseAsk } else { OpenAsk } }
132
- # One box at a time: while the ask box is open, what the bot does on the machine only updates the text; the bubble
133
- # (notification) comes back with the latest step once the box closes, if the bot is still busy.
134
- $script:baseShowBubble = (Get-Item function:ShowBubble).ScriptBlock
135
- function ShowBubble($text) { if ($script:askOpen) { (E 'NowText').Text = $text; return }; & $script:baseShowBubble $text }
136
- $script:baseCloseAsk = (Get-Item function:CloseAsk).ScriptBlock
137
- function CloseAsk {
138
- $was = $script:askOpen; & $script:baseCloseAsk
139
- if (-not $was -or (E 'Panel').Visibility -eq 'Visible') { return }
140
- if ($script:chatBusy -and $script:chatLast) { ChatBubble $script:chatLast }
141
- elseif ((IsBusy) -or $script:state -eq 'waiting') { & $script:baseShowBubble (E 'NowText').Text }
142
- }
143
- # What the chat turn is doing, short, for the bubble on the bot's head while the box is closed: progress lines, the answer as it is
144
- # written (its tail), the answer / error. Stays up while the turn runs; once it ends the bubble times out as usual.
145
- $script:chatLast = ''
146
- function ChatShort($m) {
147
- $text = ([string]$m.text -replace '\s+', ' ').Trim()
148
- if ($m.partial -and $text.Length -gt 90) { $text = "$([char]0x2026)" + $text.Substring($text.Length - 89) }
149
- $text
150
- }
151
- function ChatBubble($text) {
152
- if (-not $text -or (E 'Panel').Visibility -eq 'Visible') { return }
153
- & $script:baseShowBubble $text
154
- if ($script:chatBusy) { $script:bubbleTimer.Stop() } else { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
155
- }
156
- # Hover: the box peeks while the mouse is over the bot / the box and slips away shortly after it leaves, unless it is in use.
157
- $script:askHideTimer = New-Object Windows.Threading.DispatcherTimer
158
- $script:askHideTimer.Add_Tick({ $script:askHideTimer.Stop(); if (-not (AskInUse)) { CloseAsk } })
159
- # In use = keep the box out: mouse over it, talking, dragging, a pinned question, or focused with unsent text. Waiting on a turn is not
160
- # in use - the box slips away and the bot shows what it is doing in the bubble on its head (ChatBubble).
161
- function AskInUse {
162
- $w.IsMouseOver -or $script:voiceLive -or $script:drag -or $script:askPinned -or ($script:askFocused -and (E 'AskBox').Text.Trim())
163
- }
164
- # Aivin is waiting for an answer (HIL): the box stays out with the question + option buttons until it is answered (no focus taken).
165
- $script:askPinned = $false
166
- function HideAskLater($ms) { $script:askHideTimer.Stop(); $script:askHideTimer.Interval = [TimeSpan]::FromMilliseconds($ms); $script:askHideTimer.Start() }
167
- (E 'Mascot').ToolTip = $null
168
- (E 'Mascot').Add_MouseEnter({ $script:askHideTimer.Stop(); if ((E 'Panel').Visibility -ne 'Visible' -and -not $script:drag) { PeekAsk } })
169
- (E 'Ask').Add_MouseEnter({ $script:askHideTimer.Stop() })
170
- # Focused but empty: a longer grace (clicked the bot, then moved the mouse off to type).
171
- $w.Add_MouseLeave({ if ($script:askOpen) { HideAskLater $(if ($script:askFocused) { 2500 } else { 600 }) } })
172
- # Clicked somewhere else: give the keyboard back and let the box go once the mouse is away too.
173
- $w.Add_Deactivated({ if ($script:askFocused) { $script:askFocused = $false; SetActivatable $false; if (-not $w.IsMouseOver) { HideAskLater 600 } } })
174
- # Clicking into the peeking box = about to type: take keyboard focus.
175
- (E 'Ask').Add_PreviewMouseLeftButtonDown({ if (-not $script:askFocused) { OpenAsk } })
176
- # Right-click on the bot: the activity panel.
177
- (E 'Mascot').Add_MouseRightButtonUp({ param($s, $e) CloseAsk; TogglePanel; $e.Handled = $true })
178
- # One button: empty box = mic, typed text = send.
179
- # Waiting on a turn the server can stop (chat_busy { cancel }): the empty-box button is a stop button instead of the mic.
180
- function StopMode { $script:chatBusy -and $script:canCancel -and -not $script:voiceLive -and -not (E 'AskBox').Text.Trim() }
181
- function SyncAction {
182
- $typed = [bool](E 'AskBox').Text.Trim()
183
- $stop = StopMode
184
- (E 'AskHint').Visibility = if ((E 'AskBox').Text) { 'Collapsed' } else { 'Visible' }
185
- (E 'SendIcon').Visibility = if ($typed) { 'Visible' } else { 'Collapsed' }; (E 'MicIcon').Visibility = if ($typed -or $stop) { 'Collapsed' } else { 'Visible' }
186
- (E 'StopIcon').Visibility = if ($stop) { 'Visible' } else { 'Collapsed' }
187
- (E 'MicBtn').ToolTip = if ($typed) { $T.ask_send } elseif ($stop) { $T.ask_stop } else { $T.ask_mic }
188
- InputLayout
189
- }
190
- # Input row height: two lines for a fresh question; once a conversation is above it (or while talking), one line with the hint and the mic
191
- # button centred on the same line - the box only grows (mic back at the bottom) when the typed text wraps.
192
- function InputLayout {
193
- $box = E 'AskBox'
194
- # Box hidden = the voice bar is in its place (VoiceLook hides it before the voice state is set).
195
- $compact = $box.Visibility -ne 'Visible' -or [bool]$script:voiceLive -or (E 'ChatList').Children.Count -gt 0
196
- $wrapped = $box.Visibility -eq 'Visible' -and $box.LineCount -gt 1
197
- $box.Parent.MinHeight = if ($compact) { 26 } else { 40 }
198
- $mid = if ($compact -and -not $wrapped) { 'Center' } else { 'Top' }
199
- $box.VerticalAlignment = $mid; (E 'AskHint').VerticalAlignment = $mid
200
- (E 'MicBtn').VerticalAlignment = if ($compact -and -not $wrapped) { 'Center' } else { 'Bottom' }
201
- }
202
- (E 'AskBox').Add_TextChanged({ SyncAction; AttendAsk })
203
- # Typing: the bot looks at the box (above or below it) while keys come in; a little nod when a question / answer goes out.
204
- function AttendAsk {
205
- if (-not (E 'AskBox').Text) { return }
206
- $a = E 'Ask'; $p = $a.TranslatePoint((New-Object Windows.Point ($a.ActualWidth / 2), ($a.ActualHeight / 2)), (E 'Mascot'))
207
- $script:rig.Attend($p.X - ${MASCOT_CENTER.x}, $p.Y - ${MASCOT_CENTER.y})
208
- }
209
-
210
- $script:chatBusy = $false
211
- $script:canCancel = $false
212
- function SubmitAsk {
213
- $text = (E 'AskBox').Text.Trim(); if (-not $text -or $script:chatBusy -or $script:voiceLive) { return }
214
- NoteTarget; (E 'AskBox').Text = ''; $script:rig.Play('ack'); Send @{ t = 'ask'; text = $text; window = $script:askTarget }
215
- }
216
- (E 'AskBox').Add_KeyDown({ param($s, $e)
217
- if ($e.Key -eq 'Return') { SubmitAsk; $e.Handled = $true }
218
- elseif ($e.Key -eq 'Escape') { CloseAsk; $e.Handled = $true }
219
- })
220
-
221
- # Conversation rows: user (right, light brand), assistant (left, grey), one live progress line, errors. Bubbles point at their speaker
222
- # (the corner on the speaker's side is nearly square, 3 px) and new ones fade + rise in.
223
- $script:chatRows = @{}
224
- # "Working on it": three dots bouncing in turn inside an assistant bubble (a staggered key-frame hop, then a rest).
225
- function TypingDots {
226
- $sp = New-Object Windows.Controls.StackPanel; $sp.Orientation = 'Horizontal'; $sp.Margin = '1,5,1,5'
227
- for ($i = 0; $i -lt 3; $i++) {
228
- $e = New-Object Windows.Shapes.Ellipse; $e.Width = 6; $e.Height = 6; $e.Margin = '2,0,2,0'; $e.Fill = Brush '#9AA0AB'
229
- $tt = New-Object Windows.Media.TranslateTransform; $e.RenderTransform = $tt
230
- $a = New-Object Windows.Media.Animation.DoubleAnimationUsingKeyFrames
231
- $a.Duration = [TimeSpan]::FromMilliseconds(1200); $a.BeginTime = [TimeSpan]::FromMilliseconds(160 * $i)
232
- $a.RepeatBehavior = [Windows.Media.Animation.RepeatBehavior]::Forever
233
- foreach ($k in @(@(0, 0), @(280, -4.5), @(560, 0), @(1200, 0))) {
234
- $f = New-Object Windows.Media.Animation.EasingDoubleKeyFrame ([double]$k[1]), ([Windows.Media.Animation.KeyTime]::FromTimeSpan([TimeSpan]::FromMilliseconds($k[0])))
235
- $f.EasingFunction = New-Object Windows.Media.Animation.SineEase; [void]$a.KeyFrames.Add($f)
236
- }
237
- $tt.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $a)
238
- [void]$sp.Children.Add($e)
239
- }
240
- $sp
241
- }
242
- function ChatRow($m) {
243
- $list = E 'ChatList'; $id = [string]$m.id
244
- $row = $null; if ($id) { $row = $script:chatRows[$id] }
245
- if ($m.remove) { if ($row) { [void]$list.Children.Remove($row.box); $script:chatRows.Remove($id) }; return }
246
- (E 'ChatScroll').Visibility = 'Visible'
247
- if (-not $row) {
248
- # Segoe UI adds its own space above / below the letters: block line height + slim vertical padding so the space you see is about
249
- # the same on all four sides.
250
- $b = New-Object Windows.Controls.Border; $b.Padding = '9,4,9,4'; $b.Margin = '0,0,0,4'; $b.MaxWidth = 188
251
- $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.FontSize = 12; $tb.LineHeight = 16; $tb.LineStackingStrategy = 'BlockLineHeight'
252
- $b.Child = $tb; [void]$list.Children.Add($b)
253
- $slide = New-Object Windows.Media.TranslateTransform 0, 6; $b.RenderTransform = $slide
254
- $ease = New-Object Windows.Media.Animation.CubicEase; $ease.EasingMode = 'EaseOut'
255
- $fade = New-Object Windows.Media.Animation.DoubleAnimation 0, 1, ([TimeSpan]::FromMilliseconds(200)); $fade.EasingFunction = $ease
256
- $rise = New-Object Windows.Media.Animation.DoubleAnimation 6, 0, ([TimeSpan]::FromMilliseconds(240)); $rise.EasingFunction = $ease
257
- $b.BeginAnimation([Windows.UIElement]::OpacityProperty, $fade); $slide.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $rise)
258
- $row = @{ box = $b; text = $tb }
259
- if ($id) { $script:chatRows[$id] = $row }
260
- while ($list.Children.Count -gt 40) { $list.Children.RemoveAt(0) }
261
- }
262
- $role = [string]$m.role
263
- $row.box.HorizontalAlignment = if ($role -eq 'user') { 'Right' } else { 'Left' }
264
- # CornerRadius = top-left, top-right, bottom-right, bottom-left.
265
- $row.box.CornerRadius = if ($role -eq 'user') { '10,10,3,10' } elseif ($role -eq 'progress') { '0' } else { '10,10,10,3' }
266
- $bg = if ($role -eq 'user') { '#E8F3FF' } elseif ($role -eq 'error') { '#FFECE8' } elseif ($role -eq 'progress') { '#00FFFFFF' } else { '#F4F6FA' }
267
- $fg = if ($role -eq 'progress') { $P.muted } elseif ($role -eq 'error') { '#CB2634' } else { $P.ink }
268
- $row.box.Background = Brush $bg; $row.text.Foreground = Brush $fg
269
- $row.text.FontStyle = if ($role -eq 'progress') { 'Italic' } else { 'Normal' }
270
- $row.text.Text = [string]$m.text
271
- if ($m.typing) {
272
- if (-not $row.dots) { $row.dots = TypingDots }
273
- $row.box.Child = $row.dots; $row.box.Background = Brush '#F4F6FA'; $row.box.CornerRadius = '10,10,10,3'
274
- } elseif ($row.dots -and $row.box.Child -ne $row.text) { $row.box.Child = $row.text }
275
- # Words the owner is still saying: lighter until the sentence is settled (the box's own opacity is the fade-in).
276
- $row.text.Opacity = if ($m.partial) { 0.55 } else { 1 }
277
- (E 'ChatScroll').ScrollToEnd()
278
- InputLayout
279
- }
280
-
281
- # Aivin asked something with choices: a vertical list, one full-width card per option (the daemon clears them once answered). Typing
282
- # still works. Like the cards in Aivin: a round dot at the start (pick one: click = answer) or a square box (pick several: click ticks /
283
- # unticks, a confirm button sends the ticked ones), the text, the option's icon at the end when it has one we can draw.
284
- # Soft look: each card filled with a light pastel (cycling the ask box's glow colors), no border, dark-grey text; hover deepens it.
285
- $script:iconGlyphs = ConvertFrom-Json '${JSON.stringify(CHOICE_ICON_GLYPHS)}'
286
- function ChoiceIcon($name) {
287
- $n = [string]$name; if (-not $n) { return $null }
288
- $tb = New-Object Windows.Controls.TextBlock; $tb.FontSize = 12; $tb.Margin = '8,1,0,0'; $tb.VerticalAlignment = 'Top'; $tb.Foreground = Brush '${CHOICE_INK}'
289
- # An emoji / short symbol is drawn as is; a Lucide name (as Aivin's cards use) maps to the matching Segoe MDL2 glyph, unknown = none.
290
- if ($n.Length -le 2) { $tb.Text = $n; $tb.FontFamily = 'Segoe UI Emoji'; return $tb }
291
- $code = $script:iconGlyphs.(($n -replace '[^A-Za-z0-9]', '').ToLowerInvariant()); if (-not $code) { return $null }
292
- $tb.Text = [string][char][Convert]::ToInt32($code, 16); $tb.FontFamily = 'Segoe MDL2 Assets'; $tb.Opacity = 0.75; return $tb
293
- }
294
- function ChoiceMark($multi) {
295
- $m = New-Object Windows.Controls.Border; $m.Width = 13; $m.Height = 13; $m.Margin = '0,2,8,0'; $m.VerticalAlignment = 'Top'
296
- $m.CornerRadius = if ($multi) { '3.5' } else { '6.5' }; $m.BorderThickness = '1.4'
297
- $tick = New-Object Windows.Shapes.Path; $tick.Data = [Windows.Media.Geometry]::Parse('M2.4,6.2 L4.9,8.6 L9.4,3.6'); $tick.Stroke = Brush '#FFFFFF'
298
- $tick.StrokeThickness = 1.7; $tick.StrokeStartLineCap = 'Round'; $tick.StrokeEndLineCap = 'Round'; $tick.StrokeLineJoin = 'Round'
299
- $m.Child = $tick; SetTicked $m $false; $m
300
- }
301
- function SetTicked($mark, $on) {
302
- $mark.Background = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '#B3FFFFFF' }
303
- $mark.BorderBrush = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '${CHOICE_MARK}' }
304
- $mark.Child.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
305
- }
306
- $script:picked = New-Object Collections.ArrayList; $script:choiceMarks = @{}; $script:choiceConfirm = $null
307
- function SyncConfirm {
308
- $b = $script:choiceConfirm; if (-not $b) { return }
309
- $b.Content = $T.ask_confirm -replace '\{n\}', $script:picked.Count
310
- $b.Visibility = if ($script:picked.Count) { 'Visible' } else { 'Collapsed' }
311
- }
312
- function ChoiceButtons($options, $multiple) {
313
- $panel = E 'Choices'; $panel.Children.Clear(); $k = 0; $multi = [bool]$multiple
314
- $script:picked.Clear(); $script:choiceMarks = @{}; $script:choiceConfirm = $null
315
- $cards = @(${CHOICE_CARDS.map((c) => `'${c}'`).join(', ')})
316
- foreach ($o in @($options)) {
317
- if (-not $o) { continue }
318
- $c = $cards[$k % $cards.Count]; $k++; $id = [string]$o.id
319
- $row = New-Object Windows.Controls.DockPanel; $row.Width = 192
320
- $mark = ChoiceMark $multi; [Windows.Controls.DockPanel]::SetDock($mark, 'Left'); [void]$row.Children.Add($mark)
321
- $icon = ChoiceIcon $o.icon; if ($icon) { [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$row.Children.Add($icon) }
322
- $tb = New-Object Windows.Controls.TextBlock; $tb.Text = [string]$o.text; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; [void]$row.Children.Add($tb)
323
- $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $row; $btn.CommandParameter = $id
324
- $btn.FontSize = 12; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,4'; $btn.HorizontalAlignment = 'Stretch'
325
- $btn.Background = Brush $c; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
326
- $script:choiceMarks[$id] = $mark
327
- if ($multi) {
328
- $btn.Add_Click({ param($s)
329
- $id = [string]$s.CommandParameter; $on = -not $script:picked.Contains($id)
330
- if ($on) { [void]$script:picked.Add($id) } else { $script:picked.Remove($id) }
331
- SetTicked $script:choiceMarks[$id] $on; SyncConfirm
332
- })
333
- } else {
334
- $btn.Add_Click({ param($s) if (-not $script:chatBusy) { SetTicked $script:choiceMarks[[string]$s.CommandParameter] $true; $script:rig.Play('ack'); Send @{ t = 'choose'; id = [string]$s.CommandParameter } } })
335
- }
336
- [void]$panel.Children.Add($btn)
337
- }
338
- if ($multi -and $panel.Children.Count) {
339
- $ok = New-Object Windows.Controls.Button; $ok.Style = $w.FindResource('Btn'); $ok.FontSize = 12; $ok.Padding = '12,5,12,5'; $ok.Margin = '0,1,0,4'
340
- $ok.HorizontalAlignment = 'Right'; $ok.Background = Brush '${ASK_BTN.icon}'; $ok.Foreground = Brush '#FFFFFF'; $ok.BorderThickness = '0'; $ok.Tag = Brush '#1F000000'
341
- $ok.Add_Click({ if (-not $script:chatBusy -and $script:picked.Count) { $script:rig.Play('ack'); Send @{ t = 'choose'; ids = @($script:picked.ToArray()) } } })
342
- $script:choiceConfirm = $ok; [void]$panel.Children.Add($ok); SyncConfirm
343
- }
344
- $panel.Visibility = if ($panel.Children.Count) { 'Visible' } else { 'Collapsed' }
345
- }
346
-
347
- # Voice: a live conversation with Aivin (voiceSource.mjs streams the mic / speaker). '' = off, else connecting | listening | thinking | speaking,
348
- # or recording (older Aivin server without live voice: talk, click the mic to send, it goes through voice-to-text).
349
- $script:voiceLive = ''
350
- # While talking, the text input gives way to a voice bar in the same spot: level bars (the mic while listening, the bot's voice while it
351
- # talks, a soft wave while it thinks) + a short state. The mic button turns red (its tooltip says what a click does now).
352
- $inputCell = (E 'AskBox').Parent
353
- $voiceBar = New-Object Windows.Controls.StackPanel; $voiceBar.Orientation = 'Horizontal'; $voiceBar.VerticalAlignment = 'Center'; $voiceBar.Visibility = 'Collapsed'
354
- $voiceBar.Margin = '2,0,0,0'
355
- $script:levelBars = @()
356
- foreach ($i in 0..4) {
357
- $r = New-Object Windows.Shapes.Rectangle; $r.Width = 3; $r.Height = 4; $r.RadiusX = 1.5; $r.RadiusY = 1.5; $r.Margin = '0,0,3,0'
358
- $r.VerticalAlignment = 'Center'; $r.Fill = Brush '#8B7CF6'; [void]$voiceBar.Children.Add($r); $script:levelBars += $r
359
- }
360
- $voiceLabel = New-Object Windows.Controls.TextBlock; $voiceLabel.FontSize = 13; $voiceLabel.Foreground = Brush $P.ink; $voiceLabel.Margin = '7,0,0,1'
361
- $voiceLabel.VerticalAlignment = 'Center'; $voiceLabel.TextTrimming = 'CharacterEllipsis'; [void]$voiceBar.Children.Add($voiceLabel)
362
- [void]$inputCell.Children.Add($voiceBar)
363
- $script:levelShape = @(0.55, 0.85, 1, 0.85, 0.55); $script:levelNow = @(0, 0, 0, 0, 0)
364
- $script:levelTimer = New-Object Windows.Threading.DispatcherTimer; $script:levelTimer.Interval = [TimeSpan]::FromMilliseconds(50)
365
- $script:levelTimer.Add_Tick({
366
- $t = [Environment]::TickCount / 1000.0
367
- $level = switch ($script:voiceLive) {
368
- 'listening' { [AivinMascot.Voice]::MicLevel }
369
- 'recording' { [AivinMascot.Voice]::MicLevel }
370
- 'speaking' { [AivinMascot.Voice]::OutLevel }
371
- default { -1 }
372
- }
373
- for ($i = 0; $i -lt 5; $i++) {
374
- # No live level (connecting / thinking): a slow travelling wave, so it reads as "working on it".
375
- $target = if ($level -lt 0) { 0.18 + 0.22 * (0.5 + 0.5 * [Math]::Sin($t * 5 - $i * 0.9)) } else { [Math]::Min(1, $level * $script:levelShape[$i] * (0.8 + 0.2 * [Math]::Sin($t * 17 + $i * 1.7))) }
376
- $script:levelNow[$i] = $script:levelNow[$i] + ($target - $script:levelNow[$i]) * $(if ($target -gt $script:levelNow[$i]) { 0.6 } else { 0.25 })
377
- $script:levelBars[$i].Height = 4 + 16 * $script:levelNow[$i]
378
- }
379
- })
380
- function VoiceLook($on) {
381
- (E 'MicBtn').Background = Brush $(if ($on) { '${ASK_BTN.recBg}' } else { '${ASK_BTN.bg}' })
382
- (E 'MicIcon').Stroke = Brush $(if ($on) { '${ASK_BTN.recIcon}' } else { '${ASK_BTN.icon}' })
383
- # The voice bar only needs the button's height (InputLayout, via SyncAction / below).
384
- (E 'AskBox').Visibility = if ($on) { 'Collapsed' } else { 'Visible' }
385
- $voiceBar.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
386
- if ($on) { (E 'MicIcon').Visibility = 'Visible'; (E 'SendIcon').Visibility = 'Collapsed'; (E 'AskHint').Visibility = 'Collapsed'; $script:levelTimer.Start(); InputLayout }
387
- else { $script:levelTimer.Stop(); SyncAction }
388
- }
389
- function VoiceState($state) {
390
- $script:voiceLive = [string]$state
391
- $voiceLabel.Text = switch ($state) { 'connecting' { $T.voice_connecting } 'listening' { $T.voice_listening } 'thinking' { $T.voice_thinking } 'speaking' { $T.voice_speaking } 'recording' { $T.voice_recording } default { '' } }
392
- $bars = if ($state -eq 'speaking') { '#F472B6' } elseif ($state -eq 'listening' -or $state -eq 'recording') { '#8B7CF6' } else { '#C4B5FD' }
393
- foreach ($r in $script:levelBars) { $r.Fill = Brush $bars }
394
- AskStatus ''
395
- (E 'MicBtn').ToolTip = switch ($state) { 'speaking' { $T.voice_hint_interrupt } 'recording' { $T.voice_hint_send } default { $T.voice_hint_end } }
396
- # The bot's face follows the conversation: all ears, thinking, talking (animated mouth).
397
- SetFace $(switch ($state) { 'thinking' { 'thinking' } 'speaking' { 'speaking' } default { 'listening' } })
398
- }
399
- # The server says the bot finished talking, but the speaker still plays what it has: keep "talking" (and a click = interrupt) until it is
400
- # really quiet, then show the next state.
401
- $script:afterSpeak = ''
402
- $script:speakTimer = New-Object Windows.Threading.DispatcherTimer; $script:speakTimer.Interval = [TimeSpan]::FromMilliseconds(150)
403
- $script:speakTimer.Add_Tick({
404
- if ($script:afterSpeak -and -not [AivinMascot.Voice]::Playing) { $s = $script:afterSpeak; $script:afterSpeak = ''; if ($script:voiceLive) { VoiceState $s } }
405
- })
406
- function StartVoice { VoiceLook $true; VoiceState 'connecting'; $script:speakTimer.Start(); NoteTarget; Send @{ t = 'voice_start'; window = $script:askTarget } }
407
- function EndVoice($text) {
408
- [AivinMascot.Voice]::End(); $script:speakTimer.Stop(); $script:afterSpeak = ''; $script:voiceLive = ''; VoiceLook $false; AskStatus $text
409
- SetFace $script:state
410
- }
411
- function StopVoice { Send @{ t = 'voice_stop' }; EndVoice $T.voice_ended }
412
- function InterruptVoice { [AivinMascot.Voice]::Flush(); $script:afterSpeak = ''; Send @{ t = 'voice_interrupt' }; VoiceState 'listening' }
413
- # One action for the mic button and the hotkey: bot talking -> interrupt; talking with it -> end; idle -> start.
414
- function VoiceToggle {
415
- if ($script:voiceLive -and $script:voiceLive -ne 'recording' -and [AivinMascot.Voice]::Playing) { InterruptVoice }
416
- elseif ($script:voiceLive) { StopVoice }
417
- elseif (-not $script:chatBusy) { PeekAsk; StartVoice }
418
- }
419
- (E 'MicBtn').Add_Click({
420
- if (-not $script:voiceLive -and (E 'AskBox').Text.Trim()) { SubmitAsk }
421
- elseif (StopMode) { $script:canCancel = $false; (E 'MicBtn').Opacity = 0.5; SyncAction; Send @{ t = 'cancel' } }
422
- else { VoiceToggle }
423
- })
424
- # A hotkey anywhere = the mic button (no need to reach for the bot): the first free of Ctrl+Alt+Space, Win+Alt+Space, Ctrl+Alt+V
425
- # (other apps often hold the first one). Shown in the mic button's tooltip; none free -> no hotkey.
426
- $w.Add_ContentRendered({
427
- if (-not $script:hwnd) { return }
428
- $keys = @(@{ n = 'Ctrl+Alt+Space'; m = 0x4003; v = 0x20 }, @{ n = 'Win+Alt+Space'; m = 0x4009; v = 0x20 }, @{ n = 'Ctrl+Alt+V'; m = 0x4003; v = 0x56 })
429
- $key = $null
430
- foreach ($k in $keys) { if ([AivinMascotAsk.Native]::RegisterHotKey($script:hwnd, 0xA171, $k.m, $k.v)) { $key = $k; break } }
431
- if (-not $key) { Dbg 'voice hotkey: all taken'; return }
432
- Dbg "voice hotkey: $($key.n)"
433
- $T.ask_mic = "$($T.ask_mic) ($($key.n))"; SyncAction
434
- [System.Windows.Interop.HwndSource]::FromHwnd($script:hwnd).AddHook([System.Windows.Interop.HwndSourceHook]{
435
- param($h, $msg, $wp, $lp, [ref]$handled)
436
- if ($msg -eq 0x0312 -and $wp.ToInt32() -eq 0xA171) { VoiceToggle; $handled.Value = $true }
437
- [IntPtr]::Zero
438
- })
439
- })
440
-
441
- # Route the ask-box commands; everything else goes to the base handler of hostSource.mjs.
442
- $script:baseHandle = (Get-Item function:Handle).ScriptBlock
443
- function Handle($m) {
444
- switch ($m.t) {
445
- 'chat' {
446
- ChatRow $m
447
- if (-not $m.remove -and [string]$m.role -ne 'user' -and $m.text) {
448
- $script:chatLast = ChatShort $m
449
- if (-not $script:askOpen) { ChatBubble $script:chatLast }
450
- }
451
- return
452
- }
453
- 'chat_clear' { (E 'ChatList').Children.Clear(); $script:chatRows.Clear(); (E 'ChatScroll').Visibility = 'Collapsed'; InputLayout; return }
454
- 'chat_busy' {
455
- $script:chatBusy = [bool]$m.busy; $script:canCancel = [bool]$m.cancel
456
- (E 'MicBtn').Opacity = if ($script:chatBusy -and -not $script:canCancel) { 0.5 } else { 1 }
457
- SyncAction
458
- # Answer arrived while the user looked elsewhere: leave it readable a while, then tuck the box away.
459
- if (-not $script:chatBusy -and $script:askOpen -and -not $script:askFocused -and -not $w.IsMouseOver) { HideAskLater 8000 }
460
- # Turn over with the box closed: the answer / error stays in the bubble a while, then the bubble times out.
461
- if (-not $script:chatBusy -and -not $script:askOpen -and (E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
462
- if ($script:chatBusy) { $script:chatLast = '' }
463
- return
464
- }
465
- 'ask_status' { AskStatus $m.text; return }
466
- 'ask_choices' { ChoiceButtons $m.options $m.multiple; return }
467
- 'ask_pin' {
468
- $script:askPinned = [bool]$m.on
469
- if ($script:askPinned) { $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; PeekAsk; (E 'ChatScroll').ScrollToEnd() }
470
- elseif ($script:askOpen -and -not $script:askFocused) { HideAskLater 4000 }
471
- return
472
- }
473
- 'voice_begin' {
474
- if (-not $script:voiceLive) { Send @{ t = 'voice_stop' }; return }
475
- if ([AivinMascot.Voice]::Begin([int]$m.in_rate, [int]$m.out_rate, $true)) {
476
- Dbg "voice: on, echo cancelled=$([AivinMascot.Voice]::EchoCancelled) $([AivinMascot.Voice]::AecError)"
477
- VoiceState $(if ($m.state) { [string]$m.state } else { 'listening' })
478
- } else { Dbg 'voice: no mic'; Send @{ t = 'voice_stop' }; EndVoice $T.ask_no_mic }
479
- return
480
- }
481
- 'voice_state' {
482
- if (-not $script:voiceLive) { return }
483
- if ($script:voiceLive -eq 'speaking' -and $m.state -ne 'speaking' -and [AivinMascot.Voice]::Playing) { $script:afterSpeak = [string]$m.state }
484
- else { $script:afterSpeak = ''; VoiceState $m.state }
485
- return
486
- }
487
- 'voice_end' { if ($script:voiceLive) { EndVoice $m.text }; return }
488
- # aivin ui: the user just asked for the mascot from a terminal -> show it and open the ask box ready to type.
489
- 'open_ask' { $script:userHidden = $false; ApplyVisibility; if (-not $script:askFocused) { OpenAsk }; return }
490
- # Debug only (AIVIN_MASCOT_DEBUG): show the ask box WITHOUT taking keyboard focus, to look at it / screenshot it.
491
- 'ask_preview' { if ($env:AIVIN_MASCOT_DEBUG) { PeekAsk }; return }
492
- # Debug only: start talking as if the mic was clicked (end-to-end voice test without clicking / taking focus).
493
- 'voice_preview' { if ($env:AIVIN_MASCOT_DEBUG -and -not $script:voiceLive) { VoiceToggle }; return }
494
- # Debug only: render the ask box (not the screen) to a PNG, to look at the design without screenshots.
495
- 'snap' {
496
- if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
497
- $el = E 'Ask'; $el.UpdateLayout(); $dpi = 2
498
- $bmp = New-Object Windows.Media.Imaging.RenderTargetBitmap ([int]($el.ActualWidth * $dpi + 24)), ([int]($el.ActualHeight * $dpi + 24)), (96 * $dpi), (96 * $dpi), ([Windows.Media.PixelFormats]::Pbgra32)
499
- $vis = New-Object Windows.Media.DrawingVisual; $dc = $vis.RenderOpen()
500
- $dc.DrawRectangle((Brush '#F3F4F6'), $null, (New-Object Windows.Rect 0, 0, ($el.ActualWidth + 12), ($el.ActualHeight + 12)))
501
- # 1:1, no stretching (the drop shadow makes the visual's bounds bigger than the box).
502
- $vb = New-Object Windows.Media.VisualBrush $el; $vb.Stretch = 'None'; $vb.AlignmentX = 'Left'; $vb.AlignmentY = 'Top'
503
- $vb.ViewboxUnits = 'Absolute'; $vb.Viewbox = New-Object Windows.Rect 0, 0, $el.ActualWidth, $el.ActualHeight
504
- $dc.DrawRectangle($vb, $null, (New-Object Windows.Rect 6, 6, $el.ActualWidth, $el.ActualHeight)); $dc.Close()
505
- $bmp.Render($vis); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
506
- $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
507
- }
508
- }
509
- & $script:baseHandle $m
510
- }
511
- # ---- end ask box ----
512
- `;
1
+ /**
2
+ * Ô hỏi của linh vật, phía cửa sổ (29/10/2026) — mã PowerShell chèn vào host.ps1 tại dấu `# @ASK_HOOK` (index.mjs ghép), dùng khung
3
+ * XAML `Ask` / `ChatList` / `AskBox` / `MicBtn` (`MicIcon` / `SendIcon`) / `AskStatus` của hostSource.mjs.
4
+ *
5
+ * - Rê chuột vào bot → ô hỏi hiện ra (chưa nhận bàn phím); rời chuột ~0,6 s → ẩn. Bấm bot / bấm vào ô / phím tắt → cửa sổ nhận bàn phím (bỏ
6
+ * WS_EX_NOACTIVATE + đưa lên trước) để gõ; bấm ra ngoài / Esc / bấm bot lần nữa thì đóng, về không cướp focus. Chữ gõ dở vẫn giữ cho lần
7
+ * hiện sau. Chuột phải → nhật ký.
8
+ * - Ô đang mở mà rảnh `ASK_IDLE_MS` thì tự thu lại (kể cả mở bằng cú bấm / phím tắt; đang nhận bàn phím thì trả bàn phím về cửa sổ trước đó).
9
+ * Còn đang dùng thì đếm lại: chuột trên ô / bot, đang nói chuyện, đang kéo, Aivin đang chờ trả lời (HIL), hoặc đang nhận bàn phím mà có chữ
10
+ * gõ dở / tệp chờ gửi / lượt đang chạy.
11
+ * - Mỗi lúc một khung: ô hỏi đang mở thì việc bot làm trên máy không bật bong bóng (chỉ cập nhật chữ); ô đóng mà bot còn bận thì
12
+ * bong bóng hiện lại bước mới nhất.
13
+ * - Một nút ở góc dưới: ô trống = mic, có chữ = gửi. Enter / nút gửi → `{ t: 'ask', text, window }`. Mic = nói chuyện trực tiếp (realtime) với Aivin:
14
+ * bấm → `{ t: 'voice_start', window }`, daemon mở phiên thoại trên BE rồi gửi `voice_begin { in_rate, out_rate }` → mở mic + loa (voiceSource.mjs,
15
+ * âm thanh đi thẳng giữa C# và stdin/stdout). Đang nghe mà bấm → `voice_stop`; bot đang nói mà bấm → `voice_interrupt` (ngắt lời; có
16
+ * khử tiếng vọng thì nói chen bằng giọng cũng được). BE cũ chưa có nói chuyện: `voice_begin { state: 'recording' }` — nói xong bấm mic để gửi.
17
+ * Phím tắt nói (`hotkeys.voice` trong config.json do daemon ghi theo hotkey.mjs — mặc định Alt+Shift+Space, chủ máy đặt riêng / tắt bằng
18
+ * `aivin remote mascot hotkey`; hiện trong chú thích nút mic) ở đâu cũng = bấm mic; phím tắt chat (`hotkeys.chat`) = mở ô hỏi. Trạng thái "đang nói" giữ tới khi loa im thật (BE báo xong sớm hơn loa phát hết); mặt bot theo
19
+ * trạng thái nói chuyện (nghe / nghĩ / nói).
20
+ * - `window` = `{ window: '0x..', title, process }` của cửa sổ chủ máy đang dùng ngay trước khi rê / bấm vào bot hay nhấn phím tắt (không tính
21
+ * chính bot, thanh tác vụ, màn nền), hoặc null — để "cái này" trong câu hỏi trỏ đúng cửa sổ đó.
22
+ * - Lệnh vào thêm: `chat { role, id, text, remove? }`, `chat_busy { busy }`, `ask_status { text }`, `voice_begin`, `voice_state { state }`
23
+ * (listening | thinking | speaking), `voice_end { text? }`.
24
+ * Giữ toàn ASCII (xem hostSource.mjs).
25
+ */
26
+ import { ASK_BLOCKS_PS1, ICON_INKS } from './askBlocksSource.mjs';
27
+ import { ASK_BTN, MASCOT_CENTER } from './hostSource.mjs';
28
+ import { lucidePath } from './lucideIcons.mjs';
29
+
30
+ /** Ô hỏi rảnh chừng này thì tự thu lại. */
31
+ export const ASK_IDLE_MS = 10000;
32
+ /** Câu trả lời có bảng / thẻ / ảnh: cần thời gian đọc hơn một câu chữ. */
33
+ const ASK_RICH_IDLE_MS = 30000;
34
+
35
+ /**
36
+ * Lựa chọn khi Aivin hỏi lại: mỗi thẻ tô một màu pastel nhạt (xoay vòng hồng → tím nhạt → xanh trời → xanh bạc hà, theo viền ô hỏi), không
37
+ * viền, chữ xám đậm; rê chuột thì thẻ đậm lên nhẹ.
38
+ */
39
+ const CHOICE_CARDS = Object.freeze(['#FDF2F8', '#F5F3FF', '#EFF6FF', '#ECFDF5']);
40
+ const CHOICE_INK = '#3B4256';
41
+ const CHOICE_HOVER = '#0F1E1B4B';
42
+ /** Viền chấm tròn / ô vuông đầu mỗi lựa chọn (chưa tích). */
43
+ const CHOICE_MARK = '#9AA1B2';
44
+ /** Nút mở link: icon Lucide + màu đậm cùng tông với nền nút (`CHOICE_CARDS[2]`, xanh trời). */
45
+ const LINK_ICON_PATH = lucidePath('external-link');
46
+ /** Nút x trên chip tệp đính kèm. */
47
+ const DETACH_ICON_PATH = lucidePath('x');
48
+
49
+ export const ASK_PS1 = String.raw`
50
+ # ---- Ask box (askHostSource.mjs) ----
51
+ Add-Type -TypeDefinition @'
52
+ using System; using System.Runtime.InteropServices;
53
+ namespace AivinMascotAsk {
54
+ public static class Native {
55
+ [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);
56
+ [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr h);
57
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
58
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, IntPtr pid);
59
+ [DllImport("user32.dll")] static extern bool AttachThreadInput(uint a, uint b, bool attach);
60
+ [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
61
+ [DllImport("user32.dll")] static extern short GetAsyncKeyState(int vKey);
62
+ public static bool ClickOutside() { return (GetAsyncKeyState(1) & 0x8000) != 0; }
63
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr h, System.Text.StringBuilder s, int n);
64
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, System.Text.StringBuilder s, int n);
65
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
66
+ /** The window the person is using (not the bot, the taskbar or the desktop): { "0x..", title, pid }, or null. */
67
+ public static string[] UserWindow() {
68
+ IntPtr h = GetForegroundWindow(); if (h == IntPtr.Zero) return null;
69
+ uint pid; GetWindowThreadProcessId(h, out pid);
70
+ if (pid == (uint)System.Diagnostics.Process.GetCurrentProcess().Id) return null;
71
+ var c = new System.Text.StringBuilder(256); GetClassName(h, c, 256);
72
+ string cls = c.ToString(); if (cls == "Shell_TrayWnd" || cls == "Progman" || cls == "WorkerW") return null;
73
+ var t = new System.Text.StringBuilder(512); GetWindowText(h, t, 512);
74
+ return new string[] { "0x" + h.ToInt64().ToString("x"), t.ToString(), pid.ToString() };
75
+ }
76
+ /** The user just clicked the bot: take keyboard focus (Windows refuses SetForegroundWindow from a background window otherwise). */
77
+ public static bool TakeFocus(IntPtr h) {
78
+ uint fg = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero), me = GetCurrentThreadId();
79
+ bool attached = fg != 0 && fg != me && AttachThreadInput(fg, me, true);
80
+ try { BringWindowToTop(h); return SetForegroundWindow(h); }
81
+ finally { if (attached) AttachThreadInput(fg, me, false); }
82
+ }
83
+ [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h);
84
+ /** The box closed by itself while holding the keyboard: back to the window the person came from (only if we still hold it). */
85
+ public static bool GiveFocusBack(IntPtr me, string target) {
86
+ if (GetForegroundWindow() != me) return false;
87
+ IntPtr h = new IntPtr(Convert.ToInt64(target, 16));
88
+ return IsWindow(h) && SetForegroundWindow(h);
89
+ }
90
+ }
91
+ }
92
+ '@
93
+ (E 'AskHint').Text = $T.ask_hint; (E 'MicBtn').ToolTip = $T.ask_mic
94
+ # "New chat" on the activity panel: the daemon opens a new chat on the server and sends chat_clear; the ask box opens for the first line.
95
+ (E 'NewChatText').Text = $T.new_chat; (E 'NewChatBtn').ToolTip = $T.new_chat_tip
96
+ (E 'NewChatBtn').Add_Click({ Send @{ t = 'new_chat' }; OpenAsk })
97
+
98
+ function AskShow($name) {
99
+ $script:bubbleTimer.Stop(); (E 'Bubble').Visibility = 'Collapsed'; (E 'Bubble').Opacity = 0
100
+ $el = E $name; $el.Visibility = 'Visible'; $w.FindResource('PanelIn').Begin($el)
101
+ }
102
+ function AskHide($name) {
103
+ $el = E $name; if ($el.Visibility -ne 'Visible') { return }
104
+ # The ask box may be shown again while it is still fading out: then the finished fade must not collapse it.
105
+ $sb = $w.FindResource('PanelOut').Clone(); $sb.Add_Completed({ if ($name -ne 'Ask' -or -not $script:askOpen) { (E $name).Visibility = 'Collapsed' } }.GetNewClosure()); $sb.Begin($el)
106
+ }
107
+ function SetActivatable($on) {
108
+ if (-not $script:hwnd) { return }
109
+ $ex = [AivinMascot.Native]::GetWindowLong($script:hwnd, -20)
110
+ $ex = if ($on) { $ex -band (-bnot 0x08000000) } else { $ex -bor 0x08000000 }
111
+ [void][AivinMascot.Native]::SetWindowLong($script:hwnd, -20, $ex)
112
+ }
113
+ function AskStatus($text) {
114
+ $el = E 'AskStatus'; SetText $el $text; $el.Visibility = if ($text) { 'Visible' } else { 'Collapsed' }
115
+ }
116
+ $script:askOpen = $false; $script:askFocused = $false
117
+ # The window the person was on right before reaching for the bot: sent with each question / talk so "this" means that window.
118
+ $script:askTarget = $null
119
+ function NoteTarget {
120
+ $i = $null; try { $i = [AivinMascotAsk.Native]::UserWindow() } catch { }
121
+ if (-not $i) { return }
122
+ $p = ''; try { $p = (Get-Process -Id ([int]$i[2]) -ErrorAction Stop).ProcessName } catch { }
123
+ $script:askTarget = @{ window = $i[0]; title = $i[1]; process = $p }
124
+ }
125
+ function PeekAsk {
126
+ NoteTarget
127
+ if ($script:askOpen) { return }
128
+ $script:askOpen = $true; AskShow 'Ask'; $w.FindResource('AskGlow').Begin($w, $true)
129
+ }
130
+ function OpenAsk {
131
+ NoteTarget; AskHide 'Panel'
132
+ $script:askOpen = $true; AskShow 'Ask'; $w.FindResource('AskGlow').Begin($w, $true)
133
+ $script:askFocused = $true; SetActivatable $true; $ok = [AivinMascotAsk.Native]::TakeFocus($script:hwnd); [void]$w.Activate(); Dbg "ask focus=$ok"
134
+ [void](E 'AskBox').Focus(); [void][Windows.Input.Keyboard]::Focus((E 'AskBox'))
135
+ HideAskLater ${ASK_IDLE_MS}
136
+ }
137
+ function CloseAsk {
138
+ $script:askHideTimer.Stop()
139
+ if (-not $script:askOpen) { return }
140
+ if ($script:voiceLive) { StopVoice }
141
+ $script:askOpen = $false; $script:askFocused = $false
142
+ AskHide 'Ask'; SetActivatable $false; $w.FindResource('AskGlow').Stop($w)
143
+ }
144
+ function MascotClick { if ($script:askFocused) { CloseAsk } else { OpenAsk } }
145
+ # One box at a time: while the ask box is open, what the bot does on the machine only updates the text; the bubble
146
+ # (notification) comes back with the latest step once the box closes, if the bot is still busy.
147
+ $script:baseShowBubble = (Get-Item function:ShowBubble).ScriptBlock
148
+ function ShowBubble($text) { if ($script:askOpen) { SetText (E 'NowText') $text; return }; & $script:baseShowBubble $text }
149
+ $script:baseCloseAsk = (Get-Item function:CloseAsk).ScriptBlock
150
+ function CloseAsk {
151
+ $was = $script:askOpen; & $script:baseCloseAsk
152
+ if (-not $was -or (E 'Panel').Visibility -eq 'Visible') { return }
153
+ if ($script:chatBusy -and $script:chatLast) { ChatBubble $script:chatLast }
154
+ elseif ((IsBusy) -or $script:state -eq 'waiting') { & $script:baseShowBubble ([AivinMascot.Emoji]::Text((E 'NowText'))) }
155
+ if ((E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
156
+ }
157
+ # What the chat turn is doing, short, for the bubble on the bot's head while the box is closed: progress lines, the answer as it is
158
+ # written (its tail), the answer / error. Stays up while the turn runs; once it ends the bubble times out as usual.
159
+ $script:chatLast = ''
160
+ function ChatShort($m) {
161
+ $text = ([string]$m.text -replace '\s+', ' ').Trim()
162
+ if ($m.partial -and $text.Length -gt 90) { $text = "$([char]0x2026)" + $text.Substring($text.Length - 89) }
163
+ $text
164
+ }
165
+ function ChatBubble($text) {
166
+ if (-not $text -or (E 'Panel').Visibility -eq 'Visible') { return }
167
+ & $script:baseShowBubble $text
168
+ $script:bubbleTimer.Stop(); $script:bubbleTimer.Start()
169
+ }
170
+ # The box only stays out for a while: it peeks while the mouse is over the bot / the box and slips away shortly after it leaves; opened with
171
+ # a click / hotkey, or left open after an answer, it folds away once idle for ASK_IDLE_MS. Still in use when the timer fires = count again.
172
+ $script:askHideTimer = New-Object Windows.Threading.DispatcherTimer
173
+ $script:askHideTimer.Add_Tick({
174
+ if ($script:askOpen -and (AskInUse)) { HideAskLater ${ASK_IDLE_MS}; return }
175
+ $held = $script:askFocused; CloseAsk
176
+ if ($held -and $script:askTarget) { try { [void][AivinMascotAsk.Native]::GiveFocusBack($script:hwnd, [string]$script:askTarget.window) } catch { } }
177
+ })
178
+ # In use = keep the box out: mouse over it, talking, dragging, a pinned question, or holding the keyboard with unsent text / files or a running turn.
179
+ function AskInUse {
180
+ $w.IsMouseOver -or $script:voiceLive -or $script:drag -or $script:askPinned -or ($script:askFocused -and ($script:chatBusy -or $script:files -or (E 'AskBox').Text.Trim()))
181
+ }
182
+ # Aivin is waiting for an answer (HIL): the box stays out with the question + option buttons until it is answered (no focus taken).
183
+ $script:askPinned = $false
184
+ function HideAskLater($ms) { $script:askHideTimer.Stop(); $script:askHideTimer.Interval = [TimeSpan]::FromMilliseconds($ms); $script:askHideTimer.Start() }
185
+ (E 'Mascot').ToolTip = $null
186
+ (E 'Mascot').Add_MouseEnter({ $script:askHideTimer.Stop(); if ((E 'Panel').Visibility -ne 'Visible' -and -not $script:drag) { PeekAsk } })
187
+ (E 'Ask').Add_MouseEnter({ $script:askHideTimer.Stop() })
188
+ # Only peeking: gone right after the mouse leaves. Holding the keyboard: the person may be about to type, so the full wait.
189
+ $w.Add_MouseLeave({ if ($script:askOpen) { HideAskLater $(if ($script:askFocused) { ${ASK_IDLE_MS} } else { 600 }) } })
190
+ # Clicked somewhere else: release keyboard focus and close the box.
191
+ $w.Add_Deactivated({
192
+ $script:askFocused = $false; SetActivatable $false
193
+ if ($script:askOpen -and -not $script:voiceLive -and -not $script:drag -and -not $script:askPinned) { CloseAsk }
194
+ if ((E 'Panel').Visibility -eq 'Visible') { ClosePanel }
195
+ })
196
+ # Click outside detection: transparent window region or anywhere on other windows
197
+ $w.Add_PreviewMouseLeftButtonDown({ param($s, $e)
198
+ if (-not $script:askOpen -or $script:drag) { return }
199
+ $pt = $e.GetPosition($w)
200
+ $askBox = E 'Ask'; $mascot = E 'Mascot'; $panel = E 'Panel'
201
+ $inAsk = $askBox.Visibility -eq 'Visible' -and (New-Object Windows.Rect ($askBox.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $askBox.RenderSize).Contains($pt)
202
+ $inMascot = (New-Object Windows.Rect ($mascot.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $mascot.RenderSize).Contains($pt)
203
+ $inPanel = $panel.Visibility -eq 'Visible' -and (New-Object Windows.Rect ($panel.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $panel.RenderSize).Contains($pt)
204
+ if (-not $inAsk -and -not $inMascot -and -not $inPanel -and -not $script:askPinned) {
205
+ CloseAsk
206
+ }
207
+ if (-not $inPanel -and (E 'Panel').Visibility -eq 'Visible' -and -not $inMascot) {
208
+ ClosePanel
209
+ }
210
+ })
211
+ $script:clickCheckTimer = New-Object Windows.Threading.DispatcherTimer
212
+ $script:clickCheckTimer.Interval = [TimeSpan]::FromMilliseconds(50)
213
+ $script:clickCheckTimer.Add_Tick({
214
+ if ($script:askOpen -and -not $script:voiceLive -and -not $script:drag -and -not $script:askPinned) {
215
+ if (-not $w.IsMouseOver -and [AivinMascotAsk.Native]::ClickOutside()) {
216
+ CloseAsk
217
+ }
218
+ }
219
+ if ((E 'Panel').Visibility -eq 'Visible' -and -not $script:drag) {
220
+ if (-not $w.IsMouseOver -and [AivinMascotAsk.Native]::ClickOutside()) {
221
+ ClosePanel
222
+ }
223
+ }
224
+ })
225
+ $script:clickCheckTimer.Start()
226
+ # Clicking into the peeking box = about to type: take keyboard focus.
227
+ (E 'Ask').Add_PreviewMouseLeftButtonDown({ if (-not $script:askFocused) { OpenAsk } })
228
+ # Right-click on the bot: the activity panel.
229
+ (E 'Mascot').Add_MouseRightButtonUp({ param($s, $e) CloseAsk; OpenPanel; $e.Handled = $true })
230
+ # One button: empty box = mic, typed text = send.
231
+ # Waiting on a turn the server can stop (chat_busy { cancel }): the empty-box button is a stop button instead of the mic.
232
+ function StopMode { $script:chatBusy -and $script:canCancel -and -not $script:voiceLive -and -not (E 'AskBox').Text.Trim() -and -not $script:files }
233
+ function SyncAction {
234
+ # Files waiting (chips above the input): the button sends even with nothing typed, and the hint asks what to do with them.
235
+ $typed = [bool](E 'AskBox').Text.Trim() -or ($script:files -gt 0 -and -not $script:voiceLive)
236
+ $stop = StopMode
237
+ (E 'AskHint').Text = if ($script:files -gt 0) { $T.ask_attached } else { $T.ask_hint }
238
+ (E 'AskHint').Visibility = if ((E 'AskBox').Text) { 'Collapsed' } else { 'Visible' }
239
+ (E 'SendIcon').Visibility = if ($typed) { 'Visible' } else { 'Collapsed' }; (E 'MicIcon').Visibility = if ($typed -or $stop) { 'Collapsed' } else { 'Visible' }
240
+ (E 'StopIcon').Visibility = if ($stop) { 'Visible' } else { 'Collapsed' }
241
+ (E 'MicBtn').ToolTip = if ($typed) { $T.ask_send } elseif ($stop) { $T.ask_stop } else { $T.ask_mic }
242
+ InputLayout
243
+ }
244
+ # Input row height: two lines for a fresh question; once a conversation is above it (or while talking), one line with the hint and the mic
245
+ # button centred on the same line - the box only grows (mic back at the bottom) when the typed text wraps.
246
+ function InputLayout {
247
+ $box = E 'AskBox'
248
+ # Box hidden = the voice bar is in its place (VoiceLook hides it before the voice state is set).
249
+ $compact = $box.Visibility -ne 'Visible' -or [bool]$script:voiceLive -or (E 'ChatList').Children.Count -gt 0
250
+ $wrapped = $box.Visibility -eq 'Visible' -and $box.LineCount -gt 1
251
+ $box.Parent.MinHeight = if ($compact) { 26 } else { 40 }
252
+ $mid = if ($compact -and -not $wrapped) { 'Center' } else { 'Top' }
253
+ $box.VerticalAlignment = $mid; (E 'AskHint').VerticalAlignment = $mid
254
+ (E 'MicBtn').VerticalAlignment = if ($compact -and -not $wrapped) { 'Center' } else { 'Bottom' }
255
+ }
256
+ (E 'AskBox').Add_TextChanged({ SyncAction; AttendAsk; if ($script:askOpen) { HideAskLater ${ASK_IDLE_MS} } })
257
+ # Typing: the bot looks at the box (above or below it) while keys come in; a little nod when a question / answer goes out.
258
+ function AttendAsk {
259
+ if (-not (E 'AskBox').Text) { return }
260
+ $a = E 'Ask'; $p = $a.TranslatePoint((New-Object Windows.Point ($a.ActualWidth / 2), ($a.ActualHeight / 2)), (E 'Mascot'))
261
+ $script:rig.Attend($p.X - ${MASCOT_CENTER.x}, $p.Y - ${MASCOT_CENTER.y})
262
+ }
263
+
264
+ $script:chatBusy = $false
265
+ $script:canCancel = $false
266
+ function SubmitAsk {
267
+ $text = (E 'AskBox').Text.Trim(); if ((-not $text -and -not $script:files) -or $script:chatBusy -or $script:voiceLive) { return }
268
+ NoteTarget; (E 'AskBox').Text = ''; $script:rig.Play('ack'); Send @{ t = 'ask'; text = $text; window = $script:askTarget }
269
+ }
270
+ (E 'AskBox').Add_KeyDown({ param($s, $e)
271
+ if ($e.Key -eq 'Return') { SubmitAsk; $e.Handled = $true }
272
+ elseif ($e.Key -eq 'Escape') { CloseAsk; $e.Handled = $true }
273
+ })
274
+
275
+ # Conversation rows: user (right, light brand), assistant (left, grey), one live progress line, errors. Bubbles point at their speaker
276
+ # (the corner on the speaker's side is nearly square, 3 px) and new ones fade + rise in.
277
+ $script:chatRows = @{}
278
+ # "Working on it": three dots bouncing in turn inside an assistant bubble (a staggered key-frame hop, then a rest).
279
+ function TypingDots {
280
+ $sp = New-Object Windows.Controls.StackPanel; $sp.Orientation = 'Horizontal'; $sp.Margin = '1,5,1,5'
281
+ for ($i = 0; $i -lt 3; $i++) {
282
+ $e = New-Object Windows.Shapes.Ellipse; $e.Width = 6; $e.Height = 6; $e.Margin = '2,0,2,0'; $e.Fill = Brush '#9AA0AB'
283
+ $tt = New-Object Windows.Media.TranslateTransform; $e.RenderTransform = $tt
284
+ $a = New-Object Windows.Media.Animation.DoubleAnimationUsingKeyFrames
285
+ $a.Duration = [TimeSpan]::FromMilliseconds(1200); $a.BeginTime = [TimeSpan]::FromMilliseconds(160 * $i)
286
+ $a.RepeatBehavior = [Windows.Media.Animation.RepeatBehavior]::Forever
287
+ foreach ($k in @(@(0, 0), @(280, -4.5), @(560, 0), @(1200, 0))) {
288
+ $f = New-Object Windows.Media.Animation.EasingDoubleKeyFrame ([double]$k[1]), ([Windows.Media.Animation.KeyTime]::FromTimeSpan([TimeSpan]::FromMilliseconds($k[0])))
289
+ $f.EasingFunction = New-Object Windows.Media.Animation.SineEase; [void]$a.KeyFrames.Add($f)
290
+ }
291
+ $tt.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $a)
292
+ [void]$sp.Children.Add($e)
293
+ }
294
+ $sp
295
+ }
296
+ # Link buttons under a bubble (the answer's "open this page" buttons, "view on Aivin"): a click opens the browser, nothing goes to the agent.
297
+ function LinkCard($text, $url, $iconPath = '${LINK_ICON_PATH}') {
298
+ $dock = New-Object Windows.Controls.DockPanel; $dock.MaxWidth = 192
299
+ $icon = LucideIcon $(if ($iconPath) { $iconPath } else { '${LINK_ICON_PATH}' }) 13 '${ICON_INKS[2]}'; $icon.Margin = '8,3,0,0'; $icon.VerticalAlignment = 'Top'; [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$dock.Children.Add($icon)
300
+ $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; SetText $tb $text; [void]$dock.Children.Add($tb)
301
+ $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; $btn.ToolTip = [string]$url
302
+ $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,3'; $btn.HorizontalAlignment = 'Left'
303
+ $btn.Background = Brush '${CHOICE_CARDS[2]}'; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
304
+ $btn.Add_Click({ param($s) OpenWebUrl $s.CommandParameter })
305
+ $btn
306
+ }
307
+ function ChatLinks($row, $links) {
308
+ $list = E 'ChatList'
309
+ if ($row.links) { [void]$list.Children.Remove($row.links); $row.links = $null }
310
+ $items = @(@($links) | Where-Object { $_ -and $_.url })
311
+ if (-not $items.Count) { return }
312
+ $sp = New-Object Windows.Controls.StackPanel; $sp.Margin = '0,0,0,4'; $sp.HorizontalAlignment = 'Left'
313
+ foreach ($l in $items) { [void]$sp.Children.Add((LinkCard $l.text $l.url $l.icon_path)) }
314
+ $after = if ($row.blocks) { $row.blocks } else { $row.box }
315
+ $list.Children.Insert($list.Children.IndexOf($after) + 1, $sp); $row.links = $sp
316
+ }
317
+ ${ASK_BLOCKS_PS1}
318
+ function ChatRow($m) {
319
+ $list = E 'ChatList'; $id = [string]$m.id
320
+ $row = $null; if ($id) { $row = $script:chatRows[$id] }
321
+ if ($m.remove) { if ($row) { ChatLinks $row $null; ChatBlocks $row $null; [void]$list.Children.Remove($row.box); $script:chatRows.Remove($id) }; return }
322
+ (E 'ChatScroll').Visibility = 'Visible'
323
+ if (-not $row) {
324
+ # Segoe UI adds its own space above / below the letters: block line height + slim vertical padding so the space you see is about
325
+ # the same on all four sides.
326
+ $b = New-Object Windows.Controls.Border; $b.Padding = '10,5,10,5'; $b.Margin = '0,0,0,4'; $b.MaxWidth = $script:bubbleMax
327
+ $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.FontSize = 14; $tb.LineHeight = 20; $tb.LineStackingStrategy = 'BlockLineHeight'
328
+ $b.Child = $tb; [void]$list.Children.Add($b)
329
+ $slide = New-Object Windows.Media.TranslateTransform 0, 6; $b.RenderTransform = $slide
330
+ $ease = New-Object Windows.Media.Animation.CubicEase; $ease.EasingMode = 'EaseOut'
331
+ $fade = New-Object Windows.Media.Animation.DoubleAnimation 0, 1, ([TimeSpan]::FromMilliseconds(200)); $fade.EasingFunction = $ease
332
+ $rise = New-Object Windows.Media.Animation.DoubleAnimation 6, 0, ([TimeSpan]::FromMilliseconds(240)); $rise.EasingFunction = $ease
333
+ $b.BeginAnimation([Windows.UIElement]::OpacityProperty, $fade); $slide.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $rise)
334
+ $row = @{ box = $b; text = $tb; url = $null }
335
+ # The link rides on the bubble itself (Tag, updated below): the handler is not a closure, $row at click time is not this row.
336
+ $b.Add_MouseLeftButtonUp({ param($s) OpenWebUrl $s.Tag })
337
+ if ($id) { $script:chatRows[$id] = $row }
338
+ while ($list.Children.Count -gt 40) { $list.Children.RemoveAt(0) }
339
+ }
340
+ if ($m.url) {
341
+ $row.url = [string]$m.url; $row.box.Tag = [string]$m.url
342
+ $row.box.Cursor = [Windows.Input.Cursors]::Hand
343
+ $row.box.ToolTip = [string]$m.url
344
+ } else {
345
+ $row.url = $null; $row.box.Tag = $null
346
+ $row.box.Cursor = [Windows.Input.Cursors]::Arrow
347
+ $row.box.ToolTip = $null
348
+ }
349
+ $role = [string]$m.role
350
+ $row.box.HorizontalAlignment = if ($role -eq 'user') { 'Right' } else { 'Left' }
351
+ # CornerRadius = top-left, top-right, bottom-right, bottom-left.
352
+ $row.box.CornerRadius = if ($role -eq 'user') { '10,10,3,10' } elseif ($role -eq 'progress') { '0' } else { '10,10,10,3' }
353
+ $bg = if ($role -eq 'user') { '#E8F3FF' } elseif ($role -eq 'error') { '#FFECE8' } elseif ($role -eq 'progress') { '#00FFFFFF' } else { '#F4F6FA' }
354
+ $fg = if ($role -eq 'progress') { $P.muted } elseif ($role -eq 'error') { '#CB2634' } else { $P.ink }
355
+ $row.box.Background = Brush $bg; $row.text.Foreground = Brush $fg
356
+ $row.text.FontStyle = if ($role -eq 'progress') { 'Italic' } else { 'Normal' }
357
+ SetText $row.text $m.text
358
+ ChatLinks $row $null
359
+ ChatBlocks $row $m.blocks
360
+ ChatLinks $row $m.links
361
+ # The bubble on the bot's head cannot show a table: the owner just asked, so open the box (without taking the keyboard).
362
+ if ($m.peek -and -not $script:askOpen -and (E 'Panel').Visibility -ne 'Visible') { PeekAsk }
363
+ if ($m.typing) {
364
+ if (-not $row.dots) { $row.dots = TypingDots }
365
+ $row.box.Child = $row.dots; $row.box.Background = Brush '#F4F6FA'; $row.box.CornerRadius = '10,10,10,3'
366
+ } elseif ($row.dots -and $row.box.Child -ne $row.text) { $row.box.Child = $row.text }
367
+ # Words the owner is still saying: lighter until the sentence is settled (the box's own opacity is the fade-in).
368
+ $row.text.Opacity = if ($m.partial) { 0.55 } else { 1 }
369
+ $script:scrollRow = if ($row.blocks) { $row } else { $null }
370
+ if ($script:scrollRow) { ScrollToRow $row } else { (E 'ChatScroll').ScrollToEnd() }
371
+ InputLayout
372
+ }
373
+
374
+ # Aivin asked something with choices: a vertical list, one full-width card per option (the daemon clears them once answered). Typing
375
+ # still works. Like the cards in Aivin: a round dot at the start (pick one: click = answer) or a square box (pick several: click ticks /
376
+ # unticks, a confirm button sends the ticked ones), the text, the option's icon at the end when it has one we can draw.
377
+ # Soft look: each card filled with a light pastel (cycling the ask box's glow colors), no border, dark-grey text; hover deepens it.
378
+ # Icon at the end of an option: the daemon looks up the Lucide name (the set Aivin's web uses) and sends its outline; an emoji is drawn as is.
379
+ function ChoiceIcon($o, $ink) {
380
+ if ($o.icon_path) { $i = LucideIcon $o.icon_path 14 $ink; $i.Margin = '8,3,0,0'; $i.VerticalAlignment = 'Top'; return $i }
381
+ if (-not $o.icon) { return $null }
382
+ $tb = New-Object Windows.Controls.TextBlock; $tb.FontSize = 13; $tb.Margin = '8,1,0,0'; $tb.VerticalAlignment = 'Top'; SetText $tb $o.icon; $tb
383
+ }
384
+ function ChoiceMark($multi) {
385
+ $m = New-Object Windows.Controls.Border; $m.Width = 13; $m.Height = 13; $m.Margin = '0,2,8,0'; $m.VerticalAlignment = 'Top'
386
+ $m.CornerRadius = if ($multi) { '3.5' } else { '6.5' }; $m.BorderThickness = '1.4'
387
+ $tick = New-Object Windows.Shapes.Path; $tick.Data = [Windows.Media.Geometry]::Parse('M2.4,6.2 L4.9,8.6 L9.4,3.6'); $tick.Stroke = Brush '#FFFFFF'
388
+ $tick.StrokeThickness = 1.7; $tick.StrokeStartLineCap = 'Round'; $tick.StrokeEndLineCap = 'Round'; $tick.StrokeLineJoin = 'Round'
389
+ $m.Child = $tick; SetTicked $m $false; $m
390
+ }
391
+ function SetTicked($mark, $on) {
392
+ $mark.Background = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '#B3FFFFFF' }
393
+ $mark.BorderBrush = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '${CHOICE_MARK}' }
394
+ $mark.Child.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
395
+ }
396
+ $script:picked = New-Object Collections.ArrayList; $script:choiceMarks = @{}; $script:choiceConfirm = $null
397
+ function SyncConfirm {
398
+ $b = $script:choiceConfirm; if (-not $b) { return }
399
+ $b.Content = $T.ask_confirm -replace '\{n\}', $script:picked.Count
400
+ $b.Visibility = if ($script:picked.Count) { 'Visible' } else { 'Collapsed' }
401
+ }
402
+ function ChoiceButtons($options, $multiple) {
403
+ $panel = E 'Choices'; $panel.Children.Clear(); $k = 0; $multi = [bool]$multiple
404
+ $script:picked.Clear(); $script:choiceMarks = @{}; $script:choiceConfirm = $null
405
+ $cards = @(${CHOICE_CARDS.map((c) => `'${c}'`).join(', ')}); $inks = @(${ICON_INKS.map((c) => `'${c}'`).join(', ')})
406
+ foreach ($o in @($options)) {
407
+ if (-not $o) { continue }
408
+ $c = $cards[$k % $cards.Count]; $k++; $id = [string]$o.id
409
+ $row = New-Object Windows.Controls.DockPanel; $row.Width = 192
410
+ $mark = ChoiceMark $multi; [Windows.Controls.DockPanel]::SetDock($mark, 'Left'); [void]$row.Children.Add($mark)
411
+ $icon = ChoiceIcon $o $inks[($k - 1) % $inks.Count]; if ($icon) { [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$row.Children.Add($icon) }
412
+ $tb = New-Object Windows.Controls.TextBlock; SetText $tb $o.text; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; [void]$row.Children.Add($tb)
413
+ $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $row; $btn.CommandParameter = $id
414
+ $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,4'; $btn.HorizontalAlignment = 'Stretch'
415
+ $btn.Background = Brush $c; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
416
+ $script:choiceMarks[$id] = $mark
417
+ if ($multi) {
418
+ $btn.Add_Click({ param($s)
419
+ $id = [string]$s.CommandParameter; $on = -not $script:picked.Contains($id)
420
+ if ($on) { [void]$script:picked.Add($id) } else { $script:picked.Remove($id) }
421
+ SetTicked $script:choiceMarks[$id] $on; SyncConfirm
422
+ })
423
+ } else {
424
+ $btn.Add_Click({ param($s) if (-not $script:chatBusy) { SetTicked $script:choiceMarks[[string]$s.CommandParameter] $true; $script:rig.Play('ack'); Send @{ t = 'choose'; id = [string]$s.CommandParameter } } })
425
+ }
426
+ [void]$panel.Children.Add($btn)
427
+ }
428
+ if ($multi -and $panel.Children.Count) {
429
+ $ok = New-Object Windows.Controls.Button; $ok.Style = $w.FindResource('Btn'); $ok.FontSize = 13; $ok.Padding = '12,5,12,5'; $ok.Margin = '0,1,0,4'
430
+ $ok.HorizontalAlignment = 'Right'; $ok.Background = Brush '${ASK_BTN.icon}'; $ok.Foreground = Brush '#FFFFFF'; $ok.BorderThickness = '0'; $ok.Tag = Brush '#1F000000'
431
+ $ok.Add_Click({ if (-not $script:chatBusy -and $script:picked.Count) { $script:rig.Play('ack'); Send @{ t = 'choose'; ids = @($script:picked.ToArray()) } } })
432
+ $script:choiceConfirm = $ok; [void]$panel.Children.Add($ok); SyncConfirm
433
+ }
434
+ $panel.Visibility = if ($panel.Children.Count) { 'Visible' } else { 'Collapsed' }
435
+ if ($panel.Children.Count) { (E 'ChatScroll').Visibility = 'Visible'; (E 'ChatScroll').ScrollToEnd() }
436
+ }
437
+
438
+ # Attached files: one chip each above the input - the file type's icon + colour (fileChips.mjs), its name (full path in the tooltip),
439
+ # an x that drops it (detach -> the daemon answers with the new ask_files).
440
+ function AttachChips($chips) {
441
+ $bar = E 'AttachBar'; $bar.Children.Clear()
442
+ foreach ($c in @($chips)) {
443
+ if (-not $c -or -not $c.path) { continue }
444
+ $ink = [string]$c.ink; if (-not $ink) { $ink = '#64748B' }
445
+ $chip = New-Object Windows.Controls.Border; $chip.CornerRadius = '8'; $chip.Padding = '6,2,2,2'; $chip.Margin = '4,0,0,4'; $chip.ToolTip = [string]$c.path
446
+ $chip.Background = Brush $(if ($c.bg) { [string]$c.bg } else { '#F8FAFC' })
447
+ # Hairline in the type's colour (ink at ~20 %): keeps the very light chip readable on the white box.
448
+ $chip.BorderThickness = '1'; $chip.BorderBrush = Brush ('#33' + $ink.TrimStart('#'))
449
+ $row = New-Object Windows.Controls.StackPanel; $row.Orientation = 'Horizontal'
450
+ if ($c.icon_path) { $i = LucideIcon $c.icon_path 13 $ink; $i.VerticalAlignment = 'Center'; $i.Margin = '0,0,5,0'; [void]$row.Children.Add($i) }
451
+ $tb = New-Object Windows.Controls.TextBlock; $tb.Text = [string]$c.name; $tb.FontSize = 12; $tb.Foreground = Brush $ink; $tb.MaxWidth = 140
452
+ $tb.TextTrimming = 'CharacterEllipsis'; $tb.VerticalAlignment = 'Center'; [void]$row.Children.Add($tb)
453
+ $x = New-Object Windows.Controls.Button; $x.Style = $w.FindResource('IconBtn'); $x.Width = 18; $x.Height = 18; $x.Margin = '3,0,0,0'
454
+ $x.Background = Brush '#00000000'; $x.BorderThickness = '0'; $x.Tag = Brush '#1F000000'; $x.ToolTip = $T.ask_detach
455
+ $x.Content = LucideIcon '${DETACH_ICON_PATH}' 10 $ink; $x.CommandParameter = [string]$c.path
456
+ $x.Add_Click({ param($s) Send @{ t = 'detach'; path = [string]$s.CommandParameter } })
457
+ [void]$row.Children.Add($x); $chip.Child = $row; [void]$bar.Children.Add($chip)
458
+ }
459
+ $bar.Visibility = if ($bar.Children.Count) { 'Visible' } else { 'Collapsed' }
460
+ }
461
+
462
+ # Voice: a live conversation with Aivin (voiceSource.mjs streams the mic / speaker). '' = off, else connecting | listening | thinking | speaking,
463
+ # or recording (older Aivin server without live voice: talk, click the mic to send, it goes through voice-to-text).
464
+ $script:voiceLive = ''
465
+ # While talking, the text input gives way to a voice bar in the same spot: level bars (the mic while listening, the bot's voice while it
466
+ # talks, a soft wave while it thinks) + a short state. The mic button turns red (its tooltip says what a click does now).
467
+ $inputCell = (E 'AskBox').Parent
468
+ $voiceBar = New-Object Windows.Controls.StackPanel; $voiceBar.Orientation = 'Horizontal'; $voiceBar.VerticalAlignment = 'Center'; $voiceBar.Visibility = 'Collapsed'
469
+ $voiceBar.Margin = '2,0,0,0'
470
+ $script:levelBars = @()
471
+ foreach ($i in 0..4) {
472
+ $r = New-Object Windows.Shapes.Rectangle; $r.Width = 3; $r.Height = 4; $r.RadiusX = 1.5; $r.RadiusY = 1.5; $r.Margin = '0,0,3,0'
473
+ $r.VerticalAlignment = 'Center'; $r.Fill = Brush '#8B7CF6'; [void]$voiceBar.Children.Add($r); $script:levelBars += $r
474
+ }
475
+ $voiceLabel = New-Object Windows.Controls.TextBlock; $voiceLabel.FontSize = 14; $voiceLabel.Foreground = Brush $P.ink; $voiceLabel.Margin = '7,0,0,1'
476
+ $voiceLabel.VerticalAlignment = 'Center'; $voiceLabel.TextTrimming = 'CharacterEllipsis'; [void]$voiceBar.Children.Add($voiceLabel)
477
+ [void]$inputCell.Children.Add($voiceBar)
478
+ $script:levelShape = @(0.55, 0.85, 1, 0.85, 0.55); $script:levelNow = @(0, 0, 0, 0, 0)
479
+ $script:levelTimer = New-Object Windows.Threading.DispatcherTimer; $script:levelTimer.Interval = [TimeSpan]::FromMilliseconds(50)
480
+ $script:levelTimer.Add_Tick({
481
+ $t = [Environment]::TickCount / 1000.0
482
+ $level = switch ($script:voiceLive) {
483
+ 'listening' { [AivinMascot.Voice]::MicLevel }
484
+ 'recording' { [AivinMascot.Voice]::MicLevel }
485
+ 'speaking' { [AivinMascot.Voice]::OutLevel }
486
+ default { -1 }
487
+ }
488
+ for ($i = 0; $i -lt 5; $i++) {
489
+ # No live level (connecting / thinking): a slow travelling wave, so it reads as "working on it".
490
+ $target = if ($level -lt 0) { 0.18 + 0.22 * (0.5 + 0.5 * [Math]::Sin($t * 5 - $i * 0.9)) } else { [Math]::Min(1, $level * $script:levelShape[$i] * (0.8 + 0.2 * [Math]::Sin($t * 17 + $i * 1.7))) }
491
+ $script:levelNow[$i] = $script:levelNow[$i] + ($target - $script:levelNow[$i]) * $(if ($target -gt $script:levelNow[$i]) { 0.6 } else { 0.25 })
492
+ $script:levelBars[$i].Height = 4 + 16 * $script:levelNow[$i]
493
+ }
494
+ })
495
+ function VoiceLook($on) {
496
+ (E 'MicBtn').Background = Brush $(if ($on) { '${ASK_BTN.recBg}' } else { '${ASK_BTN.bg}' })
497
+ (E 'MicIcon').Stroke = Brush $(if ($on) { '${ASK_BTN.recIcon}' } else { '${ASK_BTN.icon}' })
498
+ # The voice bar only needs the button's height (InputLayout, via SyncAction / below).
499
+ (E 'AskBox').Visibility = if ($on) { 'Collapsed' } else { 'Visible' }
500
+ $voiceBar.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
501
+ if ($on) { (E 'MicIcon').Visibility = 'Visible'; (E 'SendIcon').Visibility = 'Collapsed'; (E 'AskHint').Visibility = 'Collapsed'; $script:levelTimer.Start(); InputLayout }
502
+ else { $script:levelTimer.Stop(); SyncAction }
503
+ }
504
+ function VoiceState($state) {
505
+ $script:voiceLive = [string]$state
506
+ $voiceLabel.Text = switch ($state) { 'connecting' { $T.voice_connecting } 'listening' { $T.voice_listening } 'thinking' { $T.voice_thinking } 'speaking' { $T.voice_speaking } 'recording' { $T.voice_recording } default { '' } }
507
+ $bars = if ($state -eq 'speaking') { '#F472B6' } elseif ($state -eq 'listening' -or $state -eq 'recording') { '#8B7CF6' } else { '#C4B5FD' }
508
+ foreach ($r in $script:levelBars) { $r.Fill = Brush $bars }
509
+ AskStatus ''
510
+ (E 'MicBtn').ToolTip = switch ($state) { 'speaking' { $T.voice_hint_interrupt } 'recording' { $T.voice_hint_send } default { $T.voice_hint_end } }
511
+ # The bot's face follows the conversation: all ears, thinking, talking (animated mouth).
512
+ SetFace $(switch ($state) { 'thinking' { 'thinking' } 'speaking' { 'speaking' } default { 'listening' } })
513
+ }
514
+ # The server says the bot finished talking, but the speaker still plays what it has: keep "talking" (and a click = interrupt) until it is
515
+ # really quiet, then show the next state.
516
+ $script:afterSpeak = ''
517
+ $script:speakTimer = New-Object Windows.Threading.DispatcherTimer; $script:speakTimer.Interval = [TimeSpan]::FromMilliseconds(150)
518
+ $script:speakTimer.Add_Tick({
519
+ if ($script:afterSpeak -and -not [AivinMascot.Voice]::Playing) { $s = $script:afterSpeak; $script:afterSpeak = ''; if ($script:voiceLive) { VoiceState $s } }
520
+ })
521
+ function StartVoice { VoiceLook $true; VoiceState 'connecting'; $script:speakTimer.Start(); NoteTarget; Send @{ t = 'voice_start'; window = $script:askTarget } }
522
+ function EndVoice($text) {
523
+ [AivinMascot.Voice]::End(); $script:speakTimer.Stop(); $script:afterSpeak = ''; $script:voiceLive = ''; VoiceLook $false; AskStatus $text
524
+ SetFace $script:state
525
+ if ($script:askOpen) { HideAskLater ${ASK_IDLE_MS} }
526
+ }
527
+ function StopVoice { Send @{ t = 'voice_stop' }; EndVoice $T.voice_ended }
528
+ function InterruptVoice { [AivinMascot.Voice]::Flush(); $script:afterSpeak = ''; Send @{ t = 'voice_interrupt' }; VoiceState 'listening' }
529
+ # One action for the mic button and the hotkey: bot talking -> interrupt; talking with it -> end; idle -> start.
530
+ function VoiceToggle {
531
+ if ($script:voiceLive -and $script:voiceLive -ne 'recording' -and [AivinMascot.Voice]::Playing) { InterruptVoice }
532
+ elseif ($script:voiceLive) { StopVoice }
533
+ elseif (-not $script:chatBusy) { PeekAsk; StartVoice }
534
+ }
535
+ (E 'MicBtn').Add_Click({
536
+ if (-not $script:voiceLive -and (E 'AskBox').Text.Trim()) { SubmitAsk }
537
+ elseif (StopMode) { $script:canCancel = $false; (E 'MicBtn').Opacity = 0.5; SyncAction; Send @{ t = 'cancel' } }
538
+ else { VoiceToggle }
539
+ })
540
+ # Hotkeys anywhere (no need to reach for the bot): voice = the mic button, chat = open the ask box. Each is the first free combination of
541
+ # the list the daemon wrote into config.json (hotkey.mjs: the owner's own choice first, then the defaults; "hotkey off" = empty lists ->
542
+ # none). Shown in the mic button's tooltip / the tray menu; none free -> no hotkey. WM_HOTKEY is filtered in C# (AivinMascot.HotKeys).
543
+ function RegisterKeyList($id, $list) {
544
+ $keys = @(@($list) | Where-Object { $_ -and $_.n })
545
+ if (-not $keys.Count) { return $null }
546
+ $mods = [uint32[]]@($keys | ForEach-Object { [uint32]$_.m }); $vks = [uint32[]]@($keys | ForEach-Object { [uint32]$_.v })
547
+ $i = [AivinMascot.HotKeys]::RegisterFirst($script:hwnd, $id, $mods, $vks)
548
+ if ($i -lt 0) { Dbg ('hotkey ' + $id + ': none free'); return $null }
549
+ [string]$keys[$i].n
550
+ }
551
+ $w.Add_ContentRendered({
552
+ if (-not $script:hwnd) { return }
553
+ $voiceKey = RegisterKeyList 0xA171 $cfg.hotkeys.voice
554
+ if ($voiceKey) { $T.ask_mic = "$($T.ask_mic) ($voiceKey)"; SyncAction }
555
+ $chatKey = RegisterKeyList 0xA172 $cfg.hotkeys.chat
556
+ # The tray menu shows the same combinations next to its Quick chat / Quick voice items.
557
+ Send @{ t = 'hotkeys'; chat = $chatKey; voice = $voiceKey }
558
+ if ($voiceKey -or $chatKey) {
559
+ [AivinMascot.HotKeys]::Start($script:hwnd, [Action[int]]{ param($id)
560
+ if ($id -eq 0xA171) { VoiceToggle }
561
+ elseif ($id -eq 0xA172) { OpenAsk; [void](E 'AskBox').Focus() }
562
+ })
563
+ }
564
+ })
565
+
566
+ # Route the ask-box commands; everything else goes to the base handler of hostSource.mjs.
567
+ $script:baseHandle = (Get-Item function:Handle).ScriptBlock
568
+ function Handle($m) {
569
+ switch ($m.t) {
570
+ 'chat' {
571
+ ChatRow $m
572
+ if (-not $m.remove -and [string]$m.role -ne 'user' -and $m.text) {
573
+ $script:chatLast = ChatShort $m
574
+ if ($script:askOpen) { HideAskLater $(if ($m.blocks) { ${ASK_RICH_IDLE_MS} } else { ${ASK_IDLE_MS} }) } else { ChatBubble $script:chatLast }
575
+ }
576
+ return
577
+ }
578
+ 'chat_clear' { (E 'ChatList').Children.Clear(); $script:chatRows.Clear(); $script:scrollRow = $null; AskWidth $false; (E 'ChatScroll').Visibility = 'Collapsed'; InputLayout; return }
579
+ 'chat_busy' {
580
+ $script:chatBusy = [bool]$m.busy; $script:canCancel = [bool]$m.cancel
581
+ (E 'MicBtn').Opacity = if ($script:chatBusy -and -not $script:canCancel) { 0.5 } else { 1 }
582
+ SyncAction
583
+ # Answer arrived: leave it readable a while, then tuck the box away.
584
+ if (-not $script:chatBusy -and $script:askOpen) { HideAskLater ${ASK_IDLE_MS} }
585
+ # Turn over with the box closed: the answer / error stays in the bubble a while, then the bubble times out.
586
+ if (-not $script:chatBusy -and -not $script:askOpen -and (E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
587
+ if ($script:chatBusy) { $script:chatLast = '' }
588
+ return
589
+ }
590
+ 'ask_status' { AskStatus $m.text; return }
591
+ 'ask_choices' { ChoiceButtons $m.options $m.multiple; return }
592
+ # Files waiting for the next question: chips above the input; then on to the bot's tray (no return).
593
+ 'ask_files' { $chips = @($m.files | Where-Object { $_ }); $more = $chips.Count -gt (E 'AttachBar').Children.Count; $script:files = [int]$m.n; AttachChips $chips; SyncAction; if ($more) { PeekAsk; HideAskLater ${ASK_IDLE_MS} } }
594
+ 'ask_pin' {
595
+ $script:askPinned = [bool]$m.on
596
+ if ($script:askPinned) { $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; PeekAsk; (E 'ChatScroll').ScrollToEnd() }
597
+ elseif ($script:askOpen) { HideAskLater $(if ($script:askFocused) { ${ASK_IDLE_MS} } else { 4000 }) }
598
+ return
599
+ }
600
+ 'voice_begin' {
601
+ if (-not $script:voiceLive) { Send @{ t = 'voice_stop' }; return }
602
+ if ([AivinMascot.Voice]::Begin([int]$m.in_rate, [int]$m.out_rate, $true)) {
603
+ Dbg "voice: on, echo cancelled=$([AivinMascot.Voice]::EchoCancelled) $([AivinMascot.Voice]::AecError)"
604
+ VoiceState $(if ($m.state) { [string]$m.state } else { 'listening' })
605
+ } else { Dbg 'voice: no mic'; Send @{ t = 'voice_stop' }; EndVoice $T.ask_no_mic }
606
+ return
607
+ }
608
+ 'voice_state' {
609
+ if (-not $script:voiceLive) { return }
610
+ if ($script:voiceLive -eq 'speaking' -and $m.state -ne 'speaking' -and [AivinMascot.Voice]::Playing) { $script:afterSpeak = [string]$m.state }
611
+ else { $script:afterSpeak = ''; VoiceState $m.state }
612
+ return
613
+ }
614
+ 'voice_end' { if ($script:voiceLive) { EndVoice $m.text }; return }
615
+ # aivin ui: the user just asked for the mascot from a terminal -> show it and open the ask box ready to type.
616
+ 'open_ask' { $script:userHidden = $false; ApplyVisibility; if (-not $script:askFocused) { OpenAsk }; return }
617
+ 'voice_toggle' { $script:userHidden = $false; ApplyVisibility; VoiceToggle; return }
618
+ # Debug only (AIVIN_MASCOT_DEBUG): show the ask box WITHOUT taking keyboard focus, to look at it / screenshot it.
619
+ 'ask_preview' { if ($env:AIVIN_MASCOT_DEBUG) { PeekAsk }; return }
620
+ # Debug/docs preview of the real file-drag UI, using the same tray, face and hint code as DragEnter without requiring Explorer.
621
+ 'drop_preview' {
622
+ if ($env:AIVIN_MASCOT_DEBUG) {
623
+ $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; CloseAsk
624
+ $script:dragFiles = @('bao-cao.xlsx', 'anh-man-hinh.png'); $script:rig.Hover = $true; $script:rig.Tray('open', $script:files); SetFace 'waiting'
625
+ DropHint ($T.drop_many.Replace('{n}', '2'))
626
+ }
627
+ return
628
+ }
629
+ 'drop_preview_end' { if ($env:AIVIN_MASCOT_DEBUG) { DragEnd }; return }
630
+ # Debug only: start talking as if the mic was clicked (end-to-end voice test without clicking / taking focus).
631
+ 'voice_preview' { if ($env:AIVIN_MASCOT_DEBUG -and -not $script:voiceLive) { VoiceToggle }; return }
632
+ # Debug only: render the ask box (not the screen) to a PNG, to look at the design without screenshots.
633
+ 'snap' {
634
+ if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
635
+ $el = E 'Ask'; $el.UpdateLayout(); $dpi = 2
636
+ $bmp = New-Object Windows.Media.Imaging.RenderTargetBitmap ([int]($el.ActualWidth * $dpi + 24)), ([int]($el.ActualHeight * $dpi + 24)), (96 * $dpi), (96 * $dpi), ([Windows.Media.PixelFormats]::Pbgra32)
637
+ $vis = New-Object Windows.Media.DrawingVisual; $dc = $vis.RenderOpen()
638
+ $dc.DrawRectangle((Brush '#F3F4F6'), $null, (New-Object Windows.Rect 0, 0, ($el.ActualWidth + 12), ($el.ActualHeight + 12)))
639
+ # 1:1, no stretching (the drop shadow makes the visual's bounds bigger than the box).
640
+ $vb = New-Object Windows.Media.VisualBrush $el; $vb.Stretch = 'None'; $vb.AlignmentX = 'Left'; $vb.AlignmentY = 'Top'
641
+ $vb.ViewboxUnits = 'Absolute'; $vb.Viewbox = New-Object Windows.Rect 0, 0, $el.ActualWidth, $el.ActualHeight
642
+ $dc.DrawRectangle($vb, $null, (New-Object Windows.Rect 6, 6, $el.ActualWidth, $el.ActualHeight)); $dc.Close()
643
+ $bmp.Render($vis); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
644
+ $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
645
+ }
646
+ # Debug/docs only: render the complete live WPF visual tree (bot + every visible box), not the static seed artwork.
647
+ 'snap_full' {
648
+ if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
649
+ $el = E 'Root'; $el.UpdateLayout(); $dpi = 2
650
+ $bmp = New-Object Windows.Media.Imaging.RenderTargetBitmap ([int]($el.ActualWidth * $dpi)), ([int]($el.ActualHeight * $dpi)), (96 * $dpi), (96 * $dpi), ([Windows.Media.PixelFormats]::Pbgra32)
651
+ $bmp.Render($el); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
652
+ $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
653
+ }
654
+ }
655
+ & $script:baseHandle $m
656
+ }
657
+ # ---- end ask box ----
658
+ `;