@aivin-labs/cli 1.0.60 → 1.0.62

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.
@@ -1,667 +1,706 @@
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
- /**
45
- * Bề rộng nội dung nút lựa chọn / nút link. Trong ô hỏi (240) nút rộng 213, còn 207 khi thanh cuộn hiện; trừ lề trong 10 + 10 còn 187. Rộng hơn
46
- * thì mép phải bị cắt — đúng chỗ icon (05/11/2026: 192 làm mất nửa icon khi hội thoại đủ dài để cuộn).
47
- */
48
- export const CHOICE_ROW_WIDTH = 186;
49
- /** 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). */
50
- const LINK_ICON_PATH = lucidePath('external-link');
51
- /** Nút x trên chip tệp đính kèm. */
52
- const DETACH_ICON_PATH = lucidePath('x');
53
-
54
- export const ASK_PS1 = String.raw`
55
- # ---- Ask box (askHostSource.mjs) ----
56
- Add-Type -TypeDefinition @'
57
- using System; using System.Runtime.InteropServices;
58
- namespace AivinMascotAsk {
59
- public static class Native {
60
- [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);
61
- [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr h);
62
- [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
63
- [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, IntPtr pid);
64
- [DllImport("user32.dll")] static extern bool AttachThreadInput(uint a, uint b, bool attach);
65
- [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
66
- [DllImport("user32.dll")] static extern short GetAsyncKeyState(int vKey);
67
- public static bool ClickOutside() { return (GetAsyncKeyState(1) & 0x8000) != 0; }
68
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr h, System.Text.StringBuilder s, int n);
69
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, System.Text.StringBuilder s, int n);
70
- [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
71
- /** The window the person is using (not the bot, the taskbar or the desktop): { "0x..", title, pid }, or null. */
72
- public static string[] UserWindow() {
73
- IntPtr h = GetForegroundWindow(); if (h == IntPtr.Zero) return null;
74
- uint pid; GetWindowThreadProcessId(h, out pid);
75
- if (pid == (uint)System.Diagnostics.Process.GetCurrentProcess().Id) return null;
76
- var c = new System.Text.StringBuilder(256); GetClassName(h, c, 256);
77
- string cls = c.ToString(); if (cls == "Shell_TrayWnd" || cls == "Progman" || cls == "WorkerW") return null;
78
- var t = new System.Text.StringBuilder(512); GetWindowText(h, t, 512);
79
- return new string[] { "0x" + h.ToInt64().ToString("x"), t.ToString(), pid.ToString() };
80
- }
81
- /** The user just clicked the bot: take keyboard focus (Windows refuses SetForegroundWindow from a background window otherwise). */
82
- public static bool TakeFocus(IntPtr h) {
83
- uint fg = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero), me = GetCurrentThreadId();
84
- bool attached = fg != 0 && fg != me && AttachThreadInput(fg, me, true);
85
- try { BringWindowToTop(h); return SetForegroundWindow(h); }
86
- finally { if (attached) AttachThreadInput(fg, me, false); }
87
- }
88
- [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h);
89
- /** The box closed by itself while holding the keyboard: back to the window the person came from (only if we still hold it). */
90
- public static bool GiveFocusBack(IntPtr me, string target) {
91
- if (GetForegroundWindow() != me) return false;
92
- IntPtr h = new IntPtr(Convert.ToInt64(target, 16));
93
- return IsWindow(h) && SetForegroundWindow(h);
94
- }
95
- }
96
- }
97
- '@
98
- (E 'AskHint').Text = $T.ask_hint; (E 'MicBtn').ToolTip = $T.ask_mic
99
- # "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.
100
- (E 'NewChatText').Text = $T.new_chat; (E 'NewChatBtn').ToolTip = $T.new_chat_tip
101
- (E 'NewChatBtn').Add_Click({ Send @{ t = 'new_chat' }; OpenAsk })
102
-
103
- function AskShow($name) {
104
- $script:bubbleTimer.Stop(); (E 'Bubble').Visibility = 'Collapsed'; (E 'Bubble').Opacity = 0
105
- $el = E $name; $el.Visibility = 'Visible'; $w.FindResource('PanelIn').Begin($el)
106
- }
107
- function AskHide($name) {
108
- $el = E $name; if ($el.Visibility -ne 'Visible') { return }
109
- # The ask box may be shown again while it is still fading out: then the finished fade must not collapse it.
110
- $sb = $w.FindResource('PanelOut').Clone(); $sb.Add_Completed({ if ($name -ne 'Ask' -or -not $script:askOpen) { (E $name).Visibility = 'Collapsed' } }.GetNewClosure()); $sb.Begin($el)
111
- }
112
- function SetActivatable($on) {
113
- if (-not $script:hwnd) { return }
114
- $ex = [AivinMascot.Native]::GetWindowLong($script:hwnd, -20)
115
- $ex = if ($on) { $ex -band (-bnot 0x08000000) } else { $ex -bor 0x08000000 }
116
- [void][AivinMascot.Native]::SetWindowLong($script:hwnd, -20, $ex)
117
- }
118
- function AskStatus($text) {
119
- $el = E 'AskStatus'; SetText $el $text; $el.Visibility = if ($text) { 'Visible' } else { 'Collapsed' }
120
- }
121
- $script:askOpen = $false; $script:askFocused = $false
122
- # The window the person was on right before reaching for the bot: sent with each question / talk so "this" means that window.
123
- $script:askTarget = $null
124
- function NoteTarget {
125
- $i = $null; try { $i = [AivinMascotAsk.Native]::UserWindow() } catch { }
126
- if (-not $i) { return }
127
- $p = ''; try { $p = (Get-Process -Id ([int]$i[2]) -ErrorAction Stop).ProcessName } catch { }
128
- $script:askTarget = @{ window = $i[0]; title = $i[1]; process = $p }
129
- }
130
- function PeekAsk {
131
- NoteTarget
132
- if ($script:askOpen) { return }
133
- $script:askOpen = $true; AskShow 'Ask'; $w.FindResource('AskGlow').Begin($w, $true)
134
- }
135
- function OpenAsk {
136
- NoteTarget; AskHide 'Panel'
137
- $script:askOpen = $true; AskShow 'Ask'; $w.FindResource('AskGlow').Begin($w, $true)
138
- $script:askFocused = $true; SetActivatable $true; $ok = [AivinMascotAsk.Native]::TakeFocus($script:hwnd); [void]$w.Activate(); Dbg "ask focus=$ok"
139
- [void](E 'AskBox').Focus(); [void][Windows.Input.Keyboard]::Focus((E 'AskBox'))
140
- HideAskLater ${ASK_IDLE_MS}
141
- }
142
- function CloseAsk {
143
- $script:askHideTimer.Stop()
144
- if (-not $script:askOpen) { return }
145
- if ($script:voiceLive) { StopVoice }
146
- $script:askOpen = $false; $script:askFocused = $false
147
- AskHide 'Ask'; SetActivatable $false; $w.FindResource('AskGlow').Stop($w)
148
- }
149
- function MascotClick { if ($script:askFocused) { CloseAsk } else { OpenAsk } }
150
- # One box at a time: while the ask box is open, what the bot does on the machine only updates the text; the bubble
151
- # (notification) comes back with the latest step once the box closes, if the bot is still busy.
152
- $script:baseShowBubble = (Get-Item function:ShowBubble).ScriptBlock
153
- function ShowBubble($text) { if ($script:askOpen) { SetText (E 'NowText') $text; return }; & $script:baseShowBubble $text }
154
- $script:baseCloseAsk = (Get-Item function:CloseAsk).ScriptBlock
155
- function CloseAsk {
156
- $was = $script:askOpen; & $script:baseCloseAsk
157
- if (-not $was -or (E 'Panel').Visibility -eq 'Visible') { return }
158
- if ($script:chatBusy -and $script:chatLast) { ChatBubble $script:chatLast }
159
- elseif ((IsBusy) -or $script:state -eq 'waiting') { & $script:baseShowBubble ([AivinMascot.Emoji]::Text((E 'NowText'))) }
160
- if ((E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
161
- }
162
- # 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
163
- # written (its tail), the answer / error. Stays up while the turn runs; once it ends the bubble times out as usual.
164
- $script:chatLast = ''
165
- function ChatShort($m) {
166
- $text = ([string]$m.text -replace '\s+', ' ').Trim()
167
- if ($m.partial -and $text.Length -gt 90) { $text = "$([char]0x2026)" + $text.Substring($text.Length - 89) }
168
- $text
169
- }
170
- function ChatBubble($text) {
171
- if (-not $text -or (E 'Panel').Visibility -eq 'Visible') { return }
172
- & $script:baseShowBubble $text
173
- $script:bubbleTimer.Stop(); $script:bubbleTimer.Start()
174
- }
175
- # 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
176
- # 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.
177
- $script:askHideTimer = New-Object Windows.Threading.DispatcherTimer
178
- $script:askHideTimer.Add_Tick({
179
- if ($script:askOpen -and (AskInUse)) { HideAskLater ${ASK_IDLE_MS}; return }
180
- $held = $script:askFocused; CloseAsk
181
- if ($held -and $script:askTarget) { try { [void][AivinMascotAsk.Native]::GiveFocusBack($script:hwnd, [string]$script:askTarget.window) } catch { } }
182
- })
183
- # 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.
184
- function AskInUse {
185
- $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()))
186
- }
187
- # Aivin is waiting for an answer (HIL): the box stays out with the question + option buttons until it is answered (no focus taken).
188
- $script:askPinned = $false
189
- function HideAskLater($ms) { $script:askHideTimer.Stop(); $script:askHideTimer.Interval = [TimeSpan]::FromMilliseconds($ms); $script:askHideTimer.Start() }
190
- (E 'Mascot').ToolTip = $null
191
- (E 'Mascot').Add_MouseEnter({ $script:askHideTimer.Stop(); if ((E 'Panel').Visibility -ne 'Visible' -and -not $script:drag) { PeekAsk } })
192
- (E 'Ask').Add_MouseEnter({ $script:askHideTimer.Stop() })
193
- # Only peeking: gone right after the mouse leaves. Holding the keyboard: the person may be about to type, so the full wait.
194
- $w.Add_MouseLeave({ if ($script:askOpen) { HideAskLater $(if ($script:askFocused) { ${ASK_IDLE_MS} } else { 600 }) } })
195
- # Clicked somewhere else: release keyboard focus and close the box.
196
- $w.Add_Deactivated({
197
- $script:askFocused = $false; SetActivatable $false
198
- if ($script:askOpen -and -not $script:voiceLive -and -not $script:drag -and -not $script:askPinned) { CloseAsk }
199
- if ((E 'Panel').Visibility -eq 'Visible') { ClosePanel }
200
- })
201
- # Click outside detection: transparent window region or anywhere on other windows
202
- $w.Add_PreviewMouseLeftButtonDown({ param($s, $e)
203
- if (-not $script:askOpen -or $script:drag) { return }
204
- $pt = $e.GetPosition($w)
205
- $askBox = E 'Ask'; $mascot = E 'Mascot'; $panel = E 'Panel'
206
- $inAsk = $askBox.Visibility -eq 'Visible' -and (New-Object Windows.Rect ($askBox.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $askBox.RenderSize).Contains($pt)
207
- $inMascot = (New-Object Windows.Rect ($mascot.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $mascot.RenderSize).Contains($pt)
208
- $inPanel = $panel.Visibility -eq 'Visible' -and (New-Object Windows.Rect ($panel.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $panel.RenderSize).Contains($pt)
209
- if (-not $inAsk -and -not $inMascot -and -not $inPanel -and -not $script:askPinned) {
210
- CloseAsk
211
- }
212
- if (-not $inPanel -and (E 'Panel').Visibility -eq 'Visible' -and -not $inMascot) {
213
- ClosePanel
214
- }
215
- })
216
- $script:clickCheckTimer = New-Object Windows.Threading.DispatcherTimer
217
- $script:clickCheckTimer.Interval = [TimeSpan]::FromMilliseconds(50)
218
- $script:clickCheckTimer.Add_Tick({
219
- if ($script:askOpen -and -not $script:voiceLive -and -not $script:drag -and -not $script:askPinned) {
220
- if (-not $w.IsMouseOver -and [AivinMascotAsk.Native]::ClickOutside()) {
221
- CloseAsk
222
- }
223
- }
224
- if ((E 'Panel').Visibility -eq 'Visible' -and -not $script:drag) {
225
- if (-not $w.IsMouseOver -and [AivinMascotAsk.Native]::ClickOutside()) {
226
- ClosePanel
227
- }
228
- }
229
- })
230
- $script:clickCheckTimer.Start()
231
- # Clicking into the peeking box = about to type: take keyboard focus.
232
- (E 'Ask').Add_PreviewMouseLeftButtonDown({ if (-not $script:askFocused) { OpenAsk } })
233
- # Right-click on the bot: the activity panel.
234
- (E 'Mascot').Add_MouseRightButtonUp({ param($s, $e) CloseAsk; OpenPanel; $e.Handled = $true })
235
- # One button: empty box = mic, typed text = send.
236
- # Waiting on a turn the server can stop (chat_busy { cancel }): the empty-box button is a stop button instead of the mic.
237
- function StopMode { $script:chatBusy -and $script:canCancel -and -not $script:voiceLive -and -not (E 'AskBox').Text.Trim() -and -not $script:files }
238
- function SyncAction {
239
- # Files waiting (chips above the input): the button sends even with nothing typed, and the hint asks what to do with them.
240
- $typed = [bool](E 'AskBox').Text.Trim() -or ($script:files -gt 0 -and -not $script:voiceLive)
241
- $stop = StopMode
242
- (E 'AskHint').Text = if ($script:files -gt 0) { $T.ask_attached } else { $T.ask_hint }
243
- (E 'AskHint').Visibility = if ((E 'AskBox').Text) { 'Collapsed' } else { 'Visible' }
244
- (E 'SendIcon').Visibility = if ($typed) { 'Visible' } else { 'Collapsed' }; (E 'MicIcon').Visibility = if ($typed -or $stop) { 'Collapsed' } else { 'Visible' }
245
- (E 'StopIcon').Visibility = if ($stop) { 'Visible' } else { 'Collapsed' }
246
- (E 'MicBtn').ToolTip = if ($typed) { $T.ask_send } elseif ($stop) { $T.ask_stop } else { $T.ask_mic }
247
- InputLayout
248
- }
249
- # 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
250
- # button centred on the same line - the box only grows (mic back at the bottom) when the typed text wraps.
251
- function InputLayout {
252
- $box = E 'AskBox'
253
- # Box hidden = the voice bar is in its place (VoiceLook hides it before the voice state is set).
254
- $compact = $box.Visibility -ne 'Visible' -or [bool]$script:voiceLive -or (E 'ChatList').Children.Count -gt 0
255
- $wrapped = $box.Visibility -eq 'Visible' -and $box.LineCount -gt 1
256
- $box.Parent.MinHeight = if ($compact) { 26 } else { 40 }
257
- $mid = if ($compact -and -not $wrapped) { 'Center' } else { 'Top' }
258
- $box.VerticalAlignment = $mid; (E 'AskHint').VerticalAlignment = $mid
259
- (E 'MicBtn').VerticalAlignment = if ($compact -and -not $wrapped) { 'Center' } else { 'Bottom' }
260
- }
261
- (E 'AskBox').Add_TextChanged({ SyncAction; AttendAsk; if ($script:askOpen) { HideAskLater ${ASK_IDLE_MS} } })
262
- # Typing: the bot looks at the box (above or below it) while keys come in; a little nod when a question / answer goes out.
263
- function AttendAsk {
264
- if (-not (E 'AskBox').Text) { return }
265
- $a = E 'Ask'; $p = $a.TranslatePoint((New-Object Windows.Point ($a.ActualWidth / 2), ($a.ActualHeight / 2)), (E 'Mascot'))
266
- $script:rig.Attend($p.X - ${MASCOT_CENTER.x}, $p.Y - ${MASCOT_CENTER.y})
267
- }
268
-
269
- $script:chatBusy = $false
270
- $script:canCancel = $false
271
- function SubmitAsk {
272
- $text = (E 'AskBox').Text.Trim(); if ((-not $text -and -not $script:files) -or $script:chatBusy -or $script:voiceLive) { return }
273
- NoteTarget; (E 'AskBox').Text = ''; $script:rig.Play('ack'); Send @{ t = 'ask'; text = $text; window = $script:askTarget }
274
- }
275
- (E 'AskBox').Add_KeyDown({ param($s, $e)
276
- if ($e.Key -eq 'Return') { SubmitAsk; $e.Handled = $true }
277
- elseif ($e.Key -eq 'Escape') { CloseAsk; $e.Handled = $true }
278
- })
279
-
280
- # Conversation rows: user (right, light brand), assistant (left, grey), one live progress line, errors. Bubbles point at their speaker
281
- # (the corner on the speaker's side is nearly square, 3 px) and new ones fade + rise in.
282
- $script:chatRows = @{}
283
- # "Working on it": three dots bouncing in turn inside an assistant bubble (a staggered key-frame hop, then a rest).
284
- function TypingDots {
285
- $sp = New-Object Windows.Controls.StackPanel; $sp.Orientation = 'Horizontal'; $sp.Margin = '1,5,1,5'
286
- for ($i = 0; $i -lt 3; $i++) {
287
- $e = New-Object Windows.Shapes.Ellipse; $e.Width = 6; $e.Height = 6; $e.Margin = '2,0,2,0'; $e.Fill = Brush '#9AA0AB'
288
- $tt = New-Object Windows.Media.TranslateTransform; $e.RenderTransform = $tt
289
- $a = New-Object Windows.Media.Animation.DoubleAnimationUsingKeyFrames
290
- $a.Duration = [TimeSpan]::FromMilliseconds(1200); $a.BeginTime = [TimeSpan]::FromMilliseconds(160 * $i)
291
- $a.RepeatBehavior = [Windows.Media.Animation.RepeatBehavior]::Forever
292
- foreach ($k in @(@(0, 0), @(280, -4.5), @(560, 0), @(1200, 0))) {
293
- $f = New-Object Windows.Media.Animation.EasingDoubleKeyFrame ([double]$k[1]), ([Windows.Media.Animation.KeyTime]::FromTimeSpan([TimeSpan]::FromMilliseconds($k[0])))
294
- $f.EasingFunction = New-Object Windows.Media.Animation.SineEase; [void]$a.KeyFrames.Add($f)
295
- }
296
- $tt.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $a)
297
- [void]$sp.Children.Add($e)
298
- }
299
- $sp
300
- }
301
- # 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.
302
- function LinkCard($text, $url, $iconPath = '${LINK_ICON_PATH}') {
303
- $dock = New-Object Windows.Controls.DockPanel; $dock.MaxWidth = ${CHOICE_ROW_WIDTH}
304
- $icon = LucideIcon $(if ($iconPath) { $iconPath } else { '${LINK_ICON_PATH}' }) 13 '${ICON_INKS[2]}'; $icon.Margin = '8,2,0,0'; $icon.VerticalAlignment = 'Top'; [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$dock.Children.Add($icon)
305
- $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; SetText $tb $text; [void]$dock.Children.Add($tb)
306
- $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; $btn.ToolTip = [string]$url
307
- $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,3'; $btn.HorizontalAlignment = 'Left'
308
- $btn.Background = Brush '${CHOICE_CARDS[2]}'; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
309
- $btn.Add_Click({ param($s) OpenWebUrl $s.CommandParameter })
310
- $btn
311
- }
312
- function ChatLinks($row, $links) {
313
- $list = E 'ChatList'
314
- if ($row.links) { [void]$list.Children.Remove($row.links); $row.links = $null }
315
- $items = @(@($links) | Where-Object { $_ -and $_.url })
316
- if (-not $items.Count) { return }
317
- $sp = New-Object Windows.Controls.StackPanel; $sp.Margin = '0,0,0,4'; $sp.HorizontalAlignment = 'Left'
318
- foreach ($l in $items) { [void]$sp.Children.Add((LinkCard $l.text $l.url $l.icon_path)) }
319
- $after = if ($row.blocks) { $row.blocks } else { $row.box }
320
- $list.Children.Insert($list.Children.IndexOf($after) + 1, $sp); $row.links = $sp
321
- }
322
- ${ASK_BLOCKS_PS1}
323
- function ChatRow($m) {
324
- $list = E 'ChatList'; $id = [string]$m.id
325
- $row = $null; if ($id) { $row = $script:chatRows[$id] }
326
- if ($m.remove) { if ($row) { ChatLinks $row $null; ChatBlocks $row $null; [void]$list.Children.Remove($row.box); $script:chatRows.Remove($id) }; return }
327
- (E 'ChatScroll').Visibility = 'Visible'
328
- if (-not $row) {
329
- # Segoe UI adds its own space above / below the letters: block line height + slim vertical padding so the space you see is about
330
- # the same on all four sides.
331
- $b = New-Object Windows.Controls.Border; $b.Padding = '10,5,10,5'; $b.Margin = '0,0,0,4'; $b.MaxWidth = $script:bubbleMax
332
- $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.FontSize = 14; $tb.LineHeight = 20; $tb.LineStackingStrategy = 'BlockLineHeight'
333
- $b.Child = $tb; [void]$list.Children.Add($b)
334
- $slide = New-Object Windows.Media.TranslateTransform 0, 6; $b.RenderTransform = $slide
335
- $ease = New-Object Windows.Media.Animation.CubicEase; $ease.EasingMode = 'EaseOut'
336
- $fade = New-Object Windows.Media.Animation.DoubleAnimation 0, 1, ([TimeSpan]::FromMilliseconds(200)); $fade.EasingFunction = $ease
337
- $rise = New-Object Windows.Media.Animation.DoubleAnimation 6, 0, ([TimeSpan]::FromMilliseconds(240)); $rise.EasingFunction = $ease
338
- $b.BeginAnimation([Windows.UIElement]::OpacityProperty, $fade); $slide.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $rise)
339
- $row = @{ box = $b; text = $tb; url = $null }
340
- # The link rides on the bubble itself (Tag, updated below): the handler is not a closure, $row at click time is not this row.
341
- $b.Add_MouseLeftButtonUp({ param($s) OpenWebUrl $s.Tag })
342
- if ($id) { $script:chatRows[$id] = $row }
343
- while ($list.Children.Count -gt 40) { $list.Children.RemoveAt(0) }
344
- }
345
- if ($m.url) {
346
- $row.url = [string]$m.url; $row.box.Tag = [string]$m.url
347
- $row.box.Cursor = [Windows.Input.Cursors]::Hand
348
- $row.box.ToolTip = [string]$m.url
349
- } else {
350
- $row.url = $null; $row.box.Tag = $null
351
- $row.box.Cursor = [Windows.Input.Cursors]::Arrow
352
- $row.box.ToolTip = $null
353
- }
354
- $role = [string]$m.role
355
- $row.box.HorizontalAlignment = if ($role -eq 'user') { 'Right' } else { 'Left' }
356
- # CornerRadius = top-left, top-right, bottom-right, bottom-left.
357
- $row.box.CornerRadius = if ($role -eq 'user') { '10,10,3,10' } elseif ($role -eq 'progress') { '0' } else { '10,10,10,3' }
358
- $bg = if ($role -eq 'user') { '#E8F3FF' } elseif ($role -eq 'error') { '#FFECE8' } elseif ($role -eq 'progress') { '#00FFFFFF' } else { '#F4F6FA' }
359
- $fg = if ($role -eq 'progress') { $P.muted } elseif ($role -eq 'error') { '#CB2634' } else { $P.ink }
360
- $row.box.Background = Brush $bg; $row.text.Foreground = Brush $fg
361
- $row.text.FontStyle = if ($role -eq 'progress') { 'Italic' } else { 'Normal' }
362
- SetText $row.text $m.text
363
- ChatLinks $row $null
364
- ChatBlocks $row $m.blocks
365
- ChatLinks $row $m.links
366
- # The bubble on the bot's head cannot show a table: the owner just asked, so open the box (without taking the keyboard).
367
- if ($m.peek -and -not $script:askOpen -and (E 'Panel').Visibility -ne 'Visible') { PeekAsk }
368
- if ($m.typing) {
369
- if (-not $row.dots) { $row.dots = TypingDots }
370
- $row.box.Child = $row.dots; $row.box.Background = Brush '#F4F6FA'; $row.box.CornerRadius = '10,10,10,3'
371
- } elseif ($row.dots -and $row.box.Child -ne $row.text) { $row.box.Child = $row.text }
372
- # Words the owner is still saying: lighter until the sentence is settled (the box's own opacity is the fade-in).
373
- $row.text.Opacity = if ($m.partial) { 0.55 } else { 1 }
374
- $script:scrollRow = if ($row.blocks) { $row } else { $null }
375
- if ($script:scrollRow) { ScrollToRow $row } else { (E 'ChatScroll').ScrollToEnd() }
376
- InputLayout
377
- }
378
-
379
- # Aivin asked something with choices: a vertical list, one full-width card per option (the daemon clears them once answered). Typing
380
- # 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 /
381
- # unticks, a confirm button sends the ticked ones), the text, the option's icon at the end when it has one we can draw.
382
- # Soft look: each card filled with a light pastel (cycling the ask box's glow colors), no border, dark-grey text; hover deepens it.
383
- # 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.
384
- # Top margin 2 centres it on the first line of text (17 high), so it stays level with the tick mark.
385
- function ChoiceIcon($o, $ink) {
386
- if ($o.icon_path) { $i = LucideIcon $o.icon_path 14 $ink; $i.Margin = '8,2,0,0'; $i.VerticalAlignment = 'Top'; return $i }
387
- if (-not $o.icon) { return $null }
388
- $tb = New-Object Windows.Controls.TextBlock; $tb.FontSize = 13; $tb.Margin = '8,1,0,0'; $tb.VerticalAlignment = 'Top'; SetText $tb $o.icon; $tb
389
- }
390
- function ChoiceMark($multi) {
391
- $m = New-Object Windows.Controls.Border; $m.Width = 13; $m.Height = 13; $m.Margin = '0,2,8,0'; $m.VerticalAlignment = 'Top'
392
- $m.CornerRadius = if ($multi) { '3.5' } else { '6.5' }; $m.BorderThickness = '1.4'
393
- $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'
394
- $tick.StrokeThickness = 1.7; $tick.StrokeStartLineCap = 'Round'; $tick.StrokeEndLineCap = 'Round'; $tick.StrokeLineJoin = 'Round'
395
- $m.Child = $tick; SetTicked $m $false; $m
396
- }
397
- function SetTicked($mark, $on) {
398
- $mark.Background = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '#B3FFFFFF' }
399
- $mark.BorderBrush = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '${CHOICE_MARK}' }
400
- $mark.Child.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
401
- }
402
- $script:picked = New-Object Collections.ArrayList; $script:choiceMarks = @{}; $script:choiceConfirm = $null
403
- function SyncConfirm {
404
- $b = $script:choiceConfirm; if (-not $b) { return }
405
- $b.Content = $T.ask_confirm -replace '\{n\}', $script:picked.Count
406
- $b.Visibility = if ($script:picked.Count) { 'Visible' } else { 'Collapsed' }
407
- }
408
- function ChoiceButtons($options, $multiple) {
409
- $panel = E 'Choices'; $panel.Children.Clear(); $k = 0; $multi = [bool]$multiple
410
- $script:picked.Clear(); $script:choiceMarks = @{}; $script:choiceConfirm = $null
411
- $cards = @(${CHOICE_CARDS.map((c) => `'${c}'`).join(', ')}); $inks = @(${ICON_INKS.map((c) => `'${c}'`).join(', ')})
412
- foreach ($o in @($options)) {
413
- if (-not $o) { continue }
414
- $c = $cards[$k % $cards.Count]; $k++; $id = [string]$o.id
415
- $row = New-Object Windows.Controls.DockPanel; $row.Width = ${CHOICE_ROW_WIDTH}
416
- $mark = ChoiceMark $multi; [Windows.Controls.DockPanel]::SetDock($mark, 'Left'); [void]$row.Children.Add($mark)
417
- $icon = ChoiceIcon $o $inks[($k - 1) % $inks.Count]; if ($icon) { [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$row.Children.Add($icon) }
418
- $tb = New-Object Windows.Controls.TextBlock; SetText $tb $o.text; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; [void]$row.Children.Add($tb)
419
- $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $row; $btn.CommandParameter = $id
420
- $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,4'; $btn.HorizontalAlignment = 'Stretch'
421
- $btn.Background = Brush $c; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
422
- $script:choiceMarks[$id] = $mark
423
- if ($multi) {
424
- $btn.Add_Click({ param($s)
425
- $id = [string]$s.CommandParameter; $on = -not $script:picked.Contains($id)
426
- if ($on) { [void]$script:picked.Add($id) } else { $script:picked.Remove($id) }
427
- SetTicked $script:choiceMarks[$id] $on; SyncConfirm
428
- })
429
- } else {
430
- $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 } } })
431
- }
432
- [void]$panel.Children.Add($btn)
433
- }
434
- if ($multi -and $panel.Children.Count) {
435
- $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'
436
- $ok.HorizontalAlignment = 'Right'; $ok.Background = Brush '${ASK_BTN.icon}'; $ok.Foreground = Brush '#FFFFFF'; $ok.BorderThickness = '0'; $ok.Tag = Brush '#1F000000'
437
- $ok.Add_Click({ if (-not $script:chatBusy -and $script:picked.Count) { $script:rig.Play('ack'); Send @{ t = 'choose'; ids = @($script:picked.ToArray()) } } })
438
- $script:choiceConfirm = $ok; [void]$panel.Children.Add($ok); SyncConfirm
439
- }
440
- $panel.Visibility = if ($panel.Children.Count) { 'Visible' } else { 'Collapsed' }
441
- if ($panel.Children.Count) { (E 'ChatScroll').Visibility = 'Visible'; (E 'ChatScroll').ScrollToEnd() }
442
- }
443
-
444
- # Attached files: one chip each above the input - the file type's icon + colour (fileChips.mjs), its name (full path in the tooltip),
445
- # an x that drops it (detach -> the daemon answers with the new ask_files).
446
- function AttachChips($chips) {
447
- $bar = E 'AttachBar'; $bar.Children.Clear()
448
- foreach ($c in @($chips)) {
449
- if (-not $c -or -not $c.path) { continue }
450
- $ink = [string]$c.ink; if (-not $ink) { $ink = '#64748B' }
451
- $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
452
- # The working folder's chip stays after a question goes out and is not a waiting file (ask_files).
453
- if ($c.pinned) { $chip.Tag = 'pinned' }
454
- $chip.Background = Brush $(if ($c.bg) { [string]$c.bg } else { '#F8FAFC' })
455
- # Hairline in the type's colour (ink at ~20 %): keeps the very light chip readable on the white box.
456
- $chip.BorderThickness = '1'; $chip.BorderBrush = Brush ('#33' + $ink.TrimStart('#'))
457
- $row = New-Object Windows.Controls.StackPanel; $row.Orientation = 'Horizontal'
458
- 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) }
459
- $tb = New-Object Windows.Controls.TextBlock; $tb.Text = [string]$c.name; $tb.FontSize = 12; $tb.Foreground = Brush $ink; $tb.MaxWidth = 140
460
- $tb.TextTrimming = 'CharacterEllipsis'; $tb.VerticalAlignment = 'Center'; [void]$row.Children.Add($tb)
461
- $x = New-Object Windows.Controls.Button; $x.Style = $w.FindResource('IconBtn'); $x.Width = 18; $x.Height = 18; $x.Margin = '3,0,0,0'
462
- $x.Background = Brush '#00000000'; $x.BorderThickness = '0'; $x.Tag = Brush '#1F000000'; $x.ToolTip = $(if ($c.detach_tip) { [string]$c.detach_tip } else { $T.ask_detach })
463
- $x.Content = LucideIcon '${DETACH_ICON_PATH}' 10 $ink; $x.CommandParameter = [string]$c.path
464
- $x.Add_Click({ param($s) Send @{ t = 'detach'; path = [string]$s.CommandParameter } })
465
- [void]$row.Children.Add($x); $chip.Child = $row; [void]$bar.Children.Add($chip)
466
- }
467
- $bar.Visibility = if ($bar.Children.Count) { 'Visible' } else { 'Collapsed' }
468
- }
469
-
470
- # Voice: a live conversation with Aivin (voiceSource.mjs streams the mic / speaker). '' = off, else connecting | listening | thinking | speaking,
471
- # or recording (older Aivin server without live voice: talk, click the mic to send, it goes through voice-to-text).
472
- $script:voiceLive = ''
473
- # 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
474
- # talks, a soft wave while it thinks) + a short state. The mic button turns red (its tooltip says what a click does now).
475
- $inputCell = (E 'AskBox').Parent
476
- $voiceBar = New-Object Windows.Controls.StackPanel; $voiceBar.Orientation = 'Horizontal'; $voiceBar.VerticalAlignment = 'Center'; $voiceBar.Visibility = 'Collapsed'
477
- $voiceBar.Margin = '2,0,0,0'
478
- $script:levelBars = @()
479
- foreach ($i in 0..4) {
480
- $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'
481
- $r.VerticalAlignment = 'Center'; $r.Fill = Brush '#8B7CF6'; [void]$voiceBar.Children.Add($r); $script:levelBars += $r
482
- }
483
- $voiceLabel = New-Object Windows.Controls.TextBlock; $voiceLabel.FontSize = 14; $voiceLabel.Foreground = Brush $P.ink; $voiceLabel.Margin = '7,0,0,1'
484
- $voiceLabel.VerticalAlignment = 'Center'; $voiceLabel.TextTrimming = 'CharacterEllipsis'; [void]$voiceBar.Children.Add($voiceLabel)
485
- [void]$inputCell.Children.Add($voiceBar)
486
- $script:levelShape = @(0.55, 0.85, 1, 0.85, 0.55); $script:levelNow = @(0, 0, 0, 0, 0)
487
- $script:levelTimer = New-Object Windows.Threading.DispatcherTimer; $script:levelTimer.Interval = [TimeSpan]::FromMilliseconds(50)
488
- $script:levelTimer.Add_Tick({
489
- $t = [Environment]::TickCount / 1000.0
490
- $level = switch ($script:voiceLive) {
491
- 'listening' { [AivinMascot.Voice]::MicLevel }
492
- 'recording' { [AivinMascot.Voice]::MicLevel }
493
- 'speaking' { [AivinMascot.Voice]::OutLevel }
494
- default { -1 }
495
- }
496
- for ($i = 0; $i -lt 5; $i++) {
497
- # No live level (connecting / thinking): a slow travelling wave, so it reads as "working on it".
498
- $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))) }
499
- $script:levelNow[$i] = $script:levelNow[$i] + ($target - $script:levelNow[$i]) * $(if ($target -gt $script:levelNow[$i]) { 0.6 } else { 0.25 })
500
- $script:levelBars[$i].Height = 4 + 16 * $script:levelNow[$i]
501
- }
502
- })
503
- function VoiceLook($on) {
504
- (E 'MicBtn').Background = Brush $(if ($on) { '${ASK_BTN.recBg}' } else { '${ASK_BTN.bg}' })
505
- (E 'MicIcon').Stroke = Brush $(if ($on) { '${ASK_BTN.recIcon}' } else { '${ASK_BTN.icon}' })
506
- # The voice bar only needs the button's height (InputLayout, via SyncAction / below).
507
- (E 'AskBox').Visibility = if ($on) { 'Collapsed' } else { 'Visible' }
508
- $voiceBar.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
509
- if ($on) { (E 'MicIcon').Visibility = 'Visible'; (E 'SendIcon').Visibility = 'Collapsed'; (E 'AskHint').Visibility = 'Collapsed'; $script:levelTimer.Start(); InputLayout }
510
- else { $script:levelTimer.Stop(); SyncAction }
511
- }
512
- function VoiceState($state) {
513
- $script:voiceLive = [string]$state
514
- $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 { '' } }
515
- $bars = if ($state -eq 'speaking') { '#F472B6' } elseif ($state -eq 'listening' -or $state -eq 'recording') { '#8B7CF6' } else { '#C4B5FD' }
516
- foreach ($r in $script:levelBars) { $r.Fill = Brush $bars }
517
- AskStatus ''
518
- (E 'MicBtn').ToolTip = switch ($state) { 'speaking' { $T.voice_hint_interrupt } 'recording' { $T.voice_hint_send } default { $T.voice_hint_end } }
519
- # The bot's face follows the conversation: all ears, thinking, talking (animated mouth).
520
- SetFace $(switch ($state) { 'thinking' { 'thinking' } 'speaking' { 'speaking' } default { 'listening' } })
521
- }
522
- # The server says the bot finished talking, but the speaker still plays what it has: keep "talking" (and a click = interrupt) until it is
523
- # really quiet, then show the next state.
524
- $script:afterSpeak = ''
525
- $script:speakTimer = New-Object Windows.Threading.DispatcherTimer; $script:speakTimer.Interval = [TimeSpan]::FromMilliseconds(150)
526
- $script:speakTimer.Add_Tick({
527
- if ($script:afterSpeak -and -not [AivinMascot.Voice]::Playing) { $s = $script:afterSpeak; $script:afterSpeak = ''; if ($script:voiceLive) { VoiceState $s } }
528
- })
529
- function StartVoice { VoiceLook $true; VoiceState 'connecting'; $script:speakTimer.Start(); NoteTarget; Send @{ t = 'voice_start'; window = $script:askTarget } }
530
- function EndVoice($text) {
531
- [AivinMascot.Voice]::End(); $script:speakTimer.Stop(); $script:afterSpeak = ''; $script:voiceLive = ''; VoiceLook $false; AskStatus $text
532
- SetFace $script:state
533
- if ($script:askOpen) { HideAskLater ${ASK_IDLE_MS} }
534
- }
535
- function StopVoice { Send @{ t = 'voice_stop' }; EndVoice $T.voice_ended }
536
- function InterruptVoice { [AivinMascot.Voice]::Flush(); $script:afterSpeak = ''; Send @{ t = 'voice_interrupt' }; VoiceState 'listening' }
537
- # One action for the mic button and the hotkey: bot talking -> interrupt; talking with it -> end; idle -> start.
538
- function VoiceToggle {
539
- if ($script:voiceLive -and $script:voiceLive -ne 'recording' -and [AivinMascot.Voice]::Playing) { InterruptVoice }
540
- elseif ($script:voiceLive) { StopVoice }
541
- elseif (-not $script:chatBusy) { PeekAsk; StartVoice }
542
- }
543
- (E 'MicBtn').Add_Click({
544
- if (-not $script:voiceLive -and (E 'AskBox').Text.Trim()) { SubmitAsk }
545
- elseif (StopMode) { $script:canCancel = $false; (E 'MicBtn').Opacity = 0.5; SyncAction; Send @{ t = 'cancel' } }
546
- else { VoiceToggle }
547
- })
548
- # 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
549
- # the list the daemon wrote into config.json (hotkey.mjs: the owner's own choice first, then the defaults; "hotkey off" = empty lists ->
550
- # none). Shown in the mic button's tooltip / the tray menu; none free -> no hotkey. WM_HOTKEY is filtered in C# (AivinMascot.HotKeys).
551
- function RegisterKeyList($id, $list) {
552
- $keys = @(@($list) | Where-Object { $_ -and $_.n })
553
- if (-not $keys.Count) { return $null }
554
- $mods = [uint32[]]@($keys | ForEach-Object { [uint32]$_.m }); $vks = [uint32[]]@($keys | ForEach-Object { [uint32]$_.v })
555
- $i = [AivinMascot.HotKeys]::RegisterFirst($script:hwnd, $id, $mods, $vks)
556
- if ($i -lt 0) { Dbg ('hotkey ' + $id + ': none free'); return $null }
557
- [string]$keys[$i].n
558
- }
559
- $w.Add_ContentRendered({
560
- if (-not $script:hwnd) { return }
561
- $voiceKey = RegisterKeyList 0xA171 $cfg.hotkeys.voice
562
- if ($voiceKey) { $T.ask_mic = "$($T.ask_mic) ($voiceKey)"; SyncAction }
563
- $chatKey = RegisterKeyList 0xA172 $cfg.hotkeys.chat
564
- # The tray menu shows the same combinations next to its Quick chat / Quick voice items.
565
- Send @{ t = 'hotkeys'; chat = $chatKey; voice = $voiceKey }
566
- if ($voiceKey -or $chatKey) {
567
- [AivinMascot.HotKeys]::Start($script:hwnd, [Action[int]]{ param($id)
568
- if ($id -eq 0xA171) { VoiceToggle }
569
- elseif ($id -eq 0xA172) { OpenAsk; [void](E 'AskBox').Focus() }
570
- })
571
- }
572
- })
573
-
574
- # Route the ask-box commands; everything else goes to the base handler of hostSource.mjs.
575
- $script:baseHandle = (Get-Item function:Handle).ScriptBlock
576
- function Handle($m) {
577
- switch ($m.t) {
578
- 'chat' {
579
- ChatRow $m
580
- if (-not $m.remove -and [string]$m.role -ne 'user' -and $m.text) {
581
- $script:chatLast = ChatShort $m
582
- if ($script:askOpen) { HideAskLater $(if ($m.blocks) { ${ASK_RICH_IDLE_MS} } else { ${ASK_IDLE_MS} }) } else { ChatBubble $script:chatLast }
583
- }
584
- return
585
- }
586
- 'chat_clear' { (E 'ChatList').Children.Clear(); $script:chatRows.Clear(); $script:scrollRow = $null; AskWidth $false; (E 'ChatScroll').Visibility = 'Collapsed'; InputLayout; return }
587
- 'chat_busy' {
588
- $script:chatBusy = [bool]$m.busy; $script:canCancel = [bool]$m.cancel
589
- (E 'MicBtn').Opacity = if ($script:chatBusy -and -not $script:canCancel) { 0.5 } else { 1 }
590
- SyncAction
591
- # Answer arrived: leave it readable a while, then tuck the box away.
592
- if (-not $script:chatBusy -and $script:askOpen) { HideAskLater ${ASK_IDLE_MS} }
593
- # Turn over with the box closed: the answer / error stays in the bubble a while, then the bubble times out.
594
- if (-not $script:chatBusy -and -not $script:askOpen -and (E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
595
- if ($script:chatBusy) { $script:chatLast = '' }
596
- return
597
- }
598
- 'ask_status' { AskStatus $m.text; return }
599
- 'ask_choices' { ChoiceButtons $m.options $m.multiple; return }
600
- # Files waiting for the next question: chips above the input; then on to the bot's tray (no return).
601
- 'ask_files' { $chips = @($m.files | Where-Object { $_ }); $more = @($chips | Where-Object { -not $_.pinned }).Count -gt @((E 'AttachBar').Children | Where-Object { $_.Tag -ne 'pinned' }).Count; $script:files = [int]$m.n; AttachChips $chips; SyncAction; if ($more) { PeekAsk; HideAskLater ${ASK_IDLE_MS} } }
602
- 'ask_pin' {
603
- $script:askPinned = [bool]$m.on
604
- if ($script:askPinned) { $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; PeekAsk; (E 'ChatScroll').ScrollToEnd() }
605
- elseif ($script:askOpen) { HideAskLater $(if ($script:askFocused) { ${ASK_IDLE_MS} } else { 4000 }) }
606
- return
607
- }
608
- 'voice_begin' {
609
- if (-not $script:voiceLive) { Send @{ t = 'voice_stop' }; return }
610
- if ([AivinMascot.Voice]::Begin([int]$m.in_rate, [int]$m.out_rate, $true)) {
611
- Dbg "voice: on, echo cancelled=$([AivinMascot.Voice]::EchoCancelled) $([AivinMascot.Voice]::AecError)"
612
- VoiceState $(if ($m.state) { [string]$m.state } else { 'listening' })
613
- } else { Dbg 'voice: no mic'; Send @{ t = 'voice_stop' }; EndVoice $T.ask_no_mic }
614
- return
615
- }
616
- 'voice_state' {
617
- if (-not $script:voiceLive) { return }
618
- if ($script:voiceLive -eq 'speaking' -and $m.state -ne 'speaking' -and [AivinMascot.Voice]::Playing) { $script:afterSpeak = [string]$m.state }
619
- else { $script:afterSpeak = ''; VoiceState $m.state }
620
- return
621
- }
622
- 'voice_end' { if ($script:voiceLive) { EndVoice $m.text }; return }
623
- # aivin ui: the user just asked for the mascot from a terminal -> show it and open the ask box ready to type.
624
- 'open_ask' { $script:userHidden = $false; ApplyVisibility; if (-not $script:askFocused) { OpenAsk }; return }
625
- 'voice_toggle' { $script:userHidden = $false; ApplyVisibility; VoiceToggle; return }
626
- 'quick_voice' { $script:userHidden = $false; ApplyVisibility; if (-not $script:voiceLive) { PeekAsk; StartVoice }; return }
627
- # Debug only (AIVIN_MASCOT_DEBUG): show the ask box WITHOUT taking keyboard focus, to look at it / screenshot it.
628
- 'ask_preview' { if ($env:AIVIN_MASCOT_DEBUG) { PeekAsk }; return }
629
- # Debug/docs preview of the real file-drag UI, using the same tray, face and hint code as DragEnter without requiring Explorer.
630
- 'drop_preview' {
631
- if ($env:AIVIN_MASCOT_DEBUG) {
632
- $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; CloseAsk
633
- $script:dragFiles = @('bao-cao.xlsx', 'anh-man-hinh.png'); $script:rig.Hover = $true; $script:rig.Tray('open', $script:files); SetFace 'waiting'
634
- DropHint ($T.drop_many.Replace('{n}', '2'))
635
- }
636
- return
637
- }
638
- 'drop_preview_end' { if ($env:AIVIN_MASCOT_DEBUG) { DragEnd }; return }
639
- # Debug only: start talking as if the mic was clicked (end-to-end voice test without clicking / taking focus).
640
- 'voice_preview' { if ($env:AIVIN_MASCOT_DEBUG -and -not $script:voiceLive) { VoiceToggle }; return }
641
- # Debug only: render the ask box (not the screen) to a PNG, to look at the design without screenshots.
642
- 'snap' {
643
- if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
644
- $el = E 'Ask'; $el.UpdateLayout(); $dpi = 2
645
- $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)
646
- $vis = New-Object Windows.Media.DrawingVisual; $dc = $vis.RenderOpen()
647
- $dc.DrawRectangle((Brush '#F3F4F6'), $null, (New-Object Windows.Rect 0, 0, ($el.ActualWidth + 12), ($el.ActualHeight + 12)))
648
- # 1:1, no stretching (the drop shadow makes the visual's bounds bigger than the box).
649
- $vb = New-Object Windows.Media.VisualBrush $el; $vb.Stretch = 'None'; $vb.AlignmentX = 'Left'; $vb.AlignmentY = 'Top'
650
- $vb.ViewboxUnits = 'Absolute'; $vb.Viewbox = New-Object Windows.Rect 0, 0, $el.ActualWidth, $el.ActualHeight
651
- $dc.DrawRectangle($vb, $null, (New-Object Windows.Rect 6, 6, $el.ActualWidth, $el.ActualHeight)); $dc.Close()
652
- $bmp.Render($vis); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
653
- $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
654
- }
655
- # Debug/docs only: render the complete live WPF visual tree (bot + every visible box), not the static seed artwork.
656
- 'snap_full' {
657
- if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
658
- $el = E 'Root'; $el.UpdateLayout(); $dpi = 2
659
- $bmp = New-Object Windows.Media.Imaging.RenderTargetBitmap ([int]($el.ActualWidth * $dpi)), ([int]($el.ActualHeight * $dpi)), (96 * $dpi), (96 * $dpi), ([Windows.Media.PixelFormats]::Pbgra32)
660
- $bmp.Render($el); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
661
- $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
662
- }
663
- }
664
- & $script:baseHandle $m
665
- }
666
- # ---- end ask box ----
667
- `;
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
+ /**
33
+ * Aivin dang cho tra loi (HIL) ma khong ai dong vao: o hoi tu cat di sau chung nay. Truoc 14/11/2026 cau hoi ghim o hoi mo MAI
34
+ * (user: "linh vat hoi mot luc tam 5s ko thay phan hoi thi tu dong box chu") - cau hoi van con, huy hieu tren bot va re vao bot la mo lai.
35
+ */
36
+ export const ASK_PINNED_IDLE_MS = 5000;
37
+ /** Câu trả lời có bảng / thẻ / ảnh: cần thời gian đọc hơn một câu chữ. */
38
+ const ASK_RICH_IDLE_MS = 30000;
39
+
40
+ /**
41
+ * 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
42
+ * viền, chữ xám đậm; rê chuột thì thẻ đậm lên nhẹ.
43
+ */
44
+ const CHOICE_CARDS = Object.freeze(['#FDF2F8', '#F5F3FF', '#EFF6FF', '#ECFDF5']);
45
+ const CHOICE_INK = '#3B4256';
46
+ const CHOICE_HOVER = '#0F1E1B4B';
47
+ /** Viền chấm tròn / ô vuông đầu mỗi lựa chọn (chưa tích). */
48
+ const CHOICE_MARK = '#9AA1B2';
49
+ /**
50
+ * Bề rộng nội dung nút lựa chọn / nút link. Trong ô hỏi (240) nút rộng 213, còn 207 khi thanh cuộn hiện; trừ lề trong 10 + 10 còn 187. Rộng hơn
51
+ * thì mép phải bị cắt — đúng chỗ icon (05/11/2026: 192 làm mất nửa icon khi hội thoại đủ dài để cuộn).
52
+ */
53
+ export const CHOICE_ROW_WIDTH = 186;
54
+ /** 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). */
55
+ const LINK_ICON_PATH = lucidePath('external-link');
56
+ /** Nút x trên chip tệp đính kèm. */
57
+ const DETACH_ICON_PATH = lucidePath('x');
58
+
59
+ export const ASK_PS1 = String.raw`
60
+ # ---- Ask box (askHostSource.mjs) ----
61
+ Add-Type -TypeDefinition @'
62
+ using System; using System.Runtime.InteropServices;
63
+ namespace AivinMascotAsk {
64
+ public static class Native {
65
+ [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);
66
+ [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr h);
67
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
68
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, IntPtr pid);
69
+ [DllImport("user32.dll")] static extern bool AttachThreadInput(uint a, uint b, bool attach);
70
+ [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
71
+ [DllImport("user32.dll")] static extern short GetAsyncKeyState(int vKey);
72
+ public static bool ClickOutside() { return (GetAsyncKeyState(1) & 0x8000) != 0; }
73
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr h, System.Text.StringBuilder s, int n);
74
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, System.Text.StringBuilder s, int n);
75
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
76
+ /** The window the person is using (not the bot, the taskbar or the desktop): { "0x..", title, pid }, or null. */
77
+ public static string[] UserWindow() {
78
+ IntPtr h = GetForegroundWindow(); if (h == IntPtr.Zero) return null;
79
+ uint pid; GetWindowThreadProcessId(h, out pid);
80
+ if (pid == (uint)System.Diagnostics.Process.GetCurrentProcess().Id) return null;
81
+ var c = new System.Text.StringBuilder(256); GetClassName(h, c, 256);
82
+ string cls = c.ToString(); if (cls == "Shell_TrayWnd" || cls == "Progman" || cls == "WorkerW") return null;
83
+ var t = new System.Text.StringBuilder(512); GetWindowText(h, t, 512);
84
+ return new string[] { "0x" + h.ToInt64().ToString("x"), t.ToString(), pid.ToString() };
85
+ }
86
+ /** The user just clicked the bot: take keyboard focus (Windows refuses SetForegroundWindow from a background window otherwise). */
87
+ public static bool TakeFocus(IntPtr h) {
88
+ uint fg = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero), me = GetCurrentThreadId();
89
+ bool attached = fg != 0 && fg != me && AttachThreadInput(fg, me, true);
90
+ try { BringWindowToTop(h); return SetForegroundWindow(h); }
91
+ finally { if (attached) AttachThreadInput(fg, me, false); }
92
+ }
93
+ [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h);
94
+ /** The box closed by itself while holding the keyboard: back to the window the person came from (only if we still hold it). */
95
+ public static bool GiveFocusBack(IntPtr me, string target) {
96
+ if (GetForegroundWindow() != me) return false;
97
+ IntPtr h = new IntPtr(Convert.ToInt64(target, 16));
98
+ return IsWindow(h) && SetForegroundWindow(h);
99
+ }
100
+ }
101
+ }
102
+ '@
103
+ (E 'AskHint').Text = $T.ask_hint; (E 'MicBtn').ToolTip = $T.ask_mic
104
+ (E 'AttachBtn').ToolTip = $T.ask_attach; (E 'AskClose').ToolTip = $T.ask_close
105
+ # Dau x goc phai tren: mo han, dam len khi re chuot; bam = cat o hoi di ngay (ke ca khi dang co cau hoi cho).
106
+ (E 'AskClose').Add_MouseEnter({ (E 'AskClose').Opacity = 0.85 })
107
+ (E 'AskClose').Add_MouseLeave({ (E 'AskClose').Opacity = 0.3 })
108
+ (E 'AskClose').Add_Click({ $script:askHideTimer.Stop(); CloseAsk })
109
+ (E 'AttachBtn').Add_Click({ PickFiles })
110
+ # Hop chon tep cua he dieu hanh ngay trong o hoi (14/11/2026): cung duong voi keo tha tep vao bot - daemon nhan 'drop' roi tra ve chip.
111
+ $script:picking = $false
112
+ function PickFiles {
113
+ if ($script:picking) { return }
114
+ if (TrayFull) { PeekAsk; DropHint ($T.drop_full.Replace('{n}', [string]$cfg.max_files)); return }
115
+ $script:picking = $true
116
+ try {
117
+ OpenAsk
118
+ $dlg = New-Object Microsoft.Win32.OpenFileDialog
119
+ $dlg.Multiselect = $true
120
+ $dlg.Title = $T.ask_pick_title
121
+ if ($dlg.ShowDialog($w) -ne $true) { return }
122
+ $picked = @(@($dlg.FileNames) | Where-Object { $_ })
123
+ if (-not $picked.Count) { return }
124
+ Send @{ t = 'drop'; files = $picked }
125
+ # Dem tam cho toi khi daemon xac nhan (ask_files: trung / qua gioi han bi bo) - giong het duong keo tha.
126
+ $script:files = [Math]::Min($script:files + $picked.Count, [int]$cfg.max_files)
127
+ $script:rig.Tray('hold', $script:files); PlayFace 'gulp' 'hello' 1.4; SyncAction
128
+ } catch { Dbg "pick files failed: $_" }
129
+ finally { $script:picking = $false; if ($script:askOpen) { HideAskLater ${ASK_IDLE_MS} } }
130
+ }
131
+ # "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.
132
+ (E 'NewChatText').Text = $T.new_chat; (E 'NewChatBtn').ToolTip = $T.new_chat_tip
133
+ (E 'NewChatBtn').Add_Click({ Send @{ t = 'new_chat' }; OpenAsk })
134
+
135
+ function AskShow($name) {
136
+ $script:bubbleTimer.Stop(); (E 'Bubble').Visibility = 'Collapsed'; (E 'Bubble').Opacity = 0
137
+ $el = E $name; $el.Visibility = 'Visible'; $w.FindResource('PanelIn').Begin($el)
138
+ }
139
+ function AskHide($name) {
140
+ $el = E $name; if ($el.Visibility -ne 'Visible') { return }
141
+ # The ask box may be shown again while it is still fading out: then the finished fade must not collapse it.
142
+ $sb = $w.FindResource('PanelOut').Clone(); $sb.Add_Completed({ if ($name -ne 'Ask' -or -not $script:askOpen) { (E $name).Visibility = 'Collapsed' } }.GetNewClosure()); $sb.Begin($el)
143
+ }
144
+ function SetActivatable($on) {
145
+ if (-not $script:hwnd) { return }
146
+ $ex = [AivinMascot.Native]::GetWindowLong($script:hwnd, -20)
147
+ $ex = if ($on) { $ex -band (-bnot 0x08000000) } else { $ex -bor 0x08000000 }
148
+ [void][AivinMascot.Native]::SetWindowLong($script:hwnd, -20, $ex)
149
+ }
150
+ function AskStatus($text) {
151
+ $el = E 'AskStatus'; SetText $el $text; $el.Visibility = if ($text) { 'Visible' } else { 'Collapsed' }
152
+ }
153
+ $script:askOpen = $false; $script:askFocused = $false
154
+ # The window the person was on right before reaching for the bot: sent with each question / talk so "this" means that window.
155
+ $script:askTarget = $null
156
+ function NoteTarget {
157
+ $i = $null; try { $i = [AivinMascotAsk.Native]::UserWindow() } catch { }
158
+ if (-not $i) { return }
159
+ $p = ''; try { $p = (Get-Process -Id ([int]$i[2]) -ErrorAction Stop).ProcessName } catch { }
160
+ $script:askTarget = @{ window = $i[0]; title = $i[1]; process = $p }
161
+ }
162
+ function PeekAsk {
163
+ NoteTarget
164
+ if ($script:askOpen) { return }
165
+ $script:askOpen = $true; AskShow 'Ask'; $w.FindResource('AskGlow').Begin($w, $true)
166
+ }
167
+ function OpenAsk {
168
+ NoteTarget; AskHide 'Panel'
169
+ $script:askOpen = $true; AskShow 'Ask'; $w.FindResource('AskGlow').Begin($w, $true)
170
+ $script:askFocused = $true; SetActivatable $true; $ok = [AivinMascotAsk.Native]::TakeFocus($script:hwnd); [void]$w.Activate(); Dbg "ask focus=$ok"
171
+ [void](E 'AskBox').Focus(); [void][Windows.Input.Keyboard]::Focus((E 'AskBox'))
172
+ HideAskLater ${ASK_IDLE_MS}
173
+ }
174
+ function CloseAsk {
175
+ $script:askHideTimer.Stop()
176
+ if (-not $script:askOpen) { return }
177
+ if ($script:voiceLive) { StopVoice }
178
+ $script:askOpen = $false; $script:askFocused = $false
179
+ AskHide 'Ask'; SetActivatable $false; $w.FindResource('AskGlow').Stop($w)
180
+ }
181
+ function MascotClick { if ($script:askFocused) { CloseAsk } else { OpenAsk } }
182
+ # One box at a time: while the ask box is open, what the bot does on the machine only updates the text; the bubble
183
+ # (notification) comes back with the latest step once the box closes, if the bot is still busy.
184
+ $script:baseShowBubble = (Get-Item function:ShowBubble).ScriptBlock
185
+ function ShowBubble($text) { if ($script:askOpen) { SetText (E 'NowText') $text; return }; & $script:baseShowBubble $text }
186
+ $script:baseCloseAsk = (Get-Item function:CloseAsk).ScriptBlock
187
+ function CloseAsk {
188
+ $was = $script:askOpen; & $script:baseCloseAsk
189
+ if (-not $was -or (E 'Panel').Visibility -eq 'Visible') { return }
190
+ if ($script:chatBusy -and $script:chatLast) { ChatBubble $script:chatLast }
191
+ elseif ((IsBusy) -or $script:state -eq 'waiting') { & $script:baseShowBubble ([AivinMascot.Emoji]::Text((E 'NowText'))) }
192
+ if ((E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
193
+ }
194
+ # 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
195
+ # written (its tail), the answer / error. Stays up while the turn runs; once it ends the bubble times out as usual.
196
+ $script:chatLast = ''
197
+ function ChatShort($m) {
198
+ $text = ([string]$m.text -replace '\s+', ' ').Trim()
199
+ if ($m.partial -and $text.Length -gt 90) { $text = "$([char]0x2026)" + $text.Substring($text.Length - 89) }
200
+ $text
201
+ }
202
+ function ChatBubble($text) {
203
+ if (-not $text -or (E 'Panel').Visibility -eq 'Visible') { return }
204
+ & $script:baseShowBubble $text
205
+ $script:bubbleTimer.Stop(); $script:bubbleTimer.Start()
206
+ }
207
+ # 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
208
+ # 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.
209
+ $script:askHideTimer = New-Object Windows.Threading.DispatcherTimer
210
+ $script:askHideTimer.Add_Tick({
211
+ if ($script:askOpen -and (AskInUse)) { HideAskLater ${ASK_IDLE_MS}; return }
212
+ $held = $script:askFocused; CloseAsk
213
+ if ($held -and $script:askTarget) { try { [void][AivinMascotAsk.Native]::GiveFocusBack($script:hwnd, [string]$script:askTarget.window) } catch { } }
214
+ })
215
+ # In use = keep the box out: the mouse over THE BOX or THE BOT, talking, dragging, picking a file, or holding the keyboard with unsent
216
+ # text / files or a running turn. 14/11/2026: this used to be the whole window, which is a large transparent rectangle - a cursor
217
+ # merely resting anywhere near the bot kept the box out for ever (seen in the live run of the 5 s auto-fold).
218
+ # A pending question no longer counts (14/11/2026): the box slips away after ASK_PINNED_IDLE_MS and the question waits on the bot's badge.
219
+ function AskInUse {
220
+ (E 'Ask').IsMouseOver -or (E 'Mascot').IsMouseOver -or $script:voiceLive -or $script:drag -or $script:picking -or ($script:askFocused -and ($script:chatBusy -or $script:files -or (E 'AskBox').Text.Trim()))
221
+ }
222
+ # Aivin is waiting for an answer (HIL): the box stays out with the question + option buttons until it is answered (no focus taken).
223
+ $script:askPinned = $false
224
+ function HideAskLater($ms) { $script:askHideTimer.Stop(); $script:askHideTimer.Interval = [TimeSpan]::FromMilliseconds($ms); $script:askHideTimer.Start() }
225
+ (E 'Mascot').ToolTip = $null
226
+ (E 'Mascot').Add_MouseEnter({ $script:askHideTimer.Stop(); if ((E 'Panel').Visibility -ne 'Visible' -and -not $script:drag) { PeekAsk } })
227
+ (E 'Ask').Add_MouseEnter({ $script:askHideTimer.Stop() })
228
+ # Only peeking: gone right after the mouse leaves. Holding the keyboard: the person may be about to type, so the full wait.
229
+ $w.Add_MouseLeave({ if ($script:askOpen) { HideAskLater $(if ($script:askFocused) { ${ASK_IDLE_MS} } else { 600 }) } })
230
+ # Clicked somewhere else: release keyboard focus and close the box.
231
+ $w.Add_Deactivated({
232
+ $script:askFocused = $false; SetActivatable $false
233
+ if ($script:askOpen -and -not $script:voiceLive -and -not $script:drag -and -not $script:picking) { CloseAsk }
234
+ if ((E 'Panel').Visibility -eq 'Visible') { ClosePanel }
235
+ })
236
+ # Click outside detection: transparent window region or anywhere on other windows
237
+ $w.Add_PreviewMouseLeftButtonDown({ param($s, $e)
238
+ if (-not $script:askOpen -or $script:drag) { return }
239
+ $pt = $e.GetPosition($w)
240
+ $askBox = E 'Ask'; $mascot = E 'Mascot'; $panel = E 'Panel'
241
+ $inAsk = $askBox.Visibility -eq 'Visible' -and (New-Object Windows.Rect ($askBox.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $askBox.RenderSize).Contains($pt)
242
+ $inMascot = (New-Object Windows.Rect ($mascot.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $mascot.RenderSize).Contains($pt)
243
+ $inPanel = $panel.Visibility -eq 'Visible' -and (New-Object Windows.Rect ($panel.TranslatePoint((New-Object Windows.Point 0, 0), $w)), $panel.RenderSize).Contains($pt)
244
+ if (-not $inAsk -and -not $inMascot -and -not $inPanel -and -not $script:picking) {
245
+ CloseAsk
246
+ }
247
+ if (-not $inPanel -and (E 'Panel').Visibility -eq 'Visible' -and -not $inMascot) {
248
+ ClosePanel
249
+ }
250
+ })
251
+ $script:clickCheckTimer = New-Object Windows.Threading.DispatcherTimer
252
+ $script:clickCheckTimer.Interval = [TimeSpan]::FromMilliseconds(50)
253
+ $script:clickCheckTimer.Add_Tick({
254
+ if ($script:askOpen -and -not $script:voiceLive -and -not $script:drag -and -not $script:picking) {
255
+ if (-not $w.IsMouseOver -and [AivinMascotAsk.Native]::ClickOutside()) {
256
+ CloseAsk
257
+ }
258
+ }
259
+ if ((E 'Panel').Visibility -eq 'Visible' -and -not $script:drag) {
260
+ if (-not $w.IsMouseOver -and [AivinMascotAsk.Native]::ClickOutside()) {
261
+ ClosePanel
262
+ }
263
+ }
264
+ })
265
+ $script:clickCheckTimer.Start()
266
+ # Clicking into the peeking box = about to type: take keyboard focus.
267
+ (E 'Ask').Add_PreviewMouseLeftButtonDown({ if (-not $script:askFocused) { OpenAsk } })
268
+ # Right-click on the bot: the activity panel.
269
+ (E 'Mascot').Add_MouseRightButtonUp({ param($s, $e) CloseAsk; OpenPanel; $e.Handled = $true })
270
+ # One button: empty box = mic, typed text = send.
271
+ # Waiting on a turn the server can stop (chat_busy { cancel }): the empty-box button is a stop button instead of the mic.
272
+ function StopMode { $script:chatBusy -and $script:canCancel -and -not $script:voiceLive -and -not (E 'AskBox').Text.Trim() -and -not $script:files }
273
+ function SyncAction {
274
+ # Files waiting (chips above the input): the button sends even with nothing typed, and the hint asks what to do with them.
275
+ $typed = [bool](E 'AskBox').Text.Trim() -or ($script:files -gt 0 -and -not $script:voiceLive)
276
+ $stop = StopMode
277
+ (E 'AskHint').Text = if ($script:files -gt 0) { $T.ask_attached } else { $T.ask_hint }
278
+ (E 'AskHint').Visibility = if ((E 'AskBox').Text) { 'Collapsed' } else { 'Visible' }
279
+ (E 'SendIcon').Visibility = if ($typed) { 'Visible' } else { 'Collapsed' }; (E 'MicIcon').Visibility = if ($typed -or $stop) { 'Collapsed' } else { 'Visible' }
280
+ (E 'StopIcon').Visibility = if ($stop) { 'Visible' } else { 'Collapsed' }
281
+ (E 'MicBtn').ToolTip = if ($typed) { $T.ask_send } elseif ($stop) { $T.ask_stop } else { $T.ask_mic }
282
+ InputLayout
283
+ }
284
+ # 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
285
+ # button centred on the same line - the box only grows (mic back at the bottom) when the typed text wraps.
286
+ function InputLayout {
287
+ $box = E 'AskBox'
288
+ # Box hidden = the voice bar is in its place (VoiceLook hides it before the voice state is set).
289
+ $compact = $box.Visibility -ne 'Visible' -or [bool]$script:voiceLive -or (E 'ChatList').Children.Count -gt 0
290
+ $wrapped = $box.Visibility -eq 'Visible' -and $box.LineCount -gt 1
291
+ $box.Parent.MinHeight = if ($compact) { 26 } else { 40 }
292
+ $mid = if ($compact -and -not $wrapped) { 'Center' } else { 'Top' }
293
+ $box.VerticalAlignment = $mid; (E 'AskHint').VerticalAlignment = $mid
294
+ (E 'MicBtn').VerticalAlignment = if ($compact -and -not $wrapped) { 'Center' } else { 'Bottom' }
295
+ }
296
+ (E 'AskBox').Add_TextChanged({ SyncAction; AttendAsk; if ($script:askOpen) { HideAskLater ${ASK_IDLE_MS} } })
297
+ # Typing: the bot looks at the box (above or below it) while keys come in; a little nod when a question / answer goes out.
298
+ function AttendAsk {
299
+ if (-not (E 'AskBox').Text) { return }
300
+ $a = E 'Ask'; $p = $a.TranslatePoint((New-Object Windows.Point ($a.ActualWidth / 2), ($a.ActualHeight / 2)), (E 'Mascot'))
301
+ $script:rig.Attend($p.X - ${MASCOT_CENTER.x}, $p.Y - ${MASCOT_CENTER.y})
302
+ }
303
+
304
+ $script:chatBusy = $false
305
+ $script:canCancel = $false
306
+ function SubmitAsk {
307
+ $text = (E 'AskBox').Text.Trim(); if ((-not $text -and -not $script:files) -or $script:chatBusy -or $script:voiceLive) { return }
308
+ NoteTarget; (E 'AskBox').Text = ''; $script:rig.Play('ack'); Send @{ t = 'ask'; text = $text; window = $script:askTarget }
309
+ }
310
+ (E 'AskBox').Add_KeyDown({ param($s, $e)
311
+ if ($e.Key -eq 'Return') { SubmitAsk; $e.Handled = $true }
312
+ elseif ($e.Key -eq 'Escape') { CloseAsk; $e.Handled = $true }
313
+ })
314
+
315
+ # Conversation rows: user (right, light brand), assistant (left, grey), one live progress line, errors. Bubbles point at their speaker
316
+ # (the corner on the speaker's side is nearly square, 3 px) and new ones fade + rise in.
317
+ $script:chatRows = @{}
318
+ # "Working on it": three dots bouncing in turn inside an assistant bubble (a staggered key-frame hop, then a rest).
319
+ function TypingDots {
320
+ $sp = New-Object Windows.Controls.StackPanel; $sp.Orientation = 'Horizontal'; $sp.Margin = '1,5,1,5'
321
+ for ($i = 0; $i -lt 3; $i++) {
322
+ $e = New-Object Windows.Shapes.Ellipse; $e.Width = 6; $e.Height = 6; $e.Margin = '2,0,2,0'; $e.Fill = Brush '#9AA0AB'
323
+ $tt = New-Object Windows.Media.TranslateTransform; $e.RenderTransform = $tt
324
+ $a = New-Object Windows.Media.Animation.DoubleAnimationUsingKeyFrames
325
+ $a.Duration = [TimeSpan]::FromMilliseconds(1200); $a.BeginTime = [TimeSpan]::FromMilliseconds(160 * $i)
326
+ $a.RepeatBehavior = [Windows.Media.Animation.RepeatBehavior]::Forever
327
+ foreach ($k in @(@(0, 0), @(280, -4.5), @(560, 0), @(1200, 0))) {
328
+ $f = New-Object Windows.Media.Animation.EasingDoubleKeyFrame ([double]$k[1]), ([Windows.Media.Animation.KeyTime]::FromTimeSpan([TimeSpan]::FromMilliseconds($k[0])))
329
+ $f.EasingFunction = New-Object Windows.Media.Animation.SineEase; [void]$a.KeyFrames.Add($f)
330
+ }
331
+ $tt.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $a)
332
+ [void]$sp.Children.Add($e)
333
+ }
334
+ $sp
335
+ }
336
+ # 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.
337
+ function LinkCard($text, $url, $iconPath = '${LINK_ICON_PATH}') {
338
+ $dock = New-Object Windows.Controls.DockPanel; $dock.MaxWidth = ${CHOICE_ROW_WIDTH}
339
+ $icon = LucideIcon $(if ($iconPath) { $iconPath } else { '${LINK_ICON_PATH}' }) 13 '${ICON_INKS[2]}'; $icon.Margin = '8,2,0,0'; $icon.VerticalAlignment = 'Top'; [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$dock.Children.Add($icon)
340
+ $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; SetText $tb $text; [void]$dock.Children.Add($tb)
341
+ $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; $btn.ToolTip = [string]$url
342
+ $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,3'; $btn.HorizontalAlignment = 'Left'
343
+ $btn.Background = Brush '${CHOICE_CARDS[2]}'; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
344
+ $btn.Add_Click({ param($s) OpenWebUrl $s.CommandParameter })
345
+ $btn
346
+ }
347
+ function ChatLinks($row, $links) {
348
+ $list = E 'ChatList'
349
+ if ($row.links) { [void]$list.Children.Remove($row.links); $row.links = $null }
350
+ $items = @(@($links) | Where-Object { $_ -and $_.url })
351
+ if (-not $items.Count) { return }
352
+ $sp = New-Object Windows.Controls.StackPanel; $sp.Margin = '0,0,0,4'; $sp.HorizontalAlignment = 'Left'
353
+ foreach ($l in $items) { [void]$sp.Children.Add((LinkCard $l.text $l.url $l.icon_path)) }
354
+ $after = if ($row.blocks) { $row.blocks } else { $row.box }
355
+ $list.Children.Insert($list.Children.IndexOf($after) + 1, $sp); $row.links = $sp
356
+ }
357
+ ${ASK_BLOCKS_PS1}
358
+ function ChatRow($m) {
359
+ $list = E 'ChatList'; $id = [string]$m.id
360
+ $row = $null; if ($id) { $row = $script:chatRows[$id] }
361
+ if ($m.remove) { if ($row) { ChatLinks $row $null; ChatBlocks $row $null; [void]$list.Children.Remove($row.box); $script:chatRows.Remove($id) }; return }
362
+ (E 'ChatScroll').Visibility = 'Visible'
363
+ if (-not $row) {
364
+ # Segoe UI adds its own space above / below the letters: block line height + slim vertical padding so the space you see is about
365
+ # the same on all four sides.
366
+ $b = New-Object Windows.Controls.Border; $b.Padding = '10,5,10,5'; $b.Margin = '0,0,0,4'; $b.MaxWidth = $script:bubbleMax
367
+ $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.FontSize = 14; $tb.LineHeight = 20; $tb.LineStackingStrategy = 'BlockLineHeight'
368
+ $b.Child = $tb; [void]$list.Children.Add($b)
369
+ $slide = New-Object Windows.Media.TranslateTransform 0, 6; $b.RenderTransform = $slide
370
+ $ease = New-Object Windows.Media.Animation.CubicEase; $ease.EasingMode = 'EaseOut'
371
+ $fade = New-Object Windows.Media.Animation.DoubleAnimation 0, 1, ([TimeSpan]::FromMilliseconds(200)); $fade.EasingFunction = $ease
372
+ $rise = New-Object Windows.Media.Animation.DoubleAnimation 6, 0, ([TimeSpan]::FromMilliseconds(240)); $rise.EasingFunction = $ease
373
+ $b.BeginAnimation([Windows.UIElement]::OpacityProperty, $fade); $slide.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $rise)
374
+ $row = @{ box = $b; text = $tb; url = $null }
375
+ # The link rides on the bubble itself (Tag, updated below): the handler is not a closure, $row at click time is not this row.
376
+ $b.Add_MouseLeftButtonUp({ param($s) OpenWebUrl $s.Tag })
377
+ if ($id) { $script:chatRows[$id] = $row }
378
+ while ($list.Children.Count -gt 40) { $list.Children.RemoveAt(0) }
379
+ }
380
+ if ($m.url) {
381
+ $row.url = [string]$m.url; $row.box.Tag = [string]$m.url
382
+ $row.box.Cursor = [Windows.Input.Cursors]::Hand
383
+ $row.box.ToolTip = [string]$m.url
384
+ } else {
385
+ $row.url = $null; $row.box.Tag = $null
386
+ $row.box.Cursor = [Windows.Input.Cursors]::Arrow
387
+ $row.box.ToolTip = $null
388
+ }
389
+ $role = [string]$m.role
390
+ $row.box.HorizontalAlignment = if ($role -eq 'user') { 'Right' } else { 'Left' }
391
+ # CornerRadius = top-left, top-right, bottom-right, bottom-left.
392
+ $row.box.CornerRadius = if ($role -eq 'user') { '10,10,3,10' } elseif ($role -eq 'progress') { '0' } else { '10,10,10,3' }
393
+ $bg = if ($role -eq 'user') { '#E8F3FF' } elseif ($role -eq 'error') { '#FFECE8' } elseif ($role -eq 'progress') { '#00FFFFFF' } else { '#F4F6FA' }
394
+ $fg = if ($role -eq 'progress') { $P.muted } elseif ($role -eq 'error') { '#CB2634' } else { $P.ink }
395
+ $row.box.Background = Brush $bg; $row.text.Foreground = Brush $fg
396
+ $row.text.FontStyle = if ($role -eq 'progress') { 'Italic' } else { 'Normal' }
397
+ SetText $row.text $m.text
398
+ ChatLinks $row $null
399
+ ChatBlocks $row $m.blocks
400
+ ChatLinks $row $m.links
401
+ # The bubble on the bot's head cannot show a table: the owner just asked, so open the box (without taking the keyboard).
402
+ if ($m.peek -and -not $script:askOpen -and (E 'Panel').Visibility -ne 'Visible') { PeekAsk }
403
+ if ($m.typing) {
404
+ if (-not $row.dots) { $row.dots = TypingDots }
405
+ $row.box.Child = $row.dots; $row.box.Background = Brush '#F4F6FA'; $row.box.CornerRadius = '10,10,10,3'
406
+ } elseif ($row.dots -and $row.box.Child -ne $row.text) { $row.box.Child = $row.text }
407
+ # Words the owner is still saying: lighter until the sentence is settled (the box's own opacity is the fade-in).
408
+ $row.text.Opacity = if ($m.partial) { 0.55 } else { 1 }
409
+ $script:scrollRow = if ($row.blocks) { $row } else { $null }
410
+ if ($script:scrollRow) { ScrollToRow $row } else { (E 'ChatScroll').ScrollToEnd() }
411
+ InputLayout
412
+ }
413
+
414
+ # Aivin asked something with choices: a vertical list, one full-width card per option (the daemon clears them once answered). Typing
415
+ # 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 /
416
+ # unticks, a confirm button sends the ticked ones), the text, the option's icon at the end when it has one we can draw.
417
+ # Soft look: each card filled with a light pastel (cycling the ask box's glow colors), no border, dark-grey text; hover deepens it.
418
+ # 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.
419
+ # Top margin 2 centres it on the first line of text (17 high), so it stays level with the tick mark.
420
+ function ChoiceIcon($o, $ink) {
421
+ if ($o.icon_path) { $i = LucideIcon $o.icon_path 14 $ink; $i.Margin = '8,2,0,0'; $i.VerticalAlignment = 'Top'; return $i }
422
+ if (-not $o.icon) { return $null }
423
+ $tb = New-Object Windows.Controls.TextBlock; $tb.FontSize = 13; $tb.Margin = '8,1,0,0'; $tb.VerticalAlignment = 'Top'; SetText $tb $o.icon; $tb
424
+ }
425
+ function ChoiceMark($multi) {
426
+ $m = New-Object Windows.Controls.Border; $m.Width = 13; $m.Height = 13; $m.Margin = '0,2,8,0'; $m.VerticalAlignment = 'Top'
427
+ $m.CornerRadius = if ($multi) { '3.5' } else { '6.5' }; $m.BorderThickness = '1.4'
428
+ $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'
429
+ $tick.StrokeThickness = 1.7; $tick.StrokeStartLineCap = 'Round'; $tick.StrokeEndLineCap = 'Round'; $tick.StrokeLineJoin = 'Round'
430
+ $m.Child = $tick; SetTicked $m $false; $m
431
+ }
432
+ function SetTicked($mark, $on) {
433
+ $mark.Background = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '#B3FFFFFF' }
434
+ $mark.BorderBrush = if ($on) { Brush '${ASK_BTN.icon}' } else { Brush '${CHOICE_MARK}' }
435
+ $mark.Child.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
436
+ }
437
+ $script:picked = New-Object Collections.ArrayList; $script:choiceMarks = @{}; $script:choiceConfirm = $null
438
+ function SyncConfirm {
439
+ $b = $script:choiceConfirm; if (-not $b) { return }
440
+ $b.Content = $T.ask_confirm -replace '\{n\}', $script:picked.Count
441
+ $b.Visibility = if ($script:picked.Count) { 'Visible' } else { 'Collapsed' }
442
+ }
443
+ function ChoiceButtons($options, $multiple) {
444
+ $panel = E 'Choices'; $panel.Children.Clear(); $k = 0; $multi = [bool]$multiple
445
+ $script:picked.Clear(); $script:choiceMarks = @{}; $script:choiceConfirm = $null
446
+ $cards = @(${CHOICE_CARDS.map((c) => `'${c}'`).join(', ')}); $inks = @(${ICON_INKS.map((c) => `'${c}'`).join(', ')})
447
+ foreach ($o in @($options)) {
448
+ if (-not $o) { continue }
449
+ $c = $cards[$k % $cards.Count]; $k++; $id = [string]$o.id
450
+ $row = New-Object Windows.Controls.DockPanel; $row.Width = ${CHOICE_ROW_WIDTH}
451
+ $mark = ChoiceMark $multi; [Windows.Controls.DockPanel]::SetDock($mark, 'Left'); [void]$row.Children.Add($mark)
452
+ $icon = ChoiceIcon $o $inks[($k - 1) % $inks.Count]; if ($icon) { [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$row.Children.Add($icon) }
453
+ $tb = New-Object Windows.Controls.TextBlock; SetText $tb $o.text; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; [void]$row.Children.Add($tb)
454
+ $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $row; $btn.CommandParameter = $id
455
+ $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,4'; $btn.HorizontalAlignment = 'Stretch'
456
+ $btn.Background = Brush $c; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
457
+ $script:choiceMarks[$id] = $mark
458
+ if ($multi) {
459
+ $btn.Add_Click({ param($s)
460
+ $id = [string]$s.CommandParameter; $on = -not $script:picked.Contains($id)
461
+ if ($on) { [void]$script:picked.Add($id) } else { $script:picked.Remove($id) }
462
+ SetTicked $script:choiceMarks[$id] $on; SyncConfirm
463
+ })
464
+ } else {
465
+ $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 } } })
466
+ }
467
+ [void]$panel.Children.Add($btn)
468
+ }
469
+ if ($multi -and $panel.Children.Count) {
470
+ $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'
471
+ $ok.HorizontalAlignment = 'Right'; $ok.Background = Brush '${ASK_BTN.icon}'; $ok.Foreground = Brush '#FFFFFF'; $ok.BorderThickness = '0'; $ok.Tag = Brush '#1F000000'
472
+ $ok.Add_Click({ if (-not $script:chatBusy -and $script:picked.Count) { $script:rig.Play('ack'); Send @{ t = 'choose'; ids = @($script:picked.ToArray()) } } })
473
+ $script:choiceConfirm = $ok; [void]$panel.Children.Add($ok); SyncConfirm
474
+ }
475
+ $panel.Visibility = if ($panel.Children.Count) { 'Visible' } else { 'Collapsed' }
476
+ if ($panel.Children.Count) { (E 'ChatScroll').Visibility = 'Visible'; (E 'ChatScroll').ScrollToEnd() }
477
+ }
478
+
479
+ # Attached files: one chip each above the input - the file type's icon + colour (fileChips.mjs), its name (full path in the tooltip),
480
+ # an x that drops it (detach -> the daemon answers with the new ask_files).
481
+ function AttachChips($chips) {
482
+ $bar = E 'AttachBar'; $bar.Children.Clear()
483
+ foreach ($c in @($chips)) {
484
+ if (-not $c -or -not $c.path) { continue }
485
+ $ink = [string]$c.ink; if (-not $ink) { $ink = '#64748B' }
486
+ $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
487
+ # The working folder's chip stays after a question goes out and is not a waiting file (ask_files).
488
+ if ($c.pinned) { $chip.Tag = 'pinned' }
489
+ $chip.Background = Brush $(if ($c.bg) { [string]$c.bg } else { '#F8FAFC' })
490
+ # Hairline in the type's colour (ink at ~20 %): keeps the very light chip readable on the white box.
491
+ $chip.BorderThickness = '1'; $chip.BorderBrush = Brush ('#33' + $ink.TrimStart('#'))
492
+ $row = New-Object Windows.Controls.StackPanel; $row.Orientation = 'Horizontal'
493
+ 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) }
494
+ $tb = New-Object Windows.Controls.TextBlock; $tb.Text = [string]$c.name; $tb.FontSize = 12; $tb.Foreground = Brush $ink; $tb.MaxWidth = 140
495
+ $tb.TextTrimming = 'CharacterEllipsis'; $tb.VerticalAlignment = 'Center'; [void]$row.Children.Add($tb)
496
+ $x = New-Object Windows.Controls.Button; $x.Style = $w.FindResource('IconBtn'); $x.Width = 18; $x.Height = 18; $x.Margin = '3,0,0,0'
497
+ $x.Background = Brush '#00000000'; $x.BorderThickness = '0'; $x.Tag = Brush '#1F000000'; $x.ToolTip = $(if ($c.detach_tip) { [string]$c.detach_tip } else { $T.ask_detach })
498
+ $x.Content = LucideIcon '${DETACH_ICON_PATH}' 10 $ink; $x.CommandParameter = [string]$c.path
499
+ $x.Add_Click({ param($s) Send @{ t = 'detach'; path = [string]$s.CommandParameter } })
500
+ [void]$row.Children.Add($x); $chip.Child = $row; [void]$bar.Children.Add($chip)
501
+ }
502
+ $bar.Visibility = if ($bar.Children.Count) { 'Visible' } else { 'Collapsed' }
503
+ }
504
+
505
+ # Voice: a live conversation with Aivin (voiceSource.mjs streams the mic / speaker). '' = off, else connecting | listening | thinking | speaking,
506
+ # or recording (older Aivin server without live voice: talk, click the mic to send, it goes through voice-to-text).
507
+ $script:voiceLive = ''
508
+ # 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
509
+ # talks, a soft wave while it thinks) + a short state. The mic button turns red (its tooltip says what a click does now).
510
+ $inputCell = (E 'AskBox').Parent
511
+ $voiceBar = New-Object Windows.Controls.StackPanel; $voiceBar.Orientation = 'Horizontal'; $voiceBar.VerticalAlignment = 'Center'; $voiceBar.Visibility = 'Collapsed'
512
+ $voiceBar.Margin = '2,0,0,0'
513
+ $script:levelBars = @()
514
+ foreach ($i in 0..4) {
515
+ $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'
516
+ $r.VerticalAlignment = 'Center'; $r.Fill = Brush '#8B7CF6'; [void]$voiceBar.Children.Add($r); $script:levelBars += $r
517
+ }
518
+ $voiceLabel = New-Object Windows.Controls.TextBlock; $voiceLabel.FontSize = 14; $voiceLabel.Foreground = Brush $P.ink; $voiceLabel.Margin = '7,0,0,1'
519
+ $voiceLabel.VerticalAlignment = 'Center'; $voiceLabel.TextTrimming = 'CharacterEllipsis'; [void]$voiceBar.Children.Add($voiceLabel)
520
+ [void]$inputCell.Children.Add($voiceBar)
521
+ $script:levelShape = @(0.55, 0.85, 1, 0.85, 0.55); $script:levelNow = @(0, 0, 0, 0, 0)
522
+ $script:levelTimer = New-Object Windows.Threading.DispatcherTimer; $script:levelTimer.Interval = [TimeSpan]::FromMilliseconds(50)
523
+ $script:levelTimer.Add_Tick({
524
+ $t = [Environment]::TickCount / 1000.0
525
+ $level = switch ($script:voiceLive) {
526
+ 'listening' { [AivinMascot.Voice]::MicLevel }
527
+ 'recording' { [AivinMascot.Voice]::MicLevel }
528
+ 'speaking' { [AivinMascot.Voice]::OutLevel }
529
+ default { -1 }
530
+ }
531
+ for ($i = 0; $i -lt 5; $i++) {
532
+ # No live level (connecting / thinking): a slow travelling wave, so it reads as "working on it".
533
+ $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))) }
534
+ $script:levelNow[$i] = $script:levelNow[$i] + ($target - $script:levelNow[$i]) * $(if ($target -gt $script:levelNow[$i]) { 0.6 } else { 0.25 })
535
+ $script:levelBars[$i].Height = 4 + 16 * $script:levelNow[$i]
536
+ }
537
+ })
538
+ function VoiceLook($on) {
539
+ (E 'MicBtn').Background = Brush $(if ($on) { '${ASK_BTN.recBg}' } else { '${ASK_BTN.bg}' })
540
+ (E 'MicIcon').Stroke = Brush $(if ($on) { '${ASK_BTN.recIcon}' } else { '${ASK_BTN.icon}' })
541
+ # The voice bar only needs the button's height (InputLayout, via SyncAction / below).
542
+ (E 'AskBox').Visibility = if ($on) { 'Collapsed' } else { 'Visible' }
543
+ $voiceBar.Visibility = if ($on) { 'Visible' } else { 'Collapsed' }
544
+ if ($on) { (E 'MicIcon').Visibility = 'Visible'; (E 'SendIcon').Visibility = 'Collapsed'; (E 'AskHint').Visibility = 'Collapsed'; $script:levelTimer.Start(); InputLayout }
545
+ else { $script:levelTimer.Stop(); SyncAction }
546
+ }
547
+ function VoiceState($state) {
548
+ $script:voiceLive = [string]$state
549
+ $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 { '' } }
550
+ $bars = if ($state -eq 'speaking') { '#F472B6' } elseif ($state -eq 'listening' -or $state -eq 'recording') { '#8B7CF6' } else { '#C4B5FD' }
551
+ foreach ($r in $script:levelBars) { $r.Fill = Brush $bars }
552
+ AskStatus ''
553
+ (E 'MicBtn').ToolTip = switch ($state) { 'speaking' { $T.voice_hint_interrupt } 'recording' { $T.voice_hint_send } default { $T.voice_hint_end } }
554
+ # The bot's face follows the conversation: all ears, thinking, talking (animated mouth).
555
+ SetFace $(switch ($state) { 'thinking' { 'thinking' } 'speaking' { 'speaking' } default { 'listening' } })
556
+ }
557
+ # The server says the bot finished talking, but the speaker still plays what it has: keep "talking" (and a click = interrupt) until it is
558
+ # really quiet, then show the next state.
559
+ $script:afterSpeak = ''
560
+ $script:speakTimer = New-Object Windows.Threading.DispatcherTimer; $script:speakTimer.Interval = [TimeSpan]::FromMilliseconds(150)
561
+ $script:speakTimer.Add_Tick({
562
+ if ($script:afterSpeak -and -not [AivinMascot.Voice]::Playing) { $s = $script:afterSpeak; $script:afterSpeak = ''; if ($script:voiceLive) { VoiceState $s } }
563
+ })
564
+ function StartVoice { VoiceLook $true; VoiceState 'connecting'; $script:speakTimer.Start(); NoteTarget; Send @{ t = 'voice_start'; window = $script:askTarget } }
565
+ function EndVoice($text) {
566
+ [AivinMascot.Voice]::End(); $script:speakTimer.Stop(); $script:afterSpeak = ''; $script:voiceLive = ''; VoiceLook $false; AskStatus $text
567
+ SetFace $script:state
568
+ if ($script:askOpen) { HideAskLater ${ASK_IDLE_MS} }
569
+ }
570
+ function StopVoice { Send @{ t = 'voice_stop' }; EndVoice $T.voice_ended }
571
+ function InterruptVoice { [AivinMascot.Voice]::Flush(); $script:afterSpeak = ''; Send @{ t = 'voice_interrupt' }; VoiceState 'listening' }
572
+ # One action for the mic button and the hotkey: bot talking -> interrupt; talking with it -> end; idle -> start.
573
+ function VoiceToggle {
574
+ if ($script:voiceLive -and $script:voiceLive -ne 'recording' -and [AivinMascot.Voice]::Playing) { InterruptVoice }
575
+ elseif ($script:voiceLive) { StopVoice }
576
+ elseif (-not $script:chatBusy) { PeekAsk; StartVoice }
577
+ }
578
+ (E 'MicBtn').Add_Click({
579
+ if (-not $script:voiceLive -and (E 'AskBox').Text.Trim()) { SubmitAsk }
580
+ elseif (StopMode) { $script:canCancel = $false; (E 'MicBtn').Opacity = 0.5; SyncAction; Send @{ t = 'cancel' } }
581
+ else { VoiceToggle }
582
+ })
583
+ # 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
584
+ # the list the daemon wrote into config.json (hotkey.mjs: the owner's own choice first, then the defaults; "hotkey off" = empty lists ->
585
+ # none). Shown in the mic button's tooltip / the tray menu; none free -> no hotkey. WM_HOTKEY is filtered in C# (AivinMascot.HotKeys).
586
+ function RegisterKeyList($id, $list) {
587
+ $keys = @(@($list) | Where-Object { $_ -and $_.n })
588
+ if (-not $keys.Count) { return $null }
589
+ $mods = [uint32[]]@($keys | ForEach-Object { [uint32]$_.m }); $vks = [uint32[]]@($keys | ForEach-Object { [uint32]$_.v })
590
+ $i = [AivinMascot.HotKeys]::RegisterFirst($script:hwnd, $id, $mods, $vks)
591
+ if ($i -lt 0) { Dbg ('hotkey ' + $id + ': none free'); return $null }
592
+ [string]$keys[$i].n
593
+ }
594
+ $w.Add_ContentRendered({
595
+ if (-not $script:hwnd) { return }
596
+ $voiceKey = RegisterKeyList 0xA171 $cfg.hotkeys.voice
597
+ if ($voiceKey) { $T.ask_mic = "$($T.ask_mic) ($voiceKey)"; SyncAction }
598
+ $chatKey = RegisterKeyList 0xA172 $cfg.hotkeys.chat
599
+ # The tray menu shows the same combinations next to its Quick chat / Quick voice items.
600
+ Send @{ t = 'hotkeys'; chat = $chatKey; voice = $voiceKey }
601
+ if ($voiceKey -or $chatKey) {
602
+ [AivinMascot.HotKeys]::Start($script:hwnd, [Action[int]]{ param($id)
603
+ if ($id -eq 0xA171) { VoiceToggle }
604
+ elseif ($id -eq 0xA172) { OpenAsk; [void](E 'AskBox').Focus() }
605
+ })
606
+ }
607
+ })
608
+
609
+ # Route the ask-box commands; everything else goes to the base handler of hostSource.mjs.
610
+ $script:baseHandle = (Get-Item function:Handle).ScriptBlock
611
+ function Handle($m) {
612
+ switch ($m.t) {
613
+ 'chat' {
614
+ ChatRow $m
615
+ if (-not $m.remove -and [string]$m.role -ne 'user' -and $m.text) {
616
+ $script:chatLast = ChatShort $m
617
+ if ($script:askOpen) { HideAskLater $(if ($m.blocks) { ${ASK_RICH_IDLE_MS} } else { ${ASK_IDLE_MS} }) } else { ChatBubble $script:chatLast }
618
+ }
619
+ return
620
+ }
621
+ 'chat_clear' { (E 'ChatList').Children.Clear(); $script:chatRows.Clear(); $script:scrollRow = $null; AskWidth $false; (E 'ChatScroll').Visibility = 'Collapsed'; InputLayout; return }
622
+ 'chat_busy' {
623
+ $script:chatBusy = [bool]$m.busy; $script:canCancel = [bool]$m.cancel
624
+ (E 'MicBtn').Opacity = if ($script:chatBusy -and -not $script:canCancel) { 0.5 } else { 1 }
625
+ SyncAction
626
+ # Answer arrived: leave it readable a while, then tuck the box away.
627
+ if (-not $script:chatBusy -and $script:askOpen) { HideAskLater ${ASK_IDLE_MS} }
628
+ # Turn over with the box closed: the answer / error stays in the bubble a while, then the bubble times out.
629
+ if (-not $script:chatBusy -and -not $script:askOpen -and (E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
630
+ if ($script:chatBusy) { $script:chatLast = '' }
631
+ return
632
+ }
633
+ 'ask_status' { AskStatus $m.text; return }
634
+ 'ask_choices' { ChoiceButtons $m.options $m.multiple; return }
635
+ # Files waiting for the next question: chips above the input; then on to the bot's tray (no return).
636
+ 'ask_files' { $chips = @($m.files | Where-Object { $_ }); $more = @($chips | Where-Object { -not $_.pinned }).Count -gt @((E 'AttachBar').Children | Where-Object { $_.Tag -ne 'pinned' }).Count; $script:files = [int]$m.n; AttachChips $chips; SyncAction; if ($more) { PeekAsk; HideAskLater ${ASK_IDLE_MS} } }
637
+ 'ask_pin' {
638
+ $script:askPinned = [bool]$m.on
639
+ if ($script:askPinned) {
640
+ $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; PeekAsk; (E 'ChatScroll').ScrollToEnd()
641
+ # Khong ai dong vao trong ASK_PINNED_IDLE_MS -> cat o hoi, cau hoi van cho (huy hieu tren bot); dang go thi cho nhu thuong.
642
+ HideAskLater $(if ($script:askFocused) { ${ASK_IDLE_MS} } else { ${ASK_PINNED_IDLE_MS} })
643
+ }
644
+ elseif ($script:askOpen) { HideAskLater $(if ($script:askFocused) { ${ASK_IDLE_MS} } else { 4000 }) }
645
+ return
646
+ }
647
+ 'voice_begin' {
648
+ if (-not $script:voiceLive) { Send @{ t = 'voice_stop' }; return }
649
+ if ([AivinMascot.Voice]::Begin([int]$m.in_rate, [int]$m.out_rate, $true)) {
650
+ Dbg "voice: on, echo cancelled=$([AivinMascot.Voice]::EchoCancelled) $([AivinMascot.Voice]::AecError)"
651
+ VoiceState $(if ($m.state) { [string]$m.state } else { 'listening' })
652
+ } else { Dbg 'voice: no mic'; Send @{ t = 'voice_stop' }; EndVoice $T.ask_no_mic }
653
+ return
654
+ }
655
+ 'voice_state' {
656
+ if (-not $script:voiceLive) { return }
657
+ if ($script:voiceLive -eq 'speaking' -and $m.state -ne 'speaking' -and [AivinMascot.Voice]::Playing) { $script:afterSpeak = [string]$m.state }
658
+ else { $script:afterSpeak = ''; VoiceState $m.state }
659
+ return
660
+ }
661
+ 'voice_end' { if ($script:voiceLive) { EndVoice $m.text }; return }
662
+ # aivin ui: the user just asked for the mascot from a terminal -> show it and open the ask box ready to type.
663
+ 'open_ask' { $script:userHidden = $false; ApplyVisibility; if (-not $script:askFocused) { OpenAsk }; return }
664
+ 'voice_toggle' { $script:userHidden = $false; ApplyVisibility; VoiceToggle; return }
665
+ 'quick_voice' { $script:userHidden = $false; ApplyVisibility; if (-not $script:voiceLive) { PeekAsk; StartVoice }; return }
666
+ # Debug only (AIVIN_MASCOT_DEBUG): show the ask box WITHOUT taking keyboard focus, to look at it / screenshot it.
667
+ 'ask_preview' { if ($env:AIVIN_MASCOT_DEBUG) { PeekAsk }; return }
668
+ # Debug/docs preview of the real file-drag UI, using the same tray, face and hint code as DragEnter without requiring Explorer.
669
+ 'drop_preview' {
670
+ if ($env:AIVIN_MASCOT_DEBUG) {
671
+ $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; CloseAsk
672
+ $script:dragFiles = @('bao-cao.xlsx', 'anh-man-hinh.png'); $script:rig.Hover = $true; $script:rig.Tray('open', $script:files); SetFace 'waiting'
673
+ DropHint ($T.drop_many.Replace('{n}', '2'))
674
+ }
675
+ return
676
+ }
677
+ 'drop_preview_end' { if ($env:AIVIN_MASCOT_DEBUG) { DragEnd }; return }
678
+ # Debug only: start talking as if the mic was clicked (end-to-end voice test without clicking / taking focus).
679
+ 'voice_preview' { if ($env:AIVIN_MASCOT_DEBUG -and -not $script:voiceLive) { VoiceToggle }; return }
680
+ # Debug only: render the ask box (not the screen) to a PNG, to look at the design without screenshots.
681
+ 'snap' {
682
+ if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
683
+ $el = E 'Ask'; $el.UpdateLayout(); $dpi = 2
684
+ $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)
685
+ $vis = New-Object Windows.Media.DrawingVisual; $dc = $vis.RenderOpen()
686
+ $dc.DrawRectangle((Brush '#F3F4F6'), $null, (New-Object Windows.Rect 0, 0, ($el.ActualWidth + 12), ($el.ActualHeight + 12)))
687
+ # 1:1, no stretching (the drop shadow makes the visual's bounds bigger than the box).
688
+ $vb = New-Object Windows.Media.VisualBrush $el; $vb.Stretch = 'None'; $vb.AlignmentX = 'Left'; $vb.AlignmentY = 'Top'
689
+ $vb.ViewboxUnits = 'Absolute'; $vb.Viewbox = New-Object Windows.Rect 0, 0, $el.ActualWidth, $el.ActualHeight
690
+ $dc.DrawRectangle($vb, $null, (New-Object Windows.Rect 6, 6, $el.ActualWidth, $el.ActualHeight)); $dc.Close()
691
+ $bmp.Render($vis); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
692
+ $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
693
+ }
694
+ # Debug/docs only: render the complete live WPF visual tree (bot + every visible box), not the static seed artwork.
695
+ 'snap_full' {
696
+ if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
697
+ $el = E 'Root'; $el.UpdateLayout(); $dpi = 2
698
+ $bmp = New-Object Windows.Media.Imaging.RenderTargetBitmap ([int]($el.ActualWidth * $dpi)), ([int]($el.ActualHeight * $dpi)), (96 * $dpi), (96 * $dpi), ([Windows.Media.PixelFormats]::Pbgra32)
699
+ $bmp.Render($el); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
700
+ $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
701
+ }
702
+ }
703
+ & $script:baseHandle $m
704
+ }
705
+ # ---- end ask box ----
706
+ `;