@aivin-labs/cli 1.0.8 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +41 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1979 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +187 -37
  9. package/bin/lib/remote/callLedger.mjs +74 -15
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +174 -11
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +293 -0
  15. package/bin/lib/remote/constants.mjs +78 -0
  16. package/bin/lib/remote/dailyBrowser.mjs +9 -3
  17. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  18. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  19. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  20. package/bin/lib/remote/desktop/index.mjs +309 -0
  21. package/bin/lib/remote/desktop/linux.mjs +144 -0
  22. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
  23. package/bin/lib/remote/desktop/mac.mjs +187 -0
  24. package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
  25. package/bin/lib/remote/desktop/strings.mjs +74 -0
  26. package/bin/lib/remote/desktop/traySource.mjs +541 -0
  27. package/bin/lib/remote/deviceProfile.mjs +1 -0
  28. package/bin/lib/remote/docText.mjs +86 -1
  29. package/bin/lib/remote/fileIndexer.mjs +757 -399
  30. package/bin/lib/remote/folderRules.mjs +140 -0
  31. package/bin/lib/remote/gui/index.mjs +208 -18
  32. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  33. package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
  34. package/bin/lib/remote/idempotency.mjs +50 -21
  35. package/bin/lib/remote/localPolicy.mjs +17 -4
  36. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  37. package/bin/lib/remote/mascot/ask.mjs +768 -0
  38. package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
  39. package/bin/lib/remote/mascot/assets.mjs +825 -216
  40. package/bin/lib/remote/mascot/bot.mjs +397 -0
  41. package/bin/lib/remote/mascot/hostSource.mjs +500 -103
  42. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  43. package/bin/lib/remote/mascot/index.mjs +199 -28
  44. package/bin/lib/remote/mascot/labels.mjs +2 -3
  45. package/bin/lib/remote/mascot/rigSource.mjs +614 -0
  46. package/bin/lib/remote/mascot/strings.mjs +204 -18
  47. package/bin/lib/remote/mascot/ui.mjs +104 -0
  48. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  49. package/bin/lib/remote/meeting/index.mjs +415 -0
  50. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  51. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  52. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  53. package/bin/lib/remote/osSearch.mjs +107 -0
  54. package/bin/lib/remote/sqliteDb.mjs +51 -0
  55. package/bin/lib/remote/tabGroups.mjs +209 -0
  56. package/bin/lib/remote/toolHandlers.mjs +788 -726
  57. package/bin/lib/remoteControl.mjs +26 -26
  58. package/docs/AIVIN_MASCOT.md +130 -0
  59. package/docs/CLI.md +1504 -1353
  60. package/docs/media/aivin-mascot-live.gif +0 -0
  61. package/docs/media/aivin-mascot-live.png +0 -0
  62. package/docs/media/aivin-remote-architecture.svg +102 -0
  63. package/package.json +71 -71
@@ -1,4 +1,7 @@
1
1
  import { AIVIN_BRAND } from '../brand.mjs';
2
+ import { BOT_FACES, BOT_LAYER_FILES, BOT_XAML } from './bot.mjs';
3
+ import { RIG_CS, RIG_REFERENCES_PS } from './rigSource.mjs';
4
+ import { VOICE_CS } from './voiceSource.mjs';
2
5
 
3
6
  /**
4
7
  * Cửa sổ linh vật (Windows, WPF qua PowerShell) — sống suốt phiên `aivin remote start`, nhận lệnh từng dòng JSON trên stdin, gửi sự kiện
@@ -9,17 +12,37 @@ import { AIVIN_BRAND } from '../brand.mjs';
9
12
  * - Không có trong ảnh chụp màn hình (WDA_EXCLUDEFROMCAPTURE, Windows 10 2004+): ảnh AI chụp để điều khiển giao diện, chia sẻ màn hình
10
13
  * khi họp không thấy linh vật. Thử nghiệm cần chụp được thì đặt AIVIN_MASCOT_CAPTURABLE=1.
11
14
  * - Kéo để di chuyển (nhớ chỗ), bấm để mở / thu bảng nhật ký; bảng mở về phía còn chỗ trên màn hình, kẹp trong vùng màn hình.
15
+ * - Chuyển động của bot: rigSource.mjs (C#, theo nhịp màn hình) — PowerShell chỉ báo trạng thái / rê chuột / nhấn / kéo cho rig.
12
16
  * Lệnh vào: state | main | log | gui | show | quit. Sự kiện ra: ready | pos | pause | resume | hide | off.
13
17
  * Tệp .ps1 giữ toàn ASCII (PowerShell 5 đọc .ps1 không BOM theo bảng mã cũ) — mọi chữ hiện ra nằm trong config.json (UTF-8).
14
18
  */
15
19
 
16
20
  const B = AIVIN_BRAND;
17
21
 
22
+ /** Cỡ linh vật: thân vẽ trên khung gốc rồi Viewbox thu về MASCOT_BOX (60 px); khung bấm / kéo bao quanh thân; tâm khung = điểm neo vị trí. */
23
+ // The rendered bot is a MASCOT_BOX-sized Viewbox. Keep the hit/layout box equally large so the rounded lower body is not clipped.
24
+ const MASCOT_BOX = { w: 60, h: 60 };
25
+ export const MASCOT_CENTER = Object.freeze({ x: 30, y: 28.5 });
26
+ /** Rảnh (idle) liền chừng này phút mà không ai rê chuột → bot ngủ gật; có việc / rê chuột vào thì thức. */
27
+ const MASCOT_DOZE_MIN = 10;
28
+ /** Không chạm chuột / bàn phím chừng này phút = chủ máy đi vắng (khoá máy, đi họp…) → daemon gom việc xảy ra để báo khi quay lại. */
29
+ const MASCOT_AWAY_MIN = 10;
30
+ /** Lề trong cửa sổ quanh bot / các hộp (chỗ cho bóng đổ). */
31
+ const ROOT_MARGIN = 14;
32
+ /**
33
+ * Cửa sổ cỡ cố định (đủ cho bảng nhật ký 372 px + lề bóng, cao đủ cho bảng / ô hỏi + bot): hiện / ẩn ô hỏi, bảng, bong bóng chỉ đổi
34
+ * chỗ bên trong cửa sổ, không đổi cỡ / dời cửa sổ — cửa sổ layered bị dời thì ảnh cũ nhảy theo một nhịp trước khi vẽ lại (bot "chập").
35
+ * Vùng trong suốt hẳn bấm xuyên qua nên cửa sổ lớn không che gì.
36
+ */
37
+ const WINDOW = { w: 372 + 2 * ROOT_MARGIN, h: 640 };
38
+ /** Kéo tệp vào trong bán kính này (DIP, quanh tâm bot) là thùng nhận tệp bật ra — không cần chạm đúng vào bot. */
39
+ const DROP_ZONE_R = 90;
40
+
18
41
  /** Màu từng trạng thái: `fg` chấm / chữ, `bg` nền chip. */
