@myrialabs/clopen 0.2.16 → 0.2.17

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 (286) hide show
  1. package/.env.example +4 -4
  2. package/backend/utils/env.ts +5 -5
  3. package/bin/clopen.ts +21 -298
  4. package/dist/assets/addon-clipboard-wHJhZAA4.js +1 -0
  5. package/dist/assets/addon-fit-DX4qG4td.js +1 -0
  6. package/dist/assets/addon-ligatures-DpDY8N_X.js +2 -0
  7. package/dist/assets/addon-unicode11-Bt8F3D7-.js +7 -0
  8. package/dist/assets/addon-web-links-DIbG5aQx.js +1 -0
  9. package/dist/assets/index-C-eR9PGW.js +2 -0
  10. package/dist/assets/main-D1IISCsM.js +247 -0
  11. package/dist/assets/main-DzSwlujO.css +1 -0
  12. package/dist/assets/xterm-B-qIQCd3.js +16 -0
  13. package/{index.html → dist/index.html} +2 -1
  14. package/package.json +11 -2
  15. package/scripts/start.ts +3 -3
  16. package/shared/utils/logger.ts +1 -1
  17. package/.dockerignore +0 -5
  18. package/.github/workflows/ci.yml +0 -86
  19. package/CONTRIBUTING.md +0 -188
  20. package/bun.lock +0 -1127
  21. package/docker-compose.yml +0 -31
  22. package/frontend/App.svelte +0 -77
  23. package/frontend/app-environment.ts +0 -10
  24. package/frontend/app.css +0 -313
  25. package/frontend/components/auth/InvitePage.svelte +0 -215
  26. package/frontend/components/auth/LoginPage.svelte +0 -129
  27. package/frontend/components/auth/SetupPage.svelte +0 -1054
  28. package/frontend/components/chat/ChatInterface.svelte +0 -426
  29. package/frontend/components/chat/formatters/ErrorMessage.svelte +0 -57
  30. package/frontend/components/chat/formatters/MessageFormatter.svelte +0 -244
  31. package/frontend/components/chat/formatters/TextMessage.svelte +0 -383
  32. package/frontend/components/chat/formatters/Tools.svelte +0 -79
  33. package/frontend/components/chat/formatters/index.ts +0 -3
  34. package/frontend/components/chat/input/ChatInput.svelte +0 -492
  35. package/frontend/components/chat/input/components/ChatInputActions.svelte +0 -88
  36. package/frontend/components/chat/input/components/DragDropOverlay.svelte +0 -30
  37. package/frontend/components/chat/input/components/EditModeIndicator.svelte +0 -33
  38. package/frontend/components/chat/input/components/EngineModelPicker.svelte +0 -642
  39. package/frontend/components/chat/input/components/FileAttachmentPreview.svelte +0 -48
  40. package/frontend/components/chat/input/components/LoadingIndicator.svelte +0 -43
  41. package/frontend/components/chat/input/composables/use-animations.svelte.ts +0 -217
  42. package/frontend/components/chat/input/composables/use-chat-actions.svelte.ts +0 -152
  43. package/frontend/components/chat/input/composables/use-file-handling.svelte.ts +0 -216
  44. package/frontend/components/chat/input/composables/use-input-state.svelte.ts +0 -357
  45. package/frontend/components/chat/input/composables/use-textarea-resize.svelte.ts +0 -69
  46. package/frontend/components/chat/message/ChatMessage.svelte +0 -509
  47. package/frontend/components/chat/message/ChatMessages.svelte +0 -553
  48. package/frontend/components/chat/message/DateSeparator.svelte +0 -86
  49. package/frontend/components/chat/message/MessageBubble.svelte +0 -114
  50. package/frontend/components/chat/message/MessageHeader.svelte +0 -143
  51. package/frontend/components/chat/modal/DebugModal.svelte +0 -59
  52. package/frontend/components/chat/shared/index.ts +0 -2
  53. package/frontend/components/chat/shared/utils.ts +0 -116
  54. package/frontend/components/chat/tools/AgentTool.svelte +0 -96
  55. package/frontend/components/chat/tools/AskUserQuestionTool.svelte +0 -391
  56. package/frontend/components/chat/tools/BashOutputTool.svelte +0 -35
  57. package/frontend/components/chat/tools/BashTool.svelte +0 -51
  58. package/frontend/components/chat/tools/CustomMcpTool.svelte +0 -141
  59. package/frontend/components/chat/tools/EditTool.svelte +0 -48
  60. package/frontend/components/chat/tools/EnterPlanModeTool.svelte +0 -24
  61. package/frontend/components/chat/tools/ExitPlanModeTool.svelte +0 -29
  62. package/frontend/components/chat/tools/GlobTool.svelte +0 -51
  63. package/frontend/components/chat/tools/GrepTool.svelte +0 -90
  64. package/frontend/components/chat/tools/ListMcpResourcesTool.svelte +0 -31
  65. package/frontend/components/chat/tools/NotebookEditTool.svelte +0 -38
  66. package/frontend/components/chat/tools/ReadMcpResourceTool.svelte +0 -34
  67. package/frontend/components/chat/tools/ReadTool.svelte +0 -41
  68. package/frontend/components/chat/tools/SkillTool.svelte +0 -21
  69. package/frontend/components/chat/tools/TaskStopTool.svelte +0 -26
  70. package/frontend/components/chat/tools/TaskTool.svelte +0 -64
  71. package/frontend/components/chat/tools/TodoWriteTool.svelte +0 -75
  72. package/frontend/components/chat/tools/WebFetchTool.svelte +0 -35
  73. package/frontend/components/chat/tools/WebSearchTool.svelte +0 -84
  74. package/frontend/components/chat/tools/WriteTool.svelte +0 -33
  75. package/frontend/components/chat/tools/components/CodeBlock.svelte +0 -79
  76. package/frontend/components/chat/tools/components/DiffBlock.svelte +0 -408
  77. package/frontend/components/chat/tools/components/FileHeader.svelte +0 -59
  78. package/frontend/components/chat/tools/components/InfoLine.svelte +0 -19
  79. package/frontend/components/chat/tools/components/StatsBadges.svelte +0 -27
  80. package/frontend/components/chat/tools/components/TerminalCommand.svelte +0 -61
  81. package/frontend/components/chat/tools/components/index.ts +0 -7
  82. package/frontend/components/chat/tools/index.ts +0 -30
  83. package/frontend/components/chat/widgets/ContextIndicator.svelte +0 -186
  84. package/frontend/components/chat/widgets/FloatingTodoList.svelte +0 -367
  85. package/frontend/components/checkpoint/ConflictResolutionModal.svelte +0 -189
  86. package/frontend/components/checkpoint/TimelineModal.svelte +0 -447
  87. package/frontend/components/checkpoint/timeline/TimelineEdge.svelte +0 -26
  88. package/frontend/components/checkpoint/timeline/TimelineGraph.svelte +0 -87
  89. package/frontend/components/checkpoint/timeline/TimelineNode.svelte +0 -119
  90. package/frontend/components/checkpoint/timeline/TimelineVersionGroup.svelte +0 -59
  91. package/frontend/components/checkpoint/timeline/animation.ts +0 -168
  92. package/frontend/components/checkpoint/timeline/config.ts +0 -44
  93. package/frontend/components/checkpoint/timeline/graph-builder.ts +0 -304
  94. package/frontend/components/checkpoint/timeline/types.ts +0 -69
  95. package/frontend/components/checkpoint/timeline/utils.ts +0 -53
  96. package/frontend/components/common/display/AvatarBubble.svelte +0 -56
  97. package/frontend/components/common/display/Button.svelte +0 -71
  98. package/frontend/components/common/display/Card.svelte +0 -102
  99. package/frontend/components/common/display/Icon.svelte +0 -58
  100. package/frontend/components/common/display/PageTemplate.svelte +0 -76
  101. package/frontend/components/common/display/ProjectUserAvatars.svelte +0 -79
  102. package/frontend/components/common/display/ThemeToggle.svelte +0 -44
  103. package/frontend/components/common/editor/MonacoEditor.svelte +0 -583
  104. package/frontend/components/common/feedback/Alert.svelte +0 -139
  105. package/frontend/components/common/feedback/ConnectionBanner.svelte +0 -55
  106. package/frontend/components/common/feedback/LoadingScreen.svelte +0 -52
  107. package/frontend/components/common/feedback/LoadingSpinner.svelte +0 -48
  108. package/frontend/components/common/feedback/NotificationToast.svelte +0 -128
  109. package/frontend/components/common/feedback/RestartRequiredModal.svelte +0 -53
  110. package/frontend/components/common/feedback/UpdateBanner.svelte +0 -99
  111. package/frontend/components/common/form/Checkbox.svelte +0 -48
  112. package/frontend/components/common/form/FolderBrowser.svelte +0 -856
  113. package/frontend/components/common/form/Input.svelte +0 -72
  114. package/frontend/components/common/form/ModelSelector.svelte +0 -110
  115. package/frontend/components/common/form/Select.svelte +0 -98
  116. package/frontend/components/common/form/Textarea.svelte +0 -80
  117. package/frontend/components/common/lucide-icons.ts +0 -1642
  118. package/frontend/components/common/material-icons.ts +0 -1082
  119. package/frontend/components/common/media/MediaPreview.svelte +0 -187
  120. package/frontend/components/common/overlay/Dialog.svelte +0 -251
  121. package/frontend/components/common/overlay/Lightbox.svelte +0 -233
  122. package/frontend/components/common/overlay/Modal.svelte +0 -177
  123. package/frontend/components/common/overlay/ModalProvider.svelte +0 -28
  124. package/frontend/components/common/xterm/XTerm.svelte +0 -743
  125. package/frontend/components/common/xterm/index.ts +0 -16
  126. package/frontend/components/common/xterm/terminal-config.ts +0 -68
  127. package/frontend/components/common/xterm/types.ts +0 -32
  128. package/frontend/components/common/xterm/xterm-service.ts +0 -437
  129. package/frontend/components/files/FileNode.svelte +0 -327
  130. package/frontend/components/files/FileTree.svelte +0 -690
  131. package/frontend/components/files/FileViewer.svelte +0 -551
  132. package/frontend/components/files/SearchResults.svelte +0 -303
  133. package/frontend/components/git/BranchManager.svelte +0 -446
  134. package/frontend/components/git/ChangesSection.svelte +0 -196
  135. package/frontend/components/git/CommitForm.svelte +0 -128
  136. package/frontend/components/git/ConflictResolver.svelte +0 -158
  137. package/frontend/components/git/DiffViewer.svelte +0 -298
  138. package/frontend/components/git/FileChangeItem.svelte +0 -119
  139. package/frontend/components/git/GitButton.svelte +0 -33
  140. package/frontend/components/git/GitLog.svelte +0 -401
  141. package/frontend/components/git/GitModal.svelte +0 -80
  142. package/frontend/components/history/HistoryModal.svelte +0 -602
  143. package/frontend/components/history/HistoryView.svelte +0 -561
  144. package/frontend/components/index.ts +0 -34
  145. package/frontend/components/preview/browser/BrowserPreview.svelte +0 -558
  146. package/frontend/components/preview/browser/components/Canvas.svelte +0 -1523
  147. package/frontend/components/preview/browser/components/ConsolePanel.svelte +0 -757
  148. package/frontend/components/preview/browser/components/Container.svelte +0 -507
  149. package/frontend/components/preview/browser/components/ContextMenu.svelte +0 -236
  150. package/frontend/components/preview/browser/components/SelectDropdown.svelte +0 -224
  151. package/frontend/components/preview/browser/components/Toolbar.svelte +0 -358
  152. package/frontend/components/preview/browser/components/VirtualCursor.svelte +0 -36
  153. package/frontend/components/preview/browser/core/cleanup.svelte.ts +0 -155
  154. package/frontend/components/preview/browser/core/coordinator.svelte.ts +0 -885
  155. package/frontend/components/preview/browser/core/interactions.svelte.ts +0 -113
  156. package/frontend/components/preview/browser/core/mcp-handlers.svelte.ts +0 -331
  157. package/frontend/components/preview/browser/core/native-ui-handlers.svelte.ts +0 -391
  158. package/frontend/components/preview/browser/core/stream-handler.svelte.ts +0 -288
  159. package/frontend/components/preview/browser/core/tab-manager.svelte.ts +0 -210
  160. package/frontend/components/preview/browser/core/tab-operations.svelte.ts +0 -241
  161. package/frontend/components/preview/index.ts +0 -2
  162. package/frontend/components/settings/SettingsModal.svelte +0 -268
  163. package/frontend/components/settings/SettingsView.svelte +0 -54
  164. package/frontend/components/settings/account/AccountSettings.svelte +0 -5
  165. package/frontend/components/settings/admin/InviteManagement.svelte +0 -239
  166. package/frontend/components/settings/admin/UserManagement.svelte +0 -127
  167. package/frontend/components/settings/appearance/AppearanceSettings.svelte +0 -104
  168. package/frontend/components/settings/appearance/LayoutPresetSettings.svelte +0 -160
  169. package/frontend/components/settings/appearance/LayoutPreview.svelte +0 -76
  170. package/frontend/components/settings/engines/AIEnginesSettings.svelte +0 -917
  171. package/frontend/components/settings/general/AdvancedSettings.svelte +0 -193
  172. package/frontend/components/settings/general/AuthModeSettings.svelte +0 -229
  173. package/frontend/components/settings/general/DataManagementSettings.svelte +0 -89
  174. package/frontend/components/settings/general/GeneralSettings.svelte +0 -20
  175. package/frontend/components/settings/general/UpdateSettings.svelte +0 -130
  176. package/frontend/components/settings/git/GitSettings.svelte +0 -392
  177. package/frontend/components/settings/model/EngineModelPicker.svelte +0 -284
  178. package/frontend/components/settings/model/ModelSettings.svelte +0 -240
  179. package/frontend/components/settings/notifications/NotificationSettings.svelte +0 -205
  180. package/frontend/components/settings/security/SecuritySettings.svelte +0 -10
  181. package/frontend/components/settings/system/SystemSettings.svelte +0 -10
  182. package/frontend/components/settings/tunnel/TunnelSettings.svelte +0 -1060
  183. package/frontend/components/settings/user/UserSettings.svelte +0 -270
  184. package/frontend/components/terminal/Terminal.svelte +0 -338
  185. package/frontend/components/terminal/TerminalTabs.svelte +0 -88
  186. package/frontend/components/terminal/TerminalView.svelte +0 -55
  187. package/frontend/components/tunnel/TunnelActive.svelte +0 -218
  188. package/frontend/components/tunnel/TunnelButton.svelte +0 -60
  189. package/frontend/components/tunnel/TunnelInactive.svelte +0 -260
  190. package/frontend/components/tunnel/TunnelModal.svelte +0 -101
  191. package/frontend/components/tunnel/TunnelQRCode.svelte +0 -49
  192. package/frontend/components/workspace/DesktopNavigator.svelte +0 -445
  193. package/frontend/components/workspace/MobileNavigator.svelte +0 -427
  194. package/frontend/components/workspace/PanelContainer.svelte +0 -100
  195. package/frontend/components/workspace/PanelHeader.svelte +0 -664
  196. package/frontend/components/workspace/ViewMenu.svelte +0 -146
  197. package/frontend/components/workspace/WorkspaceLayout.svelte +0 -199
  198. package/frontend/components/workspace/layout/DesktopLayout.svelte +0 -15
  199. package/frontend/components/workspace/layout/MobileLayout.svelte +0 -17
  200. package/frontend/components/workspace/layout/split-pane/Container.svelte +0 -42
  201. package/frontend/components/workspace/layout/split-pane/Handle.svelte +0 -85
  202. package/frontend/components/workspace/layout/split-pane/Layout.svelte +0 -62
  203. package/frontend/components/workspace/panels/ChatPanel.svelte +0 -282
  204. package/frontend/components/workspace/panels/FilesPanel.svelte +0 -1376
  205. package/frontend/components/workspace/panels/GitPanel.svelte +0 -1601
  206. package/frontend/components/workspace/panels/PreviewPanel.svelte +0 -153
  207. package/frontend/components/workspace/panels/TerminalPanel.svelte +0 -73
  208. package/frontend/main.ts +0 -17
  209. package/frontend/services/chat/chat.service.ts +0 -975
  210. package/frontend/services/chat/index.ts +0 -7
  211. package/frontend/services/favicon.service.ts +0 -103
  212. package/frontend/services/notification/global-stream-monitor.ts +0 -120
  213. package/frontend/services/notification/index.ts +0 -8
  214. package/frontend/services/notification/push.service.ts +0 -144
  215. package/frontend/services/notification/sound.service.ts +0 -127
  216. package/frontend/services/preview/browser/browser-console.service.ts +0 -61
  217. package/frontend/services/preview/browser/browser-webcodecs.service.ts +0 -1643
  218. package/frontend/services/preview/browser/mcp-integration.svelte.ts +0 -67
  219. package/frontend/services/preview/index.ts +0 -23
  220. package/frontend/services/project/index.ts +0 -8
  221. package/frontend/services/project/status.service.ts +0 -170
  222. package/frontend/services/snapshot/snapshot.service.ts +0 -86
  223. package/frontend/services/terminal/background/index.ts +0 -130
  224. package/frontend/services/terminal/background/session-restore.ts +0 -274
  225. package/frontend/services/terminal/background/stream-manager.ts +0 -286
  226. package/frontend/services/terminal/index.ts +0 -14
  227. package/frontend/services/terminal/persistence.service.ts +0 -260
  228. package/frontend/services/terminal/project.service.ts +0 -1004
  229. package/frontend/services/terminal/session.service.ts +0 -364
  230. package/frontend/services/terminal/terminal.service.ts +0 -379
  231. package/frontend/stores/core/app.svelte.ts +0 -296
  232. package/frontend/stores/core/files.svelte.ts +0 -87
  233. package/frontend/stores/core/presence.svelte.ts +0 -128
  234. package/frontend/stores/core/projects.svelte.ts +0 -325
  235. package/frontend/stores/core/sessions.svelte.ts +0 -452
  236. package/frontend/stores/features/auth.svelte.ts +0 -336
  237. package/frontend/stores/features/claude-accounts.svelte.ts +0 -58
  238. package/frontend/stores/features/models.svelte.ts +0 -89
  239. package/frontend/stores/features/settings.svelte.ts +0 -151
  240. package/frontend/stores/features/terminal.svelte.ts +0 -747
  241. package/frontend/stores/features/tunnel-config.svelte.ts +0 -205
  242. package/frontend/stores/features/tunnel.svelte.ts +0 -277
  243. package/frontend/stores/features/user.svelte.ts +0 -54
  244. package/frontend/stores/ui/chat-input.svelte.ts +0 -57
  245. package/frontend/stores/ui/chat-model.svelte.ts +0 -61
  246. package/frontend/stores/ui/connection.svelte.ts +0 -40
  247. package/frontend/stores/ui/dialog.svelte.ts +0 -59
  248. package/frontend/stores/ui/edit-mode.svelte.ts +0 -214
  249. package/frontend/stores/ui/notification.svelte.ts +0 -169
  250. package/frontend/stores/ui/settings-modal.svelte.ts +0 -116
  251. package/frontend/stores/ui/theme.svelte.ts +0 -179
  252. package/frontend/stores/ui/todo-panel.svelte.ts +0 -39
  253. package/frontend/stores/ui/update.svelte.ts +0 -159
  254. package/frontend/stores/ui/workspace.svelte.ts +0 -798
  255. package/frontend/utils/chat/date-separator.ts +0 -39
  256. package/frontend/utils/chat/message-grouper.ts +0 -329
  257. package/frontend/utils/chat/message-processor.ts +0 -169
  258. package/frontend/utils/chat/tool-handler.ts +0 -287
  259. package/frontend/utils/chat/virtual-scroll.svelte.ts +0 -142
  260. package/frontend/utils/click-outside.ts +0 -20
  261. package/frontend/utils/context-manager.ts +0 -55
  262. package/frontend/utils/file-icon-mappings.ts +0 -769
  263. package/frontend/utils/file-type.ts +0 -68
  264. package/frontend/utils/folder-icon-mappings.ts +0 -1030
  265. package/frontend/utils/git-status.ts +0 -68
  266. package/frontend/utils/native-ui.ts +0 -73
  267. package/frontend/utils/platform.ts +0 -113
  268. package/frontend/utils/port-check.ts +0 -65
  269. package/frontend/utils/preview-constants.ts +0 -45
  270. package/frontend/utils/terminal-formatter.ts +0 -207
  271. package/frontend/utils/theme.ts +0 -6
  272. package/frontend/utils/tree-visualizer.ts +0 -320
  273. package/frontend/utils/ws.ts +0 -90
  274. package/scripts/dev.ts +0 -46
  275. package/scripts/generate-icons.ts +0 -87
  276. package/svelte.config.js +0 -20
  277. package/tsconfig.json +0 -41
  278. package/vite.config.ts +0 -51
  279. /package/{static → dist}/audio/notification.ogg +0 -0
  280. /package/{static → dist}/favicon.svg +0 -0
  281. /package/{static → dist}/fonts/dm-sans/dm-sans-italic-latin-ext.woff2 +0 -0
  282. /package/{static → dist}/fonts/dm-sans/dm-sans-italic-latin.woff2 +0 -0
  283. /package/{static → dist}/fonts/dm-sans/dm-sans-normal-latin-ext.woff2 +0 -0
  284. /package/{static → dist}/fonts/dm-sans/dm-sans-normal-latin.woff2 +0 -0
  285. /package/{static → dist}/fonts/dm-sans.css +0 -0
  286. /package/{static → dist}/manifest.json +0 -0