19
42
  export const MASCOT_PALETTE = Object.freeze({
20
- idle: { fg: '#00B42A', bg: '#E8FFEA' },
43
+ idle: { fg: '#14C9C9', bg: '#E6FFFB' },
21
44
  working: { fg: B.brand, bg: '#E8F3FF' },
22
- thinking: { fg: B.light, bg: '#E6F9FF' },
45
+ thinking: { fg: '#722ED1', bg: '#F9F0FF' },
23
46
  waiting: { fg: B.warn, bg: B.warnBg },
24
47
  paused: { fg: B.muted, bg: '#F2F3F5' },
25
48
  offline: { fg: B.muted, bg: '#F2F3F5' },
@@ -66,14 +89,24 @@ const buttonStyle = (key, radius) => `<Style x:Key="${key}" TargetType="Button">
66
89
 
67
90
  const SHADOW = '<DropShadowEffect BlurRadius="24" ShadowDepth="6" Direction="270" Opacity="0.16" Color="#0B1B3F"/>';
68
91
 
69
- /** Mắt vẽ trên thân 80×80 (biểu tượng 160×160 thu nửa): tròng trắng + con ngươi + đốm sáng, nằm trên dải phía trên của dải lụa. */
70
- const EYES = [{ x: 38, y: 20 }, { x: 50.5, y: 18.5 }];
71
- const eyeWhites = EYES.map(({ x, y }) => `<Ellipse Canvas.Left="${x - 3.75}" Canvas.Top="${y - 4.5}" Width="7.5" Height="9" Fill="White"/>`).join('\n ');
72
- const pupils = EYES.map(({ x, y }) => `<Ellipse Canvas.Left="${x - 1.6}" Canvas.Top="${y - 1.8}" Width="4.4" Height="5.4" Fill="${B.ink}"/>
73
- <Ellipse Canvas.Left="${x - 0.8}" Canvas.Top="${y - 0.9}" Width="1.7" Height="1.7" Fill="White"/>`).join('\n ');
92
+ /** Biểu tượng nét (Path) cho ô hỏi: mic (thân + vòng + chân), gửi (mũi tên giấy). */
93
+ const ICON_MIC = 'M12,3 A3,3 0 0 1 15,6 L15,12 A3,3 0 0 1 9,12 L9,6 A3,3 0 0 1 12,3 Z M5,11 A7,7 0 0 0 19,11 M12,18 L12,21';
94
+ /** Gửi: mũi tên lên (nét). */
95
+ const ICON_SEND_UP = 'M12,20 L12,5 M5,11 L12,4 L19,11';
96
+ /** Chat mới (nút trên bảng): bong bóng chat có dấu cộng (nét). */
97
+ /** Tắt (nút tắt linh vật): vòng nguồn hở trên + vạch. */
98
+ const ICON_POWER = 'M12,3 L12,11 M7.05,6.05 A7,7 0 1 0 16.95,6.05';
99
+ const OFF_RED = '#F53F3F';
100
+ const ICON_NEW_CHAT = 'M5,4 L19,4 A2,2 0 0 1 21,6 L21,15 A2,2 0 0 1 19,17 L10,17 L6,20.5 L6,17 L5,17 A2,2 0 0 1 3,15 L3,6 A2,2 0 0 1 5,4 Z M12,7.5 L12,13.5 M9,10.5 L15,10.5';
101
+ /** Viền ô hỏi: pastel hồng → tím nhạt → xanh nhạt (theo ô nhập của FE), khép vòng để xoay không bị nối gãy. */
102
+ const ASK_GLOW_STOPS = [['#F9A8D4', 0], ['#C4B5FD', 0.3], ['#93C5FD', 0.58], ['#A5F3FC', 0.8], ['#F9A8D4', 1]]
103
+ .map(([color, offset]) => `<GradientStop Color="${color}" Offset="${offset}"/>`).join('');
104
+ /** Nút của ô hỏi: nền tím nhạt, biểu tượng tím (ghi âm: nền đỏ nhạt, biểu tượng đỏ). Dùng cả ở askHostSource.mjs. */
105
+ export const ASK_BTN = Object.freeze({ bg: '#EEF0FF', icon: '#8B7CF6', recBg: '#FEE2E2', recIcon: '#EF4444' });
106
+
74
107
 
75
108
  export const MASCOT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
76
- SizeToContent="WidthAndHeight" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize"
109
+ Width="${WINDOW.w}" Height="${WINDOW.h}" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize"
77
110
  Topmost="True" ShowInTaskbar="False" ShowActivated="False" FontFamily="Segoe UI" UseLayoutRounding="True" Opacity="0">
78
111
  <Window.Resources>
79
112
  ${buttonStyle('Btn', 9)}
@@ -82,25 +115,37 @@ export const MASCOT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/20
82
115
  ${motion('PanelOut', 0, 0.96, 120, 'EaseIn')}
83
116
  ${motion('BubbleIn', 1, 1, 160, 'EaseOut')}
84
117
  ${motion('BubbleOut', 0, 0.94, 140, 'EaseIn')}
118
+ <Style TargetType="ScrollBar">
119
+ <Setter Property="Width" Value="6"/>
120
+ <Setter Property="MinWidth" Value="6"/>
121
+ <Setter Property="Template"><Setter.Value>
122
+ <ControlTemplate TargetType="ScrollBar">
123
+ <Track x:Name="PART_Track" IsDirectionReversed="True">
124
+ <Track.Thumb><Thumb><Thumb.Template><ControlTemplate TargetType="Thumb">
125
+ <Border x:Name="ThumbBar" CornerRadius="3" Background="#D5D8DE" Margin="1,2"/>
126
+ <ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter TargetName="ThumbBar" Property="Background" Value="#AEB3BC"/></Trigger></ControlTemplate.Triggers>
127
+ </ControlTemplate></Thumb.Template></Thumb></Track.Thumb>
128
+ </Track>
129
+ </ControlTemplate>
130
+ </Setter.Value></Setter>
131
+ </Style>
85
132
  <Storyboard x:Key="WindowIn"><DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0.250"/></Storyboard>
86
- <Storyboard x:Key="Pulse" RepeatBehavior="Forever" AutoReverse="True">
87
- <DoubleAnimation Storyboard.TargetName="Dot" Storyboard.TargetProperty="Opacity" From="1" To="0.3" Duration="0:0:0.700"/>
133
+ <Storyboard x:Key="WindowOut">
134
+ <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:0.220">${ease('EaseIn')}</DoubleAnimation>
135
+ <DoubleAnimation Storyboard.TargetName="Root" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.Y)" To="14" Duration="0:0:0.240">${ease('EaseIn')}</DoubleAnimation>
88
136
  </Storyboard>
89
- <Storyboard x:Key="Look" RepeatBehavior="Forever">
90
- <DoubleAnimationUsingKeyFrames Storyboard.TargetName="LookX" Storyboard.TargetProperty="X">
91
- <EasingDoubleKeyFrame KeyTime="0:0:0" Value="0"/><EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="-1.3"/>
92
- <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="-1.3"/><EasingDoubleKeyFrame KeyTime="0:0:2.2" Value="1.3"/>
93
- <EasingDoubleKeyFrame KeyTime="0:0:3.2" Value="1.3"/><EasingDoubleKeyFrame KeyTime="0:0:3.8" Value="0"/>
94
- </DoubleAnimationUsingKeyFrames>
95
- </Storyboard>
96
- <Storyboard x:Key="Hop">
97
- <DoubleAnimationUsingKeyFrames Storyboard.TargetName="HopY" Storyboard.TargetProperty="Y">
98
- <EasingDoubleKeyFrame KeyTime="0:0:0" Value="0"/><EasingDoubleKeyFrame KeyTime="0:0:0.16" Value="-9"><EasingDoubleKeyFrame.EasingFunction><CubicEase EasingMode="EaseOut"/></EasingDoubleKeyFrame.EasingFunction></EasingDoubleKeyFrame>
99
- <EasingDoubleKeyFrame KeyTime="0:0:0.36" Value="0"><EasingDoubleKeyFrame.EasingFunction><BounceEase Bounces="1" Bounciness="3" EasingMode="EaseOut"/></EasingDoubleKeyFrame.EasingFunction></EasingDoubleKeyFrame>
100
- </DoubleAnimationUsingKeyFrames>
137
+ <Storyboard x:Key="AskGlow" RepeatBehavior="Forever">
138
+ <DoubleAnimation Storyboard.TargetName="AskGlowSpin" Storyboard.TargetProperty="Angle" From="0" To="360" Duration="0:0:3"/>
101
139
  </Storyboard>
102
140
  </Window.Resources>
103
- <StackPanel x:Name="Root" Margin="14">
141
+ <!-- Bot và các hộp đặt bằng toạ độ trong cửa sổ (Place / ArrangeBoxes): bot đứng đúng điểm neo, hộp nằm trên bot (hoặc dưới khi
142
+ sát mép trên), kẹp trong cửa sổ. -->
143
+ <Canvas x:Name="Root" RenderTransformOrigin="0.5,1">
144
+ <Canvas.RenderTransform><TranslateTransform Y="0"/></Canvas.RenderTransform>
145
+ <!-- Vùng thả tệp quanh bot: trong suốt hẳn (bấm xuyên qua) — DropSense chỉ phủ nền alpha 1/255 lên khi đang giữ chuột ở gần bot, để
146
+ tệp đang kéo tới "chạm" được vào cửa sổ trước khi tới đúng bot. -->
147
+ <Ellipse x:Name="DropZone" Width="${DROP_ZONE_R * 2}" Height="${DROP_ZONE_R * 2}"/>
148
+ <StackPanel x:Name="Boxes">
104
149
  <Border x:Name="Panel" Visibility="Collapsed" Width="372" Margin="0,0,0,10" CornerRadius="16" Background="White" BorderBrush="#E5E6EB"
105
150
  BorderThickness="1" Opacity="0" RenderTransformOrigin="0.5,1">
106
151
  <Border.RenderTransform><ScaleTransform ScaleX="0.96" ScaleY="0.96"/></Border.RenderTransform>
@@ -116,14 +161,27 @@ export const MASCOT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/20
116
161
  FontWeight="Normal" Background="Transparent" BorderThickness="0" Tag="#F2F3F5" Foreground="${B.muted}"/>
117
162
  </DockPanel>
118
163
  <TextBlock x:Name="NowLabel" DockPanel.Dock="Top" Margin="0,14,0,4" FontSize="11" FontWeight="SemiBold" Foreground="${B.muted}"/>
119
- <TextBlock x:Name="NowText" DockPanel.Dock="Top" FontSize="14" Foreground="${B.ink}" TextWrapping="Wrap" LineHeight="20" Margin="0,0,6,0"/>
164
+ <TextBlock x:Name="NowText" DockPanel.Dock="Top" Margin="0,0,6,0" FontSize="14" Foreground="${B.ink}" TextWrapping="Wrap" LineHeight="20"/>
165
+ <!-- Hàng nút: phiên chat mới (nút chính); "Cho AI làm tiếp" chỉ hiện khi AI đang tạm dừng (dừng bằng aivin remote pause); tắt linh vật (đỏ). -->
120
166
  <DockPanel DockPanel.Dock="Bottom" Margin="0,12,6,0" LastChildFill="False">
121
- <Button x:Name="PauseBtn" Style="{StaticResource Btn}" Height="34" Padding="14,0" Background="White" Foreground="${B.ink}"
122
- BorderBrush="#C9CDD4" BorderThickness="1" Tag="#0F000000"/>
167
+ <Button x:Name="NewChatBtn" Style="{StaticResource Btn}" Height="34" Padding="12,0,14,0" Background="${B.brand}" Foreground="White"
168
+ BorderThickness="0" Tag="#1F000000">
169
+ <StackPanel Orientation="Horizontal">
170
+ <Path Data="${ICON_NEW_CHAT}" Stroke="White" StrokeThickness="1.8" StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeLineJoin="Round"
171
+ Width="14" Height="14" Stretch="Uniform" Margin="0,0,7,0" VerticalAlignment="Center"/>
172
+ <TextBlock x:Name="NewChatText" VerticalAlignment="Center"/>
173
+ </StackPanel>
174
+ </Button>
175
+ <Button x:Name="PauseBtn" Style="{StaticResource Btn}" Height="34" Padding="14,0" Margin="8,0,0,0" Background="White" Foreground="${B.ink}"
176
+ BorderBrush="#C9CDD4" BorderThickness="1" Tag="#0F000000" Visibility="Collapsed"/>
123
177
  <Button x:Name="OffBtn" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="34" Padding="10,0" Background="Transparent"
124
- Foreground="${B.muted}" BorderThickness="0" Tag="#F2F3F5" FontWeight="Normal"/>
125
- <Button x:Name="HideBtn" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="34" Padding="10,0" Background="Transparent"
126
- Foreground="${B.body}" BorderThickness="0" Tag="#F2F3F5" FontWeight="Normal"/>
178
+ Foreground="${OFF_RED}" BorderThickness="0" Tag="#FFECE8" FontWeight="Normal">
179
+ <StackPanel Orientation="Horizontal">
180
+ <Path Data="${ICON_POWER}" Stroke="${OFF_RED}" StrokeThickness="2" StrokeStartLineCap="Round" StrokeEndLineCap="Round"
181
+ Width="13" Height="13" Stretch="Uniform" Margin="0,0,6,0" VerticalAlignment="Center"/>
182
+ <TextBlock x:Name="OffText" VerticalAlignment="Center"/>
183
+ </StackPanel>
184
+ </Button>
127
185
  </DockPanel>
128
186
  <TextBlock x:Name="LogLabel" DockPanel.Dock="Top" Margin="0,16,0,6" FontSize="11" FontWeight="SemiBold" Foreground="${B.muted}"/>
129
187
  <Border CornerRadius="10" Background="#F7F8FA" BorderBrush="#EEF0F4" BorderThickness="1" Margin="0,0,6,0">
@@ -134,68 +192,171 @@ export const MASCOT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/20
134
192
  </Border>
135
193
  </DockPanel>
136
194
  </Border>
195
+ <!-- Ô hỏi (gọn, ô nhập cao 2 dòng): cả khung là ô nhập, viền mảnh chuyển màu pastel xoay quanh khi hiện (storyboard AskGlow). Nút
196
+ cùng dòng bên phải: trống = mic, có chữ = gửi (mũi tên lên). Hội thoại hiện phía trên dòng nhập khi đã hỏi. -->
197
+ <Border x:Name="Ask" Visibility="Collapsed" Width="240" Margin="0,0,0,7" CornerRadius="14" Background="White" BorderThickness="1.2"
198
+ Opacity="0" RenderTransformOrigin="0.5,1">
199
+ <Border.BorderBrush>
200
+ <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
201
+ <LinearGradientBrush.RelativeTransform><RotateTransform x:Name="AskGlowSpin" CenterX="0.5" CenterY="0.5"/></LinearGradientBrush.RelativeTransform>
202
+ ${ASK_GLOW_STOPS}
203
+ </LinearGradientBrush>
204
+ </Border.BorderBrush>
205
+ <Border.RenderTransform><ScaleTransform ScaleX="0.96" ScaleY="0.96"/></Border.RenderTransform>
206
+ <Border.Effect><DropShadowEffect BlurRadius="12" ShadowDepth="1" Direction="270" Opacity="0.10" Color="#6B5CE7"/></Border.Effect>
207
+ <StackPanel Margin="12,8,7,7">
208
+ <ScrollViewer x:Name="ChatScroll" MaxHeight="160" VerticalScrollBarVisibility="Hidden" Visibility="Collapsed" Margin="0,3,4,5">
209
+ <StackPanel x:Name="ChatList"/>
210
+ </ScrollViewer>
211
+ <!-- Nút trả lời nhanh khi Aivin hỏi lại (thẻ chọn của agent) — askHostSource.mjs dựng theo lệnh ask_choices. -->
212
+ <StackPanel x:Name="Choices" Visibility="Collapsed" Margin="0,0,4,5"/>
213
+ <DockPanel>
214
+ <Button x:Name="MicBtn" DockPanel.Dock="Right" Style="{StaticResource IconBtn}" Width="26" Height="26" Margin="6,0,0,0" VerticalAlignment="Bottom"
215
+ Background="${ASK_BTN.bg}" BorderThickness="0" Tag="#14000000">
216
+ <Grid>
217
+ <Path x:Name="MicIcon" Data="${ICON_MIC}" Stroke="${ASK_BTN.icon}" StrokeThickness="1.8" StrokeStartLineCap="Round" StrokeEndLineCap="Round"
218
+ Width="11" Height="13" Stretch="Uniform"/>
219
+ <Path x:Name="SendIcon" Data="${ICON_SEND_UP}" Stroke="${ASK_BTN.icon}" StrokeThickness="1.9" StrokeStartLineCap="Round" StrokeEndLineCap="Round"
220
+ StrokeLineJoin="Round" Width="11" Height="12" Stretch="Uniform" Visibility="Collapsed"/>
221
+ <Rectangle x:Name="StopIcon" Width="9" Height="9" RadiusX="2" RadiusY="2" Fill="${ASK_BTN.icon}" Visibility="Collapsed"/>
222
+ </Grid>
223
+ </Button>
224
+ <Grid MinHeight="40">
225
+ <TextBox x:Name="AskBox" BorderThickness="0" Background="Transparent" FontSize="13" Foreground="${B.ink}" TextWrapping="Wrap"
226
+ MaxHeight="60" VerticalScrollBarVisibility="Hidden" CaretBrush="#8B7CF6" MaxLength="2000" Padding="0,1,0,1"/>
227
+ <TextBlock x:Name="AskHint" IsHitTestVisible="False" FontSize="13" Foreground="#A9AEB8" Margin="2,1,0,0" TextTrimming="CharacterEllipsis"/>
228
+ </Grid>
229
+ </DockPanel>
230
+ <TextBlock x:Name="AskStatus" Visibility="Collapsed" FontSize="11" Foreground="${B.muted}" Margin="0,2,4,1" TextTrimming="CharacterEllipsis"/>
231
+ </StackPanel>
232
+ </Border>
137
233
  <Grid x:Name="Bubble" Visibility="Collapsed" Opacity="0" RenderTransformOrigin="0.5,1">
138
234
  <Grid.RenderTransform><ScaleTransform ScaleX="0.94" ScaleY="0.94"/></Grid.RenderTransform>
139
- <Border CornerRadius="14" Background="White" BorderBrush="#E5E6EB" BorderThickness="1" Padding="12,8,14,9" MaxWidth="250" Margin="0,0,0,7">
235
+ <Border x:Name="BubbleBox" CornerRadius="12" Background="White" BorderBrush="#E5E6EB" BorderThickness="1" Padding="10,6,12,7" MaxWidth="220" Margin="0,0,0,7">
140
236
  <Border.Effect>${SHADOW}</Border.Effect>
141
237
  <DockPanel>
142
- <Ellipse x:Name="BubbleDot" Width="7" Height="7" Margin="0,6,8,0" VerticalAlignment="Top"/>
143
- <TextBlock x:Name="BubbleText" FontSize="13" Foreground="${B.ink}" TextWrapping="Wrap" MaxHeight="38" TextTrimming="CharacterEllipsis" LineHeight="19"/>
238
+ <!-- Chấm trạng thái đã có ở quả cầu ăng-ten trên đầu bot — bong bóng không lặp lại (giữ phần tử ẩn vì SetState còn tô màu nó). -->
239
+ <Ellipse x:Name="BubbleDot" Width="6" Height="6" Margin="0,5,7,0" VerticalAlignment="Top" Visibility="Collapsed"/>
240
+ <TextBlock x:Name="BubbleText" FontSize="12" Foreground="${B.ink}" TextWrapping="Wrap" MaxHeight="34" TextTrimming="CharacterEllipsis" LineHeight="17"/>
144
241
  </DockPanel>
145
242
  </Border>
146
- <Path x:Name="Tail" Data="M0,0 L14,0 L7,8 Z" Fill="White" Stroke="#E5E6EB" StrokeThickness="1" VerticalAlignment="Bottom" Margin="0,0,0,0"/>
147
- <Rectangle x:Name="TailCover" Width="12" Height="2" Fill="White" VerticalAlignment="Bottom" Margin="0,0,0,7"/>
148
- </Grid>
149
- <!-- Nền alpha 1/255: cửa sổ layered cho bấm xuyên qua điểm trong suốt hẳn — khe giữa dải lụa vẫn phải bấm / kéo được. -->
150
- <Grid x:Name="Mascot" Width="84" Height="88" Cursor="Hand" Background="#01FFFFFF">
151
- <Ellipse Width="44" Height="7" VerticalAlignment="Bottom" Margin="0,0,0,2" Fill="#140B1B3F"/>
152
- <Canvas x:Name="Floater" Width="80" Height="80" VerticalAlignment="Top" HorizontalAlignment="Center">
153
- <Canvas.RenderTransform><TransformGroup><TranslateTransform x:Name="FloatY"/><TranslateTransform x:Name="HopY"/></TransformGroup></Canvas.RenderTransform>
154
- <Canvas.Triggers>
155
- <EventTrigger RoutedEvent="FrameworkElement.Loaded"><BeginStoryboard><Storyboard RepeatBehavior="Forever" AutoReverse="True">
156
- <DoubleAnimation Storyboard.TargetName="FloatY" Storyboard.TargetProperty="Y" From="-3" To="3" Duration="0:0:1.800"><DoubleAnimation.EasingFunction><SineEase EasingMode="EaseInOut"/></DoubleAnimation.EasingFunction></DoubleAnimation>
157
- </Storyboard></BeginStoryboard></EventTrigger>
158
- </Canvas.Triggers>
159
- <Image x:Name="Body" Width="80" Height="80" RenderOptions.BitmapScalingMode="HighQuality"/>
160
- <Canvas x:Name="Eyes" Width="80" Height="80" IsHitTestVisible="False" RenderTransformOrigin="0.5,0.24">
161
- <Canvas.RenderTransform><TransformGroup><ScaleTransform x:Name="Lid" ScaleY="1"/><ScaleTransform x:Name="Blink" ScaleY="1"/></TransformGroup></Canvas.RenderTransform>
162
- <Canvas.Triggers>
163
- <EventTrigger RoutedEvent="FrameworkElement.Loaded"><BeginStoryboard><Storyboard RepeatBehavior="Forever">
164
- <DoubleAnimationUsingKeyFrames Storyboard.TargetName="Blink" Storyboard.TargetProperty="ScaleY" Duration="0:0:4.300">
165
- <DiscreteDoubleKeyFrame KeyTime="0:0:0" Value="1"/><LinearDoubleKeyFrame KeyTime="0:0:3.700" Value="1"/>
166
- <LinearDoubleKeyFrame KeyTime="0:0:3.780" Value="0.1"/><LinearDoubleKeyFrame KeyTime="0:0:3.880" Value="1"/>
167
- </DoubleAnimationUsingKeyFrames>
168
- </Storyboard></BeginStoryboard></EventTrigger>
169
- </Canvas.Triggers>
170
- ${eyeWhites}
171
- <Canvas>
172
- <Canvas.RenderTransform><TranslateTransform x:Name="LookX"/></Canvas.RenderTransform>
173
- ${pupils}
174
- </Canvas>
175
- </Canvas>
176
- </Canvas>
177
- <Ellipse x:Name="Dot" Width="13" Height="13" Stroke="White" StrokeThickness="2.5" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,56,9,0"/>
243
+ <Path x:Name="Tail" Data="M0,0 L14,0 L7,7 Z" Fill="#D9DCE1" VerticalAlignment="Bottom" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5"/>
178
244
  </Grid>
179
245
  </StackPanel>
246
+ <!-- Nền alpha 1/255: cửa sổ layered cho bấm xuyên qua điểm trong suốt hẳn — khoảng trống quanh bot vẫn phải bấm / kéo được.
247
+ Bóng dưới đất nằm trong BOT_XAML (co / nhạt theo cú nhún). -->
248
+ <Grid x:Name="Mascot" Width="${MASCOT_BOX.w}" Height="${MASCOT_BOX.h}" Cursor="Hand" Background="#01FFFFFF">
249
+ <Viewbox x:Name="Floater" Width="${MASCOT_BOX.w}" Height="${MASCOT_BOX.h}" VerticalAlignment="Top" HorizontalAlignment="Center" Stretch="Uniform">
250
+ ${BOT_XAML}
251
+ </Viewbox>
252
+ </Grid>
253
+ </Canvas>
180
254
  </Window>`;
181
255
 
182
256
  export const MASCOT_PS1 = String.raw`$ErrorActionPreference = 'Stop'
183
- Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase
257
+ Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase, System.Xaml
184
258
  $utf8 = New-Object Text.UTF8Encoding $false
185
259
  $dir = $env:AIVIN_MASCOT_DIR
186
260
  function ReadText($name) { [IO.File]::ReadAllText((Join-Path $dir $name), $utf8) }
187
261
  $cfg = ReadText 'config.json' | ConvertFrom-Json
188
262
  $T = $cfg.strings; $P = $cfg.palette
189
- $out = New-Object IO.StreamWriter([Console]::OpenStandardOutput(), $utf8); $out.AutoFlush = $true
190
- function Send($o) { $out.WriteLine(($o | ConvertTo-Json -Compress)) }
191
- # Win32 calls + a background thread that reads stdin lines into a queue (stream ReadLineAsync faults on a console pipe in .NET Framework).
192
- Add-Type -TypeDefinition @'
193
- using System; using System.Collections.Concurrent; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading;
263
+ # stdout goes through AivinMascot.Output (one lock shared with the voice capture thread, see voiceSource.mjs) so lines never interleave.
264
+ function Send($o) { [AivinMascot.Output]::Line(($o | ConvertTo-Json -Compress)) }
265
+ # Debug trace: stderr + debug.log in the host folder (stderr is only kept as the last error line by the daemon).
266
+ function Dbg($text) { if ($env:AIVIN_MASCOT_DEBUG) { $line = "$([DateTime]::Now.ToString('HH:mm:ss.fff')) $text"; [Console]::Error.WriteLine("mascot: $line"); try { [IO.File]::AppendAllText((Join-Path $dir 'debug.log'), ($line + [Environment]::NewLine), $utf8) } catch {} } }
267
+ # Win32 calls + a background thread that reads stdin lines into a queue (stream ReadLineAsync faults on a console pipe in .NET Framework)
268
+ # + the bot's per-frame motion rig (C#, see rigSource.mjs) + live voice: mic / speaker streaming (C#, see voiceSource.mjs).
269
+ Add-Type -ReferencedAssemblies ${RIG_REFERENCES_PS} -TypeDefinition @'
270
+ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO;
271
+ using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows; using System.Windows.Media;
194
272
  namespace AivinMascot {
195
273
  public static class Native {
196
274
  [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr h, int i);
197
275
  [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr h, int i, int v);
198
276
  [DllImport("user32.dll")] public static extern bool SetWindowDisplayAffinity(IntPtr h, uint a);
277
+ [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
278
+ [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
279
+ [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO p);
280
+ /** Seconds since the last mouse / keyboard input anywhere in this session (locked screen counts as no input). */
281
+ public static double IdleSeconds() {
282
+ var l = new LASTINPUTINFO(); l.cbSize = (uint)Marshal.SizeOf(l);
283
+ return GetLastInputInfo(ref l) ? unchecked((uint)Environment.TickCount - l.dwTime) / 1000.0 : 0;
284
+ }
285
+ [StructLayout(LayoutKind.Sequential)] struct POINT { public int X, Y; }
286
+ [StructLayout(LayoutKind.Sequential)] struct RECT { public int L, T, R, B; }
287
+ [StructLayout(LayoutKind.Sequential)] struct MONITORINFO { public int cbSize; public RECT rcMonitor, rcWork; public uint dwFlags; }
288
+ [DllImport("user32.dll")] static extern IntPtr MonitorFromPoint(POINT p, uint flags);
289
+ [DllImport("user32.dll")] static extern bool GetMonitorInfo(IntPtr m, ref MONITORINFO i);
290
+ /** Bounds (left, top, right, bottom; device pixels) of the monitor at / nearest to a point - a saved spot on a monitor that is gone
291
+ lands on the nearest one. */
292
+ public static int[] MonitorAt(int x, int y) {
293
+ var p = new POINT(); p.X = x; p.Y = y;
294
+ var i = new MONITORINFO(); i.cbSize = Marshal.SizeOf(i);
295
+ if (!GetMonitorInfo(MonitorFromPoint(p, 2), ref i)) return null;
296
+ return new[] { i.rcMonitor.L, i.rcMonitor.T, i.rcMonitor.R, i.rcMonitor.B };
297
+ }
298
+ }
299
+ /** Screens added / removed / resized or the taskbar moved: the window re-places itself (C# hook - a PowerShell one would run for
300
+ every window message). */
301
+ public static class DisplayWatch {
302
+ static Action changed; static System.Windows.Interop.HwndSourceHook hook;
303
+ public static void Start(IntPtr h, Action onChanged) {
304
+ changed = onChanged; hook = Hook;
305
+ System.Windows.Interop.HwndSource.FromHwnd(h).AddHook(hook);
306
+ }
307
+ static IntPtr Hook(IntPtr h, int msg, IntPtr wp, IntPtr lp, ref bool handled) {
308
+ // WM_DISPLAYCHANGE, WM_DPICHANGED, WM_SETTINGCHANGE + SPI_SETWORKAREA.
309
+ if (msg == 0x007E || msg == 0x02E0 || (msg == 0x001A && wp.ToInt64() == 0x2F)) {
310
+ System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, changed);
311
+ }
312
+ return IntPtr.Zero;
313
+ }
314
+ }
315
+ /** Keep the mascot above the taskbar: the taskbar is topmost too and jumps to the front when it (or any window) is activated, so
316
+ re-assert HWND_TOPMOST right at each foreground change and once more shortly after (the shell raises itself a beat later). */
317
+ public static class TopKeeper {
318
+ delegate void WinEventProc(IntPtr hook, uint ev, IntPtr hwnd, int obj, int child, uint thread, uint time);
319
+ [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint min, uint max, IntPtr mod, WinEventProc proc, uint pid, uint tid, uint flags);
320
+ static WinEventProc proc; static IntPtr target; static System.Windows.Threading.DispatcherTimer again;
321
+ public static void Raise() { if (target != IntPtr.Zero) Native.SetWindowPos(target, new IntPtr(-1), 0, 0, 0, 0, 0x0013); }
322
+ public static void Start(IntPtr h) {
323
+ target = h;
324
+ again = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(180) };
325
+ again.Tick += (s, e) => { again.Stop(); Raise(); };
326
+ proc = (hook, ev, hwnd, obj, child, thread, time) => { if (hwnd == target) return; Raise(); again.Stop(); again.Start(); };
327
+ // EVENT_SYSTEM_FOREGROUND, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS: delivered on this (UI) thread's message loop.
328
+ SetWinEventHook(0x0003, 0x0003, IntPtr.Zero, proc, 0, 0, 0x0002);
329
+ }
330
+ }
331
+ /**
332
+ * Files dragged toward the bot: the drop zone around it is fully transparent (clicks pass through), so a drag would only reach the
333
+ * window on the bot itself. While a mouse button is held with the pointer inside the zone, give it a 1/255 alpha fill so it takes part in
334
+ * drag and drop (DragEnter -> the tray shows); let go -> transparent again. Nothing is shown here - only a real file drag reacts.
335
+ */
336
+ public static class DropSense {
337
+ [DllImport("user32.dll")] static extern short GetAsyncKeyState(int vk);
338
+ [DllImport("user32.dll")] static extern int GetSystemMetrics(int i);
339
+ [DllImport("user32.dll")] static extern bool GetCursorPos(out POINT p);
340
+ [StructLayout(LayoutKind.Sequential)] struct POINT { public int X, Y; }
341
+ static System.Windows.Threading.DispatcherTimer timer;
342
+ public static void Start(System.Windows.Shapes.Shape zone, Brush armed) {
343
+ bool on = false;
344
+ timer = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(60) };
345
+ timer.Tick += (s, e) => {
346
+ // Physical buttons: with swapped buttons the primary one is VK_RBUTTON (SM_SWAPBUTTON).
347
+ bool down = (GetAsyncKeyState(GetSystemMetrics(23) != 0 ? 0x02 : 0x01) & 0x8000) != 0;
348
+ bool next = false;
349
+ if (down && zone.IsVisible && PresentationSource.FromVisual(zone) != null) {
350
+ if (on) next = true;
351
+ else { POINT p; if (GetCursorPos(out p)) {
352
+ var q = zone.PointFromScreen(new Point(p.X, p.Y)); double rx = zone.ActualWidth / 2, ry = zone.ActualHeight / 2;
353
+ double dx = (q.X - rx) / rx, dy = (q.Y - ry) / ry; next = dx * dx + dy * dy <= 1;
354
+ } }
355
+ }
356
+ if (next != on) { on = next; zone.Fill = on ? armed : null; }
357
+ };
358
+ timer.Start();
359
+ }
199
360
  }
200
361
  public static class Input {
201
362
  public static readonly ConcurrentQueue<string> Lines = new ConcurrentQueue<string>();
@@ -204,13 +365,15 @@ namespace AivinMascot {
204
365
  var t = new Thread(() => {
205
366
  try {
206
367
  var r = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false));
207
- string line; while ((line = r.ReadLine()) != null) Lines.Enqueue(line);
368
+ string line; while ((line = r.ReadLine()) != null) { if (!Voice.Take(line)) Lines.Enqueue(line); }
208
369
  } catch { }
209
370
  Closed = true;
210
371
  });
211
372
  t.IsBackground = true; t.Start();
212
373
  }
213
374
  }
375
+ ${RIG_CS}
376
+ ${VOICE_CS}
214
377
  }
215
378
  '@
216
379
 
@@ -219,10 +382,11 @@ function E($n) { $w.FindName($n) }
219
382
  $conv = New-Object Windows.Media.BrushConverter
220
383
  function Brush($hex) { $conv.ConvertFromString($hex) }
221
384
  function Img($file) { $b = New-Object Windows.Media.Imaging.BitmapImage; $b.BeginInit(); $b.UriSource = New-Object Uri (Join-Path $dir $file); $b.CacheOption = 'OnLoad'; $b.EndInit(); $b.Freeze(); $b }
222
- (E 'Body').Source = Img 'mascot.png'; (E 'PanelLogo').Source = Img 'logo.png'
385
+ ${Object.entries(BOT_LAYER_FILES).map(([el, file]) => `(E '${el}').Source = Img '${file}'`).join('; ')}; (E 'PanelLogo').Source = Img 'logo.png'
386
+ $script:rig = [AivinMascot.Rig]::new($w)
223
387
  $w.Title = $T.window_title; (E 'Mascot').ToolTip = $T.tooltip; (E 'PanelTitle').Text = $T.panel_title
224
388
  (E 'NowLabel').Text = $T.now_label; (E 'LogLabel').Text = $T.log_label; (E 'Empty').Text = $T.nothing_yet; (E 'NowText').Text = $T.ready
225
- (E 'HideBtn').Content = $T.hide; (E 'OffBtn').Content = $T.turn_off; (E 'PanelClose').ToolTip = $T.close
389
+ (E 'OffText').Text = $T.turn_off; (E 'PanelClose').ToolTip = $T.close
226
390
 
227
391
  # No focus stealing + no Alt+Tab entry; hidden from screen capture (AI screenshots, screen sharing).
228
392
  $w.Add_SourceInitialized({
@@ -230,43 +394,221 @@ $w.Add_SourceInitialized({
230
394
  $ex = [AivinMascot.Native]::GetWindowLong($h, -20)
231
395
  [void][AivinMascot.Native]::SetWindowLong($h, -20, ($ex -bor 0x08000000 -bor 0x00000080))
232
396
  if (-not $env:AIVIN_MASCOT_CAPTURABLE) { [void][AivinMascot.Native]::SetWindowDisplayAffinity($h, 0x11) }
397
+ $script:hwnd = $h
398
+ [AivinMascot.TopKeeper]::Start($h)
399
+ [AivinMascot.DisplayWatch]::Start($h, [Action]{ Dbg 'display changed'; Place })
400
+ [AivinMascot.DropSense]::Start((E 'DropZone'), (Brush '#01FFFFFF'))
233
401
  })
234
402
 
235
- # Anchor = screen point of the mascot center (DIPs); the window is laid out around it, kept on screen.
403
+ # Stay above the taskbar: TopKeeper re-asserts HWND_TOPMOST on every foreground change; this timer is the fallback for the shell
404
+ # raising itself without one (SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE - no focus change, no flicker).
405
+ $script:topTimer = New-Object Windows.Threading.DispatcherTimer; $script:topTimer.Interval = [TimeSpan]::FromMilliseconds(500)
406
+ $script:topTimer.Add_Tick({ if ($script:hwnd -and $w.IsVisible) { [AivinMascot.TopKeeper]::Raise() } })
407
+ $script:topTimer.Start()
408
+
409
+ # Anchor = screen point of the mascot center (DIPs). The window has a fixed size and only moves when the bot is dragged or the screens
410
+ # change: the bot sits at the anchor inside it, the boxes (ask box, bubble, activity panel) are laid out around the bot (ArrangeBoxes).
236
411
  $wa = [Windows.SystemParameters]::WorkArea
237
412
  $script:cx = if ($cfg.x -ne $null) { [double]$cfg.x } else { $wa.Right - 76 }
238
413
  $script:cy = if ($cfg.y -ne $null) { [double]$cfg.y } else { $wa.Bottom - 70 }
414
+ # Bot center inside the window (DIPs).
415
+ $script:mx = ${WINDOW.w / 2}; $script:my = ${WINDOW.h - ROOT_MARGIN - (MASCOT_BOX.h - MASCOT_CENTER.y)}
416
+ function DeviceScale {
417
+ $src = [Windows.PresentationSource]::FromVisual($w)
418
+ if ($src -and $src.CompositionTarget) { $src.CompositionTarget.TransformToDevice.M11 } else { 1 }
419
+ }
420
+ function Clamp($v, $lo, $hi) { [Math]::Max($lo, [Math]::Min($v, $hi)) }
239
421
  function Place {
240
- $vl = [Windows.SystemParameters]::VirtualScreenLeft; $vt = [Windows.SystemParameters]::VirtualScreenTop
241
- $vw = [Windows.SystemParameters]::VirtualScreenWidth; $vh = [Windows.SystemParameters]::VirtualScreenHeight
242
- $script:cx = [Math]::Max($vl + 40, [Math]::Min($script:cx, $vl + $vw - 40)); $script:cy = [Math]::Max($vt + 40, [Math]::Min($script:cy, $vt + $vh - 40))
243
- $side = if ($script:cx -gt $vl + $vw / 2) { 'Right' } else { 'Left' }
244
- foreach ($n in 'Panel', 'Bubble', 'Mascot') { (E $n).HorizontalAlignment = $side }
245
- foreach ($n in 'Tail', 'TailCover') { (E $n).HorizontalAlignment = $side }
246
- $tm = if ($side -eq 'Right') { '0,0,35,0' } else { '35,0,0,0' }; (E 'Tail').Margin = $tm
247
- (E 'TailCover').Margin = if ($side -eq 'Right') { '0,0,36,7' } else { '36,0,0,7' }
248
- $w.UpdateLayout()
249
- $p = (E 'Mascot').TranslatePoint((New-Object Windows.Point 42, 40), $w)
250
- $left = $script:cx - $p.X; $top = $script:cy - $p.Y
251
- $w.Left = [Math]::Max($vl, [Math]::Min($left, $vl + $vw - $w.ActualWidth))
252
- $w.Top = [Math]::Max($vt, [Math]::Min($top, $vt + $vh - $w.ActualHeight))
422
+ $k = DeviceScale
423
+ # The monitor the anchor is on (nearest one if it is on none): the bot stays whole on it, the window too.
424
+ $r = [AivinMascot.Native]::MonitorAt([int]($script:cx * $k), [int]($script:cy * $k))
425
+ if ($r) { $ml = $r[0] / $k; $mt = $r[1] / $k; $mr = $r[2] / $k; $mb = $r[3] / $k }
426
+ else {
427
+ $ml = [Windows.SystemParameters]::VirtualScreenLeft; $mt = [Windows.SystemParameters]::VirtualScreenTop
428
+ $mr = $ml + [Windows.SystemParameters]::VirtualScreenWidth; $mb = $mt + [Windows.SystemParameters]::VirtualScreenHeight
429
+ }
430
+ $script:cx = Clamp $script:cx ($ml + ${MASCOT_CENTER.x}) ($mr - ${MASCOT_BOX.w - MASCOT_CENTER.x})
431
+ $script:cy = Clamp $script:cy ($mt + ${MASCOT_CENTER.y}) ($mb - ${MASCOT_BOX.h - MASCOT_CENTER.y})
432
+ # Bot centered at the bottom of the window when there is room; near a screen edge the window stays on the monitor and the bot moves
433
+ # inside it instead. One SetWindowPos (device pixels) - setting Left then Top moved the window twice.
434
+ $px = [Math]::Round((Clamp ($script:cx - ${WINDOW.w / 2}) $ml ($mr - ${WINDOW.w})) * $k)
435
+ $py = [Math]::Round((Clamp ($script:cy - ${WINDOW.h - ROOT_MARGIN - (MASCOT_BOX.h - MASCOT_CENTER.y)}) $mt ($mb - ${WINDOW.h})) * $k)
436
+ if ($script:hwnd) { [void][AivinMascot.Native]::SetWindowPos($script:hwnd, [IntPtr]::Zero, [int]$px, [int]$py, 0, 0, 0x0015) }
437
+ else { $w.Left = $px / $k; $w.Top = $py / $k }
438
+ $script:mx = $script:cx - $px / $k; $script:my = $script:cy - $py / $k
439
+ $m = E 'Mascot'; [Windows.Controls.Canvas]::SetLeft($m, $script:mx - ${MASCOT_CENTER.x}); [Windows.Controls.Canvas]::SetTop($m, $script:my - ${MASCOT_CENTER.y})
440
+ $z = E 'DropZone'; [Windows.Controls.Canvas]::SetLeft($z, $script:mx - ${DROP_ZONE_R}); [Windows.Controls.Canvas]::SetTop($z, $script:my - ${DROP_ZONE_R})
441
+ Dbg "place anchor $($script:cx),$($script:cy) -> window $px,$py px (scale $k), bot at $($script:mx),$($script:my)"
442
+ ArrangeBoxes
253
443
  }
254
- $w.Add_SizeChanged({ Place })
444
+ # Boxes centered over the bot, kept inside the window (shadow margin). Not enough room above (bot near the top of the screen) -> below
445
+ # the bot: the gap to the bot (each box's margin), the bubble tail and the grow-in origin flipped to the top.
446
+ function ArrangeBoxes {
447
+ $b = E 'Boxes'; $bw = $b.ActualWidth; $bh = $b.ActualHeight
448
+ $top = $script:my - ${MASCOT_CENTER.y}; $bottom = $top + ${MASCOT_BOX.h}
449
+ $below = $bh -gt ($top - ${ROOT_MARGIN}) -and (${WINDOW.h - ROOT_MARGIN} - $bottom) -gt ($top - ${ROOT_MARGIN})
450
+ $left = Clamp ($script:mx - $bw / 2) ${ROOT_MARGIN} (${WINDOW.w - ROOT_MARGIN} - $bw)
451
+ [Windows.Controls.Canvas]::SetLeft($b, $left)
452
+ [Windows.Controls.Canvas]::SetTop($b, $(if ($below) { $bottom } else { $top - $bh }))
453
+ if ($below -ne $script:boxesBelow) {
454
+ $script:boxesBelow = $below
455
+ $origin = if ($below) { '0.5,0' } else { '0.5,1' }
456
+ foreach ($n in 'Panel', 'Ask', 'Bubble') { (E $n).RenderTransformOrigin = $origin }
457
+ $tail = E 'Tail'
458
+ $tail.VerticalAlignment = if ($below) { 'Top' } else { 'Bottom' }
459
+ $tail.RenderTransform = if ($below) { New-Object Windows.Media.ScaleTransform 1, -1 } else { [Windows.Media.Transform]::Identity }
460
+ (E 'Panel').Margin = if ($below) { '0,10,0,0' } else { '0,0,0,10' }
461
+ foreach ($n in 'Ask', 'BubbleBox') { (E $n).Margin = if ($below) { '0,7,0,0' } else { '0,0,0,7' } }
462
+ }
463
+ # The bubble tail points at the bot even when the bubble is pushed sideways by the window edge (centered + margin 2d = moved by d).
464
+ $d = $script:mx - ($left + $bw / 2)
465
+ (E 'Tail').Margin = if ($d -ge 0) { "$(2 * $d),0,0,0" } else { "0,0,$(-2 * $d),0" }
466
+ }
467
+ $script:boxesBelow = $false
468
+ # A box shown / hidden / grown: lay the boxes out again in the same layout pass (before the frame is drawn), the window stays put.
469
+ (E 'Boxes').Add_SizeChanged({ ArrangeBoxes })
255
470
 
256
471
  $script:state = 'idle'
472
+ $faceMap = ConvertFrom-Json '${JSON.stringify(BOT_FACES)}'
473
+ # Face changes morph in the rig (eyes squash shut + reopen, mouth pops) instead of cutting.
474
+ function SetFace($s) {
475
+ $f = $faceMap.$s; if (-not $f) { $f = $faceMap.idle }
476
+ $script:rig.SetFace([string]$f.eyes, [string]$f.mouth)
477
+ }
478
+ # Reactions picked from the state pair (the rig plays them, see rigSource.mjs): busy -> needs you = startle; done after an error in the
479
+ # last minutes = relief; done after long work = cheer, after a quick one = a nod. Busy time counts from the first working / thinking
480
+ # until done / error / idle (a question in between does not reset it).
481
+ $script:busySince = $null; $script:errorAt = [DateTime]::MinValue
482
+ function React($prev, $s) {
483
+ $now = Get-Date
484
+ $busyFor = if ($script:busySince) { ($now - $script:busySince).TotalSeconds } else { 0 }
485
+ if ($s -eq 'working' -or $s -eq 'thinking') { if (-not $script:busySince) { $script:busySince = $now } }
486
+ elseif ($s -ne 'waiting') { $script:busySince = $null }
487
+ if ($s -eq 'error') { $script:errorAt = $now }
488
+ if ($s -eq 'waiting' -and ($prev -eq 'working' -or $prev -eq 'thinking')) { $script:rig.Play('startle') }
489
+ elseif ($s -eq 'done') {
490
+ if (($now - $script:errorAt).TotalMinutes -lt 5) { $script:errorAt = [DateTime]::MinValue; PlayFace 'relief' 'relief' 1.3 }
491
+ elseif ($busyFor -ge 60) { PlayFace 'cheer' 'star' 2.2 }
492
+ elseif ($busyFor -gt 0 -and $busyFor -lt 10) { $script:rig.Play('small') }
493
+ }
494
+ }
257
495
  function SetState($s) {
258
496
  if (-not $P.$s) { return }
497
+ $prev = $script:state
498
+ if ($s -ne $prev) { Wake }
259
499
  $script:state = $s; $c = $P.$s
260
- (E 'Dot').Fill = Brush $c.fg; (E 'BubbleDot').Fill = Brush $c.fg
500
+ (E 'BubbleDot').Fill = Brush $c.fg
261
501
  (E 'Chip').Background = Brush $c.bg; (E 'ChipText').Foreground = Brush $c.fg; (E 'ChipText').Text = $T.('state_' + $s)
262
502
  $busy = $s -eq 'working' -or $s -eq 'thinking'
263
- if ($busy) { $w.FindResource('Pulse').Begin($w, $true); $w.FindResource('Look').Begin($w, $true) } else { $w.FindResource('Pulse').Stop($w); $w.FindResource('Look').Stop($w); (E 'Dot').Opacity = 1 }
264
- (E 'Lid').ScaleY = if ($s -eq 'idle' -or $s -eq 'paused' -or $s -eq 'offline') { 0.55 } else { 1 }
265
- (E 'PauseBtn').Content = if ($s -eq 'paused') { $T.resume } else { $T.pause }
266
- if ($s -eq 'done' -or $s -eq 'waiting') { $w.FindResource('Hop').Begin($w) }
503
+ if (-not ($script:rig.Hover -and -not $busy) -and -not $script:rig.Dozing) { SetFace $s }
504
+ $script:rig.SetState($s, $c.fg)
505
+ if ($s -ne $prev) { React $prev $s }
506
+ # The panel has no pause button any more (new chat session took its place): it only shows "let AI continue" while paused.
507
+ (E 'PauseBtn').Content = $T.resume; (E 'PauseBtn').Visibility = if ($s -eq 'paused') { 'Visible' } else { 'Collapsed' }
267
508
  if (-not $busy -and $s -ne 'waiting' -and (E 'Bubble').Visibility -eq 'Visible') { $script:bubbleTimer.Stop(); $script:bubbleTimer.Start() }
268
509
  }
269
510
 
511
+ # Pointer: the rig follows the cursor with its eyes on its own (anywhere near the bot). Hovering greets with a happy face and a lean-in.
512
+ function IsBusy { $script:state -eq 'working' -or $script:state -eq 'thinking' }
513
+ (E 'Mascot').Add_MouseEnter({ Wake; $script:rig.Hover = $true; if (-not (IsBusy) -and -not $script:rig.Dizzy) { if ((Get-Random -Minimum 0 -Maximum 10) -lt 3) { PlayFace 'wink' 'wink' 1.4 } else { SetFace 'hello' } } })
514
+
515
+ # Doze: idle for a long while with nobody around -> the bot nods off (closed eyes, zzz); new work or the pointer wakes it up.
516
+ $script:lastActive = Get-Date
517
+ function Wake { $script:lastActive = Get-Date; $script:yawned = $false; if ($script:rig.Dozing) { $script:rig.Doze($false); SetFace $script:state } }
518
+ $script:dozeTimer = New-Object Windows.Threading.DispatcherTimer; $script:dozeTimer.Interval = [TimeSpan]::FromSeconds(15)
519
+ $script:dozeTimer.Add_Tick({
520
+ if ($script:state -eq 'idle' -and -not $script:rig.Dozing -and -not $script:rig.Hover -and ((Get-Date) - $script:lastActive).TotalMinutes -ge ${MASCOT_DOZE_MIN}) {
521
+ # A yawn first, nodding off on the next tick (PlayFace would count as activity: keep the idle clock and the yawn flag).
522
+ if (-not $script:yawned) { $script:rig.Play('yawn'); SetFace 'yawn'; $script:faceTimer.Stop(); $script:faceTimer.Interval = [TimeSpan]::FromSeconds(2); $script:faceTimer.Start(); $script:yawned = $true }
523
+ else { $script:rig.Doze($true); SetFace 'offline' }
524
+ }
525
+ })
526
+ $script:dozeTimer.Start()
527
+ (E 'Mascot').Add_MouseLeave({ $script:rig.Hover = $false; if (-not $script:rig.Dizzy) { SetFace $script:state } })
528
+
529
+ # Play: a one-shot face for a reaction, then back to the normal face (hello while hovered and free, else the state's face).
530
+ $script:faceTimer = New-Object Windows.Threading.DispatcherTimer
531
+ $script:faceTimer.Add_Tick({ $script:faceTimer.Stop(); SetFace $(if ($script:rig.Hover -and -not (IsBusy)) { 'hello' } else { $script:state }) })
532
+ function PlayFace($gesture, $face, $sec) {
533
+ Wake; $script:rig.Play($gesture); SetFace $face
534
+ $script:faceTimer.Stop(); $script:faceTimer.Interval = [TimeSpan]::FromSeconds($sec); $script:faceTimer.Start()
535
+ }
536
+ # Petting: the pointer rubs back and forth over the bot (no button) -> it leans in, eyes closed happily, antenna wagging.
537
+ $script:pet = @{ x = $null; dir = 0; flips = 0; at = Get-Date }
538
+ (E 'Mascot').Add_MouseMove({ param($s, $e)
539
+ if ($script:drag -or $script:rig.Dizzy) { return }
540
+ $p = $script:pet; $x = $e.GetPosition($w).X
541
+ if ($p.x -eq $null) { $p.x = $x; return }
542
+ $dx = $x - $p.x; if ([Math]::Abs($dx) -lt 6) { return }
543
+ $p.x = $x; $dir = [Math]::Sign($dx)
544
+ if (((Get-Date) - $p.at).TotalSeconds -gt 0.6) { $p.flips = 0 }
545
+ $p.at = Get-Date
546
+ if ($p.dir -and $dir -ne $p.dir) { $p.flips++ }
547
+ $p.dir = $dir
548
+ if ($p.flips -ge 4 -and -not (IsBusy)) { PlayFace 'purr' 'purr' 1.2 }
549
+ })
550
+
551
+ # The user is away (no input for a while) / back -> the daemon sums up what happened meanwhile.
552
+ $script:away = $false
553
+ $script:awayTimer = New-Object Windows.Threading.DispatcherTimer; $script:awayTimer.Interval = [TimeSpan]::FromSeconds(5)
554
+ $script:awayTimer.Add_Tick({
555
+ $idle = [AivinMascot.Native]::IdleSeconds()
556
+ if (-not $script:away -and $idle -ge ${MASCOT_AWAY_MIN * 60}) { $script:away = $true; Send @{ t = 'away' } }
557
+ elseif ($script:away -and $idle -lt 5) { $script:away = $false; Send @{ t = 'back' } }
558
+ })
559
+ $script:awayTimer.Start()
560
+
561
+ # Drop files / folders on the bot, the zone around it or the ask box -> they ride along with the next question. Dragged near the bot: it
562
+ # holds up the tray (lid open, wide-eyed "ooh", a hint bubble naming what comes); the tray is full -> lid shut, head shake. Dropped: the
563
+ # tray gulps them and stays in the bot's arms with the number of files waiting (ask_files from the daemon) until the question goes out.
564
+ # Handlers on the window (every part of the mascot, handled events too - the text box marks file drags handled); moving between its
565
+ # parts fires leave + enter, so a leave only counts once nothing re-entered for a moment.
566
+ $script:files = 0; $script:dragFiles = $null; $script:hinting = $false
567
+ function HasFiles($e) { $e.Data.GetDataPresent([Windows.DataFormats]::FileDrop) }
568
+ function TrayFull { $script:files -ge [int]$cfg.max_files }
569
+ function TrayRest { $script:rig.Tray($(if ($script:files -gt 0) { 'hold' } else { 'off' }), $script:files) }
570
+ # The hint bubble while files hover (not the activity text: NowText stays); gone when they leave or drop.
571
+ function DropHint($text) {
572
+ if ($text) {
573
+ if ((E 'Panel').Visibility -eq 'Visible') { return }
574
+ (E 'BubbleText').Text = $text; $script:hinting = $true; $script:bubbleTimer.Stop()
575
+ $b = E 'Bubble'; if ($b.Visibility -ne 'Visible') { $b.Visibility = 'Visible'; $w.FindResource('BubbleIn').Begin($b) }
576
+ } elseif ($script:hinting) { $script:hinting = $false; HideBubble }
577
+ }
578
+ function DragEnd { $script:dragFiles = $null; $script:rig.Hover = $false; DropHint $null; TrayRest; if (-not $script:rig.Dizzy) { SetFace $script:state } }
579
+ $script:dragLeaveTimer = New-Object Windows.Threading.DispatcherTimer; $script:dragLeaveTimer.Interval = [TimeSpan]::FromMilliseconds(140)
580
+ $script:dragLeaveTimer.Add_Tick({ $script:dragLeaveTimer.Stop(); DragEnd })
581
+ $w.AllowDrop = $true
582
+ $w.AddHandler([Windows.DragDrop]::DragEnterEvent, [Windows.DragEventHandler]{ param($s, $e)
583
+ $script:dragLeaveTimer.Stop()
584
+ if ($script:dragFiles -or -not (HasFiles $e)) { return }
585
+ $script:dragFiles = @(@($e.Data.GetData([Windows.DataFormats]::FileDrop)) | ForEach-Object { [string]$_ })
586
+ Wake; $script:rig.Hover = $true
587
+ if (TrayFull) { $script:rig.Tray('deny', $script:files); SetFace 'error'; DropHint ($T.drop_full.Replace('{n}', [string]$cfg.max_files)) }
588
+ else {
589
+ $script:rig.Tray('open', $script:files); SetFace 'waiting'
590
+ $one = $script:dragFiles.Count -eq 1
591
+ $name = if ($one) { [IO.Path]::GetFileName($script:dragFiles[0].TrimEnd('\', '/')) } else { '' }
592
+ DropHint $(if ($one) { $T.drop_one.Replace('{name}', $name) } else { $T.drop_many.Replace('{n}', [string]$script:dragFiles.Count) })
593
+ }
594
+ }, $true)
595
+ $w.AddHandler([Windows.DragDrop]::DragOverEvent, [Windows.DragEventHandler]{ param($s, $e)
596
+ $e.Effects = if ((HasFiles $e) -and -not (TrayFull)) { 'Copy' } else { 'None' }; $e.Handled = $true
597
+ }, $true)
598
+ $w.AddHandler([Windows.DragDrop]::DragLeaveEvent, [Windows.DragEventHandler]{ param($s, $e) if ($script:dragFiles) { $script:dragLeaveTimer.Stop(); $script:dragLeaveTimer.Start() } }, $true)
599
+ $w.AddHandler([Windows.DragDrop]::DropEvent, [Windows.DragEventHandler]{ param($s, $e)
600
+ $script:dragLeaveTimer.Stop()
601
+ if (-not (HasFiles $e) -or (TrayFull)) { DragEnd; return }
602
+ $files = @(@($e.Data.GetData([Windows.DataFormats]::FileDrop)) | ForEach-Object { [string]$_ })
603
+ $e.Handled = $true
604
+ Send @{ t = 'drop'; files = $files }
605
+ # The count until the daemon confirms it (ask_files: duplicates / over the limit dropped).
606
+ $script:files = [Math]::Min($script:files + $files.Count, [int]$cfg.max_files)
607
+ $script:dragFiles = $null; $script:rig.Hover = $false; DropHint $null
608
+ $script:rig.Tray('hold', $script:files); PlayFace 'gulp' 'hello' 1.4
609
+ if (Get-Command OpenAsk -ErrorAction SilentlyContinue) { OpenAsk }
610
+ }, $true)
611
+
270
612
  $script:bubbleTimer = New-Object Windows.Threading.DispatcherTimer; $script:bubbleTimer.Interval = [TimeSpan]::FromSeconds(7)
271
613
  $script:bubbleTimer.Add_Tick({ $script:bubbleTimer.Stop(); HideBubble })
272
614
  function HideBubble {
@@ -320,31 +662,83 @@ function TogglePanel {
320
662
  $script:userHidden = $false; $script:guiHidden = $false
321
663
  function ApplyVisibility { $w.Visibility = if ($script:userHidden -or $script:guiHidden) { 'Hidden' } else { 'Visible' } }
322
664
 
323
- # Drag to move, click to open / collapse the activity panel (DragMove returns on mouse up; no movement = click).
665
+ # Let the mascot leave the screen before destroying its host. The guard matters because the quit command and closed stdin can arrive
666
+ # in the same pump tick.
667
+ $script:closing = $false
668
+ function CloseAnimated {
669
+ if ($script:closing) { return }
670
+ $script:closing = $true; $w.IsHitTestVisible = $false; $pump.Stop()
671
+ $sb = $w.FindResource('WindowOut').Clone()
672
+ $sb.Add_Completed({ $w.Close() })
673
+ $sb.Begin($w)
674
+ }
675
+
676
+ # Drag to move, click to open / collapse the activity panel. Own drag loop (mouse capture + screen DIPs): Window.DragMove on a
677
+ # no-activate window jumped the window on a plain click and swallowed the click.
678
+ $script:drag = $null
679
+ function ScreenDip($e) {
680
+ $p = $w.PointToScreen($e.GetPosition($w)); $m = [Windows.PresentationSource]::FromVisual($w).CompositionTarget.TransformToDevice
681
+ New-Object Windows.Point ($p.X / $m.M11), ($p.Y / $m.M22)
682
+ }
683
+ function SendPos { Send @{ t = 'pos'; x = [int]$script:cx; y = [int]$script:cy } }
324
684
  (E 'Mascot').Add_MouseLeftButtonDown({ param($s, $e)
325
- $l0 = $w.Left; $t0 = $w.Top
326
- try { $w.DragMove() } catch { }
327
- $dx = $w.Left - $l0; $dy = $w.Top - $t0
328
- if ([Math]::Abs($dx) + [Math]::Abs($dy) -lt 4) { TogglePanel }
329
- else { $script:cx += $dx; $script:cy += $dy; Place; Send @{ t = 'pos'; x = [int]$script:cx; y = [int]$script:cy } }
685
+ $script:drag = @{ start = (ScreenDip $e); cx = $script:cx; cy = $script:cy; moved = $false }
686
+ $script:rig.Pressed = $true
687
+ $ok = (E 'Mascot').CaptureMouse(); Dbg "down at $($script:drag.start) anchor $($script:cx),$($script:cy) capture=$ok"; $e.Handled = $true
688
+ })
689
+ (E 'Mascot').Add_MouseMove({ param($s, $e)
690
+ $d = $script:drag; if (-not $d) { return }
691
+ $p = ScreenDip $e; $dx = $p.X - $d.start.X; $dy = $p.Y - $d.start.Y
692
+ if (-not $d.moved -and [Math]::Abs($dx) + [Math]::Abs($dy) -lt 5) { return }
693
+ if (-not $d.moved) { Dbg "drag starts d=$dx,$dy"; $script:rig.Pressed = $false; $script:rig.Dragging = $true }
694
+ $px = $script:cx; $py = $script:cy
695
+ $d.moved = $true; $script:cx = $d.cx + $dx; $script:cy = $d.cy + $dy; Place
696
+ $script:rig.Nudge($script:cx - $px, $script:cy - $py)
697
+ # Shaken back and forth while dragged -> dizzy when let go.
698
+ $step = $script:cx - $px
699
+ if ([Math]::Abs($step) -ge 4) { $sg = [Math]::Sign($step); if ($d.sg -and $sg -ne $d.sg) { $d.flips++ }; $d.sg = $sg }
700
+ })
701
+ (E 'Mascot').Add_MouseLeftButtonUp({ param($s, $e)
702
+ $d = $script:drag; $script:drag = $null; $script:rig.Pressed = $false; $script:rig.Dragging = $false; (E 'Mascot').ReleaseMouseCapture()
703
+ Dbg "up drag=$([bool]$d) moved=$($d.moved) anchor $($script:cx),$($script:cy)"
704
+ if (-not $d) { return }
705
+ if ($d.moved) { SendPos; if ($d.flips -ge 4) { PlayFace 'dizzy' 'dizzy' 2.6 } }
706
+ elseif (QuickClicks) { PlayFace 'giggle' 'hello' 1.1; if (Get-Command CloseAsk -ErrorAction SilentlyContinue) { CloseAsk } }
707
+ else { MascotClick }
330
708
  $e.Handled = $true
331
709
  })
710
+ # Three quick clicks = tickled: a giggle instead of opening / closing the box again.
711
+ $script:clicks = @()
712
+ function QuickClicks {
713
+ $now = Get-Date
714
+ $script:clicks = @($script:clicks | Where-Object { ($now - $_).TotalSeconds -lt 1.2 }) + $now
715
+ if ($script:clicks.Count -lt 3) { return $false }
716
+ $script:clicks = @(); return $true
717
+ }
718
+ # Click on the bot: the activity panel by default; the ask box (askHostSource.mjs, inserted at @ASK_HOOK) redefines it.
719
+ function MascotClick { TogglePanel }
720
+ (E 'Mascot').Add_LostMouseCapture({ $d = $script:drag; $script:drag = $null; $script:rig.Pressed = $false; $script:rig.Dragging = $false; Dbg "lost capture drag=$([bool]$d)"; if ($d -and $d.moved) { SendPos } })
332
721
  (E 'PanelClose').Add_Click({ TogglePanel })
333
722
  (E 'PauseBtn').Add_Click({ if ($script:state -eq 'paused') { Send @{ t = 'resume' } } else { Send @{ t = 'pause' } } })
334
- (E 'HideBtn').Add_Click({ $script:userHidden = $true; ApplyVisibility; Send @{ t = 'hide' } })
335
723
  (E 'OffBtn').Add_Click({ Send @{ t = 'off' } })
336
724
 
337
725
  function Handle($m) {
726
+ if ($env:AIVIN_MASCOT_DEBUG) { Dbg "recv $($m.t) $($m.state)$($m.text)$($m.title)" }
338
727
  switch ($m.t) {
339
728
  'state' { SetState $m.state }
340
729
  'main' { if ($m.quiet) { (E 'NowText').Text = $m.text } else { ShowBubble $m.text } }
341
730
  'log' { LogEntry $m }
342
731
  'gui' { $script:guiHidden = [bool]$m.active; ApplyVisibility }
343
732
  'show' { $script:userHidden = $false; ApplyVisibility }
344
- 'quit' { $w.Close() }
733
+ # Daemon-driven reaction, e.g. 'wave' when the user comes back.
734
+ 'gesture' { if (-not (IsBusy)) { PlayFace ([string]$m.g) 'hello' 1.6 } else { $script:rig.Play([string]$m.g) } }
735
+ # Files dropped on the bot still waiting for the next question (0 = sent / cleared): the tray in the bot's arms + its badge.
736
+ 'ask_files' { $script:files = [int]$m.n; if (-not $script:dragFiles) { TrayRest } }
737
+ 'quit' { CloseAnimated }
345
738
  }
346
739
  }
347
740
 
741
+ # @ASK_HOOK
348
742
  # Commands arrive as JSON lines on stdin (background thread -> queue); the UI drains the queue. stdin closed = daemon gone -> close.
349
743
  [AivinMascot.Input]::Start()
350
744
  $pump = New-Object Windows.Threading.DispatcherTimer; $pump.Interval = [TimeSpan]::FromMilliseconds(80)
@@ -353,9 +747,12 @@ $pump.Add_Tick({
353
747
  while ([AivinMascot.Input]::Lines.TryDequeue([ref]$line)) {
354
748
  if ($line) { try { Handle ($line | ConvertFrom-Json) } catch { [Console]::Error.WriteLine($_.Exception.Message) } }
355
749
  }
356
- if ([AivinMascot.Input]::Closed -and [AivinMascot.Input]::Lines.IsEmpty) { $pump.Stop(); $w.Close() }
750
+ if ([AivinMascot.Input]::Closed -and [AivinMascot.Input]::Lines.IsEmpty) { CloseAnimated }
751
+ })
752
+ $w.Add_ContentRendered({
753
+ SetState 'idle'; Place; $w.FindResource('WindowIn').Begin($w); $script:rig.Start(); $script:rig.Intro(); $pump.Start(); Send @{ t = 'ready' }
357
754
  })
358
- $w.Add_ContentRendered({ SetState 'idle'; Place; $w.FindResource('WindowIn').Begin($w); $pump.Start(); Send @{ t = 'ready' } })
755
+ $w.Add_Closed({ $script:rig.Stop() })
359
756
  $app = New-Object Windows.Application
360
757
  $app.ShutdownMode = 'OnMainWindowClose'
361
758
  [void]$app.Run($w)