@@ -1,1523 +0,0 @@
1
- <script lang="ts">
2
- import { onDestroy } from 'svelte';
3
- import { getViewportDimensions, type DeviceSize, type Rotation } from '$frontend/utils/preview-constants';
4
- import { BrowserWebCodecsService, type BrowserWebCodecsStreamStats } from '$frontend/services/preview/browser/browser-webcodecs.service';
5
- import { debug } from '$shared/utils/logger';
6
-
7
- let {
8
- projectId = '', // REQUIRED for project isolation (read-only from parent)
9
- sessionId = $bindable<string | null>(null),
10
- sessionInfo = $bindable<any>(null),
11
- deviceSize = $bindable<DeviceSize>('laptop'),
12
- rotation = $bindable<Rotation>('portrait'),
13
- currentCursor = $bindable('default'),
14
- canvasAPI = $bindable<any>(null),
15
- lastFrameData = $bindable<any>(null),
16
- isConnected = $bindable(false),
17
- latencyMs = $bindable<number>(0),
18
- isStreamReady = $bindable(false), // Exposed: true when first frame received
19
- isNavigating = $bindable(false), // Track if page is navigating (from parent)
20
- isReconnecting = $bindable(false), // Track if reconnecting after navigation (prevents loading overlay)
21
-
22
- // Callbacks for interactions
23
- onInteraction = $bindable<(action: any) => void>(() => {}),
24
- onCursorUpdate = $bindable<(cursor: string) => void>(() => {}),
25
- onFrameUpdate = $bindable<(data: any) => void>(() => {}),
26
- onStatsUpdate = $bindable<(stats: BrowserWebCodecsStreamStats | null) => void>(() => {}),
27
- onRequestScreencastRefresh = $bindable<() => void>(() => {}), // Called when stream is stuck
28
- touchMode = $bindable<'scroll' | 'cursor'>('scroll'),
29
- touchTarget = undefined as HTMLElement | undefined, // Container element for touch events
30
- onTouchCursorUpdate = $bindable<(pos: { x: number; y: number; visible: boolean; clicking?: boolean }) => void>(() => {})
31
- } = $props();
32
-
33
- // WebCodecs service instance
34
- let webCodecsService: BrowserWebCodecsService | null = null;
35
- let isWebCodecsActive = $state(false);
36
- let activeStreamingSessionId: string | null = null; // Track which session is currently streaming
37
- let isStartingStream = false; // Prevent concurrent start attempts
38
- let lastStartRequestId: string | null = null; // Track the last start request to prevent duplicates
39
-
40
- // Generation counter: increments on every session change (tab switch).
41
- // Async operations (startStreaming, recovery) capture the current generation
42
- // and bail out if it has changed, preventing stale operations from corrupting
43
- // the new tab's state.
44
- let streamingGeneration = 0;
45
-
46
- let canvasElement = $state<HTMLCanvasElement | undefined>();
47
- let setupCanvasTimeout: ReturnType<typeof setTimeout> | undefined;
48
-
49
- // Health check and recovery - EVENT-DRIVEN, not timeout-based
50
- let healthCheckInterval: ReturnType<typeof setInterval> | undefined;
51
- let initialFrameCheckInterval: ReturnType<typeof setInterval> | undefined;
52
- let lastFrameTime = 0;
53
- let consecutiveFailures = $state(0); // Made reactive for UI
54
- let hasReceivedFirstFrame = $state(false); // Made reactive for UI
55
- let isStreamStarting = $state(false); // Track when stream is being started
56
- let isRecovering = $state(false); // Track recovery attempts
57
- let connectionFailed = $state(false); // Track if connection actually failed (not just slow)
58
- let hasRequestedScreencastRefresh = false; // Track if we've already requested refresh for this stream
59
- let screencastRefreshCount = 0; // Track retry count for stuck detection
60
- let navigationJustCompleted = false; // Track if navigation just completed (for fast refresh)
61
-
62
- // Canvas snapshot storage for instant tab switching
63
- // Stores a clone of the canvas per sessionId so switching back shows content immediately
64
- const canvasSnapshots = new Map<string, HTMLCanvasElement>();
65
- const MAX_SNAPSHOTS = 10;
66
- let hasRestoredSnapshot = false; // Prevents canvas clear/reset during streaming start
67
-
68
- // Recovery is only triggered by ACTUAL failures, not timeouts
69
- // - ICE connection failed
70
- // - WebCodecs connection closed unexpectedly
71
- // - Explicit errors
72
- const MAX_CONSECUTIVE_FAILURES = 2;
73
- const HEALTH_CHECK_INTERVAL = 2000; // Check every 2 seconds for connection health
74
- const FRAME_CHECK_INTERVAL = 100; // Fallback poll for first frame (primary path is onFirstFrame callback)
75
- const STUCK_STREAM_TIMEOUT = 3000; // Fallback: Request screencast refresh after 3 seconds of connected but no frame
76
- const NAVIGATION_FAST_REFRESH_DELAY = 300; // Fast refresh after navigation: 300ms
77
-
78
- // Sync isStreamReady with hasReceivedFirstFrame for parent component
79
- $effect(() => {
80
- isStreamReady = hasReceivedFirstFrame;
81
- });
82
-
83
- // Watch projectId changes and recreate WebCodecs service
84
- let lastProjectId = '';
85
- $effect(() => {
86
- const currentProjectId = projectId;
87
-
88
- // Project changed - destroy and recreate service
89
- if (lastProjectId && currentProjectId && lastProjectId !== currentProjectId) {
90
- debug.log('webcodecs', `🔄 Project changed (${lastProjectId} → ${currentProjectId}), destroying old WebCodecs service`);
91
-
92
- // Clear canvas snapshots - they belong to old project's sessions
93
- canvasSnapshots.clear();
94
- hasRestoredSnapshot = false;
95
- lastStartRequestId = null; // Clear so new project sessions aren't blocked by old tab IDs
96
-
97
- // Destroy old service
98
- if (webCodecsService) {
99
- webCodecsService.destroy();
100
- webCodecsService = null;
101
- activeStreamingSessionId = null;
102
- isWebCodecsActive = false;
103
- }
104
- }
105
-
106
- lastProjectId = currentProjectId;
107
- });
108
-
109
- // Track session changes to reset stale state and increment generation counter.
110
- // This runs BEFORE the streaming $effect, ensuring isReconnecting from the old
111
- // tab doesn't leak into the new tab and that stale async operations bail out.
112
- let lastTrackedSessionId: string | null = null;
113
- $effect(() => {
114
- const currentSessionId = sessionId;
115
- if (currentSessionId !== lastTrackedSessionId) {
116
- if (lastTrackedSessionId !== null) {
117
- // Session actually changed (tab switch) — not initial mount
118
- streamingGeneration++;
119
- debug.log('webcodecs', `Session changed ${lastTrackedSessionId} → ${currentSessionId}, generation=${streamingGeneration}`);
120
-
121
- // Reset states that belong to the old tab
122
- if (isReconnecting) {
123
- isReconnecting = false;
124
- }
125
- if (isNavigating) {
126
- isNavigating = false;
127
- }
128
- lastStartRequestId = null; // Allow new start request for new session
129
- }
130
- lastTrackedSessionId = currentSessionId;
131
- }
132
- });
133
-
134
- // Sync navigation state with webCodecsService
135
- // This prevents recovery when DataChannel closes during navigation
136
- $effect(() => {
137
- if (webCodecsService) {
138
- webCodecsService.setNavigating(isNavigating);
139
- if (isNavigating) {
140
- debug.log('webcodecs', 'Navigation started - recovery will be suppressed');
141
- }
142
- }
143
- });
144
-
145
- // Convert CSS cursor values to canvas cursor styles
146
- function mapCursorStyle(browserCursor: string): string {
147
- const cursorMap: Record<string, string> = {
148
- 'default': 'default',
149
- 'auto': 'default',
150
- 'pointer': 'pointer',
151
- 'text': 'text',
152
- 'wait': 'wait',
153
- 'crosshair': 'crosshair',
154
- 'help': 'help',
155
- 'move': 'move',
156
- 'n-resize': 'n-resize',
157
- 's-resize': 's-resize',
158
- 'e-resize': 'e-resize',
159
- 'w-resize': 'w-resize',
160
- 'ne-resize': 'ne-resize',
161
- 'nw-resize': 'nw-resize',
162
- 'se-resize': 'se-resize',
163
- 'sw-resize': 'sw-resize',
164
- 'ew-resize': 'ew-resize',
165
- 'ns-resize': 'ns-resize',
166
- 'nesw-resize': 'nesw-resize',
167
- 'nwse-resize': 'nwse-resize',
168
- 'grab': 'grab',
169
- 'grabbing': 'grabbing',
170
- 'not-allowed': 'not-allowed',
171
- 'no-drop': 'no-drop',
172
- 'copy': 'copy',
173
- 'alias': 'alias',
174
- 'context-menu': 'context-menu',
175
- 'cell': 'cell',
176
- 'vertical-text': 'vertical-text',
177
- 'all-scroll': 'all-scroll',
178
- 'col-resize': 'col-resize',
179
- 'row-resize': 'row-resize',
180
- 'zoom-in': 'zoom-in',
181
- 'zoom-out': 'zoom-out'
182
- };
183
-
184
- return cursorMap[browserCursor] || 'default';
185
- }
186
-
187
- // Update canvas cursor style
188
- function updateCanvasCursor(newCursor: string) {
189
- if (canvasElement && newCursor !== currentCursor) {
190
- const mappedCursor = mapCursorStyle(newCursor);
191
- canvasElement.style.cursor = mappedCursor;
192
- currentCursor = newCursor;
193
- onCursorUpdate(newCursor);
194
- }
195
- }
196
-
197
- // Interactive canvas functions
198
- async function sendInteraction(action: any) {
199
- if (!sessionId) return;
200
- onInteraction(action);
201
- }
202
-
203
- // Utility function to convert canvas display coordinates to browser coordinates
204
- function getCanvasCoordinates(event: MouseEvent | TouchEvent, canvas: HTMLCanvasElement): { x: number, y: number } {
205
- const rect = canvas.getBoundingClientRect();
206
- const scaleX = canvas.width / rect.width;
207
- const scaleY = canvas.height / rect.height;
208
-
209
- let clientX: number, clientY: number;
210
-
211
- if (event instanceof MouseEvent) {
212
- clientX = event.clientX;
213
- clientY = event.clientY;
214
- } else {
215
- // Touch event - use first touch
216
- const touch = event.touches[0] || event.changedTouches[0];
217
- clientX = touch.clientX;
218
- clientY = touch.clientY;
219
- }
220
-
221
- const x = (clientX - rect.left) * scaleX;
222
- const y = (clientY - rect.top) * scaleY;
223
-
224
- return {
225
- x: Math.round(x),
226
- y: Math.round(y)
227
- };
228
- }
229
-
230
-
231
- function handleCanvasMouseMove(event: MouseEvent, canvas: HTMLCanvasElement) {
232
- if (!sessionId) return;
233
-
234
- const coords = getCanvasCoordinates(event, canvas);
235
-
236
- if (isMouseDown && dragStartPos) {
237
- dragCurrentPos = { x: coords.x, y: coords.y };
238
-
239
- const dragDistance = Math.sqrt(
240
- Math.pow(coords.x - dragStartPos.x, 2) + Math.pow(coords.y - dragStartPos.y, 2)
241
- );
242
-
243
- // Start drag when distance exceeds threshold
244
- if (dragDistance > 10) {
245
- // Send mousedown on first drag detection
246
- if (!dragStarted) {
247
- sendInteraction({
248
- type: 'mousedown',
249
- x: dragStartPos.x,
250
- y: dragStartPos.y,
251
- button: event.button === 2 ? 'right' : 'left'
252
- });
253
- dragStarted = true;
254
- }
255
-
256
- isDragging = true;
257
- // Send mousemove to continue dragging (mouse is already down)
258
- sendInteraction({
259
- type: 'mousemove',
260
- x: coords.x,
261
- y: coords.y
262
- });
263
- }
264
- } else if (!isMouseDown) {
265
- sendInteraction({
266
- type: 'mousemove',
267
- x: coords.x,
268
- y: coords.y
269
- });
270
- }
271
- }
272
-
273
- function handleCanvasDoubleClick(event: MouseEvent, canvas: HTMLCanvasElement) {
274
- if (!sessionId) return;
275
- const coords = getCanvasCoordinates(event, canvas);
276
- sendInteraction({ type: 'doubleclick', x: coords.x, y: coords.y });
277
- }
278
-
279
- function handleCanvasRightClick(event: MouseEvent, canvas: HTMLCanvasElement) {
280
- event.preventDefault();
281
- if (!sessionId) return;
282
- const coords = getCanvasCoordinates(event, canvas);
283
- sendInteraction({ type: 'rightclick', x: coords.x, y: coords.y });
284
- }
285
-
286
- function handleCanvasWheel(event: WheelEvent, canvas: HTMLCanvasElement) {
287
- event.preventDefault();
288
- if (!sessionId) return;
289
- sendInteraction({ type: 'scroll', deltaX: event.deltaX, deltaY: event.deltaY });
290
- }
291
-
292
- function handleCanvasKeydown(event: KeyboardEvent) {
293
- if (!sessionId) return;
294
-
295
- // Prevent default for all keyboard events to avoid affecting parent page
296
- // This prevents Ctrl+A, Ctrl+C, arrow keys, etc. from affecting the parent
297
- event.preventDefault();
298
- event.stopPropagation();
299
-
300
- const isNavigationKey = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Tab', 'Enter', 'Escape'].includes(event.key);
301
- const isModifierKey = event.ctrlKey || event.metaKey || event.altKey || event.shiftKey;
302
-
303
- if (isNavigationKey) {
304
- sendInteraction({
305
- type: 'keynav',
306
- key: event.key,
307
- ctrlKey: event.ctrlKey,
308
- metaKey: event.metaKey,
309
- altKey: event.altKey,
310
- shiftKey: event.shiftKey
311
- });
312
- } else if (event.key.length === 1 && !isModifierKey) {
313
- sendInteraction({ type: 'type', text: event.key, delay: 50 });
314
- } else {
315
- sendInteraction({
316
- type: 'key',
317
- key: event.key,
318
- ctrlKey: event.ctrlKey,
319
- metaKey: event.metaKey,
320
- altKey: event.altKey,
321
- shiftKey: event.shiftKey
322
- });
323
- }
324
- }
325
-
326
- // State variables for drag-drop functionality
327
- let isDragging = $state(false);
328
- let isMouseDown = $state(false);
329
- let dragStartPos = $state<{x: number, y: number} | null>(null);
330
- let dragCurrentPos = $state<{x: number, y: number} | null>(null);
331
- let mouseDownTime = $state(0);
332
- let dragStarted = $state(false); // Track if we've sent mousedown for drag
333
-
334
- // Touch-specific tracking (non-reactive for performance)
335
- let longPressTimer: ReturnType<typeof setTimeout> | null = null;
336
- let touchLongPressed = false;
337
- let lastTouchCoords: { x: number; y: number } | null = null;
338
-
339
- // Trackpad cursor state (cursor/trackpad mode - persists between touch gestures)
340
- let trackpadCursorX = 0;
341
- let trackpadCursorY = 0;
342
- let trackpadLastClientX = 0;
343
- let trackpadLastClientY = 0;
344
- let trackpadTouchStartClientX = 0;
345
- let trackpadTouchStartClientY = 0;
346
- let trackpadTwoFingerActive = false;
347
- let trackpadTwoFingerStartTime = 0;
348
- let trackpadTwoFingerLastCenterX = 0;
349
- let trackpadTwoFingerLastCenterY = 0;
350
- let trackpadTwoFingerTotalDist = 0;
351
-
352
- function handleCanvasMouseDown(event: MouseEvent, canvas: HTMLCanvasElement) {
353
- if (!sessionId) return;
354
-
355
- const coords = getCanvasCoordinates(event, canvas);
356
-
357
- isMouseDown = true;
358
- mouseDownTime = Date.now();
359
- dragStartPos = { x: coords.x, y: coords.y };
360
- dragCurrentPos = { x: coords.x, y: coords.y };
361
- dragStarted = false; // Reset drag started flag
362
- }
363
-
364
- function handleCanvasMouseUp(event: MouseEvent, canvas: HTMLCanvasElement) {
365
- if (!sessionId || !isMouseDown) return;
366
-
367
- const coords = getCanvasCoordinates(event, canvas);
368
-
369
- if (dragStartPos) {
370
- // If drag was started (mousedown was sent), send mouseup
371
- if (dragStarted) {
372
- sendInteraction({
373
- type: 'mouseup',
374
- x: coords.x,
375
- y: coords.y,
376
- button: event.button === 2 ? 'right' : 'left'
377
- });
378
- } else {
379
- // No drag occurred, this is a click
380
- // IMPORTANT: Only send click for left mouse button (button === 0)
381
- // Right-click (button === 2) is handled by contextmenu event
382
- if (event.button === 0) {
383
- sendInteraction({ type: 'click', x: dragStartPos.x, y: dragStartPos.y });
384
- }
385
- }
386
- }
387
-
388
- isMouseDown = false;
389
- isDragging = false;
390
- dragStartPos = null;
391
- dragCurrentPos = null;
392
- dragStarted = false;
393
- }
394
-
395
- function setupCanvasInternal() {
396
- if (!sessionInfo) return;
397
-
398
- // IMPORTANT: Use props as primary source of truth, fallback to sessionInfo
399
- // Props are reactive and updated when user changes device/rotation
400
- // sessionInfo may be stale (snapshot from launch time)
401
- const currentDevice: DeviceSize = deviceSize || sessionInfo?.deviceSize || 'laptop';
402
- const currentRotation: Rotation = rotation || sessionInfo?.rotation || 'landscape';
403
-
404
- // Use getViewportDimensions helper for consistent viewport calculation
405
- // This ensures portrait = height > width, landscape = width > height
406
- const { width: canvasWidth, height: canvasHeight } = getViewportDimensions(currentDevice, currentRotation);
407
-
408
- debug.log('webcodecs', `setupCanvasInternal: device=${currentDevice}, rotation=${currentRotation}, canvas=${canvasWidth}x${canvasHeight}`);
409
-
410
- // Get scale from parent (BrowserPreviewContainer calculates this)
411
- // This is provided via previewDimensions binding
412
- const currentScale = 1; // We keep canvas at original size, scaling handled by CSS
413
-
414
- if (canvasElement) {
415
- // Canvas dimensions stay at original viewport size
416
- // Scaling is handled by CSS transform in parent container
417
- if (canvasElement.width === canvasWidth && canvasElement.height === canvasHeight) {
418
- return;
419
- }
420
-
421
- canvasElement.width = canvasWidth;
422
- canvasElement.height = canvasHeight;
423
- canvasElement.style.width = '100%';
424
- canvasElement.style.height = '100%';
425
- // Use same background as loading overlay to avoid flash of black
426
- // This will be covered by overlay until stream is ready anyway
427
- canvasElement.style.backgroundColor = 'transparent';
428
- canvasElement.style.cursor = 'default';
429
-
430
- // Get context with low-latency optimizations
431
- const ctx = canvasElement.getContext('2d', {
432
- alpha: false, // No transparency needed - faster
433
- desynchronized: true, // Low latency rendering hint
434
- willReadFrequently: false // We won't read pixels back
435
- });
436
-
437
- // Fill with neutral gray (works for both light/dark mode)
438
- // This matches the loading overlay background roughly
439
- if (ctx) {
440
- ctx.imageSmoothingEnabled = true;
441
- ctx.imageSmoothingQuality = 'medium';
442
- ctx.fillStyle = '#f1f5f9'; // slate-100 - neutral light color
443
- ctx.fillRect(0, 0, canvasElement.width, canvasElement.height);
444
- }
445
- }
446
- }
447
-
448
- function setupCanvas() {
449
- if (setupCanvasTimeout) {
450
- clearTimeout(setupCanvasTimeout);
451
- }
452
- setupCanvasTimeout = setTimeout(() => {
453
- setupCanvasInternal();
454
- }, 5);
455
- }
456
-
457
- // Start WebCodecs streaming
458
- async function startStreaming() {
459
- debug.log('webcodecs', `startStreaming() called: sessionId=${sessionId}, generation=${streamingGeneration}`);
460
-
461
- if (!sessionId || !canvasElement) {
462
- return;
463
- }
464
-
465
- // Prevent concurrent start attempts
466
- if (isStartingStream) {
467
- debug.log('webcodecs', 'startStreaming() skipped: already starting stream');
468
- return;
469
- }
470
-
471
- // If already streaming same session, skip
472
- if (isWebCodecsActive && activeStreamingSessionId === sessionId) {
473
- debug.log('webcodecs', 'startStreaming() skipped: already streaming same session');
474
- return;
475
- }
476
-
477
- // Capture current generation — if it changes during async operations,
478
- // it means the user switched tabs and this operation is stale
479
- const myGeneration = streamingGeneration;
480
-
481
- isStartingStream = true;
482
- isStreamStarting = true; // Show loading overlay
483
- // Don't reset if we restored a snapshot - keep showing it
484
- if (!hasRestoredSnapshot) {
485
- hasReceivedFirstFrame = false; // Reset first frame state
486
- }
487
-
488
- try {
489
- // If streaming a different session, stop first
490
- if (isWebCodecsActive && activeStreamingSessionId !== sessionId) {
491
- debug.log('webcodecs', `Session mismatch (active: ${activeStreamingSessionId}, requested: ${sessionId}), stopping old stream first`);
492
- await stopStreaming();
493
- await new Promise(resolve => setTimeout(resolve, 100));
494
- }
495
-
496
- // Bail out if tab switched during cleanup
497
- if (myGeneration !== streamingGeneration) {
498
- debug.log('webcodecs', `Stale startStreaming (gen ${myGeneration} != ${streamingGeneration}), aborting`);
499
- return;
500
- }
501
-
502
- // Create WebCodecs service if not exists
503
- if (!webCodecsService) {
504
- if (!projectId) {
505
- debug.error('webcodecs', 'Cannot start streaming: projectId is required');
506
- isStartingStream = false;
507
- return;
508
- }
509
- webCodecsService = new BrowserWebCodecsService(projectId);
510
-
511
- // Setup error handler
512
- webCodecsService.setErrorHandler((error: Error) => {
513
- debug.error('webcodecs', 'Error:', error);
514
- // NOTE: do NOT reset isStartingStream here.
515
- // This handler fires from inside webCodecsService.startStreaming (before it returns false).
516
- // Canvas.svelte's startStreaming retry loop is still running with isStartingStream=true.
517
- // Resetting it here releases the concurrency guard prematurely, causing multiple
518
- // concurrent streaming sessions to start (each triggering the streaming $effect).
519
- connectionFailed = true;
520
- });
521
-
522
- // Setup connection change handler
523
- webCodecsService.setConnectionChangeHandler((connected: boolean) => {
524
- isWebCodecsActive = connected;
525
- isConnected = connected;
526
- if (!connected) {
527
- activeStreamingSessionId = null;
528
- }
529
- });
530
-
531
- // Setup connection FAILED handler - this triggers recovery
532
- // Only called on actual failures (ICE failed, connection failed)
533
- // NOT called on timeouts or slow loading
534
- webCodecsService.setConnectionFailedHandler(() => {
535
- debug.warn('webcodecs', 'Connection failed - attempting recovery');
536
- connectionFailed = true;
537
- attemptRecovery();
538
- });
539
-
540
- // Setup navigation reconnect handler - FAST path without delay
541
- // Called when DataChannel closes during navigation, backend already restarted
542
- webCodecsService.setNavigationReconnectHandler(() => {
543
- debug.log('webcodecs', '🚀 Navigation reconnect - fast path (no delay)');
544
- fastReconnect();
545
- });
546
-
547
- // Setup reconnecting start handler - fires IMMEDIATELY when DataChannel closes during navigation
548
- // This ensures isReconnecting is set before the 700ms delay, keeping progress bar visible
549
- webCodecsService.setReconnectingStartHandler(() => {
550
- debug.log('webcodecs', '🔄 Reconnecting state started (immediate)');
551
- isReconnecting = true;
552
- });
553
-
554
- // Setup stats handler
555
- webCodecsService.setStatsHandler((stats: BrowserWebCodecsStreamStats) => {
556
- onStatsUpdate(stats);
557
- });
558
-
559
- // Setup first frame handler - fires immediately when first frame decoded
560
- // This eliminates the 500ms polling delay for hiding the loading overlay
561
- webCodecsService.setFirstFrameHandler(() => {
562
- if (!hasReceivedFirstFrame) {
563
- debug.log('webcodecs', 'First frame callback - immediately updating UI');
564
- hasReceivedFirstFrame = true;
565
- consecutiveFailures = 0;
566
- connectionFailed = false;
567
- }
568
-
569
- // Always reset reconnecting state on first real frame
570
- // (outside !hasReceivedFirstFrame to handle snapshot + reconnect case)
571
- if (isReconnecting) {
572
- setTimeout(() => {
573
- isReconnecting = false;
574
- }, 300);
575
- }
576
-
577
- // Reset navigation state when first frame arrives after navigation.
578
- // The preview:browser-navigation event that normally resets this can be
579
- // missed during stream reconnect (listeners are removed/re-registered),
580
- // so use the first rendered frame as definitive signal that navigation completed.
581
- if (isNavigating) {
582
- isNavigating = false;
583
- }
584
- });
585
-
586
- // Setup cursor change handler
587
- webCodecsService.setOnCursorChange((cursor: string) => {
588
- updateCanvasCursor(cursor);
589
- });
590
- }
591
-
592
- // Start streaming with retry for session not ready cases
593
- debug.log('webcodecs', `Starting streaming for session: ${sessionId}`);
594
-
595
- let success = false;
596
- let retries = 0;
597
- const maxRetries = 5;
598
- const retryDelay = 300;
599
-
600
- while (!success && retries < maxRetries) {
601
- // Check generation before each attempt
602
- if (myGeneration !== streamingGeneration) {
603
- debug.log('webcodecs', `Stale startStreaming retry (gen ${myGeneration} != ${streamingGeneration}), aborting`);
604
- break;
605
- }
606
-
607
- try {
608
- // Guard: webCodecsService can be destroyed by a concurrent tab/project switch
609
- if (!webCodecsService) {
610
- debug.warn('webcodecs', 'webCodecsService became null during startStreaming, aborting');
611
- break;
612
- }
613
-
614
- success = await webCodecsService.startStreaming(sessionId, canvasElement);
615
-
616
- // Check generation after async operation
617
- if (myGeneration !== streamingGeneration) {
618
- debug.log('webcodecs', `Tab switched during startStreaming (gen ${myGeneration} != ${streamingGeneration}), discarding result`);
619
- if (success && webCodecsService) {
620
- await webCodecsService.stopStreaming();
621
- }
622
- break;
623
- }
624
-
625
- if (success) {
626
- isWebCodecsActive = true;
627
- isConnected = true;
628
- activeStreamingSessionId = sessionId;
629
- consecutiveFailures = 0;
630
- startHealthCheck(hasRestoredSnapshot);
631
- hasRestoredSnapshot = false;
632
- debug.log('webcodecs', 'Streaming started successfully');
633
- } else {
634
- retries++;
635
- if (retries < maxRetries) {
636
- debug.warn('webcodecs', `Streaming start returned false, retrying in ${retryDelay * retries}ms (${retries}/${maxRetries})`);
637
- await new Promise(resolve => setTimeout(resolve, retryDelay * retries));
638
- continue;
639
- }
640
- debug.error('webcodecs', 'Streaming start failed after all retries');
641
- break;
642
- }
643
- break;
644
- } catch (error: any) {
645
- const isRetriable = error?.message?.includes('not found') ||
646
- error?.message?.includes('invalid') ||
647
- error?.message?.includes('Failed to start') ||
648
- error?.message?.includes('No offer');
649
-
650
- if (isRetriable) {
651
- retries++;
652
- if (retries < maxRetries) {
653
- debug.log('webcodecs', `Streaming not ready, retrying in ${retryDelay}ms (${retries}/${maxRetries})`);
654
- await new Promise(resolve => setTimeout(resolve, retryDelay));
655
- } else {
656
- debug.error('webcodecs', 'Max retries reached, streaming still not ready');
657
- break;
658
- }
659
- } else {
660
- debug.error('webcodecs', 'Streaming error:', error);
661
- break;
662
- }
663
- }
664
- }
665
- } finally {
666
- isStartingStream = false;
667
- isStreamStarting = false; // Hide "Launching browser..." (but may still show "Connecting..." until first frame)
668
- hasRestoredSnapshot = false; // Always reset in finally
669
- }
670
- }
671
-
672
- // Clear canvas to prevent showing stale frames
673
- // Use light neutral color that works with loading overlay
674
- function clearCanvas() {
675
- if (canvasElement) {
676
- const ctx = canvasElement.getContext('2d');
677
- if (ctx) {
678
- ctx.fillStyle = '#f1f5f9'; // slate-100 - same as setup, works with overlay
679
- ctx.fillRect(0, 0, canvasElement.width, canvasElement.height);
680
- }
681
- }
682
- }
683
-
684
- // EVENT-DRIVEN health check - no timeout-based recovery
685
- // We only check for first frame to update UI, not to trigger recovery
686
- // Recovery is triggered by actual connection failures (ICE failed, connection closed)
687
- // skipFirstFrameReset: When true, don't reset hasReceivedFirstFrame (used during fast reconnect to keep overlay stable)
688
- function startHealthCheck(skipFirstFrameReset = false) {
689
- // Stop existing intervals without resetting hasReceivedFirstFrame if skipFirstFrameReset is true
690
- stopHealthCheck(skipFirstFrameReset);
691
- lastFrameTime = Date.now();
692
- if (!skipFirstFrameReset) {
693
- hasReceivedFirstFrame = false;
694
- }
695
- connectionFailed = false;
696
- hasRequestedScreencastRefresh = false; // Reset for new stream
697
- screencastRefreshCount = 0; // Reset retry counter
698
-
699
- const startTime = Date.now();
700
-
701
- // Check for first frame periodically (for UI update only, NOT recovery)
702
- initialFrameCheckInterval = setInterval(() => {
703
- if (!isWebCodecsActive || !sessionId) {
704
- return;
705
- }
706
-
707
- const stats = webCodecsService?.getStats();
708
- const now = Date.now();
709
- const elapsed = now - startTime;
710
-
711
- // Log connection state periodically for debugging
712
- if (elapsed > 0 && elapsed % 5000 < FRAME_CHECK_INTERVAL) {
713
- debug.log('webcodecs', `Status: connected=${stats?.isConnected}, firstFrame=${stats?.firstFrameRendered}, elapsed=${elapsed}ms`);
714
- }
715
-
716
- // Check if we received the first frame
717
- if (stats && stats.firstFrameRendered) {
718
- debug.log('webcodecs', `First frame rendered after ${elapsed}ms`);
719
- hasReceivedFirstFrame = true;
720
- lastFrameTime = now;
721
- consecutiveFailures = 0;
722
- connectionFailed = false;
723
- hasRequestedScreencastRefresh = false; // Reset on success
724
- screencastRefreshCount = 0; // Reset retry counter on success
725
-
726
- // Reset reconnecting state after successful frame reception
727
- // This completes the fast reconnect cycle
728
- // Add small delay to allow page to render a bit more before hiding overlay
729
- if (isReconnecting) {
730
- debug.log('webcodecs', 'First frame received during reconnect, will reset isReconnecting after delay');
731
- setTimeout(() => {
732
- debug.log('webcodecs', 'Resetting isReconnecting after first frame + delay');
733
- isReconnecting = false;
734
- }, 300); // 300ms delay to let page render more
735
- }
736
-
737
- // Stop initial check, start regular health check
738
- if (initialFrameCheckInterval) {
739
- clearInterval(initialFrameCheckInterval);
740
- initialFrameCheckInterval = undefined;
741
- }
742
- startRegularHealthCheck();
743
- return;
744
- }
745
-
746
- // FAST REFRESH AFTER NAVIGATION: If navigation just completed and we're
747
- // connected but no frame, trigger refresh quickly (don't wait 5 seconds)
748
- if (navigationJustCompleted && stats?.isConnected && !stats?.firstFrameRendered && elapsed >= NAVIGATION_FAST_REFRESH_DELAY && !hasRequestedScreencastRefresh) {
749
- debug.log('webcodecs', `Navigation completed, fast-refreshing screencast (connected but no frame for ${elapsed}ms)`);
750
- hasRequestedScreencastRefresh = true;
751
- navigationJustCompleted = false;
752
- onRequestScreencastRefresh();
753
- return; // Skip regular stuck check
754
- }
755
-
756
- // STUCK STREAM DETECTION (FALLBACK): If connected but no first frame for too long,
757
- // request screencast refresh (hot-swap) to restart CDP screencast.
758
- // This handles cases where WebRTC is connected but CDP frames aren't flowing.
759
- // Retries: 1st at 3s (screencast refresh), 2nd at 6s (another refresh), 3rd at 10s (full recovery)
760
- if (stats?.isConnected && !stats?.firstFrameRendered && !hasRequestedScreencastRefresh) {
761
- const MAX_SCREENCAST_RETRIES = 2;
762
- const retryThreshold = STUCK_STREAM_TIMEOUT + (screencastRefreshCount * 3000); // 3s, 6s
763
-
764
- if (elapsed >= retryThreshold && screencastRefreshCount < MAX_SCREENCAST_RETRIES) {
765
- screencastRefreshCount++;
766
- debug.warn('webcodecs', `Stream stuck (connected, no frame for ${elapsed}ms), screencast refresh attempt ${screencastRefreshCount}/${MAX_SCREENCAST_RETRIES}`);
767
- onRequestScreencastRefresh();
768
- } else if (elapsed >= 10000 && screencastRefreshCount >= MAX_SCREENCAST_RETRIES) {
769
- // Screencast refreshes didn't help - attempt full recovery
770
- debug.warn('webcodecs', `Stream still stuck after ${screencastRefreshCount} screencast refreshes (${elapsed}ms), attempting full recovery`);
771
- hasRequestedScreencastRefresh = true; // Prevent further retries
772
- attemptRecovery();
773
- }
774
- }
775
-
776
- }, FRAME_CHECK_INTERVAL);
777
- }
778
-
779
- // Regular health check (after first frame received)
780
- // Only monitors connection health, doesn't trigger timeout-based recovery
781
- function startRegularHealthCheck() {
782
- if (healthCheckInterval) return; // Already running
783
-
784
- healthCheckInterval = setInterval(() => {
785
- if (!isWebCodecsActive || !sessionId) {
786
- return;
787
- }
788
-
789
- const stats = webCodecsService?.getStats();
790
- const now = Date.now();
791
-
792
- // Update last frame time if we're receiving frames
793
- if (stats && (stats.firstFrameRendered || stats.videoFramesReceived > 0)) {
794
- lastFrameTime = now;
795
- consecutiveFailures = 0;
796
- }
797
-
798
- // NO TIMEOUT-BASED RECOVERY
799
- // We only log for debugging purposes
800
- // Recovery is triggered by actual connection state changes (handled in WebCodecs service)
801
-
802
- }, HEALTH_CHECK_INTERVAL);
803
- }
804
-
805
- // Stop health check intervals
806
- // skipFirstFrameReset: When true, don't reset hasReceivedFirstFrame (used during navigation reconnect)
807
- function stopHealthCheck(skipFirstFrameReset = false) {
808
- if (initialFrameCheckInterval) {
809
- clearInterval(initialFrameCheckInterval);
810
- initialFrameCheckInterval = undefined;
811
- }
812
- if (healthCheckInterval) {
813
- clearInterval(healthCheckInterval);
814
- healthCheckInterval = undefined;
815
- }
816
- // Only reset hasReceivedFirstFrame if not skipping (preserves overlay during navigation)
817
- if (!skipFirstFrameReset) {
818
- hasReceivedFirstFrame = false;
819
- }
820
- }
821
-
822
- // Attempt to recover stuck stream
823
- async function attemptRecovery() {
824
- if (isStartingStream || isRecovering) {
825
- debug.log('webcodecs', 'Recovery skipped - already starting or recovering');
826
- return;
827
- }
828
-
829
- const myGeneration = streamingGeneration;
830
- consecutiveFailures++;
831
- debug.log('webcodecs', `Recovery attempt ${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES} for session ${sessionId}`);
832
-
833
- if (consecutiveFailures > MAX_CONSECUTIVE_FAILURES) {
834
- debug.error('webcodecs', 'Max recovery attempts reached, giving up');
835
- isRecovering = false;
836
- await stopStreaming();
837
- return;
838
- }
839
-
840
- // Stop and restart streaming
841
- try {
842
- isRecovering = true;
843
- hasReceivedFirstFrame = false;
844
- await stopStreaming();
845
- lastStartRequestId = null;
846
- await new Promise(resolve => setTimeout(resolve, 500));
847
-
848
- // Bail out if tab switched during cleanup
849
- if (myGeneration !== streamingGeneration) {
850
- debug.log('webcodecs', 'Recovery aborted - tab switched during cleanup');
851
- return;
852
- }
853
-
854
- await startStreaming();
855
- } catch (error) {
856
- debug.error('webcodecs', 'Recovery failed:', error);
857
- } finally {
858
- isRecovering = false;
859
- }
860
- }
861
-
862
- // Fast reconnect after navigation - NO DELAY because backend already restarted
863
- // Uses reconnectToExistingStream which does NOT tell backend to stop
864
- async function fastReconnect() {
865
- if (isStartingStream || isRecovering) {
866
- debug.log('webcodecs', 'Fast reconnect skipped - already starting or recovering');
867
- return;
868
- }
869
-
870
- if (!sessionId || !canvasElement || !webCodecsService) {
871
- debug.warn('webcodecs', 'Fast reconnect skipped - missing session, canvas, or service');
872
- return;
873
- }
874
-
875
- const myGeneration = streamingGeneration;
876
- debug.log('webcodecs', `🚀 Fast reconnect for session ${sessionId} (gen=${myGeneration})`);
877
-
878
- try {
879
- isRecovering = true;
880
- isStartingStream = true;
881
- isReconnecting = true;
882
-
883
- const success = await webCodecsService.reconnectToExistingStream(sessionId, canvasElement);
884
-
885
- // Bail out if tab switched during reconnect
886
- if (myGeneration !== streamingGeneration) {
887
- debug.log('webcodecs', 'Fast reconnect aborted - tab switched');
888
- return;
889
- }
890
-
891
- if (success) {
892
- isWebCodecsActive = true;
893
- isConnected = true;
894
- activeStreamingSessionId = sessionId;
895
- consecutiveFailures = 0;
896
- startHealthCheck(true);
897
- debug.log('webcodecs', '✅ Fast reconnect successful');
898
- } else {
899
- throw new Error('Reconnect returned false');
900
- }
901
- } catch (error) {
902
- debug.error('webcodecs', 'Fast reconnect failed:', error);
903
- consecutiveFailures++;
904
- isStartingStream = false;
905
- isReconnecting = false;
906
- if (myGeneration === streamingGeneration) {
907
- attemptRecovery();
908
- }
909
- } finally {
910
- isRecovering = false;
911
- isStartingStream = false;
912
- }
913
- }
914
-
915
- // Stop WebCodecs streaming
916
- async function stopStreaming() {
917
- stopHealthCheck(); // Stop health monitoring
918
- if (webCodecsService) {
919
- await webCodecsService.stopStreaming();
920
- isWebCodecsActive = false;
921
- isConnected = false;
922
- latencyMs = 0;
923
- activeStreamingSessionId = null;
924
- isStartingStream = false;
925
- lastStartRequestId = null; // Clear to allow new requests
926
- // Note: Don't reset hasReceivedFirstFrame here - let startStreaming do it
927
- // This prevents flashing when switching tabs
928
- // Clear canvas to prevent stale frames, BUT keep last frame during navigation or snapshot restore
929
- if (!isNavigating && !hasRestoredSnapshot) {
930
- clearCanvas();
931
- } else {
932
- debug.log('webcodecs', `Skipping canvas clear - navigation: ${isNavigating}, snapshot: ${hasRestoredSnapshot}`);
933
- }
934
- }
935
- }
936
-
937
- // Reactive setup when sessionInfo changes
938
- $effect(() => {
939
- if (sessionInfo && canvasElement) {
940
- setupCanvasInternal();
941
- }
942
- });
943
-
944
- // Track deviceSize and rotation changes to update canvas dimensions
945
- // This is critical for hot-swap viewport changes without reconnection
946
- $effect(() => {
947
- if (canvasElement && sessionInfo) {
948
- // Access reactive values to track changes
949
- const currentDevice = deviceSize;
950
- const currentRotation = rotation;
951
-
952
- debug.log('webcodecs', `Device/rotation changed: ${currentDevice}/${currentRotation}, reconfiguring canvas`);
953
- setupCanvasInternal();
954
- }
955
- });
956
-
957
- // Start/restart streaming when session is ready
958
- // This handles both initial start and session changes (viewport switch, etc.)
959
- $effect(() => {
960
- debug.log('webcodecs', `[DIAG] streaming $effect triggered: sessionId=${sessionId}, canvasElement=${!!canvasElement}, sessionInfo=${!!sessionInfo}, isReconnecting=${isReconnecting}, isWebCodecsActive=${isWebCodecsActive}, activeStreamingSessionId=${activeStreamingSessionId}`);
961
-
962
- if (sessionId && canvasElement && sessionInfo) {
963
- // Skip during fast reconnect - fastReconnect() handles this case
964
- if (isReconnecting) {
965
- debug.log('webcodecs', 'Skipping streaming effect - fast reconnect in progress');
966
- return;
967
- }
968
-
969
- // Check if we need to start or restart streaming
970
- const needsStreaming = !isWebCodecsActive || activeStreamingSessionId !== sessionId;
971
- debug.log('webcodecs', `[DIAG] streaming $effect: needsStreaming=${needsStreaming}`);
972
-
973
- if (needsStreaming) {
974
- if (activeStreamingSessionId !== sessionId) {
975
- // SNAPSHOT: Save current canvas before switching to new session
976
- if (activeStreamingSessionId && hasReceivedFirstFrame && canvasElement.width > 0) {
977
- try {
978
- const clone = document.createElement('canvas');
979
- clone.width = canvasElement.width;
980
- clone.height = canvasElement.height;
981
- const cloneCtx = clone.getContext('2d');
982
- if (cloneCtx) {
983
- cloneCtx.drawImage(canvasElement, 0, 0);
984
- // Limit snapshot count
985
- if (canvasSnapshots.size >= MAX_SNAPSHOTS) {
986
- const firstKey = canvasSnapshots.keys().next().value;
987
- if (firstKey) canvasSnapshots.delete(firstKey);
988
- }
989
- canvasSnapshots.set(activeStreamingSessionId, clone);
990
- debug.log('webcodecs', `📸 Saved canvas snapshot for session ${activeStreamingSessionId}`);
991
- }
992
- } catch (e) {
993
- debug.warn('webcodecs', 'Failed to capture canvas snapshot:', e);
994
- }
995
- }
996
-
997
- // SNAPSHOT: Restore for new session if available
998
- const existingSnapshot = canvasSnapshots.get(sessionId);
999
- if (existingSnapshot) {
1000
- setupCanvasInternal(); // Ensure canvas dimensions are correct
1001
- try {
1002
- const ctx = canvasElement.getContext('2d');
1003
- if (ctx) {
1004
- ctx.drawImage(existingSnapshot, 0, 0, canvasElement.width, canvasElement.height);
1005
- hasRestoredSnapshot = true;
1006
- // Don't reset hasReceivedFirstFrame - snapshot is visible
1007
- debug.log('webcodecs', `📸 Restored canvas snapshot for session ${sessionId}`);
1008
- }
1009
- } catch (e) {
1010
- debug.warn('webcodecs', 'Failed to restore canvas snapshot:', e);
1011
- hasRestoredSnapshot = false;
1012
- clearCanvas();
1013
- hasReceivedFirstFrame = false;
1014
- }
1015
- } else {
1016
- hasRestoredSnapshot = false;
1017
- clearCanvas();
1018
- hasReceivedFirstFrame = false; // Reset to show loading overlay
1019
- }
1020
- }
1021
-
1022
- // Stop existing streaming first if session changed
1023
- // This ensures clean state before starting new stream
1024
- const capturedGeneration = streamingGeneration;
1025
-
1026
- // IMMEDIATELY block the old session's frames from painting onto the canvas.
1027
- // Without this, A's DataChannel continues delivering frames for up to 30ms
1028
- // after we clear/snapshot-restore the canvas, overwriting B's content.
1029
- if (activeStreamingSessionId && activeStreamingSessionId !== sessionId) {
1030
- webCodecsService?.pauseRendering();
1031
- }
1032
-
1033
- const doStartStreaming = async () => {
1034
- // Bail immediately if tab already changed
1035
- if (capturedGeneration !== streamingGeneration) return;
1036
-
1037
- if (activeStreamingSessionId && activeStreamingSessionId !== sessionId) {
1038
- debug.log('webcodecs', `Session changed from ${activeStreamingSessionId} to ${sessionId}, stopping old stream first`);
1039
- await stopStreaming();
1040
- // Bail if tab changed during cleanup
1041
- if (capturedGeneration !== streamingGeneration) return;
1042
- // Short wait for backend cleanup
1043
- await new Promise(resolve => setTimeout(resolve, 50));
1044
- if (capturedGeneration !== streamingGeneration) return;
1045
- }
1046
- await startStreaming();
1047
- };
1048
-
1049
- // Small delay to ensure backend session is ready
1050
- const timeout = setTimeout(() => {
1051
- doStartStreaming();
1052
- }, 30);
1053
-
1054
- return () => clearTimeout(timeout);
1055
- }
1056
- }
1057
- });
1058
-
1059
- // Cleanup when sessionId is cleared
1060
- $effect(() => {
1061
- if (!sessionId && isWebCodecsActive) {
1062
- hasReceivedFirstFrame = false; // Reset loading state
1063
- stopStreaming();
1064
- }
1065
- });
1066
-
1067
- // Setup event listeners when canvas is ready
1068
- $effect(() => {
1069
- if (canvasElement) {
1070
- const canvas = canvasElement;
1071
-
1072
- canvas.addEventListener('dblclick', (e) => handleCanvasDoubleClick(e, canvas));
1073
- canvas.addEventListener('contextmenu', (e) => handleCanvasRightClick(e, canvas));
1074
- canvas.addEventListener('wheel', (e) => handleCanvasWheel(e, canvas), { passive: false });
1075
- canvas.addEventListener('keydown', handleCanvasKeydown);
1076
- canvas.addEventListener('mousedown', (e) => handleCanvasMouseDown(e, canvas));
1077
- canvas.addEventListener('mouseup', (e) => handleCanvasMouseUp(e, canvas));
1078
-
1079
- let lastMoveTime = 0;
1080
- const handleMouseMove = (e: MouseEvent) => {
1081
- const now = Date.now();
1082
- // 32ms = ~30fps — enough for smooth hover/drag while keeping CDP pipeline clear
1083
- // for clicks and keypresses (halving the rate halves CDP queue pressure)
1084
- if (now - lastMoveTime >= 32) {
1085
- lastMoveTime = now;
1086
- handleCanvasMouseMove(e, canvas);
1087
- }
1088
- };
1089
- canvas.addEventListener('mousemove', handleMouseMove);
1090
-
1091
- canvas.addEventListener('mousedown', () => {
1092
- canvas.focus();
1093
- });
1094
-
1095
-
1096
- const handleMouseLeave = () => {
1097
- if (isMouseDown) {
1098
- // If drag was started, send mouseup before resetting
1099
- if (dragStarted) {
1100
- sendInteraction({
1101
- type: 'mouseup',
1102
- x: dragCurrentPos?.x || dragStartPos?.x || 0,
1103
- y: dragCurrentPos?.y || dragStartPos?.y || 0,
1104
- button: 'left'
1105
- });
1106
- }
1107
- isMouseDown = false;
1108
- isDragging = false;
1109
- dragStartPos = null;
1110
- dragCurrentPos = null;
1111
- dragStarted = false;
1112
- }
1113
- };
1114
- canvas.addEventListener('mouseleave', handleMouseLeave);
1115
-
1116
- return () => {
1117
- canvas.removeEventListener('dblclick', (e) => handleCanvasDoubleClick(e, canvas));
1118
- canvas.removeEventListener('contextmenu', (e) => handleCanvasRightClick(e, canvas));
1119
- canvas.removeEventListener('wheel', (e) => handleCanvasWheel(e, canvas));
1120
- canvas.removeEventListener('keydown', handleCanvasKeydown);
1121
- canvas.removeEventListener('mousedown', (e) => handleCanvasMouseDown(e, canvas));
1122
- canvas.removeEventListener('mouseup', (e) => handleCanvasMouseUp(e, canvas));
1123
- canvas.removeEventListener('mousemove', handleMouseMove);
1124
- };
1125
- }
1126
- });
1127
-
1128
- // Attach touch events to touchTarget (Container's previewContainer) instead of canvas
1129
- $effect(() => {
1130
- if (!touchTarget || !canvasElement) return;
1131
-
1132
- const canvas = canvasElement;
1133
- let lastTouchMoveTime = 0;
1134
-
1135
- const touchStartHandler = (e: TouchEvent) => handleTouchStart(e, canvas);
1136
- const touchMoveHandler = (e: TouchEvent) => {
1137
- const now = Date.now();
1138
- if (now - lastTouchMoveTime >= 16) {
1139
- lastTouchMoveTime = now;
1140
- handleTouchMove(e, canvas);
1141
- }
1142
- };
1143
- const touchEndHandler = (e: TouchEvent) => handleTouchEnd(e, canvas);
1144
-
1145
- touchTarget.addEventListener('touchstart', touchStartHandler, { passive: false });
1146
- touchTarget.addEventListener('touchmove', touchMoveHandler, { passive: false });
1147
- touchTarget.addEventListener('touchend', touchEndHandler, { passive: false });
1148
-
1149
- return () => {
1150
- touchTarget.removeEventListener('touchstart', touchStartHandler);
1151
- touchTarget.removeEventListener('touchmove', touchMoveHandler);
1152
- touchTarget.removeEventListener('touchend', touchEndHandler);
1153
- };
1154
- });
1155
-
1156
- // Convert canvas coordinates to viewport (screen) coordinates for VirtualCursor display
1157
- function canvasToScreen(cx: number, cy: number): { x: number; y: number } {
1158
- if (!canvasElement) return { x: 0, y: 0 };
1159
- const rect = canvasElement.getBoundingClientRect();
1160
- return {
1161
- x: rect.left + cx * (rect.width / canvasElement.width),
1162
- y: rect.top + cy * (rect.height / canvasElement.height)
1163
- };
1164
- }
1165
-
1166
- // Show / hide cursor when touchMode changes
1167
- $effect(() => {
1168
- if (touchMode === 'cursor') {
1169
- // Init cursor at canvas center on first activation
1170
- if (canvasElement && trackpadCursorX === 0 && trackpadCursorY === 0) {
1171
- trackpadCursorX = canvasElement.width / 2;
1172
- trackpadCursorY = canvasElement.height / 2;
1173
- }
1174
- if (canvasElement) {
1175
- const pos = canvasToScreen(trackpadCursorX, trackpadCursorY);
1176
- onTouchCursorUpdate({ x: pos.x, y: pos.y, visible: true });
1177
- }
1178
- } else {
1179
- onTouchCursorUpdate({ x: 0, y: 0, visible: false });
1180
- }
1181
- });
1182
-
1183
- // ── Trackpad (cursor) mode handlers ───────────────────────────────────────
1184
-
1185
- function handleTrackpadTouchStart(event: TouchEvent) {
1186
- if (event.touches.length >= 2) {
1187
- // Second finger joined → switch to two-finger mode
1188
- if (!trackpadTwoFingerActive) {
1189
- // Cancel any pending single-finger actions
1190
- if (longPressTimer) { clearTimeout(longPressTimer); longPressTimer = null; }
1191
- if (touchLongPressed && dragStarted) {
1192
- sendInteraction({ type: 'mouseup', x: Math.round(trackpadCursorX), y: Math.round(trackpadCursorY), button: 'left' });
1193
- }
1194
- isMouseDown = false;
1195
- dragStarted = false;
1196
- touchLongPressed = false;
1197
- }
1198
- trackpadTwoFingerActive = true;
1199
- trackpadTwoFingerStartTime = Date.now();
1200
- trackpadTwoFingerTotalDist = 0;
1201
- const t1 = event.touches[0];
1202
- const t2 = event.touches[1];
1203
- trackpadTwoFingerLastCenterX = (t1.clientX + t2.clientX) / 2;
1204
- trackpadTwoFingerLastCenterY = (t1.clientY + t2.clientY) / 2;
1205
- return;
1206
- }
1207
-
1208
- if (trackpadTwoFingerActive) return; // Ignore until two-finger gesture fully ends
1209
-
1210
- // Single finger
1211
- const touch = event.touches[0];
1212
- trackpadTouchStartClientX = touch.clientX;
1213
- trackpadTouchStartClientY = touch.clientY;
1214
- trackpadLastClientX = touch.clientX;
1215
- trackpadLastClientY = touch.clientY;
1216
- isMouseDown = true;
1217
- mouseDownTime = Date.now();
1218
- dragStarted = false;
1219
- touchLongPressed = false;
1220
-
1221
- // Long-press (600ms without movement) → drag mode
1222
- longPressTimer = setTimeout(() => {
1223
- if (!isMouseDown) return;
1224
- const dist = Math.sqrt(
1225
- Math.pow(trackpadLastClientX - trackpadTouchStartClientX, 2) +
1226
- Math.pow(trackpadLastClientY - trackpadTouchStartClientY, 2)
1227
- );
1228
- if (dist < 8) {
1229
- touchLongPressed = true;
1230
- dragStarted = true;
1231
- sendInteraction({ type: 'mousedown', x: Math.round(trackpadCursorX), y: Math.round(trackpadCursorY), button: 'left' });
1232
- }
1233
- }, 600);
1234
- }
1235
-
1236
- function handleTrackpadTouchMove(event: TouchEvent) {
1237
- if (!canvasElement) return;
1238
-
1239
- if (event.touches.length >= 2 && trackpadTwoFingerActive) {
1240
- // Two-finger scroll
1241
- const t1 = event.touches[0];
1242
- const t2 = event.touches[1];
1243
- const centerX = (t1.clientX + t2.clientX) / 2;
1244
- const centerY = (t1.clientY + t2.clientY) / 2;
1245
- const deltaX = trackpadTwoFingerLastCenterX - centerX;
1246
- const deltaY = trackpadTwoFingerLastCenterY - centerY;
1247
- trackpadTwoFingerLastCenterX = centerX;
1248
- trackpadTwoFingerLastCenterY = centerY;
1249
- trackpadTwoFingerTotalDist += Math.sqrt(deltaX * deltaX + deltaY * deltaY);
1250
- if (Math.abs(deltaX) > 0.3 || Math.abs(deltaY) > 0.3) {
1251
- const rect = canvasElement.getBoundingClientRect();
1252
- const scale = canvasElement.width / rect.width;
1253
- sendInteraction({ type: 'scroll', deltaX: deltaX * scale * 2, deltaY: deltaY * scale * 2 });
1254
- }
1255
- return;
1256
- }
1257
-
1258
- if (event.touches.length !== 1 || !isMouseDown || trackpadTwoFingerActive) return;
1259
-
1260
- const touch = event.touches[0];
1261
- const deltaClientX = touch.clientX - trackpadLastClientX;
1262
- const deltaClientY = touch.clientY - trackpadLastClientY;
1263
- trackpadLastClientX = touch.clientX;
1264
- trackpadLastClientY = touch.clientY;
1265
-
1266
- // Cancel long-press if finger moved significantly
1267
- const totalDist = Math.sqrt(
1268
- Math.pow(touch.clientX - trackpadTouchStartClientX, 2) +
1269
- Math.pow(touch.clientY - trackpadTouchStartClientY, 2)
1270
- );
1271
- if (totalDist > 8 && longPressTimer) {
1272
- clearTimeout(longPressTimer);
1273
- longPressTimer = null;
1274
- }
1275
-
1276
- // Convert screen delta → canvas delta and move cursor
1277
- const rect = canvasElement.getBoundingClientRect();
1278
- const scale = canvasElement.width / rect.width;
1279
- trackpadCursorX = Math.max(0, Math.min(canvasElement.width, trackpadCursorX + deltaClientX * scale));
1280
- trackpadCursorY = Math.max(0, Math.min(canvasElement.height, trackpadCursorY + deltaClientY * scale));
1281
-
1282
- // Send mousemove so the browser sees hover state changes
1283
- sendInteraction({ type: 'mousemove', x: Math.round(trackpadCursorX), y: Math.round(trackpadCursorY) });
1284
-
1285
- // Update virtual cursor display
1286
- const pos = canvasToScreen(trackpadCursorX, trackpadCursorY);
1287
- onTouchCursorUpdate({ x: pos.x, y: pos.y, visible: true });
1288
- }
1289
-
1290
- function handleTrackpadTouchEnd(event: TouchEvent) {
1291
- if (longPressTimer) { clearTimeout(longPressTimer); longPressTimer = null; }
1292
-
1293
- const remainingTouches = event.touches.length;
1294
-
1295
- if (trackpadTwoFingerActive) {
1296
- if (remainingTouches === 0) {
1297
- // All fingers lifted: check for two-finger tap → right click
1298
- const duration = Date.now() - trackpadTwoFingerStartTime;
1299
- if (duration < 300 && trackpadTwoFingerTotalDist < 20) {
1300
- sendInteraction({ type: 'rightclick', x: Math.round(trackpadCursorX), y: Math.round(trackpadCursorY) });
1301
- }
1302
- trackpadTwoFingerActive = false;
1303
- } else if (remainingTouches === 1) {
1304
- // One finger remains: transition back to single-finger tracking
1305
- const touch = event.touches[0];
1306
- trackpadLastClientX = touch.clientX;
1307
- trackpadLastClientY = touch.clientY;
1308
- trackpadTouchStartClientX = touch.clientX;
1309
- trackpadTouchStartClientY = touch.clientY;
1310
- isMouseDown = true;
1311
- mouseDownTime = Date.now();
1312
- trackpadTwoFingerActive = false;
1313
- }
1314
- return;
1315
- }
1316
-
1317
- if (!isMouseDown) return;
1318
-
1319
- if (touchLongPressed && dragStarted) {
1320
- sendInteraction({ type: 'mouseup', x: Math.round(trackpadCursorX), y: Math.round(trackpadCursorY), button: 'left' });
1321
- } else {
1322
- // Tap: short + minimal movement → left click at cursor position
1323
- const duration = Date.now() - mouseDownTime;
1324
- const moveDist = Math.sqrt(
1325
- Math.pow(trackpadLastClientX - trackpadTouchStartClientX, 2) +
1326
- Math.pow(trackpadLastClientY - trackpadTouchStartClientY, 2)
1327
- );
1328
- if (duration < 250 && moveDist < 10) {
1329
- sendInteraction({ type: 'click', x: Math.round(trackpadCursorX), y: Math.round(trackpadCursorY) });
1330
- }
1331
- }
1332
-
1333
- isMouseDown = false;
1334
- dragStarted = false;
1335
- touchLongPressed = false;
1336
- }
1337
-
1338
- // ── Touch event handlers (dispatch to scroll or trackpad mode) ────────────
1339
-
1340
- // Touch event handlers
1341
- function handleTouchStart(event: TouchEvent, canvas: HTMLCanvasElement) {
1342
- if (!sessionId || event.touches.length === 0) return;
1343
- event.preventDefault();
1344
-
1345
- if (touchMode === 'cursor') {
1346
- handleTrackpadTouchStart(event);
1347
- return;
1348
- }
1349
-
1350
- // ── Scroll mode ──────────────────────────────────────────────────────────
1351
- if (event.touches.length > 1) return;
1352
-
1353
- const coords = getCanvasCoordinates(event, canvas);
1354
- isMouseDown = true;
1355
- mouseDownTime = Date.now();
1356
- dragStartPos = { x: coords.x, y: coords.y };
1357
- dragCurrentPos = { x: coords.x, y: coords.y };
1358
- dragStarted = false;
1359
- touchLongPressed = false;
1360
- lastTouchCoords = { x: coords.x, y: coords.y };
1361
-
1362
- // Long-press detection: after 500ms without significant movement → drag mode
1363
- longPressTimer = setTimeout(() => {
1364
- if (!isMouseDown || !dragStartPos) return;
1365
- const dist = dragCurrentPos
1366
- ? Math.sqrt(
1367
- Math.pow(dragCurrentPos.x - dragStartPos.x, 2) +
1368
- Math.pow(dragCurrentPos.y - dragStartPos.y, 2)
1369
- )
1370
- : 0;
1371
- if (dist < 10) {
1372
- touchLongPressed = true;
1373
- dragStarted = true;
1374
- sendInteraction({ type: 'mousedown', x: dragStartPos.x, y: dragStartPos.y, button: 'left' });
1375
- }
1376
- }, 500);
1377
- }
1378
-
1379
- function handleTouchMove(event: TouchEvent, canvas: HTMLCanvasElement) {
1380
- if (!sessionId || event.touches.length === 0) return;
1381
- event.preventDefault();
1382
-
1383
- if (touchMode === 'cursor') {
1384
- handleTrackpadTouchMove(event);
1385
- return;
1386
- }
1387
-
1388
- // ── Scroll mode ──────────────────────────────────────────────────────────
1389
- if (!isMouseDown || !dragStartPos) return;
1390
-
1391
- const coords = getCanvasCoordinates(event, canvas);
1392
- dragCurrentPos = { x: coords.x, y: coords.y };
1393
-
1394
- const dist = Math.sqrt(
1395
- Math.pow(coords.x - dragStartPos.x, 2) + Math.pow(coords.y - dragStartPos.y, 2)
1396
- );
1397
-
1398
- if (dist > 10 && longPressTimer) {
1399
- clearTimeout(longPressTimer);
1400
- longPressTimer = null;
1401
- }
1402
-
1403
- if (touchLongPressed) {
1404
- isDragging = true;
1405
- sendInteraction({ type: 'mousemove', x: coords.x, y: coords.y });
1406
- } else {
1407
- if (lastTouchCoords) {
1408
- const deltaX = lastTouchCoords.x - coords.x;
1409
- const deltaY = lastTouchCoords.y - coords.y;
1410
- sendInteraction({ type: 'scroll', deltaX, deltaY });
1411
- }
1412
- lastTouchCoords = { x: coords.x, y: coords.y };
1413
- }
1414
- }
1415
-
1416
- function handleTouchEnd(event: TouchEvent, canvas: HTMLCanvasElement) {
1417
- if (!sessionId) return;
1418
- event.preventDefault();
1419
-
1420
- if (touchMode === 'cursor') {
1421
- handleTrackpadTouchEnd(event);
1422
- return;
1423
- }
1424
-
1425
- // ── Scroll mode ──────────────────────────────────────────────────────────
1426
- if (!isMouseDown) return;
1427
-
1428
- if (longPressTimer) { clearTimeout(longPressTimer); longPressTimer = null; }
1429
-
1430
- if (touchLongPressed && dragStarted) {
1431
- const endPos = dragCurrentPos || dragStartPos;
1432
- if (endPos) sendInteraction({ type: 'mouseup', x: endPos.x, y: endPos.y, button: 'left' });
1433
- } else if (!isDragging && dragStartPos) {
1434
- const touchDuration = Date.now() - mouseDownTime;
1435
- const dist = dragCurrentPos
1436
- ? Math.sqrt(
1437
- Math.pow(dragCurrentPos.x - dragStartPos.x, 2) +
1438
- Math.pow(dragCurrentPos.y - dragStartPos.y, 2)
1439
- )
1440
- : 0;
1441
- if (touchDuration < 300 && dist < 15) {
1442
- sendInteraction({ type: 'click', x: dragStartPos.x, y: dragStartPos.y });
1443
- }
1444
- }
1445
-
1446
- isMouseDown = false;
1447
- isDragging = false;
1448
- dragStartPos = null;
1449
- dragCurrentPos = null;
1450
- dragStarted = false;
1451
- touchLongPressed = false;
1452
- lastTouchCoords = null;
1453
- }
1454
-
1455
- function getCanvasElement() {
1456
- return canvasElement;
1457
- }
1458
-
1459
- // Notify canvas that navigation has completed
1460
- // This triggers fast reconnection if connection was lost during navigation
1461
- async function notifyNavigationComplete() {
1462
- debug.log('webcodecs', 'Navigation complete notification received');
1463
- navigationJustCompleted = true;
1464
-
1465
- // If connection was lost during navigation, trigger fast reconnection
1466
- // Backend has already restarted streaming, just need to reconnect frontend
1467
- if (webCodecsService && !webCodecsService.getConnectionStatus() && sessionId) {
1468
- debug.log('webcodecs', 'Connection lost during navigation - triggering fast reconnection');
1469
-
1470
- // Reset navigation state to allow normal error handling after reconnect
1471
- webCodecsService.setNavigating(false);
1472
-
1473
- // Small delay to ensure backend has restarted streaming
1474
- await new Promise(resolve => setTimeout(resolve, 200));
1475
-
1476
- // Restart streaming (this will reconnect to the new peer)
1477
- lastStartRequestId = null; // Clear to allow new start request
1478
- await startStreaming();
1479
- }
1480
- }
1481
-
1482
- // Expose API methods to parent component
1483
- $effect(() => {
1484
- canvasAPI = {
1485
- updateCanvasCursor,
1486
- setupCanvas,
1487
- getCanvasElement,
1488
- // Streaming control
1489
- startStreaming,
1490
- stopStreaming,
1491
- isActive: () => isWebCodecsActive,
1492
- getStats: () => webCodecsService?.getStats() ?? null,
1493
- getLatency: () => latencyMs,
1494
- // Navigation handling
1495
- notifyNavigationComplete,
1496
- freezeForSpaNavigation: () => webCodecsService?.freezeForSpaNavigation()
1497
- };
1498
- });
1499
-
1500
- onDestroy(() => {
1501
- stopHealthCheck(); // Stop health monitoring
1502
- canvasSnapshots.clear(); // Free snapshot memory
1503
- if (longPressTimer) {
1504
- clearTimeout(longPressTimer);
1505
- longPressTimer = null;
1506
- }
1507
- if (webCodecsService) {
1508
- webCodecsService.destroy();
1509
- webCodecsService = null;
1510
- }
1511
- activeStreamingSessionId = null;
1512
- isStartingStream = false;
1513
- lastStartRequestId = null;
1514
- });
1515
- </script>
1516
-
1517
- <!-- Canvas - loading overlay is handled by parent PreviewContainer -->
1518
- <canvas
1519
- bind:this={canvasElement}
1520
- class="w-full h-full object-contain"
1521
- tabindex="0"
1522
- style="cursor: default;"
1523
- ></canvas>