History

Merge origin/main into orchestrator v2

Port current mainline fixes onto the orchestrator v2 architecture.

Julius Marminge committed 4 months ago

Commit 309fcab2 parents dac514e c8a04bd880 files · +82524 −12175Browse files

Unified · Split

880 files
  1. .agents/skills/ios-debugger-agent/LICENSE +21 −0
  2. .agents/skills/ios-debugger-agent/SKILL.md +64 −0
  3. .agents/skills/ios-debugger-agent/agents/openai.yaml +9 −0
  4. .agents/skills/ios-simulator-browser/LICENSE +21 −0
  5. .agents/skills/ios-simulator-browser/SKILL.md +51 −0
  6. .agents/skills/ios-simulator-browser/agents/openai.yaml +4 −0
  7. .agents/skills/test-t3-app/SKILL.md +71 −0
  8. .agents/skills/test-t3-app/agents/openai.yaml +4 −0
  9. .agents/skills/test-t3-app/references/sqlite-fixtures.md +58 −0
  10. .agents/skills/test-t3-mobile/SKILL.md +188 −0
  11. .agents/skills/test-t3-mobile/agents/openai.yaml +4 −0
  12. .claude/skills +1 −0
  13. .codex/config.toml +9 −0
  14. .cursor/rules/cursor-cloud.mdc +72 −0
  15. .env.example +4 −0
  16. .github/workflows/mobile-eas-preview.yml +4 −1
  17. .github/workflows/mobile-eas-production.yml +113 −0
  18. .github/workflows/mobile-showcase-screenshots.yml +134 −0
  19. .gitignore +3 −0
  20. .macroscope/check-run-agents/effect-service-conventions.md +9 −0
  21. .mcp.json +11 −0
  22. .plans/t3-connect-remote-setup.html +257 −0
  23. .vite-hooks/pre-commit +1 −0
  24. AGENTS.md +11 −24
  25. app.json +3 −0
  26. apps/desktop/package.json +2 −2
  27. apps/desktop/scripts/electron-launcher.mjs +47 −15
  28. apps/desktop/scripts/electron-launcher.test.mjs +54 −1
  29. apps/desktop/src/app/DesktopEnvironment.test.ts +24 −8
  30. apps/desktop/src/app/DesktopEnvironment.ts +6 −2
  31. apps/desktop/src/app/DesktopLifecycle.ts +7 −1
  32. apps/desktop/src/backend/DesktopBackendConfiguration.ts +1 −0
  33. apps/desktop/src/backend/DesktopBackendPool.test.ts +1 −0
  34. apps/desktop/src/backend/DesktopServerExposure.test.ts +1 −0
  35. apps/desktop/src/electron/ElectronMenu.test.ts +12 −2
  36. apps/desktop/src/electron/ElectronMenu.ts +13 −3
  37. apps/desktop/src/electron/ElectronUpdater.test.ts +14 −0
  38. apps/desktop/src/electron/ElectronUpdater.ts +6 −0
  39. apps/desktop/src/ipc/DesktopIpcHandlers.ts +2 −0
  40. apps/desktop/src/ipc/channels.ts +2 −0
  41. apps/desktop/src/ipc/methods/window.test.ts +21 −1
  42. apps/desktop/src/ipc/methods/window.ts +10 −0
  43. apps/desktop/src/preload.ts +13 −0
  44. apps/desktop/src/preview/BrowserSession.test.ts +51 −0
  45. apps/desktop/src/preview/BrowserSession.ts +18 −2
  46. apps/desktop/src/settings/DesktopAppSettings.test.ts +45 −0
  47. apps/desktop/src/settings/DesktopAppSettings.ts +77 −0
  48. apps/desktop/src/updates/DesktopUpdates.test.ts +50 −0
  49. apps/desktop/src/updates/DesktopUpdates.ts +13 −2
  50. apps/desktop/src/updates/releaseNotes.test.ts +67 −0
  51. apps/desktop/src/updates/releaseNotes.ts +125 −0
  52. apps/desktop/src/updates/updateMachine.test.ts +24 −0
  53. apps/desktop/src/updates/updateMachine.ts +6 −0
  54. apps/desktop/src/window/DesktopApplicationMenu.test.ts +1 −0
  55. apps/desktop/src/window/DesktopWindow.test.ts +554 −4
  56. apps/desktop/src/window/DesktopWindow.ts +180 −4
  57. apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +24 −0
  58. apps/desktop/src/wsl/DesktopWslEnvironment.ts +42 −4
  59. apps/marketing/public/harnesses/cursor_light.svg +1 −1
  60. apps/marketing/public/harnesses/grok-dark.svg +4 −0
  61. apps/marketing/src/components/LegalPage.astro +414 −0
  62. apps/marketing/src/layouts/Layout.astro +31 −2
  63. apps/marketing/src/lib/site.ts +1 −1
  64. apps/marketing/src/pages/index.astro +44 −10
  65. apps/marketing/src/pages/legal.astro +172 −0
  66. apps/marketing/src/pages/privacy-policy.astro +445 −0
  67. apps/marketing/src/pages/security-policy.astro +187 −0
  68. apps/marketing/src/pages/terms-of-service.astro +396 −0
  69. apps/mobile/.swiftlint.yml +1 −0
  70. apps/mobile/README.md +24 −0
  71. apps/mobile/app.config.ts +212 −47
  72. apps/mobile/assets/android-icon-background.png +0 −0
  73. apps/mobile/assets/android-icon-foreground.png +0 −0
  74. apps/mobile/assets/android-icon-mark.png +0 −0
  75. apps/mobile/assets/android-icon-monochrome.png +0 −0
  76. apps/mobile/assets/android-notification-icon.png +0 −0
  77. apps/mobile/assets/favicon.png +0 −0
  78. apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg +0 −0
  79. apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png +0 −0
  80. apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg +0 −3
  81. apps/mobile/assets/icon.png +0 −0
  82. apps/mobile/assets/splash-icon.png +0 −0
  83. apps/mobile/assets/widget/T3Mark.svg +3 −0
  84. apps/mobile/eas.json +16 −5
  85. apps/mobile/global.css +29 −26
  86. apps/mobile/index.ts +15 −1
  87. apps/mobile/metro.config.js +9 −0
  88. apps/mobile/modules/t3-composer-editor/android/build.gradle +19 −0
  89. apps/mobile/modules/t3-composer-editor/android/src/main/AndroidManifest.xml +1 −0
  90. apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt +72 −0
  91. apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt +480 −0
  92. apps/mobile/modules/t3-composer-editor/expo-module.config.json +4 −1
  93. apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift +1 −0
  94. apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +24 −2
  95. apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx +14 −5
  96. apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx +21 −4
  97. apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts +1 −0
  98. apps/mobile/modules/t3-native-controls/android/build.gradle +19 −0
  99. apps/mobile/modules/t3-native-controls/android/src/main/AndroidManifest.xml +1 −0
  100. apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3HeaderButtonView.kt +97 −0
  101. apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt +47 −0
  102. apps/mobile/modules/t3-native-controls/expo-module.config.json +9 −0
  103. apps/mobile/modules/t3-native-controls/ios/T3HeaderButtonView.swift +62 −0
  104. apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift +131 −0
  105. apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec +19 −0
  106. apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +57 −0
  107. apps/mobile/modules/t3-review-diff/android/build.gradle +19 −0
  108. apps/mobile/modules/t3-review-diff/android/src/main/AndroidManifest.xml +1 −0
  109. apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +315 −0
  110. apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt +78 −0
  111. apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +1429 −0
  112. apps/mobile/modules/t3-review-diff/expo-module.config.json +4 −1
  113. apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift +40 −13
  114. apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +270 −60
  115. apps/mobile/modules/t3-review-diff/package.json +5 −0
  116. apps/mobile/modules/t3-terminal/README.md +15 −3
  117. apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md +18 −0
  118. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/LICENSE +21 −0
  119. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/VERSION +1 −0
  120. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt.h +154 −0
  121. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/allocator.h +255 −0
  122. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/build_info.h +150 −0
  123. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/color.h +97 −0
  124. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/device.h +151 −0
  125. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/focus.h +76 −0
  126. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/formatter.h +207 −0
  127. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref.h +212 −0
  128. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref_tracked.h +139 −0
  129. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key.h +73 −0
  130. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/encoder.h +255 −0
  131. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/event.h +482 −0
  132. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/kitty_graphics.h +775 −0
  133. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/modes.h +198 −0
  134. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse.h +70 −0
  135. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/encoder.h +214 −0
  136. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/event.h +195 −0
  137. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/osc.h +215 −0
  138. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/paste.h +101 −0
  139. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/point.h +89 −0
  140. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/render.h +729 −0
  141. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/screen.h +400 −0
  142. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/selection.h +1061 −0
  143. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sgr.h +350 −0
  144. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/size_report.h +101 −0
  145. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/style.h +139 −0
  146. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sys.h +210 −0
  147. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/terminal.h +1322 −0
  148. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/types.h +335 −0
  149. apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/wasm.h +160 −0
  150. apps/mobile/modules/t3-terminal/android/.gitignore +1 −0
  151. apps/mobile/modules/t3-terminal/android/build.gradle +14 −0
  152. apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Bold.ttf +0 −0
  153. apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Regular.ttf +0 −0
  154. apps/mobile/modules/t3-terminal/android/src/main/cpp/CMakeLists.txt +23 −0
  155. apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp +516 −0
  156. apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/GhosttyBridge.kt +64 −0
  157. apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt +18 −0
  158. apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt +327 −101
  159. apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt +628 −0
  160. apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalFrame.kt +82 −0
  161. apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so +0 −0
  162. apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so +0 −0
  163. apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so +0 −0
  164. apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so +0 −0
  165. apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift +14 −0
  166. apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift +159 −3
  167. apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh +152 −0
  168. apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0001-link-android-libvt-with-libc.patch +25 −0
  169. apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0002-align-android-libvt-to-16kb-pages.patch +11 −0
  170. apps/mobile/package.json +42 −21
  171. apps/mobile/plugins/lib/addWidgetAssetCatalog.cjs +81 −0
  172. apps/mobile/plugins/withAndroidGradleHeap.cjs +22 −0
  173. apps/mobile/plugins/withAndroidModernAlertDialog.cjs +188 −0
  174. apps/mobile/plugins/withAndroidModernPopupMenu.cjs +250 −0
  175. apps/mobile/plugins/withAndroidPredictiveBackCompat.cjs +104 −0
  176. apps/mobile/plugins/withIosCocoaPodsUuidCache.cjs +52 −0
  177. apps/mobile/plugins/withIosSceneLifecycle.cjs +99 −0
  178. apps/mobile/plugins/withShareExtensionDisplayName.cjs +93 −0
  179. apps/mobile/plugins/withWidgetLogoAsset.cjs +68 −0
  180. apps/mobile/plugins/withoutIosPersonalTeamCapabilities.cjs +10 −0
  181. apps/mobile/scripts/wire-widget-asset-catalog.cjs +30 −0
  182. apps/mobile/src/App.tsx +88 −0
  183. apps/mobile/src/Stack.tsx +567 −0
  184. apps/mobile/src/app/+not-found.tsx +0 −43
  185. apps/mobile/src/app/_layout.tsx +0 −149
  186. apps/mobile/src/app/connections/_layout.tsx +0 −29
  187. apps/mobile/src/app/index.tsx +0 −120
  188. apps/mobile/src/app/new/_layout.tsx +0 −50
  189. apps/mobile/src/app/new/add-project/destination.tsx +0 −5
  190. apps/mobile/src/app/new/add-project/index.tsx +0 −5
  191. apps/mobile/src/app/new/add-project/local.tsx +0 −5
  192. apps/mobile/src/app/new/add-project/repository.tsx +0 −23
  193. apps/mobile/src/app/new/draft.tsx +0 −29
  194. apps/mobile/src/app/new/index.tsx +0 −218
  195. apps/mobile/src/app/settings/_layout.tsx +0 −62
  196. apps/mobile/src/app/settings/archive.tsx +0 −3
  197. apps/mobile/src/app/settings/auth.tsx +0 −33
  198. apps/mobile/src/app/settings/environment-new.tsx +0 −1
  199. apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx +0 −107
  200. apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx +0 −5
  201. apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx +0 −5
  202. apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx +0 −5
  203. apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx +0 −58
  204. apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx +0 −5
  205. apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx +0 −5
  206. apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx +0 −5
  207. apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx +0 −18
  208. apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx +0 −5
  209. apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx +0 −5
  210. apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +0 −10
  211. apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx +0 −5
  212. apps/mobile/src/components/AndroidAnchoredMenu.tsx +337 −0
  213. apps/mobile/src/components/AndroidScreenHeader.tsx +117 −0
  214. apps/mobile/src/components/AppSymbol.tsx +202 −0
  215. apps/mobile/src/components/AppText.tsx +5 −14
  216. apps/mobile/src/components/BrandMark.tsx +15 −10
  217. apps/mobile/src/components/ComposerAttachmentStrip.tsx +5 −11
  218. apps/mobile/src/components/ComposerToolbarTrigger.tsx +11 −7
  219. apps/mobile/src/components/ConfirmDialogHost.tsx +111 −0
  220. apps/mobile/src/components/ControlPill.tsx +58 −6
  221. apps/mobile/src/components/CopyTextButton.tsx +6 −2
  222. apps/mobile/src/components/EmptyState.tsx +23 −1
  223. apps/mobile/src/components/ErrorBanner.tsx +1 −1
  224. apps/mobile/src/components/GlassSafeAreaView.tsx +5 −15
  225. apps/mobile/src/components/GlassSurface.tsx +1 −1
  226. apps/mobile/src/components/OverlayPortal.tsx +69 −0
  227. apps/mobile/src/components/PierreEntryIcon.tsx +1 −1
  228. apps/mobile/src/components/ProjectFavicon.tsx +11 −5
  229. apps/mobile/src/components/T3Wordmark.tsx +23 −0
  230. apps/mobile/src/connection/catalog-store.ts +25 −26
  231. apps/mobile/src/connection/environment-cache-store.test.ts +97 −0
  232. apps/mobile/src/connection/environment-cache-store.ts +234 −0
  233. apps/mobile/src/connection/platform.ts +94 −79
  234. apps/mobile/src/connection/runtime.ts +6 −1
  235. apps/mobile/src/connection/storage.test.ts +25 −12
  236. apps/mobile/src/connection/storage.ts +2 −300
  237. apps/mobile/src/features/agent-awareness/capabilities.ts +5 −0
  238. apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts +87 −18
  239. apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts +65 −39
  240. apps/mobile/src/features/agent-awareness/notificationNavigation.ts +4 −4
  241. apps/mobile/src/features/agent-awareness/registrationPayload.ts +16 −3
  242. apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +321 −3
  243. apps/mobile/src/features/agent-awareness/remoteRegistration.ts +442 −53
  244. apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx +1 −1
  245. apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx +487 −271
  246. apps/mobile/src/features/cloud/CloudAuthProvider.tsx +23 −1
  247. apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx +26 −113
  248. apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx +137 −0
  249. apps/mobile/src/features/cloud/connectOnboarding.ts +24 −0
  250. apps/mobile/src/features/cloud/connectOnboardingNavigation.ts +49 −0
  251. apps/mobile/src/features/cloud/connectOnboardingOptOut.ts +21 −0
  252. apps/mobile/src/features/cloud/dpop.ts +41 −9
  253. apps/mobile/src/features/cloud/linkEnvironment.test.ts +78 −8
  254. apps/mobile/src/features/cloud/linkEnvironment.ts +49 −22
  255. apps/mobile/src/features/connection/CloudEnvironmentRows.tsx +77 −149
  256. apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx +10 −23
  257. apps/mobile/src/features/connection/ConnectionSheetButton.tsx +21 −36
  258. apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +65 −45
  259. apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx +31 −23
  260. apps/mobile/src/features/connection/EnvironmentConnectionNotice.tsx +3 −3
  261. apps/mobile/src/features/connection/environmentSections.test.ts +1 −1
  262. apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts +189 −0
  263. apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts +72 −8
  264. apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts +39 −2
  265. apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts +139 −6
  266. apps/mobile/src/features/files/FileMarkdownPreview.tsx +69 −15
  267. apps/mobile/src/features/files/FileTreeBrowser.tsx +145 −55
  268. apps/mobile/src/features/files/SourceFileSurface.tsx +98 −65
  269. apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +360 −319
  270. apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx +1 −1
  271. apps/mobile/src/features/files/nativeSourceFileAdapter.ts +26 −14
  272. apps/mobile/src/features/files/preload-workspace-file.ts +74 −0
  273. apps/mobile/src/features/files/source-file-document.test.ts +16 −0
  274. apps/mobile/src/features/files/source-file-document.ts +54 −0
  275. apps/mobile/src/features/files/sourceHighlightingState.test.ts +1 −1
  276. apps/mobile/src/features/files/thread-file-navigator-pane.tsx +175 −0
  277. apps/mobile/src/features/home/AndroidHomeFab.tsx +51 −0
  278. apps/mobile/src/features/home/HomeHeader.tsx +383 −206
  279. apps/mobile/src/features/home/HomeRouteScreen.tsx +155 −0
  280. apps/mobile/src/features/home/HomeScreen.tsx +332 −452
  281. apps/mobile/src/features/home/WorkspaceConnectionStatus.test.ts +87 −0
  282. apps/mobile/src/features/home/WorkspaceConnectionStatus.tsx +56 −0
  283. apps/mobile/src/features/home/home-list-filter-menu.ts +120 −0
  284. apps/mobile/src/features/home/home-list-options.test.ts +31 −0
  285. apps/mobile/src/features/home/home-list-options.ts +144 −0
  286. apps/mobile/src/features/home/homeListItems.test.ts +254 −0
  287. apps/mobile/src/features/home/homeListItems.ts +207 −0
  288. apps/mobile/src/features/home/homeThreadList.test.ts +143 −0
  289. apps/mobile/src/features/home/homeThreadList.ts +130 −5
  290. apps/mobile/src/features/home/thread-swipe-actions.tsx +253 −12
  291. apps/mobile/src/features/home/usePendingTaskListActions.ts +57 −0
  292. apps/mobile/src/features/home/useThreadListActions.ts +18 −9
  293. apps/mobile/src/features/home/workspace-connection-status.ts +26 −0
  294. apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx +73 −0
  295. apps/mobile/src/features/keyboard/hardwareKeyboardCommands.test.ts +28 −0
  296. apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts +78 −0
  297. apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +526 −0
  298. apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx +30 −0
  299. apps/mobile/src/features/layout/native-glass-header-items.ts +33 −0
  300. apps/mobile/src/features/layout/native-mail-search-toolbar.ts +25 −0
  301. apps/mobile/src/features/layout/workspace-inspector-pane.tsx +146 −0
  302. apps/mobile/src/features/layout/workspace-pane-animation.ts +16 −0
  303. apps/mobile/src/features/layout/workspace-pane-divider.tsx +107 −0
  304. apps/mobile/src/features/layout/workspace-sidebar-toolbar.tsx +32 −0
  305. apps/mobile/src/features/projects/AddProjectDestinationRoute.tsx +15 −0
  306. apps/mobile/src/features/projects/AddProjectLocalRoute.tsx +12 −0
  307. apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx +31 −0
  308. apps/mobile/src/features/projects/AddProjectScreen.tsx +70 −71
  309. apps/mobile/src/features/projects/AddProjectSourceRoute.tsx +5 −0
  310. apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +83 −52
  311. apps/mobile/src/features/review/ReviewSheet.tsx +592 −187
  312. apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts +56 −0
  313. apps/mobile/src/features/review/nativeReviewDiffAdapter.ts +98 −36
  314. apps/mobile/src/features/review/review-section-menu.test.ts +40 −0
  315. apps/mobile/src/features/review/review-section-menu.ts +21 −0
  316. apps/mobile/src/features/review/reviewDiffBridgeKeys.test.ts +1 −1
  317. apps/mobile/src/features/review/reviewDiffBridgeKeys.ts +35 −0
  318. apps/mobile/src/features/review/reviewDiffRendering.tsx +18 −11
  319. apps/mobile/src/features/review/reviewPaneSelection.test.ts +35 −0
  320. apps/mobile/src/features/review/reviewPaneSelection.ts +16 −0
  321. apps/mobile/src/features/review/useNativeReviewDiffBridge.ts +6 −36
  322. apps/mobile/src/features/review/useReviewCommentSelectionController.ts +6 −7
  323. apps/mobile/src/features/review/useReviewDiffData.ts +11 −9
  324. apps/mobile/src/features/review/useReviewDiffPrewarming.ts +101 −0
  325. apps/mobile/src/features/settings/SettingsAppearanceRouteScreen.tsx +28 −0
  326. apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx +39 −0
  327. apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx +215 −0
  328. apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx +179 −0
  329. apps/mobile/src/features/settings/SettingsLegalRouteScreen.tsx +6 −0
  330. apps/mobile/src/features/settings/SettingsRouteScreen.tsx +221 −165
  331. apps/mobile/src/features/settings/SettingsWaitlistRouteScreen.tsx +19 −14
  332. apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx +126 −0
  333. apps/mobile/src/features/settings/appearance/components/AppearancePreviews.tsx +177 −0
  334. apps/mobile/src/features/settings/appearance/components/FontSizeSliderRow.tsx +214 −0
  335. apps/mobile/src/features/settings/appearance/sections/CodeAppearanceSection.tsx +64 −0
  336. apps/mobile/src/features/settings/appearance/sections/TerminalAppearanceSection.tsx +54 −0
  337. apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx +34 −0
  338. apps/mobile/src/features/settings/appearance/useAppearanceCodeSurface.ts +34 −0
  339. apps/mobile/src/features/settings/appearance/useScaledTextRole.ts +36 −0
  340. apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx +186 −0
  341. apps/mobile/src/features/settings/components/SettingsRow.tsx +95 −0
  342. apps/mobile/src/features/settings/components/SettingsSection.tsx +26 −0
  343. apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx +40 −0
  344. apps/mobile/src/features/settings/components/settings-sheet-targets.ts +7 −0
  345. apps/mobile/src/features/settings/lib/legal-document-url.test.ts +24 −0
  346. apps/mobile/src/features/settings/lib/legal-document-url.ts +58 −0
  347. apps/mobile/src/features/sharing/IncomingShareProvider.tsx +310 −0
  348. apps/mobile/src/features/sharing/incoming-share-inbox.test.ts +236 −0
  349. apps/mobile/src/features/sharing/incoming-share-inbox.ts +193 −0
  350. apps/mobile/src/features/sharing/incoming-share-model.test.ts +196 −0
  351. apps/mobile/src/features/sharing/incoming-share-model.ts +217 −0
  352. apps/mobile/src/features/sharing/incoming-share-presentation.test.ts +92 −0
  353. apps/mobile/src/features/sharing/incoming-share-presentation.ts +71 −0
  354. apps/mobile/src/features/sharing/incoming-share-storage.ts +80 −0
  355. apps/mobile/src/features/shortcuts/appShortcuts.test.ts +155 −0
  356. apps/mobile/src/features/shortcuts/appShortcuts.ts +137 −0
  357. apps/mobile/src/features/shortcuts/useAppShortcuts.ts +136 −0
  358. apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx +224 −0
  359. apps/mobile/src/features/showcase/nativeShowcaseScene.ts +68 −0
  360. apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts +70 −0
  361. apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts +70 −0
  362. apps/mobile/src/features/showcase/showcasePendingTasks.test.ts +72 −0
  363. apps/mobile/src/features/showcase/showcasePendingTasks.ts +66 −0
  364. apps/mobile/src/features/showcase/showcaseRetry.test.ts +44 −0
  365. apps/mobile/src/features/showcase/showcaseRetry.ts +46 −0
  366. apps/mobile/src/features/terminal/NativeTerminalSurface.tsx +26 −61
  367. apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx +91 −1
  368. apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +371 −169
  369. apps/mobile/src/features/terminal/nativeTerminalModule.ts +22 −1
  370. apps/mobile/src/features/terminal/terminalMenu.test.ts +70 −0
  371. apps/mobile/src/features/terminal/terminalMenu.ts +29 −0
  372. apps/mobile/src/features/terminal/terminalPreferences.ts +1 −1
  373. apps/mobile/src/features/threads/ComposerCommandPopover.tsx +7 −24
  374. apps/mobile/src/features/threads/GitActionProgressOverlay.tsx +3 −2
  375. apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx +49 −0
  376. apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +719 −117
  377. apps/mobile/src/features/threads/NewTaskRouteScreen.tsx +326 −0
  378. apps/mobile/src/features/threads/PendingApprovalCard.tsx +1 −1
  379. apps/mobile/src/features/threads/PendingUserInputCard.tsx +1 −1
  380. apps/mobile/src/features/threads/ThreadActivityInspector.tsx +24 −7
  381. apps/mobile/src/features/threads/ThreadComposer.tsx +203 −137
  382. apps/mobile/src/features/threads/ThreadDetailScreen.tsx +180 −130
  383. apps/mobile/src/features/threads/ThreadFeed.tsx +480 −216
  384. apps/mobile/src/features/threads/ThreadGitControls.tsx +382 −122
  385. apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx +0 −282
  386. apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +753 −0
  387. apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx +10 −8
  388. apps/mobile/src/features/threads/ThreadRouteScreen.tsx +552 −139
  389. apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +127 −149
  390. apps/mobile/src/features/threads/git/GitCommitSheet.tsx +161 −174
  391. apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +40 −25
  392. apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +289 −118
  393. apps/mobile/src/features/threads/git/git-overview-navigation.test.ts +13 −0
  394. apps/mobile/src/features/threads/git/git-overview-navigation.ts +5 −0
  395. apps/mobile/src/features/threads/git/gitSheetComponents.tsx +23 −41
  396. apps/mobile/src/features/threads/markdownCodeHighlightState.ts +87 −0
  397. apps/mobile/src/features/threads/new-task-flow-provider.tsx +404 −48
  398. apps/mobile/src/features/threads/sidebar-filter-button.tsx +42 −0
  399. apps/mobile/src/features/threads/sidebar-header-actions.android.tsx +16 −0
  400. apps/mobile/src/features/threads/sidebar-header-actions.tsx +58 −0
  401. apps/mobile/src/features/threads/sidebar-native-header-items.ts +63 −0
  402. apps/mobile/src/features/threads/sidebar-navigation-shell.tsx +73 −0
  403. apps/mobile/src/features/threads/thread-inspector-content-stack.tsx +101 −0
  404. apps/mobile/src/features/threads/thread-list-items.tsx +666 −0
  405. apps/mobile/src/features/threads/thread-work-log.tsx +41 −33
  406. apps/mobile/src/features/threads/threadContentPresentation.ts +7 −1
  407. apps/mobile/src/features/threads/threadPresentation.ts +104 −19
  408. apps/mobile/src/features/threads/use-project-actions.ts +22 −52
  409. apps/mobile/src/lib/adaptive-navigation.test.ts +68 −0
  410. apps/mobile/src/lib/adaptive-navigation.ts +35 −0
  411. apps/mobile/src/lib/appBlurTarget.ts +8 −0
  412. apps/mobile/src/lib/appearancePreferences.test.ts +142 −0
  413. apps/mobile/src/lib/appearancePreferences.ts +245 −0
  414. apps/mobile/src/lib/base64.ts +4 −0
  415. apps/mobile/src/lib/composerImages.test.ts +31 −1
  416. apps/mobile/src/lib/composerImages.ts +14 −5
  417. apps/mobile/src/lib/layout.test.ts +343 −0
  418. apps/mobile/src/lib/layout.ts +226 −4
  419. apps/mobile/src/lib/native-glass-capability.test.ts +18 −0
  420. apps/mobile/src/lib/native-glass-capability.ts +6 −0
  421. apps/mobile/src/lib/projectThreadStartTurn.ts +90 −0
  422. apps/mobile/src/lib/routes.test.ts +0 −45
  423. apps/mobile/src/lib/routes.ts +0 −134
  424. apps/mobile/src/lib/runtime.ts +3 −0
  425. apps/mobile/src/lib/serialized-async-queue.test.ts +45 −0
  426. apps/mobile/src/lib/serialized-async-queue.ts +16 −0
  427. apps/mobile/src/lib/storage.test.ts +148 −8
  428. apps/mobile/src/lib/storage.ts +0 −201
  429. apps/mobile/src/lib/time.ts +4 −3
  430. apps/mobile/src/lib/typography.test.ts +4 −7
  431. apps/mobile/src/lib/typography.ts +10 −11
  432. apps/mobile/src/lib/useFontFamily.ts +15 −0
  433. apps/mobile/src/lib/uuid.ts +6 −0
  434. apps/mobile/src/native/StackHeader.tsx +457 −0
  435. apps/mobile/src/native/T3ComposerEditor.android.tsx +6 −0
  436. apps/mobile/src/native/T3ComposerEditor.ios.tsx +10 −6
  437. apps/mobile/src/native/T3ComposerEditor.native.tsx +286 −0
  438. apps/mobile/src/native/T3ComposerEditor.tsx +7 −3
  439. apps/mobile/src/native/T3ComposerEditor.types.ts +4 −0
  440. apps/mobile/src/native/T3HeaderButton.android.tsx +26 −0
  441. apps/mobile/src/native/T3KeyboardCommands.ios.tsx +31 −0
  442. apps/mobile/src/native/T3KeyboardCommands.tsx +13 −0
  443. apps/mobile/src/native/native-glass.ts +9 −0
  444. apps/mobile/src/native/scrollEdgeEffects.test.ts +29 −0
  445. apps/mobile/src/native/scrollEdgeEffects.ts +37 −0
  446. apps/mobile/src/persistence/imperative.ts +53 −0
  447. apps/mobile/src/persistence/layer.ts +16 −0
  448. apps/mobile/src/persistence/mobile-database.test.ts +71 −0
  449. apps/mobile/src/persistence/mobile-database.ts +409 −0
  450. apps/mobile/src/persistence/mobile-preferences.ts +305 −0
  451. apps/mobile/src/persistence/mobile-secure-storage.ts +52 −0
  452. apps/mobile/src/persistence/mobile-storage.ts +266 −0
  453. apps/mobile/src/state/client-cache-state.ts +87 −0
  454. apps/mobile/src/state/preferences.test.ts +272 −0
  455. apps/mobile/src/state/preferences.ts +124 −0
  456. apps/mobile/src/state/thread-outbox-manager.ts +35 −1
  457. apps/mobile/src/state/thread-outbox-model.ts +56 −2
  458. apps/mobile/src/state/thread-outbox.test.ts +146 −0
  459. apps/mobile/src/state/thread-outbox.ts +5 −0
  460. apps/mobile/src/state/thread-pr-presentation.ts +36 −0
  461. apps/mobile/src/state/use-composer-drafts.test.ts +89 −1
  462. apps/mobile/src/state/use-composer-drafts.ts +152 −2
  463. apps/mobile/src/state/use-pending-new-tasks.ts +35 −0
  464. apps/mobile/src/state/use-thread-outbox-drain.ts +173 −62
  465. apps/mobile/src/state/use-thread-outbox.ts +31 −1
  466. apps/mobile/src/state/use-thread-pr.test.ts +36 −0
  467. apps/mobile/src/state/use-thread-pr.ts +41 −0
  468. apps/mobile/src/state/use-thread-selection.ts +138 −20
  469. apps/mobile/src/widgets/AgentActivity.test.ts +242 −8
  470. apps/mobile/src/widgets/AgentActivity.tsx +290 −230
  471. apps/server/package.json +1 −1
  472. apps/server/scripts/t3-sqlite-state.test.ts +119 −0
  473. apps/server/scripts/t3-sqlite-state.ts +285 −0
  474. apps/server/src/assets/AssetAccess.test.ts +3 −1
  475. apps/server/src/assets/AssetAccess.ts +4 −8
  476. apps/server/src/auth/http.ts +10 −0
  477. apps/server/src/cli/config.test.ts +23 −6
  478. apps/server/src/cli/config.ts +11 −7
  479. apps/server/src/cli/connect.test.ts +54 −1
  480. apps/server/src/cli/connect.ts +354 −54
  481. apps/server/src/cli/project.ts +5 −0
  482. apps/server/src/cloud/CliState.test.ts +23 −0
  483. apps/server/src/cloud/CliState.ts +26 −2
  484. apps/server/src/cloud/CliTokenManager.test.ts +264 −0
  485. apps/server/src/cloud/CliTokenManager.ts +283 −68
  486. apps/server/src/cloud/bootService.test.ts +529 −0
  487. apps/server/src/cloud/bootService.ts +452 −0
  488. apps/server/src/cloud/cliAuthHtml.test.ts +31 −0
  489. apps/server/src/cloud/cliAuthHtml.ts +155 −0
  490. apps/server/src/cloud/http.test.ts +37 −1
  491. apps/server/src/cloud/http.ts +40 −18
  492. apps/server/src/cloud/publicConfig.test.ts +35 −0
  493. apps/server/src/cloud/publicConfig.ts +40 −1
  494. apps/server/src/config.ts +9 −1
  495. apps/server/src/environment/ServerEnvironment.test.ts +1 −0
  496. apps/server/src/environment/ServerEnvironment.ts +1 −0
  497. apps/server/src/http.ts +1 −16
  498. apps/server/src/imageMime.test.ts +57 −0
  499. apps/server/src/imageMime.ts +63 −8
  500. apps/server/src/keybindings.test.ts +22 −0
  501. apps/server/src/keybindings.ts +3 −1
  502. apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +6 −0
  503. apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts +2 −1
  504. apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +24 −20
  505. apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +2 −0
  506. apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts +3 −0
  507. apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts +6 −2
  508. apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts +3 −0
  509. apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts +7 −1
  510. apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts +7 −0
  511. apps/server/src/orchestration-v2/ShellStream.test.ts +33 −0
  512. apps/server/src/orchestration-v2/ShellStream.ts +18 −0
  513. apps/server/src/orchestration-v2/http.ts +117 −0
  514. apps/server/src/orchestration/Layers/OrchestrationEngine.ts +7 −2
  515. apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +31 −0
  516. apps/server/src/orchestration/Services/OrchestrationEngine.ts +12 −0
  517. apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +11 −0
  518. apps/server/src/orchestration/commandInvariants.ts +25 −0
  519. apps/server/src/orchestration/decider.ts +23 −2
  520. apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts +14 −0
  521. apps/server/src/persistence/Layers/OrchestrationEventStore.ts +3 −2
  522. apps/server/src/persistence/Migrations.ts +4 −8
  523. apps/server/src/persistence/ProviderSessionRuntime.ts +20 −6
  524. apps/server/src/persistence/RepositoryErrorCorrelation.test.ts +18 −10
  525. apps/server/src/persistence/Services/OrchestrationEventStore.ts +6 −0
  526. apps/server/src/provider/CodexDeveloperInstructions.ts +25 −0
  527. apps/server/src/provider/Drivers/ClaudeDriver.ts +3 −2
  528. apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +124 −0
  529. apps/server/src/provider/Drivers/ClaudeExecutable.ts +90 −0
  530. apps/server/src/provider/Drivers/ClaudeHome.test.ts +11 −2
  531. apps/server/src/provider/Drivers/ClaudeHome.ts +9 −2
  532. apps/server/src/provider/Drivers/CodexHomeLayout.test.ts +36 −0
  533. apps/server/src/provider/Drivers/CodexHomeLayout.ts +29 −10
  534. apps/server/src/provider/Drivers/GrokDriver.ts +2 −0
  535. apps/server/src/provider/Layers/ClaudeProvider.ts +68 −12
  536. apps/server/src/provider/Layers/CodexProvider.ts +14 −4
  537. apps/server/src/provider/Layers/CodexSessionRuntime.test.ts +101 −3
  538. apps/server/src/provider/Layers/CodexSessionRuntime.ts +14 −14
  539. apps/server/src/provider/Layers/CursorProvider.ts +1 −4
  540. apps/server/src/provider/Layers/GrokProvider.ts +7 −9
  541. apps/server/src/provider/Layers/OpenCodeProvider.test.ts +20 −2
  542. apps/server/src/provider/Layers/OpenCodeProvider.ts +27 −40
  543. apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts +1 −0
  544. apps/server/src/provider/Layers/ProviderRegistry.test.ts +48 −6
  545. apps/server/src/provider/Layers/codexLaunchArgs.test.ts +59 −0
  546. apps/server/src/provider/Layers/codexLaunchArgs.ts +48 −0
  547. apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +37 −0
  548. apps/server/src/provider/acp/AcpSessionRuntime.ts +23 −6
  549. apps/server/src/provider/acp/GrokAcpSupport.ts +2 −1
  550. apps/server/src/provider/opencodeRuntime.cliParsers.test.ts +229 −0
  551. apps/server/src/provider/opencodeRuntime.ts +177 −1
  552. apps/server/src/provider/providerSnapshot.test.ts +20 −2
  553. apps/server/src/provider/providerSnapshot.ts +2 −3
  554. apps/server/src/relay/AgentAwarenessRelay.ts +88 −0
  555. apps/server/src/server.ts +6 −1
  556. apps/server/src/serverSettings.test.ts +2 −0
  557. apps/server/src/terminal/Manager.test.ts +57 −0
  558. apps/server/src/terminal/Manager.ts +48 −1
  559. apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +14 −14
  560. apps/server/src/textGeneration/CodexTextGeneration.test.ts +70 −2
  561. apps/server/src/textGeneration/CodexTextGeneration.ts +3 −0
  562. apps/server/src/textGeneration/GrokTextGeneration.ts +3 −1
  563. apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts +8 −0
  564. apps/server/src/vcs/GitVcsDriverCore.test.ts +91 −0
  565. apps/server/src/vcs/GitVcsDriverCore.ts +18 −3
  566. apps/server/src/ws.ts +206 −83
  567. apps/server/vite.config.ts +3 −0
  568. apps/web/package.json +1 −1
  569. apps/web/public/apple-touch-icon.png +0 −0
  570. apps/web/public/favicon-16x16.png +0 −0
  571. apps/web/public/favicon-32x32.png +0 −0
  572. apps/web/public/favicon.ico +0 −0
  573. apps/web/src/assets/assetUrls.ts +22 −2
  574. apps/web/src/branding.logic.ts +4 −0
  575. apps/web/src/branding.test.ts +11 −0
  576. apps/web/src/browser/browserTargetResolver.test.ts +104 −2
  577. apps/web/src/browser/browserTargetResolver.ts +95 −46
  578. apps/web/src/cloud/connectCliAuth.test.ts +69 −0
  579. apps/web/src/cloud/connectCliAuth.ts +91 −0
  580. apps/web/src/cloud/connectOnboarding.ts +18 −0
  581. apps/web/src/cloud/linkEnvironment.test.ts +55 −0
  582. apps/web/src/cloud/linkEnvironment.ts +19 −5
  583. apps/web/src/cloud/linkEnvironmentAtoms.ts +6 −2
  584. apps/web/src/cloud/publicConfig.ts +1 −1
  585. apps/web/src/cloud/useCloudLinkController.ts +163 −0
  586. apps/web/src/components/AppSidebarLayout.tsx +96 −18
  587. apps/web/src/components/ChatMarkdown.tsx +22 −5
  588. apps/web/src/components/ChatView.logic.test.ts +38 −1
  589. apps/web/src/components/ChatView.logic.ts +9 −1
  590. apps/web/src/components/ChatView.tsx +257 −53
  591. apps/web/src/components/ComposerPromptEditor.test.ts +73 −0
  592. apps/web/src/components/ComposerPromptEditor.tsx +149 −4
  593. apps/web/src/components/ConnectionStatusDot.tsx +56 −0
  594. apps/web/src/components/DiffPanel.tsx +14 −4
  595. apps/web/src/components/GitActionsControl.logic.test.ts +13 −0
  596. apps/web/src/components/GitActionsControl.logic.ts +10 −0
  597. apps/web/src/components/GitActionsControl.tsx +2 −3
  598. apps/web/src/components/ProjectFavicon.tsx +2 −1
  599. apps/web/src/components/RightPanelTabs.tsx +15 −0
  600. apps/web/src/components/Sidebar.logic.test.ts +140 −0
  601. apps/web/src/components/Sidebar.logic.ts +120 −20
  602. apps/web/src/components/Sidebar.tsx +96 −33
  603. apps/web/src/components/SidebarStageBackdrop.tsx +320 −0
  604. apps/web/src/components/ThreadStatusIndicators.tsx +5 −3
  605. apps/web/src/components/ThreadTerminalDrawer.tsx +43 −14
  606. apps/web/src/components/auth/AuthSurfaceShell.tsx +44 −0
  607. apps/web/src/components/chat/ChangedFilesTree.test.tsx +26 −1
  608. apps/web/src/components/chat/ChangedFilesTree.tsx +64 −32
  609. apps/web/src/components/chat/ChatComposer.tsx +128 −38
  610. apps/web/src/components/chat/ComposerBannerStack.test.tsx +37 −0
  611. apps/web/src/components/chat/ComposerBannerStack.tsx +28 −19
  612. apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx +29 −0
  613. apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx +18 −0
  614. apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +1 −1
  615. apps/web/src/components/chat/DraftHeroHeadline.tsx +114 −0
  616. apps/web/src/components/chat/MessagesTimeline.logic.ts +39 −0
  617. apps/web/src/components/chat/MessagesTimeline.test.tsx +77 −1
  618. apps/web/src/components/chat/MessagesTimeline.tsx +113 −48
  619. apps/web/src/components/chat/OpenInPicker.tsx +39 −4
  620. apps/web/src/components/chat/ThreadErrorBanner.tsx +9 −9
  621. apps/web/src/components/chat/TraitsPicker.tsx +96 −56
  622. apps/web/src/components/chat/composerMentionDrag.test.ts +123 −0
  623. apps/web/src/components/chat/composerMentionDrag.ts +98 −0
  624. apps/web/src/components/chat/draftHeroTransition.test.ts +123 −0
  625. apps/web/src/components/chat/draftHeroTransition.ts +82 −0
  626. apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx +260 −0
  627. apps/web/src/components/cloud/ConnectCliAuthSurface.tsx +188 −0
  628. apps/web/src/components/cloud/ConnectOnboardingDialog.tsx +433 −0
  629. apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.test.ts +55 −0
  630. apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.ts +58 −0
  631. apps/web/src/components/composerInlineTokenPaste.ts +104 −0
  632. apps/web/src/components/desktopUpdate.logic.test.ts +1 −0
  633. apps/web/src/components/files/FileBrowserPanel.tsx +140 −0
  634. apps/web/src/components/files/FilePreviewPanel.tsx +50 −2
  635. apps/web/src/components/files/fileTreeDragMention.test.ts +112 −0
  636. apps/web/src/components/files/fileTreeDragMention.ts +95 −0
  637. apps/web/src/components/files/projectFilesQueryState.ts +8 −2
  638. apps/web/src/components/preview/AgentBrowserCursor.tsx +1 −1
  639. apps/web/src/components/preview/PreviewAutomationHosts.tsx +9 −7
  640. apps/web/src/components/preview/PreviewChromeRow.tsx +1 −1
  641. apps/web/src/components/preview/PreviewLocalServerCard.tsx +1 −1
  642. apps/web/src/components/preview/PreviewPanelShell.test.ts +13 −0
  643. apps/web/src/components/preview/PreviewPanelShell.tsx +3 −0
  644. apps/web/src/components/preview/PreviewUnreachable.tsx +1 −1
  645. apps/web/src/components/preview/PreviewView.test.tsx +194 −0
  646. apps/web/src/components/preview/PreviewView.tsx +33 −15
  647. apps/web/src/components/preview/errorCodeMessages.ts +3 −3
  648. apps/web/src/components/settings/ConnectionsSettings.tsx +102 −412
  649. apps/web/src/components/settings/DiagnosticsSettings.tsx +8 −5
  650. apps/web/src/components/settings/KeybindingsSettings.tsx +2 −0
  651. apps/web/src/components/settings/ProviderModelsSection.tsx +3 −3
  652. apps/web/src/components/settings/ProviderSettingsForm.test.ts +1 −0
  653. apps/web/src/components/settings/ScheduledTasksSettings.tsx +1 −0
  654. apps/web/src/components/settings/SettingsPanels.tsx +13 −3
  655. apps/web/src/components/settings/itemRows.ts +5 −0
  656. apps/web/src/components/sidebar/SidebarUpdatePill.tsx +55 −1
  657. apps/web/src/components/threadSidebarWidth.test.ts +34 −0
  658. apps/web/src/components/threadSidebarWidth.ts +22 −0
  659. apps/web/src/components/ui/menu.tsx +28 −18
  660. apps/web/src/components/ui/sidebar.tsx +14 −6
  661. apps/web/src/composer-logic.test.ts +15 −0
  662. apps/web/src/composer-logic.ts +7 −0
  663. apps/web/src/connection/platform.ts +2 −2
  664. apps/web/src/connection/runtime.ts +6 −1
  665. apps/web/src/connection/storage.ts +122 −7
  666. apps/web/src/contextMenuFallback.test.ts +17 −0
  667. apps/web/src/contextMenuFallback.ts +3 −1
  668. apps/web/src/diffPanelStore.ts +6 −1
  669. apps/web/src/environmentGrouping.test.ts +121 −0
  670. apps/web/src/environments/primary/auth.ts +2 −0
  671. apps/web/src/hooks/useHandleNewThread.ts +3 −0
  672. apps/web/src/hooks/usePreviewPanelInlineSize.ts +5 −4
  673. apps/web/src/hooks/useThreadActions.ts +3 −3
  674. apps/web/src/hostedPairing.ts +2 −2
  675. apps/web/src/index.css +220 −13
  676. apps/web/src/lib/windowControlsOverlay.ts +26 −0
  677. apps/web/src/main.tsx +5 −1
  678. apps/web/src/markdown-list-indentation.test.tsx +82 −0
  679. apps/web/src/markdown-list-indentation.ts +143 −0
  680. apps/web/src/modelSelection.test.ts +33 −0
  681. apps/web/src/modelSelection.ts +4 −6
  682. apps/web/src/projectScripts.test.ts +41 −0
  683. apps/web/src/projectScripts.ts +25 −0
  684. apps/web/src/rightPanelStore.test.ts +15 −0
  685. apps/web/src/routeTree.gen.ts +42 −0
  686. apps/web/src/routes/__root.tsx +3 −1
  687. apps/web/src/routes/_chat.draft.$draftId.tsx +17 −16
  688. apps/web/src/routes/_chat.index.tsx +114 −3
  689. apps/web/src/routes/connect.tsx +13 −0
  690. apps/web/src/routes/connect_.callback.tsx +13 −0
  691. apps/web/src/sidebarProjectGrouping.ts +71 −10
  692. apps/web/src/state/desktopUpdate.test.ts +1 −0
  693. apps/web/src/state/entities.ts +5 −0
  694. apps/web/src/state/shell.ts +31 −0
  695. apps/web/src/timestampFormat.test.ts +60 −0
  696. apps/web/src/timestampFormat.ts +42 −10
  697. apps/web/src/vite-env.d.ts +1 −0
  698. apps/web/vite.config.ts +13 −0
  699. assets/README.md +50 −0
  700. assets/dev/app-icon.icon/Assets/annotations.svg +37 −0
  701. assets/dev/app-icon.icon/Assets/background.svg +51 −0
  702. assets/dev/app-icon.icon/Assets/text.svg +3 −0
  703. assets/dev/app-icon.icon/icon.json +17 −12
  704. assets/dev/blueprint-icon-composer.icon/Assets/T3.svg +0 −3
  705. assets/dev/blueprint-icon-composer.icon/Assets/Texturelabs_Paper_381XL.jpg +0 −0
  706. assets/dev/blueprint-icon-composer.icon/Assets/gpt-image-1.5-kn76n9hynne5q3qxy3g91chp2d84t871.png +0 −0
  707. assets/dev/blueprint-icon-composer.icon/icon.json +0 −47
  708. assets/dev/blueprint-ios-1024.png +0 −0
  709. assets/dev/blueprint-macos-1024.png +0 −0
  710. assets/dev/blueprint-universal-1024.png +0 −0
  711. assets/dev/blueprint-web-apple-touch-180.png +0 −0
  712. assets/dev/blueprint-web-favicon-16x16.png +0 −0
  713. assets/dev/blueprint-web-favicon-32x32.png +0 −0
  714. assets/dev/blueprint-web-favicon.ico +0 −0
  715. assets/dev/blueprint-windows.ico +0 −0
  716. assets/nightly/app-icon.icon/Assets/background.svg +43 −0
  717. assets/nightly/app-icon.icon/Assets/cloud-lower-left.svg +21 −0
  718. assets/nightly/app-icon.icon/Assets/cloud-upper-right.svg +21 −0
  719. assets/nightly/app-icon.icon/Assets/text.svg +3 −0
  720. assets/nightly/app-icon.icon/icon.json +94 −0
  721. assets/nightly/blueprint-ios-1024.png +0 −0
  722. assets/nightly/blueprint-macos-1024.png +0 −0
  723. assets/nightly/blueprint-universal-1024.png +0 −0
  724. assets/nightly/blueprint-web-apple-touch-180.png +0 −0
  725. assets/nightly/blueprint-web-favicon-16x16.png +0 −0
  726. assets/nightly/blueprint-web-favicon-32x32.png +0 −0
  727. assets/nightly/blueprint-web-favicon.ico +0 −0
  728. assets/nightly/blueprint-windows.ico +0 −0
  729. assets/nightly/nightly-ios-1024.png +0 −0
  730. assets/nightly/nightly-macos-1024.png +0 −0
  731. assets/nightly/nightly-universal-1024.png +0 −0
  732. assets/nightly/nightly-web-apple-touch-180.png +0 −0
  733. assets/nightly/nightly-web-favicon-16x16.png +0 −0
  734. assets/nightly/nightly-web-favicon-32x32.png +0 −0
  735. assets/nightly/nightly-web-favicon.ico +0 −0
  736. assets/nightly/nightly-windows.ico +0 −0
  737. assets/prod/app-icon.icon/Assets/text.svg +0 −0
  738. assets/prod/app-icon.icon/icon.json +2 −2
  739. assets/prod/black-ios-1024.png +0 −0
  740. assets/prod/black-macos-1024.png +0 −0
  741. assets/prod/black-universal-1024.png +0 −0
  742. assets/prod/t3-black-web-apple-touch-180.png +0 −0
  743. assets/prod/t3-black-web-favicon-16x16.png +0 −0
  744. assets/prod/t3-black-web-favicon-32x32.png +0 −0
  745. assets/prod/t3-black-web-favicon.ico +0 −0
  746. assets/prod/t3-black-windows.ico +0 −0
  747. docs/architecture/overview.md +18 −26
  748. docs/operations/ci.md +1 −1
  749. docs/operations/effect-fn-checklist.md +89 −89
  750. docs/operations/mobile-app-store-screenshots.md +159 −0
  751. docs/operations/observability.md +17 −9
  752. docs/reference/scripts.md +21 −19
  753. experiments/messages-glass-lab/MessagesGlassLab.xcodeproj/project.pbxproj +285 −0
  754. experiments/messages-glass-lab/MessagesGlassLab/ContentView.swift +386 −0
  755. experiments/messages-glass-lab/MessagesGlassLab/MessagesGlassLabApp.swift +10 −0
  756. favicon.svg +4 −0
  757. infra/relay/migrations/postgres/20260706061126_migration/migration.sql +3 −0
  758. infra/relay/migrations/postgres/20260706061126_migration/snapshot.json +1479 −0
  759. infra/relay/package.json +2 −0
  760. infra/relay/src/agentActivity/AgentActivityPublisher.test.ts +190 −6
  761. infra/relay/src/agentActivity/AgentActivityPublisher.ts +82 −13
  762. infra/relay/src/agentActivity/AgentActivityRows.test.ts +9 −0
  763. infra/relay/src/agentActivity/AgentActivityRows.ts +92 −1
  764. infra/relay/src/agentActivity/ApnsClient.test.ts +108 −1
  765. infra/relay/src/agentActivity/ApnsClient.ts +39 −115
  766. infra/relay/src/agentActivity/ApnsDeliveries.test.ts +644 −36
  767. infra/relay/src/agentActivity/ApnsDeliveries.ts +460 −42
  768. infra/relay/src/agentActivity/ApnsDeliveryQueue.ts +7 −0
  769. infra/relay/src/agentActivity/ApnsProviderTokens.test.ts +75 −0
  770. infra/relay/src/agentActivity/ApnsProviderTokens.ts +63 −0
  771. infra/relay/src/agentActivity/Devices.test.ts +4 −0
  772. infra/relay/src/agentActivity/Devices.ts +88 −82
  773. infra/relay/src/agentActivity/LiveActivities.test.ts +51 −0
  774. infra/relay/src/agentActivity/LiveActivities.ts +24 −4
  775. infra/relay/src/agentActivity/MobileRegistrations.test.ts +49 −41
  776. infra/relay/src/agentActivity/MobileRegistrations.ts +22 −1
  777. infra/relay/src/agentActivity/agentActivityPayloads.ts +39 −1
  778. infra/relay/src/agentActivity/apnsDeliveryJobs.ts +33 −1
  779. infra/relay/src/agentActivity/apnsJwt.ts +160 −0
  780. infra/relay/src/environments/EnvironmentLinker.test.ts +75 −1
  781. infra/relay/src/environments/EnvironmentLinker.ts +26 −1
  782. infra/relay/src/http/Api.test.ts +31 −0
  783. infra/relay/src/http/Api.ts +54 −1
  784. infra/relay/src/persistence/schema.ts +2 −0
  785. infra/relay/src/worker.ts +15 −2
  786. package.json +5 −2
  787. packages/client-runtime/src/connection/errors.ts +9 −0
  788. packages/client-runtime/src/connection/registry.test.ts +4 −0
  789. packages/client-runtime/src/connection/resolver.test.ts +2 −0
  790. packages/client-runtime/src/connection/supervisor.test.ts +1 −1
  791. packages/client-runtime/src/platform/orchestrationCache.test.ts +3 −2
  792. packages/client-runtime/src/platform/orchestrationCache.ts +3 −3
  793. packages/client-runtime/src/platform/persistence.ts +36 −3
  794. packages/client-runtime/src/relay/discovery.test.ts +52 −0
  795. packages/client-runtime/src/relay/discovery.ts +26 −5
  796. packages/client-runtime/src/relay/managedRelay.ts +49 −5
  797. packages/client-runtime/src/relay/managedRelayState.test.ts +1 −0
  798. packages/client-runtime/src/relay/managedRelayState.ts +4 −4
  799. packages/client-runtime/src/rpc/client.ts +88 −52
  800. packages/client-runtime/src/rpc/http.ts +2 −0
  801. packages/client-runtime/src/rpc/session.test.ts +78 −2
  802. packages/client-runtime/src/rpc/session.ts +10 −4
  803. packages/client-runtime/src/state/environmentHttpAuth.ts +73 −0
  804. packages/client-runtime/src/state/projects.ts +5 −31
  805. packages/client-runtime/src/state/server.test.ts +175 −2
  806. packages/client-runtime/src/state/server.ts +161 −8
  807. packages/client-runtime/src/state/shell-sync.test.ts +207 −3
  808. packages/client-runtime/src/state/shell.ts +84 −15
  809. packages/client-runtime/src/state/shellReducer.ts +4 −1
  810. packages/client-runtime/src/state/shellSnapshotHttp.ts +92 −0
  811. packages/client-runtime/src/state/threadDetail.ts +1 −1
  812. packages/client-runtime/src/state/threadSnapshotHttp.ts +120 −0
  813. packages/client-runtime/src/state/threadSort.test.ts +71 −0
  814. packages/client-runtime/src/state/threadSort.ts +4 −1
  815. packages/client-runtime/src/state/threadState.ts +16 −0
  816. packages/client-runtime/src/state/threads-atoms.test.ts +2 −2
  817. packages/client-runtime/src/state/threads-sync.test.ts +544 −58
  818. packages/client-runtime/src/state/threads.ts +154 −48
  819. packages/client-runtime/src/state/vcs.test.ts +232 −0
  820. packages/client-runtime/src/state/vcs.ts +155 −13
  821. packages/client-runtime/src/state/vcsAction.test.ts +40 −0
  822. packages/client-runtime/src/state/vcsAction.ts +1 −3
  823. packages/contracts/package.json +1 −1
  824. packages/contracts/src/environment.ts +1 −0
  825. packages/contracts/src/environmentHttp.ts +61 −1
  826. packages/contracts/src/ipc.ts +14 −0
  827. packages/contracts/src/model.ts +5 −2
  828. packages/contracts/src/orchestration.ts +7 −0
  829. packages/contracts/src/orchestrationV2.ts +44 −2
  830. packages/contracts/src/relay.ts +28 −0
  831. packages/contracts/src/rpc.ts +8 −0
  832. packages/contracts/src/server.ts +4 −0
  833. packages/contracts/src/settings.test.ts +4 −0
  834. packages/contracts/src/settings.ts +12 −4
  835. packages/effect-codex-app-server/scripts/generate.ts +3 −1
  836. packages/effect-codex-app-server/src/_generated/meta.gen.ts +43 −1
  837. packages/effect-codex-app-server/src/_generated/namespaces.gen.ts +16 −1
  838. packages/effect-codex-app-server/src/_generated/schema.gen.ts +5825 −1316
  839. packages/effect-codex-app-server/src/protocol.test.ts +86 −0
  840. packages/shared/package.json +8 −0
  841. packages/shared/src/agentAwareness.ts +0 −8
  842. packages/shared/src/cliArgs.test.ts +29 −1
  843. packages/shared/src/cliArgs.ts +59 −3
  844. packages/shared/src/connectAuth.test.ts +78 −0
  845. packages/shared/src/connectAuth.ts +124 −0
  846. packages/shared/src/dpop.ts +9 −22
  847. packages/shared/src/hostProcess.ts +14 −0
  848. packages/shared/src/model.test.ts +12 −88
  849. packages/shared/src/model.ts +10 −5
  850. packages/shared/src/path.ts +29 −0
  851. packages/shared/src/projectFavicon.test.ts +28 −0
  852. packages/shared/src/projectFavicon.ts +12 −0
  853. packages/shared/src/remote.test.ts +64 −0
  854. packages/shared/src/remote.ts +5 −5
  855. patches/@expo%2Fmetro-config@56.0.14.patch +0 −0
  856. patches/@legendapp__list@3.2.0.patch +922 −0
  857. patches/@react-native-menu__menu@2.0.0.patch +46 −0
  858. patches/@react-navigation%2Fnative-stack@7.17.6.patch +102 −0
  859. patches/expo-modules-jsi@56.0.10.patch +21 −0
  860. patches/react-native-gesture-handler@2.31.2.patch +124 −0
  861. patches/react-native-keyboard-controller@1.21.13.patch +483 −0
  862. patches/react-native-screens@4.25.2.patch +1581 −0
  863. pnpm-lock.yaml +2203 −1036
  864. pnpm-workspace.yaml +57 −43
  865. scripts/build-desktop-artifact.test.ts +89 −14
  866. scripts/build-desktop-artifact.ts +87 −39
  867. scripts/dev-runner.test.ts +51 −12
  868. scripts/dev-runner.ts +21 −15
  869. scripts/export-brand-icons.ts +810 −0
  870. scripts/lib/brand-assets.test.ts +37 −0
  871. scripts/lib/brand-assets.ts +20 −7
  872. scripts/lib/icon-export.test.ts +47 −0
  873. scripts/lib/icon-export.ts +72 −0
  874. scripts/lib/public-config.ts +6 −1
  875. scripts/mobile-showcase-environment.ts +569 −0
  876. scripts/mobile-showcase.config.ts +206 −0
  877. scripts/mobile-showcase.test.ts +296 −0
  878. scripts/mobile-showcase.ts +1344 −0
  879. scripts/package.json +2 −0
  880. vite.config.ts +4 −0
.agents/skills/ios-debugger-agent/LICENSE+21−0
@@ -0,0 +1,21 @@
1MIT License
2
3Copyright (c) OpenAI
4
5Permission is hereby granted, free of charge, to any person obtaining a copy
6of this software and associated documentation files (the "Software"), to deal
7in the Software without restriction, including without limitation the rights
8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9copies of the Software, and to permit persons to whom the Software is
10furnished to do so, subject to the following conditions:
11
12The above copyright notice and this permission notice shall be included in all
13copies or substantial portions of the Software.
14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21SOFTWARE.
.agents/skills/ios-debugger-agent/SKILL.md+64−0
@@ -0,0 +1,64 @@
1---
2name: ios-debugger-agent
3description: Build, launch, inspect, and drive iOS apps with the repository-configured XcodeBuildMCP server. Use on macOS for iOS Simulator builds, focused native test runs, semantic UI automation, screenshots, logs, or debugging, including T3 Code Mobile verification.
4---
5
6# iOS Debugger Agent
7
8Use the repository-configured `xcodebuildmcp` tools instead of requiring a globally installed Codex plugin. Prefer MCP tools over raw `xcodebuild`, `xcrun`, or `simctl` when the client exposes them.
9
10## Confirm availability
11
12This workflow requires macOS 14.5 or newer, Xcode 16 or newer, and Node.js 18 or newer. The repository pins XcodeBuildMCP in both `.mcp.json` for Claude Code and `.codex/config.toml` for Codex. Project MCP servers may require one-time trust or approval followed by a new session.
13
14If the tools are missing:
15
161. Confirm the repository is trusted and its project MCP server was approved.
172. Restart or recreate the agent session after approving configuration.
183. Run `npx --yes xcodebuildmcp@2.6.2 doctor` when the server starts but simulator or UI-automation tools are unavailable. Follow its actionable Xcode or AXe setup guidance.
194. Fall back to the pinned XcodeBuildMCP CLI or native Apple CLIs only when the current agent client cannot expose project MCP tools.
20
21Do not ask contributors to install the OpenAI `build-ios-apps` plugin globally.
22
23## Establish one simulator context
24
251. Call `session_show_defaults` before discovery, build, launch, or UI work.
262. Call `list_sims` and select one explicit simulator UDID. Prefer a simulator that is already booted; boot an installed simulator when verification requires it, but do not create or download runtimes without user authorization.
273. Call `session_set_defaults` with the project or workspace, scheme, Debug configuration, simulator ID, and bundle identifier when known.
284. Keep every subsequent build, launch, screenshot, log capture, and UI action pinned to that same UDID.
29
30Avoid generic Mac window automation for switching among Simulator windows. Explicit device identity is more reliable.
31
32## Choose build or launch
33
34- Use `build_run_sim` when native source, native dependencies, entitlements, or project configuration changed.
35- Use `test_sim` for the smallest relevant native test target or test cases; do not run an entire workspace test matrix routinely.
36- Use `launch_app_sim` when a compatible app is already installed and no native rebuild is needed.
37- To reuse an existing build artifact, use `get_sim_app_path` or `get_app_bundle_id`, install it with `install_app_sim` when necessary, and then launch it.
38- Do not run a build-only action immediately before `build_run_sim` unless the task requires both artifacts.
39
40After launch, call `snapshot_ui` or `screenshot` before interacting. An open Simulator window alone is not evidence that the intended app launched.
41
42## Drive the UI semantically
43
441. Call `snapshot_ui` to obtain the current accessibility hierarchy and element references.
452. Use only current `elementRef` values whose snapshot entries list the intended action. XcodeBuildMCP `2.6.2` does not accept coordinates for `tap`; when the app exposes no actionable reference, prefer a registered deep link or another app-supported route and otherwise report the accessibility blocker.
463. Refresh with `snapshot_ui` after navigation or layout changes. Element references are snapshot-specific.
474. Use `wait_for_ui` for asynchronous transitions when available rather than fixed sleeps.
485. Capture a final `screenshot` for the state that proves the affected flow.
49
50Use `gesture` or scoped swipe actions when needed. If a gesture is unreliable, return to a known route or relaunch rather than switching to generic desktop automation.
51
52## Capture logs and debug
53
54- Use `start_sim_log_cap` and `stop_sim_log_cap` with the exact bundle identifier for focused runtime logs.
55- Use debugger tools only when the task requires runtime diagnosis; attach to the selected simulator and app rather than an ambiguous process.
56- Summarize relevant errors instead of returning unbounded logs.
57
58## Clean up
59
60Stop only log captures, debugger sessions, apps, or simulators started for the current test. Leave pre-existing simulators and unrelated sessions alone.
61
62## Upstream
63
64Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-debugger-agent`, MIT) and aligned with XcodeBuildMCP `2.6.2` tool names.
.agents/skills/ios-debugger-agent/agents/openai.yaml+9−0
@@ -0,0 +1,9 @@
1interface:
2 display_name: "iOS Debugger Agent"
3 short_description: "Build and drive iOS Simulator apps"
4 default_prompt: "Use $ios-debugger-agent to build, launch, and inspect the current iOS app on Simulator."
5dependencies:
6 tools:
7 - type: "mcp"
8 value: "xcodebuildmcp"
9 description: "Repository-configured Xcode build, simulator, logging, debugging, and semantic UI tools"
.agents/skills/ios-simulator-browser/LICENSE+21−0
@@ -0,0 +1,21 @@
1MIT License
2
3Copyright (c) OpenAI
4
5Permission is hereby granted, free of charge, to any person obtaining a copy
6of this software and associated documentation files (the "Software"), to deal
7in the Software without restriction, including without limitation the rights
8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9copies of the Software, and to permit persons to whom the Software is
10furnished to do so, subject to the following conditions:
11
12The above copyright notice and this permission notice shall be included in all
13copies or substantial portions of the Software.
14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21SOFTWARE.
.agents/skills/ios-simulator-browser/SKILL.md+51−0
@@ -0,0 +1,51 @@
1---
2name: ios-simulator-browser
3description: Stream an explicit iOS Simulator through pinned serve-sim into the T3 Code in-app browser or another agent browser. Use on Apple Silicon macOS when the user should watch simulator verification live or when browser-visible simulator evidence is needed.
4---
5
6# iOS Simulator Browser
7
8Use serve-sim as the shared visual feed for an iOS Simulator. Use `ios-debugger-agent` and XcodeBuildMCP semantic UI tools to drive the app; do not treat browser-canvas coordinates as a substitute for missing app accessibility.
9
10## Confirm availability
11
12serve-sim `0.1.45` requires Apple Silicon macOS, Xcode command-line tools, and Node.js 20 or newer. If the host is unsupported, continue with XcodeBuildMCP screenshots and report that live streaming was unavailable.
13
14When running inside T3 Code, use its product-native browser MCP to open the stream. Other agent hosts may use their own browser or preview surface.
15
16Keep serve-sim on its default `127.0.0.1` binding. Do not expose its preview to a LAN or tunnel unless the user explicitly requests that access and the network is trusted; the preview includes a token-gated shell-execution route.
17
18## Start one owned stream
19
201. Obtain the exact simulator UDID from the iOS build or launch workflow.
212. Check whether an existing serve-sim stream for that UDID belongs to another task. Reuse it only when explicitly shared; never kill another task's stream.
223. Otherwise, clear only a stale stream for that UDID and start the pinned version with scoped cleanup:
23
24 ```bash
25 SIMULATOR_ID=<simulator-udid>
26 cleanup_serve_sim() {
27 npx --yes serve-sim@0.1.45 --kill "$SIMULATOR_ID" >/dev/null 2>&1 || true
28 }
29 trap cleanup_serve_sim EXIT INT TERM HUP
30 cleanup_serve_sim
31 npx --yes serve-sim@0.1.45 "$SIMULATOR_ID"
32 ```
33
344. Keep the terminal alive and open the exact local URL printed by serve-sim in the agent's browser.
355. Verify that a live simulator frame renders. A loaded wrapper page is not sufficient evidence.
36
37## Observe while driving semantically
38
39- Let the user watch the serve-sim stream while XcodeBuildMCP performs `snapshot_ui`, semantic taps, typing, gestures, and screenshots.
40- Keep the browser and Xcode tooling pinned to the same simulator UDID.
41- Do not switch to generic desktop automation or browser-canvas clicking merely because the stream is visible.
42
43If the in-app browser explicitly reports that previews are unavailable, do not install unrelated browser automation. Continue through XcodeBuildMCP, capture a simulator screenshot, report the unavailable live stream, and clean up the owned serve-sim process.
44
45## Finish
46
47Stop the long-running terminal and wait for its cleanup trap to finish. If it disappeared without cleanup, run `npx --yes serve-sim@0.1.45 --kill <simulator-udid>` for that exact simulator. Never run an unscoped `--kill`.
48
49## Upstream
50
51Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-simulator-browser`, MIT). It invokes serve-sim `0.1.45` under its Apache-2.0 license without vendoring the package.
.agents/skills/ios-simulator-browser/agents/openai.yaml+4−0
@@ -0,0 +1,4 @@
1interface:
2 display_name: "iOS Simulator Browser"
3 short_description: "Stream iOS Simulator in the browser"
4 default_prompt: "Use $ios-simulator-browser to stream the selected iOS Simulator into the T3 Code in-app browser."
.agents/skills/test-t3-app/SKILL.md+71−0
@@ -0,0 +1,71 @@
1---
2name: test-t3-app
3description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
4---
5
6# Test T3 App
7
8Use this skill for the web client. For iOS Simulator, Android Emulator, or physical-device testing against an isolated T3 backend, use the sibling [`test-t3-mobile`](../test-t3-mobile/SKILL.md) skill.
9
10## Start an isolated web environment
11
121. Run commands from the repository root.
132. Choose a base directory that belongs only to the current worktree or test:
14 - Use the repository's ignored `.t3` directory for reusable worktree-local state.
15 - Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
163. Start the full web stack with `vp run dev --home-dir <base-dir>`.
174. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
18
19Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
20
21The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
22
23## Authenticate the browser on the first navigation
24
251. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
262. Use the controlled in-app browser or browser-automation surface available to the agent. Do not use a system-browser launch command during automated testing.
273. Open that complete URL exactly once as the controlled browser's first navigation. Preserve the fragment and token verbatim.
284. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
295. Continue in the same browser context so its stored bearer session remains available.
30
31Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
32
33## Recover a consumed or expired pairing token
34
35Create another token against the same database and web URL as the running dev server:
36
37```bash
38T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
39 --base-dir <base-dir> \
40 --dev-url <web-url> \
41 --base-url <web-url> \
42 --ttl 15m \
43 --label agent-ui-test
44```
45
46Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
47
48Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
49
50## Inspect or seed SQLite state
51
52Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
53
54- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
55- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
56- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
57- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
58
59The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
60
61## Finish the test
62
63Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
64
65## Troubleshoot predictably
66
67- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
68- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
69- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
70- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
71- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
.agents/skills/test-t3-app/agents/openai.yaml+4−0
@@ -0,0 +1,4 @@
1interface:
2 display_name: "T3 App Testing"
3 short_description: "Launch and seed isolated T3 test environments"
4 default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
.agents/skills/test-t3-app/references/sqlite-fixtures.md+58−0
@@ -0,0 +1,58 @@
1# SQLite fixtures
2
3Load this reference only when inspecting or seeding local T3 state directly.
4
5## Select the correct database
6
7When `--base-dir` or `--home-dir` is explicit, runtime state lives under `<base-dir>/userdata` and the database path is `<base-dir>/userdata/state.sqlite`. The `<base-dir>/dev` state directory is only the fallback for an implicit development home, preventing an ordinary `vp run dev` from touching production state.
8
9Start the target runtime once before seeding so all migrations have run. Use an isolated base directory. Stop the server before writes to avoid racing application state or an active projection.
10
11## Use the helper
12
13List tables:
14
15```bash
16node apps/server/scripts/t3-sqlite-state.ts query \
17 --base-dir <base-dir> \
18 --sql "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
19```
20
21Inspect current columns before writing a fixture:
22
23```bash
24node apps/server/scripts/t3-sqlite-state.ts query \
25 --base-dir <base-dir> \
26 --sql "PRAGMA table_info(projection_threads)"
27```
28
29Apply a SQL fixture from a file:
30
31```bash
32node apps/server/scripts/t3-sqlite-state.ts exec \
33 --base-dir <base-dir> \
34 --file /tmp/t3-seed.sql
35```
36
37Use one statement per invocation for both `query` and `exec`; the helper wraps writes in a transaction and prints the backup path after a successful mutation. Use a single insert with multiple value rows when a fixture needs several records.
38
39## Seed projection data carefully
40
41The web UI primarily reads these projection tables:
42
43- `projection_projects`
44- `projection_threads`
45- `projection_thread_messages`
46- `projection_thread_activities`
47- `projection_thread_sessions`
48- `projection_turns`
49- `projection_pending_approvals`
50- `projection_thread_proposed_plans`
51
52Inspect `PRAGMA table_info(<table>)` and the current migrations under `apps/server/src/persistence/Migrations/` before constructing inserts. Keep identifiers unique, timestamps as ISO strings, JSON columns valid, and related project/thread/turn IDs consistent.
53
54For a substantial current example, inspect `seedDatabase` in `scripts/mobile-showcase-environment.ts`. Adapt its column set to the target database instead of assuming copied SQL remains current.
55
56Direct projection writes are appropriate for ephemeral visual states, edge-case counts, long titles, activity lists, and similar UI fixtures. They do not create a coherent orchestration event history. Do not modify `orchestration_events` unless the test specifically exercises projector internals, and do not use direct projection writes to claim backend business behavior works.
57
58Use the app's commands or APIs for behavior tests. Use `node apps/server/src/bin.ts auth ...` for auth state rather than editing `auth_pairing_links` or `auth_sessions`.
.agents/skills/test-t3-mobile/SKILL.md+188−0
@@ -0,0 +1,188 @@
1---
2name: test-t3-mobile
3description: Launch and test T3 Code Mobile on an iOS Simulator or Android Emulator against disposable local T3 environments, including Metro and dev-client reuse, native rebuild decisions, per-client pairing, seeded projects, semantic UI control, screenshots, and iOS serve-sim streaming. Use after mobile UI or native changes, when reproducing phone or tablet behavior, pairing an emulator to isolated state, or verifying mobile behavior on macOS, Linux, or Windows.
4---
5
6# Test T3 Mobile
7
8Run one focused, end-to-end mobile verification pass against disposable T3 state. Use the sibling [`test-t3-app`](../test-t3-app/SKILL.md) skill as the detailed reference for pairing-token semantics and SQLite fixtures.
9
10Command examples use POSIX shell syntax. On Windows, use PowerShell equivalents: set variables with `$env:NAME = "value"`, use an explicit temporary directory from `[System.IO.Path]::GetTempPath()`, and run multiline examples on one line or with PowerShell backticks. Use `$env:ANDROID_HOME\platform-tools\adb.exe` when `adb` is not already on `PATH`.
11
12## Select a viable platform
13
14Inspect the host and the affected code before launching processes:
15
16- On macOS with Xcode, prefer one representative iOS Simulator when the change is cross-platform so the user can watch through serve-sim. Load and follow [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), and load [`ios-simulator-browser`](../ios-simulator-browser/SKILL.md) when live streaming is available.
17- On macOS, Linux, or Windows with the Android SDK, use one Android Emulator when Android is the affected surface or iOS tooling is unavailable.
18- When the change is platform-specific, test that platform. When neither platform is viable, report the missing SDK, emulator, or dev-client prerequisite rather than claiming verification.
19
20Do not treat unavailable iOS tooling as a blocker when Android is a valid representative target.
21
22## Choose the lightest valid launch path
23
24- For JavaScript, TypeScript, or asset-only changes, reuse a compatible installed development client and start Metro. Do not rebuild native code merely to load a new bundle.
25- For native source, native dependencies, entitlements, config plugins, or generated project changes, rebuild the affected platform.
26- Use `vp run ios:dev` or `vp run android:dev` only when an Expo clean prebuild is actually required; both commands regenerate the native project.
27- If the user requested no native rebuild and no compatible app is installed, reuse an existing compatible `.app` or `.apk` artifact when available. Otherwise report the missing dev client instead of silently rebuilding.
28
29The development identity on both platforms is:
30
31- App: `T3 Code Dev`
32- Bundle/package identifier: `com.t3tools.t3code.dev`
33- URL scheme: `t3code-dev`
34
35Bundle or package presence proves the correct variant, not native compatibility. Reuse it only when the current changes did not alter its Expo SDK, native dependencies, config plugins, entitlements, generated project, or native source.
36
37## Start one disposable T3 environment
38
39Run backend commands from the repository root. Use the ignored, worktree-local `.t3` directory or create a fresh directory with the host OS's temporary-directory mechanism. An explicit base directory stores state in `<base-dir>/userdata`; never point testing at shared `~/.t3` state.
40
41Seed a small number of meaningful Git projects before starting the backend:
42
43```bash
44node apps/server/src/bin.ts project add <git-workspace> \
45 --base-dir <base-dir> \
46 --title <project-title>
47```
48
49Running `project add` before the backend starts gives it exclusive offline database access. If a backend is already running, wait until it is ready so the CLI dispatches through the live server; never run offline mutations concurrently with the server.
50
51Use direct SQLite mutation only for disposable projection fixtures. Follow `test-t3-app` and stop the backend before writing.
52
53Start a headless backend after seeding:
54
55```bash
56node apps/server/src/bin.ts serve \
57 --host 127.0.0.1 \
58 --port <server-port> \
59 --base-dir <base-dir> \
60 --no-browser
61```
62
63Use these client origins:
64
65- iOS Simulator: `http://127.0.0.1:<server-port>`
66- Android Emulator: `http://10.0.2.2:<server-port>`
67- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
68
69Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
70
71## Start or reuse Metro safely
72
73Run Metro from `apps/mobile`.
74
751. Inspect any process on the intended Metro port and its `/status` response. Reuse it only when it is healthy, belongs to this worktree, and matches `APP_VARIANT=development`, `--dev-client`, and scheme `t3code-dev`.
762. Never kill another worktree's Metro. Use a free explicit port when necessary.
773. Run `vp run dev:client` on the standard port. For another port, retain the complete development identity:
78
79 ```bash
80 APP_VARIANT=development vp exec expo start \
81 --dev-client \
82 --scheme t3code-dev \
83 --clear \
84 --lan \
85 --port <metro-port>
86 ```
87
88 In PowerShell, set `$env:APP_VARIANT = "development"` first and then run the `vp exec expo start ...` command without the leading assignment.
89
904. Open the exact development-client URL for the selected device and confirm the loaded bundle belongs to this worktree and Metro port.
91
92### iOS launch
93
94Use `ios-debugger-agent` to select one UDID and set these XcodeBuildMCP session defaults:
95
96- Workspace: `<repo>/apps/mobile/ios/T3CodeDev.xcworkspace`
97- Scheme: `T3CodeDev`
98- Configuration: `Debug`
99- Simulator ID: the selected UDID
100- Bundle ID: `com.t3tools.t3code.dev`
101
102Check the installed client with:
103
104```bash
105xcrun simctl get_app_container <simulator-udid> com.t3tools.t3code.dev app
106xcrun simctl openurl <simulator-udid> <printed-dev-client-url>
107```
108
109Accept the iOS confirmation prompt and dismiss the developer menu when it obscures the app.
110
111### Android launch
112
113Select one running emulator serial from `adb devices` and check the installed client:
114
115```bash
116adb -s <emulator-serial> shell pm path com.t3tools.t3code.dev
117adb -s <emulator-serial> reverse tcp:<metro-port> tcp:<metro-port>
118adb -s <emulator-serial> shell am start -W \
119 -a android.intent.action.VIEW \
120 -d '<printed-dev-client-url>' \
121 com.t3tools.t3code.dev
122```
123
124Do not start, stop, erase, or reconfigure an emulator owned by another task. Track and later stop only processes owned by this test.
125
126## Pair each client once
127
128Issue a fresh credential against the running backend's exact base directory:
129
130```bash
131T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
132 --base-dir <base-dir> \
133 --base-url <mobile-origin> \
134 --ttl 15m \
135 --label agent-mobile-<short-device-id>
136```
137
138In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
139
140If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
141
142```bash
143xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
144adb -s <emulator-serial> shell am start -W \
145 -a android.intent.action.VIEW \
146 -d 't3code-dev://connections/new' \
147 com.t3tools.t3code.dev
148```
149
150Run only the command for the selected platform.
151
152In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
153
154Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
155
156## Drive and observe the affected flow
157
158### iOS
159
160Use `snapshot_ui` and current element references from XcodeBuildMCP for taps and typing. Stream the same UDID through `ios-simulator-browser` so the user can watch in T3 Code when the host supports it. Use the stream as a visual feed rather than a reason to switch to fragile browser coordinates.
161
162### Android
163
164Prefer semantic Android automation exposed by the current agent host. Otherwise inspect the current hierarchy with `adb shell uiautomator dump`, target stable resource IDs, content descriptions, text, or bounds, and use scoped `adb shell input` actions. Refresh the hierarchy after navigation. Capture the final state with `adb exec-out screencap -p`.
165
166Android does not use serve-sim. Use a browser-compatible Android mirror when the host already provides one; otherwise return focused emulator screenshots as evidence rather than installing unrelated streaming infrastructure during verification.
167
168## Verify and clean up
169
170Exercise only the affected flow on one representative device unless the change specifically concerns platform, OS version, or screen size. Before finishing:
171
1721. Confirm the app connected to the intended disposable environment instead of merely rendering an empty disconnected state.
1732. Capture the relevant final state.
1743. Remove the disposable environment from T3 Code Dev.
1754. Remove any `adb reverse` rule created for this test with `adb -s <emulator-serial> reverse --remove tcp:<metro-port>`.
1765. Stop only the serve-sim, Metro, backend, emulator, and log processes started by this test.
1776. Remove only base directories and temporary Git repositories deliberately created for this test. Preserve them when they contain useful reproduction evidence.
178
179Keep local verification focused. Do not turn this workflow into a full repository test run.
180
181## Troubleshoot predictable failures
182
183- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
184- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
185- **A second client cannot pair:** pairing tokens are single-use; issue another token.
186- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
187- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
188- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
.agents/skills/test-t3-mobile/agents/openai.yaml+4−0
@@ -0,0 +1,4 @@
1interface:
2 display_name: "Test T3 Mobile"
3 short_description: "Test T3 Code on iOS or Android"
4 default_prompt: "Use $test-t3-mobile to launch T3 Code against an isolated backend and verify the affected flow on an available simulator or emulator."
.claude/skills+1−0
@@ -0,0 +1 @@
1../.agents/skills
.codex/config.toml+9−0
@@ -0,0 +1,9 @@
1[mcp_servers.xcodebuildmcp]
2enabled = true
3required = false
4command = "npx"
5args = ["--yes", "xcodebuildmcp@2.6.2", "mcp"]
6startup_timeout_sec = 20.0
7
8[mcp_servers.xcodebuildmcp.env]
9XCODEBUILDMCP_ENABLED_WORKFLOWS = "simulator,ui-automation,debugging,logging"
.cursor/rules/cursor-cloud.mdc+72−0
@@ -0,0 +1,72 @@
1---
2description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
3alwaysApply: true
4---
5
6# Cursor Cloud specific instructions
7
8These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
9developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
10
11## Toolchain
12
13Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
14`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
15(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
16
17- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
18 non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
19 `$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
20- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
21 `vp check --fix` before committing.
22
23## Running the web app
24
25- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
26 (`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
27 `npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
28 the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
29- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
30 (e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
31 UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
32 (`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
33- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
34 Without one installed the UI loads but no agent can run. Claude Code
35 (`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
36 environment (the server forwards `process.env` to the child; no interactive `claude auth login`
37 needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
38 server to pick up a newly installed provider CLI immediately.
39
40## Android native builds (apps/mobile)
41
42The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
43(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
44use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
45platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
46Gradle auto-downloads any additional pinned SDK packages on demand.
47
48- Generate the native project first: from `apps/mobile`,
49 `EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
50 (the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
51 minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
52- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
53 slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
54 `-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
55 `./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
56- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
57 emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
58 actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
59 Android Studio bundles is what is installed.
60- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
61 `:react-native-screens:compileDebugKotlin` fails because `patches/react-native-screens@4.25.2.patch`
62 adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
63 `headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
64 Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
65 The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
66 Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
67 scope for environment setup.
68
69## Known flaky tests (unrelated to setup)
70
71- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
72- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
.env.example+4−0
@@ -18,6 +18,10 @@ · 17 unmodified lines
18# Get this from your relay deployment. `infra/relay` deploys update it automatically.18# Get this from your relay deployment. `infra/relay` deploys update it automatically.
19# T3CODE_RELAY_URL=https://relay.example.com19# T3CODE_RELAY_URL=https://relay.example.com
20 20
21# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
22# Defaults to https://app.t3.codes; override to test against a staging deployment.
23# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes
24
21# Public, ingest-only mobile OpenTelemetry configuration.25# Public, ingest-only mobile OpenTelemetry configuration.
22# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces26# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
23# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev27# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
.github/workflows/mobile-eas-preview.yml+4−1
@@ -57,7 +57,10 @@ jobs: · 56 unmodified lines
57 with:57 with:
58 eas-version: latest58 eas-version: latest
59 token: ${{ secrets.EXPO_TOKEN }}59 token: ${{ secrets.EXPO_TOKEN }}
60 packager: pnpm60 # npm, not pnpm: this only installs eas-cli into the action's own
61 # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
62 # ignored build script (no allowBuilds config outside the repo).
63 packager: npm
61 64
62 - name: Pull preview environment variables65 - name: Pull preview environment variables
63 if: steps.expo-token.outputs.present == 'true'66 if: steps.expo-token.outputs.present == 'true'
.github/workflows/mobile-eas-production.yml+113−0
@@ -0,0 +1,113 @@
1name: Mobile EAS Production
2
3# Production builds and OTA updates run from CI (Linux) — never from a laptop.
4# Under the fingerprint runtime-version policy the fingerprint must be computed
5# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
6# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
7# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
8on:
9 workflow_dispatch:
10 inputs:
11 mode:
12 description: "build (+ auto-submit to TestFlight) or update (OTA)"
13 required: true
14 type: choice
15 default: build
16 options:
17 - build
18 - update
19 platform:
20 description: "Target platform"
21 required: true
22 type: choice
23 default: ios
24 options:
25 - ios
26 - android
27 - all
28 message:
29 description: "OTA update message (mode=update only)"
30 required: false
31 type: string
32
33jobs:
34 production:
35 name: EAS Production ${{ inputs.mode }}
36 runs-on: blacksmith-8vcpu-ubuntu-2404
37 permissions:
38 contents: read
39 env:
40 APP_VARIANT: production
41 NODE_OPTIONS: --max-old-space-size=8192
42 steps:
43 - id: expo-token
44 name: Check for EXPO_TOKEN
45 env:
46 EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
47 run: |
48 if [ -n "$EXPO_TOKEN" ]; then
49 echo "present=true" >> "$GITHUB_OUTPUT"
50 else
51 echo "present=false" >> "$GITHUB_OUTPUT"
52 echo "EXPO_TOKEN is not available; skipping EAS production job."
53 fi
54
55 - name: Checkout
56 if: steps.expo-token.outputs.present == 'true'
57 uses: actions/checkout@v6
58 with:
59 fetch-depth: 0
60
61 - name: Setup Vite+
62 if: steps.expo-token.outputs.present == 'true'
63 uses: voidzero-dev/setup-vp@v1
64 with:
65 node-version-file: package.json
66 cache: true
67 run-install: true
68
69 - name: Expose pnpm
70 if: steps.expo-token.outputs.present == 'true'
71 run: |
72 pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
73 vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
74 echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
75 "$vp_pnpm_bin/pnpm" --version
76
77 - name: Setup EAS
78 if: steps.expo-token.outputs.present == 'true'
79 uses: expo/expo-github-action@v8
80 with:
81 eas-version: latest
82 token: ${{ secrets.EXPO_TOKEN }}
83 # npm, not pnpm: this only installs eas-cli into the action's own
84 # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
85 # ignored build script (no allowBuilds config outside the repo).
86 packager: npm
87
88 - name: Pull production environment variables
89 if: steps.expo-token.outputs.present == 'true'
90 working-directory: apps/mobile
91 env:
92 EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
93 run: eas env:pull production --non-interactive
94
95 - name: Build and submit
96 if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
97 working-directory: apps/mobile
98 env:
99 EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
100 run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
101
102 - name: Publish OTA update
103 if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
104 working-directory: apps/mobile
105 env:
106 EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
107 run: |
108 eas update \
109 --channel production \
110 --environment production \
111 --platform ${{ inputs.platform }} \
112 --message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
113 --non-interactive
.github/workflows/mobile-showcase-screenshots.yml+134−0
@@ -0,0 +1,134 @@
1name: Mobile Showcase Screenshots
2
3on:
4 workflow_dispatch:
5 inputs:
6 platform:
7 description: Device platforms to capture
8 required: true
9 default: all
10 type: choice
11 options:
12 - all
13 - ios
14 - android
15 appearance:
16 description: System appearances to capture
17 required: true
18 default: both
19 type: choice
20 options:
21 - both
22 - dark
23 - light
24
25permissions:
26 contents: read
27
28env:
29 NODE_OPTIONS: --max-old-space-size=8192
30
31jobs:
32 ios:
33 name: iPhone 6.9, iPhone 6.5, and iPad 13
34 if: inputs.platform == 'all' || inputs.platform == 'ios'
35 runs-on: blacksmith-12vcpu-macos-26
36 timeout-minutes: 60
37 steps:
38 - name: Checkout
39 uses: actions/checkout@v6
40
41 - name: Setup Vite+
42 uses: voidzero-dev/setup-vp@v1
43 with:
44 node-version-file: package.json
45 cache: true
46 run-install: true
47
48 - name: Expose pnpm
49 run: |
50 pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
51 vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
52 echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
53 "$vp_pnpm_bin/pnpm" --version
54
55 - name: Capture iOS showcase
56 run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
57
58 - name: Validate App Store Connect assets
59 run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
60
61 - name: Upload iOS screenshots
62 if: always()
63 uses: actions/upload-artifact@v7
64 with:
65 name: app-store-connect-screenshots
66 path: artifacts/app-store/screenshots/apple/
67 if-no-files-found: warn
68 retention-days: 14
69
70 android:
71 name: Android phone, 7-inch tablet, and 10-inch tablet
72 if: inputs.platform == 'all' || inputs.platform == 'android'
73 runs-on: blacksmith-16vcpu-ubuntu-2404
74 timeout-minutes: 60
75 env:
76 T3_SHOWCASE_ANDROID_ABI: x86_64
77 steps:
78 - name: Checkout
79 uses: actions/checkout@v6
80
81 - name: Setup Vite+
82 uses: voidzero-dev/setup-vp@v1
83 with:
84 node-version-file: package.json
85 cache: true
86 run-install: true
87
88 - name: Expose pnpm
89 run: |
90 pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
91 vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
92 echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
93 "$vp_pnpm_bin/pnpm" --version
94
95 - name: Setup Java
96 uses: actions/setup-java@v5
97 with:
98 distribution: temurin
99 java-version: 17
100
101 - name: Setup Gradle cache
102 uses: gradle/actions/setup-gradle@v5
103
104 - name: Enable KVM
105 run: |
106 echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
107 | sudo tee /etc/udev/rules.d/99-kvm4all.rules
108 sudo udevadm control --reload-rules
109 sudo udevadm trigger --name-match=kvm
110
111 - name: Capture Android showcase
112 uses: reactivecircus/android-emulator-runner@v2
113 with:
114 api-level: 36
115 target: google_apis
116 arch: x86_64
117 profile: pixel_7_pro
118 avd-name: Pixel_10_Pro
119 cores: 8
120 ram-size: 4096M
121 disable-animations: false
122 script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
123
124 - name: Validate Google Play assets
125 run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
126
127 - name: Upload Android screenshots
128 if: always()
129 uses: actions/upload-artifact@v7
130 with:
131 name: google-play-screenshots
132 path: artifacts/app-store/screenshots/google-play/
133 if-no-files-found: warn
134 retention-days: 14
.gitignore+3−0
@@ -27,6 +27,9 @@ squashfs-root/ · 26 unmodified lines
27.gstack/27.gstack/
28dist-electron/28dist-electron/
29.electron-runtime/29.electron-runtime/
30.showcase/
31apps/mobile/.showcase/
32artifacts/app-store/screenshots/
30node_modules/33node_modules/
31.alchemy/34.alchemy/
32*.log35*.log
.macroscope/check-run-agents/effect-service-conventions.md+9−0
@@ -43,6 +43,15 @@ Review changed TypeScript and directly affected call sites for the conventions b · 42 unmodified lines
43- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.43- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
44- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.44- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
45 45
46## Dependency acquisition and runtime boundaries
47
48- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
49- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
50- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
51- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
52- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
53- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
54
46## Errors and predicates55## Errors and predicates
47 56
48- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.57- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
.mcp.json+11−0
@@ -0,0 +1,11 @@
1{
2 "mcpServers": {
3 "xcodebuildmcp": {
4 "command": "npx",
5 "args": ["--yes", "xcodebuildmcp@2.6.2", "mcp"],
6 "env": {
7 "XCODEBUILDMCP_ENABLED_WORKFLOWS": "simulator,ui-automation,debugging,logging"
8 }
9 }
10 }
11}
.plans/t3-connect-remote-setup.html+257−0
@@ -0,0 +1,257 @@
1<!doctype html>
2<html lang="en">
3<head>
4<meta charset="utf-8">
5<meta name="viewport" content="width=device-width, initial-scale=1">
6<title>Plan: seamless `npx t3 connect` for remote boxes</title>
7<style>
8 :root {
9 --bg: #000;
10 --fg: #fff;
11 --muted: #a3a3a3;
12 --surface: #121212;
13 --surface2: #1a1a1a;
14 --border: #2a2a2a;
15 --accent: #7c9cff;
16 --green: #4ade80;
17 --amber: #fbbf24;
18 --red: #f87171;
19 }
20 * { box-sizing: border-box; }
21 body {
22 margin: 0;
23 background: var(--bg);
24 color: var(--fg);
25 font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
26 }
27 main { max-width: 880px; margin: 0 auto; padding: 48px 24px 96px; }
28 h1 { font-size: 30px; line-height: 1.25; margin: 0 0 8px; }
29 h2 { font-size: 21px; margin: 48px 0 12px; padding-top: 24px; border-top: 1px solid var(--border); }
30 h3 { font-size: 16px; margin: 24px 0 8px; }
31 p, li { color: #e5e5e5; }
32 .sub { color: var(--muted); margin: 0 0 24px; }
33 code, pre {
34 font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
35 font-size: 13.5px;
36 }
37 code { background: var(--surface2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; }
38 pre {
39 background: var(--surface);
40 border: 1px solid var(--border);
41 border-radius: 8px;
42 padding: 16px;
43 overflow-x: auto;
44 line-height: 1.5;
45 }
46 pre code { background: none; border: none; padding: 0; }
47 .card {
48 background: var(--surface);
49 border: 1px solid var(--border);
50 border-radius: 10px;
51 padding: 18px 20px;
52 margin: 16px 0;
53 }
54 .card h3 { margin-top: 0; }
55 table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14.5px; }
56 th, td { text-align: left; padding: 8px 12px; border: 1px solid var(--border); vertical-align: top; }
57 th { background: var(--surface2); font-weight: 600; }
58 td code { white-space: nowrap; }
59 .pill {
60 display: inline-block; font-size: 12px; font-weight: 600; border-radius: 999px;
61 padding: 2px 10px; margin-right: 6px; vertical-align: 2px;
62 }
63 .pill.core { background: #1e2a4a; color: var(--accent); }
64 .pill.new { background: #14301e; color: var(--green); }
65 .pill.later { background: #33270e; color: var(--amber); }
66 .ok { color: var(--green); }
67 .warn { color: var(--amber); }
68 .no { color: var(--red); }
69 ul { padding-left: 22px; }
70 li { margin: 4px 0; }
71 .terminal {
72 background: #0a0a0a; border: 1px solid var(--border); border-radius: 8px;
73 padding: 16px; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
74 font-size: 13.5px; line-height: 1.65; color: #d4d4d4; overflow-x: auto;
75 }
76 .terminal .dim { color: #737373; }
77 .terminal .g { color: var(--green); }
78 .terminal .b { color: var(--accent); }
79 figure { margin: 24px 0; }
80 figcaption { color: var(--muted); font-size: 13px; margin-top: 8px; text-align: center; }
81 svg text { font-family: -apple-system, "Segoe UI", sans-serif; }
82 a { color: var(--accent); }
83 .kv { color: var(--muted); font-size: 13.5px; }
84</style>
85</head>
86<body>
87<main>
88
89<h1>Seamless <code>npx t3 connect</code> for remote boxes</h1>
90<p class="sub">Design principle: <strong>the smallest diff that ships the UX.</strong> No relay/infra changes, no new backend surface, no new auth primitives &mdash; every step reuses code that already exists. One PR, built as four phases with clear commit boundaries &mdash; each phase compiles, passes tests, and leaves the product working, so the PR reviews commit-by-commit. (Phase 4, web-triggered update, is an optional follow-up PR.)</p>
91
92<div class="terminal">
93$ npx t3 connect<br><br>
94To set up T3 Connect, open this URL and sign in:<br>
95&nbsp;&nbsp;<span class="b">https://app.t3.codes/connect#B64URL_STATE_AND_CHALLENGE</span><br><br>
96Enter your authentication code: <span class="dim">[code]</span><br><br>
97<span class="g">Connected as theo@t3.gg!</span><br><br>
98Run T3 Code in the background whenever this machine boots? (y/n): y<br><br>
99<span class="g">T3 Code is set up and ready to go.</span>
100</div>
101
102<h2>Why this is a small change</h2>
103<p>The entire <code>t3 connect</code> data plane already works: Clerk PKCE token exchange, encrypted secret store, cloudflared relay-client install, relay environment linking, DPoP tokens. The <em>only</em> broken piece on an SSH box is the redirect: <code>CliTokenManager.login()</code> hardcodes a loopback callback (<code>http://127.0.0.1:34338/callback</code>) that requires a browser on the same machine.</p>
104<p>We swap that one leg for a hosted out-of-band authorization page and keep everything else. Because PKCE's <code>code_verifier</code> never leaves the box, the displayed one-time code is useless to anyone who sees it &mdash; no new token-minting or storage is needed anywhere.</p>
105
106<div class="card">
107<h3>Reused as-is (zero changes)</h3>
108<ul>
109 <li><code>exchangeToken()</code> PKCE exchange &mdash; <code>apps/server/src/cloud/CliTokenManager.ts:147</code></li>
110 <li>Token persistence in <code>ServerSecretStore</code> (<code>cloud-cli-oauth-token</code>)</li>
111 <li><code>acquireRelayClientForLink()</code> cloudflared install + progress &mdash; <code>cli/connect.ts:146</code></li>
112 <li><code>CliState.setCliDesiredCloudLink()</code> + server-side provisioning on start</li>
113 <li>All relay endpoints (<code>infra/relay</code>) and contracts &mdash; <strong>untouched</strong></li>
114 <li>Existing subcommands <code>login/link/status/unlink/logout</code> &mdash; semantics unchanged</li>
115 <li>Web app Clerk session + hosted-page precedent (<code>routes/pair.tsx</code>, <code>hostedPairing.ts</code>)</li>
116</ul>
117</div>
118
119<h2>Auth flow (hosted out-of-band OAuth, Clerk PKCE)</h2>
120
121<figure>
122<svg viewBox="0 0 820 470" width="100%" role="img" aria-label="Sequence diagram of the out-of-band OAuth flow">
123 <!-- lanes -->
124 <rect x="20" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
125 <rect x="300" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
126 <rect x="580" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
127 <text x="130" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Remote box &#8212; t3 CLI</text>
128 <text x="410" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Laptop &#8212; app.t3.codes</text>
129 <text x="690" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Clerk</text>
130 <line x1="130" y1="60" x2="130" y2="450" stroke="#2a2a2a"/>
131 <line x1="410" y1="60" x2="410" y2="450" stroke="#2a2a2a"/>
132 <line x1="690" y1="60" x2="690" y2="450" stroke="#2a2a2a"/>
133
134 <!-- 1: generate + print -->
135 <rect x="30" y="80" width="200" height="34" rx="6" fill="#1e2a4a"/>
136 <text x="130" y="101" fill="#7c9cff" font-size="12.5" text-anchor="middle">1. gen verifier + challenge + state</text>
137
138 <!-- 2: user opens URL -->
139 <line x1="130" y1="140" x2="404" y2="140" stroke="#7c9cff" stroke-dasharray="5 4"/>
140 <polygon points="404,140 394,135 394,145" fill="#7c9cff"/>
141 <text x="267" y="132" fill="#a3a3a3" font-size="12.5" text-anchor="middle">2. user opens /connect#&#123;state,challenge&#125;</text>
142
143 <!-- 3: redirect to clerk -->
144 <line x1="410" y1="185" x2="684" y2="185" stroke="#e5e5e5"/>
145 <polygon points="684,185 674,180 674,190" fill="#e5e5e5"/>
146 <text x="547" y="177" fill="#a3a3a3" font-size="12.5" text-anchor="middle">3. sign in &#8594; /oauth/authorize (PKCE)</text>
147
148 <!-- 4: redirect back with code -->
149 <line x1="690" y1="230" x2="416" y2="230" stroke="#e5e5e5"/>
150 <polygon points="416,230 426,225 426,235" fill="#e5e5e5"/>
151 <text x="553" y="222" fill="#a3a3a3" font-size="12.5" text-anchor="middle">4. redirect /connect/callback?code&amp;state</text>
152
153 <!-- 5: page shows code -->
154 <rect x="310" y="252" width="200" height="34" rx="6" fill="#14301e"/>
155 <text x="410" y="273" fill="#4ade80" font-size="12.5" text-anchor="middle">5. shows account + authorization code</text>
156
157 <!-- 6: user enters code -->
158 <line x1="410" y1="316" x2="136" y2="316" stroke="#7c9cff" stroke-dasharray="5 4"/>
159 <polygon points="136,316 146,311 146,321" fill="#7c9cff"/>
160 <text x="273" y="308" fill="#a3a3a3" font-size="12.5" text-anchor="middle">6. user enters code in terminal</text>
161
162 <!-- 7: token exchange -->
163 <line x1="130" y1="360" x2="684" y2="360" stroke="#e5e5e5"/>
164 <polygon points="684,360 674,355 674,365" fill="#e5e5e5"/>
165 <text x="407" y="352" fill="#a3a3a3" font-size="12.5" text-anchor="middle">7. POST /oauth/token &#123;code + verifier&#125; &#8594; access/refresh tokens</text>
166
167 <!-- 8: done -->
168 <rect x="30" y="392" width="200" height="46" rx="6" fill="#14301e"/>
169 <text x="130" y="411" fill="#4ade80" font-size="12.5" text-anchor="middle">8. store token, set desired link,</text>
170 <text x="130" y="427" fill="#4ade80" font-size="12.5" text-anchor="middle">install relay client &#8594; Connected!</text>
171</svg>
172<figcaption>The verifier never leaves the box (steps 1&#8594;7), so the authorization code is worthless if observed. state/challenge ride the URL fragment &mdash; they are not secrets.</figcaption>
173</figure>
174
175<div class="card">
176<h3>Details that keep it simple</h3>
177<ul>
178 <li><strong>Stateless URL, no short-link service.</strong> The <code>/connect</code> page reads <code>state</code> + <code>code_challenge</code> from the URL fragment and builds the Clerk authorize URL client-side. ~100-char URL &mdash; fine to transfer into an SSH session.</li>
179 <li><strong>State check without a backend:</strong> the callback page displays one authorization blob of <code>code.state</code>; the CLI splits it and verifies <code>state</code> matches what it generated. One line on each side, preserves the loopback flow's CSRF check.</li>
180 <li><strong>Phishing is addressed with copy, not code:</strong> the callback page shows <em>which account</em> is being connected ("Connecting as theo@&hellip;") and warns: <em>"Only enter this code in a terminal session you started yourself."</em> No mechanism needed.</li>
181 <li><strong>Code expiry is a non-issue:</strong> Clerk auth codes live 10 minutes &mdash; the same timeout the existing loopback flow already uses. Wrong/expired code &#8594; friendly retry that reprints the URL.</li>
182 <li><strong>One external config step:</strong> register <code>https://app.t3.codes/connect/callback</code> as an allowed redirect URI on the existing Clerk CLI OAuth client. No new client, no new scopes.</li>
183</ul>
184</div>
185
186<h2>The phases (one PR, one commit each)</h2>
187<p class="kv">Ordering is dependency order: each phase is independently revertable and the tree is green at every boundary. Phases 1&ndash;3 are the PR; phase 4 ships separately later.</p>
188
189<table>
190 <tr><th style="width:1%">Phase</th><th>Scope</th><th>Files</th><th style="width:1%">~LOC</th></tr>
191 <tr>
192 <td><span class="pill core">1</span></td>
193 <td><strong>Hosted code page</strong> (web-only, purely additive, zero risk). Two static routes modeled on <code>pair.tsx</code>: <code>/connect</code> (ensure Clerk session, then client-side redirect to authorize &mdash; it's a static SPA, no server 302) and <code>/connect/callback</code> (validate params, show account + copyable code + safety warning). Both routes guard against non-hosted deployments &mdash; redirect to <code>/</code> unless <code>isHostedStaticApp()</code>, same pattern as <code>pair.tsx</code>, since this bundle also ships in local instances. Plus the Clerk dashboard redirect-URI entry.</td>
194 <td><code>apps/web/src/routes/connect.tsx</code><br><code>apps/web/src/routes/connect.callback.tsx</code></td>
195 <td>~200</td>
196 </tr>
197 <tr>
198 <td><span class="pill core">2</span></td>
199 <td><strong>CLI out-of-band OAuth flow + single command.</strong> Add an out-of-band OAuth login path to <code>CliTokenManager</code> (print URL, <code>Prompt.text</code> for the code, reuse <code>exchangeToken</code>). Make bare <code>t3 connect</code> a handler = login + link (subcommands untouched). Auto-pick headless mode inside SSH sessions (<code>SSH_CONNECTION</code>/<code>SSH_TTY</code> &mdash; nothing else); <code>--headless</code> flag as manual override. Loopback stays the default on desktop &mdash; no regression.</td>
200 <td><code>cloud/CliTokenManager.ts</code> (+60)<br><code>cloud/publicConfig.ts</code> (+10)<br><code>cli/connect.ts</code> (+60)</td>
201 <td>~150</td>
202 </tr>
203 <tr>
204 <td><span class="pill new">3</span></td>
205 <td><strong>Background on boot &mdash; Linux first</strong> (the SSH case). One new module: pinned runtime install to <code>~/.t3/runtime/versions/&lt;v&gt;</code> + <code>current</code> symlink, systemd <em>user</em> unit with absolute node/t3 paths, <code>enable-linger</code>. y/n prompt at the end of <code>connect</code>; teardown in <code>logout</code>. Install and service-start failures must land in a log file (under <code>~/.t3/userdata/logs/</code>) whose path is printed at connect time &mdash; systemd user units fail invisibly otherwise. Unit-file generation is pure string-building &#8594; trivially testable. macOS launchd / Windows follow as 3b/3c only if wanted.</td>
206 <td><code>cloud/bootService.ts</code> (new)<br><code>cli/connect.ts</code> (+prompt/teardown)</td>
207 <td>~250</td>
208 </tr>
209 <tr>
210 <td><span class="pill later">4</span></td>
211 <td><strong>Web-triggered update</strong> (optional follow-up PR; not part of this one, not needed for the core UX). Web detects <code>daemon version &lt; latest-on-channel</code> using the existing version-skew surface + hosted manifest; one authenticated "update" command &mdash; client says <em>update</em>, daemon resolves/verifies the version itself (never client-specified &mdash; that would be RCE). Stage install &#8594; verify &#8594; atomic symlink swap &#8594; <code>systemctl --user restart</code>. Progress streams reuse the <code>RelayClientInstallProgressEvent</code> pattern.</td>
212 <td>web banner + one control command + daemon update routine</td>
213 <td>later</td>
214 </tr>
215</table>
216
217<h3>Runtime layout (phase 3)</h3>
218<pre><code>~/.t3/runtime/
219├── versions/0.0.27/ &larr; npm install --prefix (gets native deps right: node-pty etc.)
220└── current -> versions/0.0.27
221
222~/.config/systemd/user/t3code.service &larr; ExecStart=/abs/path/node .../current/.../t3 serve
223loginctl enable-linger $USER &larr; survives SSH logout / reboot</code></pre>
224<p class="kv">Why a real <code>npm install</code> and not "reuse the npx binary": the npx cache is ephemeral and <code>t3</code> ships native deps (<code>node-pty</code>, <code>@ff-labs/fff-node</code>) that need per-platform prebuilds. Why pinned and not <code>npx t3@latest</code> in the unit: a boot-time registry fetch means the box may simply not come up (network down, PATH-less systemd env, nvm). Deterministic boot; updates happen out-of-band (phase 4 follow-up) or by re-running <code>npx t3 connect</code>.</p>
225
226<h2>Explicitly not doing</h2>
227<ul>
228 <li><span class="no">&#10007;</span> Relay / <code>infra</code> / contracts changes &mdash; none, in any phase</li>
229 <li><span class="no">&#10007;</span> Short-link service (<code>app.t3.codes/c/AB7K</code>) &mdash; only matters for hand-typing; revisit if ever needed</li>
230 <li><span class="no">&#10007;</span> RFC 8628 device grant &mdash; wrong UX direction, unverified Clerk support</li>
231 <li><span class="no">&#10007;</span> Auto-update loop in the daemon &mdash; web-triggered only (phase 4 follow-up), user stays in control</li>
232 <li><span class="no">&#10007;</span> Project auto-registration &mdash; workspace assumed set up; the web UI handles the rest</li>
233 <li><span class="no">&#10007;</span> Changing existing loopback flow, subcommands, or desktop behavior</li>
234</ul>
235
236<h2>Risks &amp; checks</h2>
237<ul>
238 <li><span class="warn">&#9888;</span> <strong>Clerk redirect URI:</strong> confirm the CLI OAuth client accepts the hosted redirect and that the token endpoint honors PKCE exchange for codes issued to it. Verify in staging before the phase 2 commit. <em>(Only external dependency in the plan.)</em></li>
239 <li><span class="warn">&#9888;</span> <strong>systemd user env is minimal:</strong> always write absolute paths for node + t3 into the unit; never rely on PATH. Service failures are invisible by default &mdash; hence the phase 3 requirement to log to a printed file path.</li>
240 <li><span class="warn">&#9888;</span> <strong>Linger prompt honesty:</strong> the y/n prompt should say the machine becomes reachable via T3 Connect whenever powered on &mdash; that's the feature, but say it.</li>
241 <li><span class="ok">&#10003;</span> Re-running <code>connect</code> when linked &#8594; idempotent: refresh token, re-confirm service, done.</li>
242</ul>
243
244<h2>Decision log</h2>
245<ul class="kv">
246 <li>Auth: hosted out-of-band OAuth redirect on Clerk PKCE (not relay-brokered pairing, not device grant) &mdash; chosen for minimal new surface.</li>
247 <li>URL: stateless static page, no backend short-link.</li>
248 <li>Service: real per-user login service (systemd user + linger first); detect + offer install, never silent.</li>
249 <li>Binary: pinned managed runtime under <code>~/.t3</code>; interactive <code>npx</code> usage untouched.</li>
250 <li>Updates: not always-latest; web UI surfaces available updates with one-click trigger (phase 4 follow-up).</li>
251 <li>Delivery: one PR with a commit per phase (green tree at every boundary), not separate PRs.</li>
252 <li>Workspace: assumed already set up; no auto-registration.</li>
253</ul>
254
255</main>
256</body>
257</html>
.vite-hooks/pre-commit+1−0
@@ -0,0 +1 @@
1vp staged
AGENTS.md+11−24
@@ -2,27 +2,16 @@ · 1 unmodified line
2 2
3## Task Completion Requirements3## Task Completion Requirements
4 4
5- `vp check` and `vp run typecheck` must pass before considering tasks completed.5- Keep local verification focused on the files and packages changed. Run the smallest relevant test set; do not run the full workspace test suite as a routine completion step.
6 - If changing native mobile code, `vp run lint:mobile` must also pass.6 - Use `vp test run <test-files>` for focused built-in Vite+ tests. Use `vp run test` only when the affected package specifically requires its `test` script.
7- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.7 - Backend changes must include and run focused tests for the changed behavior.
8 8 - Run targeted formatting, lint, and type checks for the affected scope when available.
9## Project Snapshot9- Do not run repo-wide `vp check`, `vp run typecheck`, `vp run test`, or equivalent full-suite commands locally unless the user explicitly requests them. CI is responsible for the full verification suite.
10 10- After frontend feature development or any user-visible frontend behavior change, the primary agent must run one integrated verification pass for each affected client surface after integrating the work:
11T3 Code is a minimal web GUI for using coding agents like Codex and Claude.11 - Web: use the `test-t3-app` skill. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
12 12 - Mobile: use the `test-t3-mobile` skill. Connect one representative iOS Simulator or Android Emulator available on the host to one isolated environment and verify the affected flow. On compatible macOS hosts, prefer iOS for cross-platform changes and stream it through serve-sim in the T3 Code in-app browser or another available agent browser; use Android when it is the affected or viable platform.
13This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.13 - Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
14 14 - Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
15## Core Priorities
16
171. Performance first.
182. Reliability first.
193. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
20
21If a tradeoff is required, choose correctness and robustness over short-term convenience.
22
23## Maintainability
24
25Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
26 15
27## Package Roles16## Package Roles
28 17
@@ -35,7 +24,6 @@ Long term maintainability is a core priority. If you add new functionality, firs · 6 unmodified lines
35## Reference Repos24## Reference Repos
36 25
37- Open-source Codex repo: https://github.com/openai/codex26- Open-source Codex repo: https://github.com/openai/codex
38- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
39 27
40Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.28Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
41 29
@@ -47,8 +35,7 @@ agents. · 5 unmodified lines
47- Prefer examples and patterns from the vendored source code over generated guesses or web search results.35- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
48- Do not edit files under `.repos/` unless explicitly asked.36- Do not edit files under `.repos/` unless explicitly asked.
49- Do not import from `.repos/`; application code must continue importing from normal package dependencies.37- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
50- Manage vendored subtrees with `bun run sync:repos`; use `bun run sync:repos --repo <id>` to sync one38- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
51 configured repository.
52- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so39- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
53 `.repos/` matches the installed dependency version.40 `.repos/` matches the installed dependency version.
54- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for41- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
app.json+3−0
@@ -0,0 +1,3 @@
1{
2 "expo": {}
3}
apps/desktop/package.json+2−2
@@ -1,6 +1,6 @@
1{1{
2 "name": "@t3tools/desktop",2 "name": "@t3tools/desktop",
3 "version": "0.0.27",3 "version": "0.0.28",
4 "private": true,4 "private": true,
5 "type": "module",5 "type": "module",
6 "main": "dist-electron/main.cjs",6 "main": "dist-electron/main.cjs",
@@ -31,7 +31,7 @@ · 24 unmodified lines
31 "@effect/vitest": "catalog:",31 "@effect/vitest": "catalog:",
32 "@types/node": "catalog:",32 "@types/node": "catalog:",
33 "cross-env": "^10.1.0",33 "cross-env": "^10.1.0",
34 "electron-builder": "26.8.1",34 "electron-builder": "26.15.6",
35 "tailwindcss": "^4.0.0",35 "tailwindcss": "^4.0.0",
36 "vite-plus": "catalog:"36 "vite-plus": "catalog:"
37 },37 },
apps/desktop/scripts/electron-launcher.mjs+47−15
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment · 19 unmodified lines
20 ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`20 ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
21 : "com.t3tools.t3code";21 : "com.t3tools.t3code";
22const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];22const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
23const LAUNCHER_VERSION = 12;23const LAUNCHER_VERSION = 14;
24const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");24const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
25const developmentMacIconPngPath = NodePath.join(25const developmentMacIconPngPath = NodePath.join(
26 repoRoot,26 repoRoot,
@@ -220,11 +220,12 @@ function ensureDevelopmentIconIcns(runtimeDir) { · 193 unmodified lines
220 }220 }
221}221}
222 222
223function patchMainBundleInfoPlist(appBundlePath, iconPath) {223function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
224 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");224 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
225 setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);225 setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
226 setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);226 setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
227 setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);227 setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
228 setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
228 setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");229 setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
229 setPlistJson(infoPlistPath, "CFBundleURLTypes", [230 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
230 {231 {
@@ -277,11 +278,25 @@ function readJson(path) { · 46 unmodified lines
277 }278 }
278}279}
279 280
281export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
282 const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
283 const launcherExecutableName = `${displayName} Launcher`;
284 return {
285 launcherExecutableName,
286 launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
287 runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
288 };
289}
290
280function buildMacLauncher(electronBinaryPath) {291function buildMacLauncher(electronBinaryPath) {
281 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");292 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
282 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");293 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
283 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);294 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
284 const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");295 const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
296 const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
297 const launcherBinaryPath = isDevelopment
298 ? developmentPaths.launcherBinaryPath
299 : runtimeElectronBinaryPath;
285 const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;300 const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
286 const metadataPath = NodePath.join(runtimeDir, "metadata.json");301 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
287 302
@@ -298,7 +313,8 @@ function buildMacLauncher(electronBinaryPath) { · 10 unmodified lines
298 313
299 const currentMetadata = readJson(metadataPath);314 const currentMetadata = readJson(metadataPath);
300 if (315 if (
301 NodeFS.existsSync(targetBinaryPath) &&316 NodeFS.existsSync(launcherBinaryPath) &&
317 (!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
302 currentMetadata &&318 currentMetadata &&
303 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)319 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
304 ) {320 ) {
@@ -306,10 +322,10 @@ function buildMacLauncher(electronBinaryPath) { · 1 unmodified line
306 // The launcher also handles protocol activations outside the dev runner,322 // The launcher also handles protocol activations outside the dev runner,
307 // so refresh its fallback environment on every launch. Never let a value323 // so refresh its fallback environment on every launch. Never let a value
308 // captured by an older parent app override the live dev-runner environment.324 // captured by an older parent app override the live dev-runner environment.
309 writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);325 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
310 }326 }
311 registerMacLauncherBundle(targetAppBundlePath);327 registerMacLauncherBundle(targetAppBundlePath);
312 return targetBinaryPath;328 return launcherBinaryPath;
313 }329 }
314 330
315 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });331 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
@@ -321,15 +337,24 @@ function buildMacLauncher(electronBinaryPath) { · 5 unmodified lines
321 recursive: true,337 recursive: true,
322 verbatimSymlinks: true,338 verbatimSymlinks: true,
323 });339 });
324 patchMainBundleInfoPlist(targetAppBundlePath, iconPath);340 patchMainBundleInfoPlist(
341 targetAppBundlePath,
342 iconPath,
343 isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
344 );
325 patchHelperBundleInfoPlists(targetAppBundlePath);345 patchHelperBundleInfoPlists(targetAppBundlePath);
326 if (isDevelopment) {346 if (isDevelopment) {
327 writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);347 // Keep Electron's native executable inside the branded bundle. Launching the
348 // node_modules copy makes macOS associate the process (and Dock label) with
349 // Electron.app even though this bundle's Info.plist has the T3 Code name.
350 // Its conventional executable name also keeps Electron's default-app runtime
351 // in development mode instead of making app.isPackaged report true.
352 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
328 }353 }
329 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);354 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
330 registerMacLauncherBundle(targetAppBundlePath);355 registerMacLauncherBundle(targetAppBundlePath);
331 356
332 return targetBinaryPath;357 return launcherBinaryPath;
333}358}
334 359
335function isLinuxSetuidSandboxConfigured(electronBinaryPath) {360function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
@@ -358,10 +383,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) { · 22 unmodified lines
358}383}
359 384
360export function resolveElectronPath() {385export function resolveElectronPath() {
361 ensureElectronRuntime();386 const electronBinaryPath = resolveElectronBinaryPath();
362
363 const require = NodeModule.createRequire(import.meta.url);
364 const electronBinaryPath = require("electron");
365 387
366 if (hostPlatform !== "darwin") {388 if (hostPlatform !== "darwin") {
367 return electronBinaryPath;389 return electronBinaryPath;
@@ -378,13 +400,23 @@ export function resolveElectronLaunchCommand(args = []) { · 10 unmodified lines
378 };400 };
379}401}
380 402
403export function resolveElectronBinaryPath({
404 ensureRuntime = ensureElectronRuntime,
405 createRequire = NodeModule.createRequire,
406 moduleUrl = import.meta.url,
407} = {}) {
408 ensureRuntime();
409
410 const require = createRequire(moduleUrl);
411 return require("electron");
412}
413
381export function resolveDevProtocolClient() {414export function resolveDevProtocolClient() {
382 if (hostPlatform !== "darwin" || !isDevelopment) {415 if (hostPlatform !== "darwin" || !isDevelopment) {
383 return null;416 return null;
384 }417 }
385 418
386 const require = NodeModule.createRequire(import.meta.url);419 const electronBinaryPath = resolveElectronBinaryPath();
387 const electronBinaryPath = require("electron");
388 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);420 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
389 return {421 return {
390 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),422 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
apps/desktop/scripts/electron-launcher.test.mjs+54−1
@@ -1,6 +1,10 @@
1import { assert, describe, it } from "vite-plus/test";1import { assert, describe, it } from "vite-plus/test";
2 2
3import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";3import {
4 makeDevelopmentLauncherScript,
5 resolveElectronBinaryPath,
6 resolveMacLauncherPaths,
7} from "./electron-launcher.mjs";
4 8
5describe("electron development launcher", () => {9describe("electron development launcher", () => {
6 it("uses captured values only as fallbacks for a live runner environment", () => {10 it("uses captured values only as fallbacks for a live runner environment", () => {
@@ -25,4 +29,53 @@ describe("electron development launcher", () => { · 18 unmodified lines
25 "exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",29 "exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
26 );30 );
27 });31 });
32
33 it("repairs Electron before loading the package entrypoint", () => {
34 const calls = [];
35 const electronPath = resolveElectronBinaryPath({
36 ensureRuntime: () => {
37 calls.push("ensure");
38 },
39 createRequire: () => (specifier) => {
40 calls.push(`require:${specifier}`);
41 return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
42 },
43 moduleUrl: import.meta.url,
44 });
45
46 assert.equal(
47 electronPath,
48 "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
49 );
50 assert.deepEqual(calls, ["ensure", "require:electron"]);
51 });
52
53 it("keeps the native Electron executable name inside the branded macOS bundle", () => {
54 const paths = resolveMacLauncherPaths(
55 "/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
56 "T3 Code (Dev)",
57 );
58
59 assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
60 assert.equal(
61 paths.launcherBinaryPath,
62 "/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
63 );
64 assert.equal(
65 paths.runtimeElectronBinaryPath,
66 "/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
67 );
68
69 const script = makeDevelopmentLauncherScript({
70 electronBinaryPath: paths.runtimeElectronBinaryPath,
71 mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
72 desktopRoot: "/repo/apps/desktop",
73 environment: {},
74 });
75 assert.include(
76 script,
77 "exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
78 );
79 assert.notInclude(script, "node_modules/electron");
80 });
28});81});
apps/desktop/src/app/DesktopEnvironment.test.ts+24−8
@@ -53,13 +53,16 @@ describe("DesktopEnvironment", () => { · 52 unmodified lines
53 assert.equal(environment.isDevelopment, true);53 assert.equal(environment.isDevelopment, true);
54 assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");54 assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
55 assert.equal(environment.baseDir, "/tmp/t3");55 assert.equal(environment.baseDir, "/tmp/t3");
56 assert.equal(environment.stateDir, "/tmp/t3/dev");56 assert.equal(environment.stateDir, "/tmp/t3/userdata");
57 assert.equal(environment.desktopSettingsPath, "/tmp/t3/dev/desktop-settings.json");57 assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
58 assert.equal(environment.clientSettingsPath, "/tmp/t3/dev/client-settings.json");58 assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
59 assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");59 assert.equal(
60 assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");60 environment.savedEnvironmentRegistryPath,
61 assert.equal(environment.logDir, "/tmp/t3/dev/logs");61 "/tmp/t3/userdata/saved-environments.json",
62 assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");62 );
63 assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
64 assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
65 assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
63 assert.equal(environment.rootDir, "/repo");66 assert.equal(environment.rootDir, "/repo");
64 assert.equal(environment.appRoot, "/repo");67 assert.equal(environment.appRoot, "/repo");
65 assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");68 assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
@@ -78,7 +81,7 @@ describe("DesktopEnvironment", () => { · 12 unmodified lines
78 }),81 }),
79 );82 );
80 83
81 it.effect("derives production state paths under userdata-v2", () =>84 it.effect("stores production state under userdata-v2 in an explicit home", () =>
82 Effect.gen(function* () {85 Effect.gen(function* () {
83 const environment = yield* makeEnvironment(86 const environment = yield* makeEnvironment(
84 {},87 {},
@@ -97,6 +100,19 @@ describe("DesktopEnvironment", () => { · 12 unmodified lines
97 }),100 }),
98 );101 );
99 102
103 it.effect("keeps implicit development state separate from production state", () =>
104 Effect.gen(function* () {
105 const development = yield* makeEnvironment(
106 {},
107 { VITE_DEV_SERVER_URL: "http://localhost:5173" },
108 );
109 const production = yield* makeEnvironment();
110
111 assert.equal(development.stateDir, "/Users/alice/.t3/dev");
112 assert.equal(production.stateDir, "/Users/alice/.t3/userdata-v2");
113 }),
114 );
115
100 it.effect("uses a configured app user model id override", () =>116 it.effect("uses a configured app user model id override", () =>
101 Effect.gen(function* () {117 Effect.gen(function* () {
102 const environment = yield* makeEnvironment(118 const environment = yield* makeEnvironment(
apps/desktop/src/app/DesktopEnvironment.ts+6−2
@@ -147,7 +147,8 @@ const make = Effect.fn("desktop.environment.make")(function* ( · 146 unmodified lines
147 : input.platform === "darwin"147 : input.platform === "darwin"
148 ? path.join(homeDirectory, "Library", "Application Support")148 ? path.join(homeDirectory, "Library", "Application Support")
149 : Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));149 : Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
150 const baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));150 const configuredBaseDir = config.t3Home;
151 const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
151 const rootDir = path.resolve(input.dirname, "../../..");152 const rootDir = path.resolve(input.dirname, "../../..");
152 const appRoot = input.isPackaged ? input.appPath : rootDir;153 const appRoot = input.isPackaged ? input.appPath : rootDir;
153 const branding = resolveDesktopAppBranding({154 const branding = resolveDesktopAppBranding({
@@ -155,7 +156,10 @@ const make = Effect.fn("desktop.environment.make")(function* ( · 1 unmodified line
155 appVersion: input.appVersion,156 appVersion: input.appVersion,
156 });157 });
157 const displayName = branding.displayName;158 const displayName = branding.displayName;
158 const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata-v2");159 const stateDir = path.join(
160 baseDir,
161 isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata-v2",
162 );
159 const userDataDirName = isDevelopment ? "t3code-dev" : "t3code-v2";163 const userDataDirName = isDevelopment ? "t3code-dev" : "t3code-v2";
160 const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha v2)";164 const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha v2)";
161 const resourcesPath = input.resourcesPath;165 const resourcesPath = input.resourcesPath;
apps/desktop/src/app/DesktopLifecycle.ts+7−1
@@ -73,8 +73,14 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>( · 72 unmodified lines
73}73}
74 74
75const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(75const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
76 function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {76 function* (): Effect.fn.Return<
77 void,
78 never,
79 DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
80 > {
77 const shutdown = yield* DesktopShutdown.DesktopShutdown;81 const shutdown = yield* DesktopShutdown.DesktopShutdown;
82 const desktopWindow = yield* DesktopWindow.DesktopWindow;
83 yield* desktopWindow.flushMainWindowBounds;
78 yield* shutdown.request;84 yield* shutdown.request;
79 yield* shutdown.awaitComplete;85 yield* shutdown.awaitComplete;
80 },86 },
apps/desktop/src/backend/DesktopBackendConfiguration.ts+1−0
@@ -607,6 +607,7 @@ export const make = Effect.gen(function* () { · 606 unmodified lines
607 const backendExposure = yield* serverExposure.backendConfig;607 const backendExposure = yield* serverExposure.backendConfig;
608 const persistedSettings = yield* settings.get;608 const persistedSettings = yield* settings.get;
609 const shared = yield* sharedInputs;609 const shared = yield* sharedInputs;
610 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
610 return yield* resolveWslStartConfig({611 return yield* resolveWslStartConfig({
611 ...shared,612 ...shared,
612 port: backendExposure.port,613 port: backendExposure.port,
apps/desktop/src/backend/DesktopBackendPool.test.ts+1−0
@@ -76,6 +76,7 @@ function makePoolLayer( · 75 unmodified lines
76 showConnectingSplash: Effect.void,76 showConnectingSplash: Effect.void,
77 handleBackendReady: () => Effect.void,77 handleBackendReady: () => Effect.void,
78 handleBackendNotReady: Effect.void,78 handleBackendNotReady: Effect.void,
79 flushMainWindowBounds: Effect.void,
79 dispatchMenuAction: () => Effect.die("unexpected menu action"),80 dispatchMenuAction: () => Effect.die("unexpected menu action"),
80 syncAppearance: Effect.void,81 syncAppearance: Effect.void,
81 } satisfies DesktopWindow.DesktopWindow["Service"]),82 } satisfies DesktopWindow.DesktopWindow["Service"]),
apps/desktop/src/backend/DesktopServerExposure.test.ts+1−0
@@ -250,6 +250,7 @@ describe("DesktopServerExposure", () => { · 249 unmodified lines
250 const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {250 const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
251 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),251 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
252 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),252 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
253 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
253 setServerExposureMode: () => Effect.fail(settingsFailure),254 setServerExposureMode: () => Effect.fail(settingsFailure),
254 setTailscaleServe: () => Effect.fail(settingsFailure),255 setTailscaleServe: () => Effect.fail(settingsFailure),
255 setUpdateChannel: () => Effect.die("unexpected update channel change"),256 setUpdateChannel: () => Effect.die("unexpected update channel change"),
apps/desktop/src/electron/ElectronMenu.test.ts+12−2
@@ -31,6 +31,12 @@ const TestLayer = ElectronMenu.layer.pipe( · 30 unmodified lines
31 Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),31 Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
32);32);
33 33
34const makeWindow = (zoomFactor = 1): Electron.BrowserWindow =>
35 ({
36 id: 7,
37 webContents: { getZoomFactor: () => zoomFactor },
38 }) as unknown as Electron.BrowserWindow;
39
34describe("ElectronMenu", () => {40describe("ElectronMenu", () => {
35 beforeEach(() => {41 beforeEach(() => {
36 buildFromTemplateMock.mockReset();42 buildFromTemplateMock.mockReset();
@@ -70,7 +76,7 @@ describe("ElectronMenu", () => { · 33 unmodified lines
70 76
71 const electronMenu = yield* ElectronMenu.ElectronMenu;77 const electronMenu = yield* ElectronMenu.ElectronMenu;
72 const selectedItemId = yield* electronMenu.showContextMenu({78 const selectedItemId = yield* electronMenu.showContextMenu({
73 window: {} as Electron.BrowserWindow,79 window: makeWindow(),
74 items: [{ id: "copy", label: "Copy" }],80 items: [{ id: "copy", label: "Copy" }],
75 position: Option.none(),81 position: Option.none(),
76 });82 });
@@ -81,20 +87,24 @@ describe("ElectronMenu", () => { · 4 unmodified lines
81 87
82 it.effect("resolves with none when the menu closes without a click", () =>88 it.effect("resolves with none when the menu closes without a click", () =>
83 Effect.gen(function* () {89 Effect.gen(function* () {
90 let popupOptions: Electron.PopupOptions | undefined;
84 buildFromTemplateMock.mockImplementation(() => ({91 buildFromTemplateMock.mockImplementation(() => ({
85 popup: (options: Electron.PopupOptions) => {92 popup: (options: Electron.PopupOptions) => {
93 popupOptions = options;
86 options.callback?.();94 options.callback?.();
87 },95 },
88 }));96 }));
89 97
90 const electronMenu = yield* ElectronMenu.ElectronMenu;98 const electronMenu = yield* ElectronMenu.ElectronMenu;
91 const selectedItemId = yield* electronMenu.showContextMenu({99 const selectedItemId = yield* electronMenu.showContextMenu({
92 window: {} as Electron.BrowserWindow,100 window: makeWindow(2),
93 items: [{ id: "copy", label: "Copy" }],101 items: [{ id: "copy", label: "Copy" }],
94 position: Option.some({ x: 10.8, y: 20.2 }),102 position: Option.some({ x: 10.8, y: 20.2 }),
95 });103 });
96 104
97 assert.isTrue(Option.isNone(selectedItemId));105 assert.isTrue(Option.isNone(selectedItemId));
106 assert.equal(popupOptions?.x, 21);
107 assert.equal(popupOptions?.y, 40);
98 assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {108 assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
99 label: "Copy",109 label: "Copy",
100 enabled: true,110 enabled: true,
apps/desktop/src/electron/ElectronMenu.ts+13−3
@@ -94,13 +94,20 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM · 93 unmodified lines
94 return normalizedItems;94 return normalizedItems;
95}95}
96 96
97// Renderer positions arrive in CSS pixels; popup() expects window points, so
98// page zoom must be factored in or menus drift proportionally to their
99// distance from the window origin.
97const normalizePosition = (100const normalizePosition = (
98 position: Option.Option<ElectronMenuPosition>,101 position: Option.Option<ElectronMenuPosition>,
102 zoomFactor: number,
99): Option.Option<ElectronMenuPosition> =>103): Option.Option<ElectronMenuPosition> =>
100 Option.filter(104 Option.filter(
101 position,105 position,
102 ({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,106 ({ x, y }) =>
103 ).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));107 Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
108 ).pipe(
109 Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
110 );
104 111
105export const make = Effect.gen(function* () {112export const make = Effect.gen(function* () {
106 const platform = yield* HostProcessPlatform;113 const platform = yield* HostProcessPlatform;
@@ -214,7 +221,10 @@ export const make = Effect.gen(function* () { · 107 unmodified lines
214 221
215 try {222 try {
216 const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));223 const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
217 const popupPosition = normalizePosition(input.position);224 const popupPosition = normalizePosition(
225 input.position,
226 input.window.webContents.getZoomFactor(),
227 );
218 const popupOptions = Option.match(popupPosition, {228 const popupOptions = Option.match(popupPosition, {
219 onNone: (): Electron.PopupOptions => ({229 onNone: (): Electron.PopupOptions => ({
220 window: input.window,230 window: input.window,
apps/desktop/src/electron/ElectronUpdater.test.ts+14−0
@@ -10,6 +10,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({ · 9 unmodified lines
10 autoInstallOnAppQuit: true,10 autoInstallOnAppQuit: true,
11 channel: "latest",11 channel: "latest",
12 disableDifferentialDownload: false,12 disableDifferentialDownload: false,
13 fullChangelog: false,
13 checkForUpdates: vi.fn(() => Promise.resolve(null)),14 checkForUpdates: vi.fn(() => Promise.resolve(null)),
14 downloadUpdate: vi.fn(() => Promise.resolve([])),15 downloadUpdate: vi.fn(() => Promise.resolve([])),
15 on: vi.fn(),16 on: vi.fn(),
@@ -33,6 +34,7 @@ describe("ElectronUpdater", () => { · 17 unmodified lines
33 autoUpdaterMock.autoInstallOnAppQuit = true;34 autoUpdaterMock.autoInstallOnAppQuit = true;
34 autoUpdaterMock.channel = "latest";35 autoUpdaterMock.channel = "latest";
35 autoUpdaterMock.disableDifferentialDownload = false;36 autoUpdaterMock.disableDifferentialDownload = false;
37 autoUpdaterMock.fullChangelog = false;
36 autoUpdaterMock.checkForUpdates.mockClear();38 autoUpdaterMock.checkForUpdates.mockClear();
37 autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));39 autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
38 autoUpdaterMock.downloadUpdate.mockClear();40 autoUpdaterMock.downloadUpdate.mockClear();
@@ -98,6 +100,18 @@ describe("ElectronUpdater", () => { · 59 unmodified lines
98 }).pipe(Effect.provide(ElectronUpdater.layer)),100 }).pipe(Effect.provide(ElectronUpdater.layer)),
99 );101 );
100 102
103 it.effect("sets full changelog mode", () =>
104 Effect.gen(function* () {
105 const updater = yield* ElectronUpdater.ElectronUpdater;
106
107 yield* updater.setFullChangelog(true);
108 assert.equal(autoUpdaterMock.fullChangelog, true);
109
110 yield* updater.setFullChangelog(false);
111 assert.equal(autoUpdaterMock.fullChangelog, false);
112 }).pipe(Effect.provide(ElectronUpdater.layer)),
113 );
114
101 it.effect("preserves quit-and-install flags and the execution-time channel", () =>115 it.effect("preserves quit-and-install flags and the execution-time channel", () =>
102 Effect.gen(function* () {116 Effect.gen(function* () {
103 const cause = new Error("quit and install failed");117 const cause = new Error("quit and install failed");
apps/desktop/src/electron/ElectronUpdater.ts+6−0
@@ -66,6 +66,7 @@ export class ElectronUpdater extends Context.Service< · 65 unmodified lines
66 readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;66 readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
67 readonly allowDowngrade: Effect.Effect<boolean>;67 readonly allowDowngrade: Effect.Effect<boolean>;
68 readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;68 readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
69 readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
69 readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;70 readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
70 readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;71 readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
71 readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;72 readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
@@ -112,6 +113,11 @@ export const make = ElectronUpdater.of({ · 40 unmodified lines
112 autoUpdater.allowDowngrade = value;113 autoUpdater.allowDowngrade = value;
113 return Effect.void;114 return Effect.void;
114 }),115 }),
116 setFullChangelog: (value) =>
117 Effect.suspend(() => {
118 autoUpdater.fullChangelog = value;
119 return Effect.void;
120 }),
115 setDisableDifferentialDownload: (value) =>121 setDisableDifferentialDownload: (value) =>
116 Effect.suspend(() => {122 Effect.suspend(() => {
117 autoUpdater.disableDifferentialDownload = value;123 autoUpdater.disableDifferentialDownload = value;
apps/desktop/src/ipc/DesktopIpcHandlers.ts+2−0
@@ -35,6 +35,7 @@ import { · 34 unmodified lines
35 getAppBranding,35 getAppBranding,
36 getLocalEnvironmentBootstraps,36 getLocalEnvironmentBootstraps,
37 getLocalEnvironmentBearerToken,37 getLocalEnvironmentBearerToken,
38 getWindowFullscreenState,
38 openExternal,39 openExternal,
39 pickFolder,40 pickFolder,
40 setTheme,41 setTheme,
@@ -48,6 +49,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" · 7 unmodified lines
48 yield* PreviewIpc.installPreviewEventForwarding();49 yield* PreviewIpc.installPreviewEventForwarding();
49 50
50 yield* ipc.handleSync(getAppBranding);51 yield* ipc.handleSync(getAppBranding);
52 yield* ipc.handleSync(getWindowFullscreenState);
51 yield* ipc.handleSync(getLocalEnvironmentBootstraps);53 yield* ipc.handleSync(getLocalEnvironmentBootstraps);
52 yield* ipc.handle(getLocalEnvironmentBearerToken);54 yield* ipc.handle(getLocalEnvironmentBearerToken);
53 55
apps/desktop/src/ipc/channels.ts+2−0
@@ -4,6 +4,8 @@ export const SET_THEME_CHANNEL = "desktop:set-theme"; · 3 unmodified lines
4export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";4export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
5export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";5export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
6export const MENU_ACTION_CHANNEL = "desktop:menu-action";6export const MENU_ACTION_CHANNEL = "desktop:menu-action";
7export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
8export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
7export const UPDATE_STATE_CHANNEL = "desktop:update-state";9export const UPDATE_STATE_CHANNEL = "desktop:update-state";
8export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";10export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
9export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";11export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
apps/desktop/src/ipc/methods/window.test.ts+21−1
@@ -1,10 +1,14 @@
1import { assert, describe, it } from "@effect/vitest";1import { assert, describe, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
3import * as Option from "effect/Option";4import * as Option from "effect/Option";
4 5
6import type * as Electron from "electron";
7
5import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";8import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
6import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";9import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
7import { getLocalEnvironmentBootstraps } from "./window.ts";10import * as ElectronWindow from "../../electron/ElectronWindow.ts";
11import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
8 12
9const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {13const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
10 executablePath: "wsl.exe",14 executablePath: "wsl.exe",
@@ -126,3 +130,19 @@ describe("getLocalEnvironmentBootstraps", () => { · 115 unmodified lines
126 }).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));130 }).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
127 });131 });
128});132});
133
134describe("getWindowFullscreenState", () => {
135 it.effect("reads the current native window state", () => {
136 const window = { isFullScreen: () => true } as Electron.BrowserWindow;
137
138 return Effect.gen(function* () {
139 assert.isTrue(yield* getWindowFullscreenState.handler());
140 }).pipe(
141 Effect.provide(
142 Layer.mock(ElectronWindow.ElectronWindow)({
143 currentMainOrFirst: Effect.succeed(Option.some(window)),
144 }),
145 ),
146 );
147 });
148});
apps/desktop/src/ipc/methods/window.ts+10−0
@@ -55,6 +55,16 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ · 54 unmodified lines
55 }),55 }),
56});56});
57 57
58export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
59 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
60 result: Schema.Boolean,
61 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
62 const electronWindow = yield* ElectronWindow.ElectronWindow;
63 const window = yield* electronWindow.currentMainOrFirst;
64 return Option.isSome(window) && window.value.isFullScreen();
65 }),
66});
67
58export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({68export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
59 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,69 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
60 result: Schema.Array(DesktopEnvironmentBootstrapSchema),70 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
apps/desktop/src/preload.ts+13−0
@@ -116,6 +116,19 @@ contextBridge.exposeInMainWorld("desktopBridge", { · 115 unmodified lines
116 ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);116 ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
117 };117 };
118 },118 },
119 getWindowFullscreenState: () =>
120 ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
121 onWindowFullscreenStateChange: (listener) => {
122 const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
123 if (typeof fullscreen !== "boolean") return;
124 listener(fullscreen);
125 };
126
127 ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
128 return () => {
129 ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
130 };
131 },
119 getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),132 getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
120 setUpdateChannel: (channel) =>133 setUpdateChannel: (channel) =>
121 ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),134 ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
apps/desktop/src/preview/BrowserSession.test.ts+51−0
@@ -15,6 +15,7 @@ const { fromPartition, sessions } = vi.hoisted(() => ({ · 14 unmodified lines
15 readonly clearStorageData: ReturnType<typeof vi.fn>;15 readonly clearStorageData: ReturnType<typeof vi.fn>;
16 readonly getUserAgent: ReturnType<typeof vi.fn>;16 readonly getUserAgent: ReturnType<typeof vi.fn>;
17 readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;17 readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
18 readonly setPermissionCheckHandler: ReturnType<typeof vi.fn>;
18 readonly setUserAgent: ReturnType<typeof vi.fn>;19 readonly setUserAgent: ReturnType<typeof vi.fn>;
19 }20 }
20 >(),21 >(),
@@ -40,6 +41,7 @@ describe("BrowserSession", () => { · 19 unmodified lines
40 clearStorageData: vi.fn(() => Promise.resolve()),41 clearStorageData: vi.fn(() => Promise.resolve()),
41 getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),42 getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
42 setPermissionRequestHandler: vi.fn(),43 setPermissionRequestHandler: vi.fn(),
44 setPermissionCheckHandler: vi.fn(),
43 setUserAgent: vi.fn(),45 setUserAgent: vi.fn(),
44 };46 };
45 sessions.set(partition, browserSession);47 sessions.set(partition, browserSession);
@@ -61,6 +63,55 @@ describe("BrowserSession", () => { · 15 unmodified lines
61 }).pipe(Effect.provide(layer)),63 }).pipe(Effect.provide(layer)),
62 );64 );
63 65
66 it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
67 Effect.gen(function* () {
68 const browserSessions = yield* BrowserSession.BrowserSession;
69 const partition = yield* browserSessions.getPartition("scope-a");
70 yield* browserSessions.getSession("scope-a");
71
72 const browserSession = sessions.get(partition);
73 assert.isDefined(browserSession);
74
75 const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
76 const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
77 assert.isFunction(requestHandler);
78 assert.isFunction(checkHandler);
79
80 const requestAllows = (permission: string): boolean => {
81 let granted: boolean | undefined;
82 requestHandler(null, permission, (value: boolean) => {
83 granted = value;
84 });
85 assert.isDefined(granted);
86 return granted;
87 };
88
89 for (const permission of [
90 "clipboard-read",
91 "clipboard-sanitized-write",
92 "notifications",
93 "geolocation",
94 ]) {
95 assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
96 assert.isTrue(
97 checkHandler(null, permission) as boolean,
98 `check handler should allow ${permission}`,
99 );
100 }
101
102 // `clipboard-write` is not a real Electron permission — the async write API
103 // uses `clipboard-sanitized-write` — so the stale name must not be granted,
104 // and unrelated permissions stay denied.
105 for (const permission of ["clipboard-write", "midi"]) {
106 assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
107 assert.isFalse(
108 checkHandler(null, permission) as boolean,
109 `check handler should deny ${permission}`,
110 );
111 }
112 }).pipe(Effect.provide(layer)),
113 );
114
64 it.effect("preserves partition scope and the platform failure chain", () => {115 it.effect("preserves partition scope and the platform failure chain", () => {
65 const nativeCause = new Error("native digest failed");116 const nativeCause = new Error("native digest failed");
66 const platformCause = PlatformError.systemError({117 const platformCause = PlatformError.systemError({
apps/desktop/src/preview/BrowserSession.ts+18−2
@@ -11,6 +11,20 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; · 10 unmodified lines
11 11
12const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";12const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
13 13
14// Permissions granted to preview web content. `clipboard-sanitized-write` is the
15// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
16// `clipboard-write`, which is not a valid Electron permission name. Async
17// clipboard writes are gated by the permission *check* handler (not only the
18// request handler), so both handlers must allow it; otherwise built-in "Copy"
19// buttons — e.g. the Next.js / Vercel error overlay — fail with
20// `Failed to execute 'writeText' on 'Clipboard': Write permission denied`.
21const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
22 "clipboard-read",
23 "clipboard-sanitized-write",
24 "notifications",
25 "geolocation",
26]);
27
14export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(28export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
15 "BrowserSessionPartitionDerivationError",29 "BrowserSessionPartitionDerivationError",
16 {30 {
@@ -120,9 +134,11 @@ export const make = Effect.gen(function* BrowserSessionMake() { · 103 unmodified lines
120 .replace(/\s*t3code\/[\d.]+/, "");134 .replace(/\s*t3code\/[\d.]+/, "");
121 browserSession.setUserAgent(userAgent);135 browserSession.setUserAgent(userAgent);
122 browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {136 browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
123 const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];137 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
124 callback(allowed.includes(permission));
125 });138 });
139 browserSession.setPermissionCheckHandler((_webContents, permission) =>
140 ALLOWED_PREVIEW_PERMISSIONS.has(permission),
141 );
126 const next = new Map(sessions);142 const next = new Map(sessions);
127 next.set(partition, browserSession);143 next.set(partition, browserSession);
128 return [browserSession, next] as const;144 return [browserSession, next] as const;
apps/desktop/src/settings/DesktopAppSettings.test.ts+45−0
@@ -11,6 +11,17 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; · 10 unmodified lines
11import * as DesktopAppSettings from "./DesktopAppSettings.ts";11import * as DesktopAppSettings from "./DesktopAppSettings.ts";
12 12
13const DesktopSettingsPatch = Schema.Struct({13const DesktopSettingsPatch = Schema.Struct({
14 mainWindowBounds: Schema.optionalKey(
15 Schema.NullOr(
16 Schema.Struct({
17 x: Schema.Number,
18 y: Schema.Number,
19 width: Schema.Number,
20 height: Schema.Number,
21 }),
22 ),
23 ),
24 mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
14 serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])),25 serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])),
15 tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),26 tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
16 tailscaleServePort: Schema.optionalKey(Schema.Number),27 tailscaleServePort: Schema.optionalKey(Schema.Number),
@@ -91,6 +102,8 @@ describe("DesktopSettings", () => { · 74 unmodified lines
91 assert.deepEqual(102 assert.deepEqual(
92 DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),103 DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
93 {104 {
105 mainWindowBounds: null,
106 mainWindowMaximized: false,
94 serverExposureMode: "local-only",107 serverExposureMode: "local-only",
95 tailscaleServeEnabled: false,108 tailscaleServeEnabled: false,
96 tailscaleServePort: 443,109 tailscaleServePort: 443,
@@ -116,6 +129,8 @@ describe("DesktopSettings", () => { · 19 unmodified lines
116 });129 });
117 130
118 assert.deepEqual(yield* settings.load, {131 assert.deepEqual(yield* settings.load, {
132 mainWindowBounds: null,
133 mainWindowMaximized: false,
119 serverExposureMode: "network-accessible",134 serverExposureMode: "network-accessible",
120 tailscaleServeEnabled: true,135 tailscaleServeEnabled: true,
121 tailscaleServePort: 8443,136 tailscaleServePort: 8443,
@@ -215,10 +230,13 @@ describe("DesktopSettings", () => { · 93 unmodified lines
215 "serverExposureMode": "network-accessible",230 "serverExposureMode": "network-accessible",
216 "tailscaleServeEnabled": true,231 "tailscaleServeEnabled": true,
217 "tailscaleServePort": 8443,232 "tailscaleServePort": 8443,
233 "mainWindowBounds": { "x": 120, "y": 80, "width": 1280, "height": 900 },
218 }\n`,234 }\n`,
219 );235 );
220 236
221 assert.deepEqual(yield* settings.load, {237 assert.deepEqual(yield* settings.load, {
238 mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
239 mainWindowMaximized: false,
222 serverExposureMode: "network-accessible",240 serverExposureMode: "network-accessible",
223 tailscaleServeEnabled: true,241 tailscaleServeEnabled: true,
224 tailscaleServePort: 8443,242 tailscaleServePort: 8443,
@@ -232,6 +250,24 @@ describe("DesktopSettings", () => { · 7 unmodified lines
232 ),250 ),
233 );251 );
234 252
253 it.effect("rejects window bounds that do not satisfy the domain schema", () =>
254 withSettings(
255 Effect.gen(function* () {
256 const settings = yield* DesktopAppSettings.DesktopAppSettings;
257 yield* writeSettingsPatch({
258 mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 },
259 mainWindowMaximized: true,
260 serverExposureMode: "network-accessible",
261 });
262
263 const loaded = yield* settings.load;
264 assert.isNull(loaded.mainWindowBounds);
265 assert.isFalse(loaded.mainWindowMaximized);
266 assert.equal(loaded.serverExposureMode, "network-accessible");
267 }),
268 ),
269 );
270
235 it.effect("persists sparse desktop settings documents", () =>271 it.effect("persists sparse desktop settings documents", () =>
236 withSettings(272 withSettings(
237 Effect.gen(function* () {273 Effect.gen(function* () {
@@ -239,12 +275,15 @@ describe("DesktopSettings", () => { · 1 unmodified line
239 const fileSystem = yield* FileSystem.FileSystem;275 const fileSystem = yield* FileSystem.FileSystem;
240 const settings = yield* DesktopAppSettings.DesktopAppSettings;276 const settings = yield* DesktopAppSettings.DesktopAppSettings;
241 277
278 yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true);
242 yield* settings.setServerExposureMode("network-accessible");279 yield* settings.setServerExposureMode("network-accessible");
243 280
244 const persisted = yield* decodeDesktopSettingsPatch(281 const persisted = yield* decodeDesktopSettingsPatch(
245 yield* fileSystem.readFileString(environment.desktopSettingsPath),282 yield* fileSystem.readFileString(environment.desktopSettingsPath),
246 );283 );
247 assert.deepEqual(persisted, {284 assert.deepEqual(persisted, {
285 mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 },
286 mainWindowMaximized: true,
248 serverExposureMode: "network-accessible",287 serverExposureMode: "network-accessible",
249 } satisfies typeof DesktopSettingsPatch.Type);288 } satisfies typeof DesktopSettingsPatch.Type);
250 }),289 }),
@@ -261,6 +300,8 @@ describe("DesktopSettings", () => { · 10 unmodified lines
261 });300 });
262 301
263 assert.deepEqual(yield* settings.load, {302 assert.deepEqual(yield* settings.load, {
303 mainWindowBounds: null,
304 mainWindowMaximized: false,
264 serverExposureMode: "local-only",305 serverExposureMode: "local-only",
265 tailscaleServeEnabled: false,306 tailscaleServeEnabled: false,
266 tailscaleServePort: 443,307 tailscaleServePort: 443,
@@ -286,6 +327,8 @@ describe("DesktopSettings", () => { · 19 unmodified lines
286 });327 });
287 328
288 assert.deepEqual(yield* settings.load, {329 assert.deepEqual(yield* settings.load, {
330 mainWindowBounds: null,
331 mainWindowMaximized: false,
289 serverExposureMode: "local-only",332 serverExposureMode: "local-only",
290 tailscaleServeEnabled: false,333 tailscaleServeEnabled: false,
291 tailscaleServePort: 443,334 tailscaleServePort: 443,
@@ -310,6 +353,8 @@ describe("DesktopSettings", () => { · 18 unmodified lines
310 });353 });
311 354
312 assert.deepEqual(yield* settings.load, {355 assert.deepEqual(yield* settings.load, {
356 mainWindowBounds: null,
357 mainWindowMaximized: false,
313 serverExposureMode: "local-only",358 serverExposureMode: "local-only",
314 tailscaleServeEnabled: true,359 tailscaleServeEnabled: true,
315 tailscaleServePort: 443,360 tailscaleServePort: 443,
apps/desktop/src/settings/DesktopAppSettings.ts+77−0
@@ -20,6 +20,8 @@ import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts · 19 unmodified lines
20import { isValidDistroName } from "../wsl/wslPathParsing.ts";20import { isValidDistroName } from "../wsl/wslPathParsing.ts";
21 21
22export interface DesktopSettings {22export interface DesktopSettings {
23 readonly mainWindowBounds: DesktopWindowBounds | null;
24 readonly mainWindowMaximized: boolean;
23 readonly serverExposureMode: DesktopServerExposureMode;25 readonly serverExposureMode: DesktopServerExposureMode;
24 readonly tailscaleServeEnabled: boolean;26 readonly tailscaleServeEnabled: boolean;
25 readonly tailscaleServePort: number;27 readonly tailscaleServePort: number;
@@ -48,8 +50,25 @@ export interface DesktopSettingsChange { · 22 unmodified lines
48}50}
49 51
50export const DEFAULT_TAILSCALE_SERVE_PORT = 443;52export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
53const MIN_MAIN_WINDOW_SIZE = {
54 width: 840,
55 height: 620,
56} as const;
57export const DesktopWindowBoundsSchema = Schema.Struct({
58 x: Schema.Int,
59 y: Schema.Int,
60 width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.width)),
61 height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.height)),
62});
63export type DesktopWindowBounds = typeof DesktopWindowBoundsSchema.Type;
64export const DEFAULT_MAIN_WINDOW_SIZE = {
65 width: 1100,
66 height: 780,
67} as const;
51 68
52export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {69export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
70 mainWindowBounds: null,
71 mainWindowMaximized: false,
53 serverExposureMode: "local-only",72 serverExposureMode: "local-only",
54 tailscaleServeEnabled: false,73 tailscaleServeEnabled: false,
55 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,74 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
@@ -60,7 +79,16 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { · 4 unmodified lines
60 wslOnly: false,79 wslOnly: false,
61};80};
62 81
82const DesktopWindowBoundsDocument = Schema.Struct({
83 x: Schema.Number,
84 y: Schema.Number,
85 width: Schema.Number,
86 height: Schema.Number,
87});
88
63const DesktopSettingsDocument = Schema.Struct({89const DesktopSettingsDocument = Schema.Struct({
90 mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
91 mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
64 serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),92 serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
65 tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),93 tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
66 tailscaleServePort: Schema.optionalKey(Schema.Number),94 tailscaleServePort: Schema.optionalKey(Schema.Number),
@@ -81,6 +109,8 @@ type Mutable<T> = { -readonly [K in keyof T]: T[K] }; · 14 unmodified lines
81const DesktopSettingsJson = fromLenientJson(DesktopSettingsDocument);109const DesktopSettingsJson = fromLenientJson(DesktopSettingsDocument);
82const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson);110const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson);
83const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson);111const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson);
112const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema);
113const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema);
84 114
85const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({115const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({
86 settings,116 settings,
@@ -114,6 +144,10 @@ export class DesktopAppSettings extends Context.Service< · 27 unmodified lines
114 {144 {
115 readonly load: Effect.Effect<DesktopSettings>;145 readonly load: Effect.Effect<DesktopSettings>;
116 readonly get: Effect.Effect<DesktopSettings>;146 readonly get: Effect.Effect<DesktopSettings>;
147 readonly setMainWindowBounds: (
148 bounds: DesktopWindowBounds,
149 isMaximized: boolean,
150 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
117 readonly setServerExposureMode: (151 readonly setServerExposureMode: (
118 mode: DesktopServerExposureMode,152 mode: DesktopServerExposureMode,
119 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;153 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
@@ -158,11 +192,16 @@ function normalizeWslDistro(value: unknown): string | null { · 38 unmodified lines
158 return typeof value === "string" && isValidDistroName(value) ? value : null;192 return typeof value === "string" && isValidDistroName(value) ? value : null;
159}193}
160 194
195export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | null {
196 return Option.getOrNull(decodeDesktopWindowBounds(value));
197}
198
161function normalizeDesktopSettingsDocument(199function normalizeDesktopSettingsDocument(
162 parsed: DesktopSettingsDocument,200 parsed: DesktopSettingsDocument,
163 appVersion: string,201 appVersion: string,
164): DesktopSettings {202): DesktopSettings {
165 const defaultSettings = resolveDefaultDesktopSettings(appVersion);203 const defaultSettings = resolveDefaultDesktopSettings(appVersion);
204 const mainWindowBounds = normalizeMainWindowBounds(parsed.mainWindowBounds);
166 const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);205 const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);
167 const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;206 const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
168 const updateChannelConfiguredByUser =207 const updateChannelConfiguredByUser =
@@ -177,6 +216,8 @@ function normalizeDesktopSettingsDocument( · 8 unmodified lines
177 (parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");216 (parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
178 217
179 return {218 return {
219 mainWindowBounds,
220 mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
180 serverExposureMode:221 serverExposureMode:
181 parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",222 parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
182 tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,223 tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
@@ -197,6 +238,12 @@ function toDesktopSettingsDocument( · 14 unmodified lines
197): DesktopSettingsDocument {238): DesktopSettingsDocument {
198 const document: Mutable<DesktopSettingsDocument> = {};239 const document: Mutable<DesktopSettingsDocument> = {};
199 240
241 if (settings.mainWindowBounds !== null) {
242 document.mainWindowBounds = settings.mainWindowBounds;
243 }
244 if (settings.mainWindowMaximized) {
245 document.mainWindowMaximized = true;
246 }
200 if (settings.serverExposureMode !== defaults.serverExposureMode) {247 if (settings.serverExposureMode !== defaults.serverExposureMode) {
201 document.serverExposureMode = settings.serverExposureMode;248 document.serverExposureMode = settings.serverExposureMode;
202 }249 }
@@ -237,6 +284,22 @@ function setServerExposureMode( · 34 unmodified lines
237 };284 };
238}285}
239 286
287function setMainWindowBounds(
288 settings: DesktopSettings,
289 bounds: DesktopWindowBounds,
290 isMaximized: boolean,
291): DesktopSettings {
292 return settings.mainWindowBounds !== null &&
293 desktopWindowBoundsEquivalence(settings.mainWindowBounds, bounds) &&
294 settings.mainWindowMaximized === isMaximized
295 ? settings
296 : {
297 ...settings,
298 mainWindowBounds: bounds,
299 mainWindowMaximized: isMaximized,
300 };
301}
302
240function setTailscaleServe(303function setTailscaleServe(
241 settings: DesktopSettings,304 settings: DesktopSettings,
242 input: { readonly enabled: boolean; readonly port: Option.Option<number> },305 input: { readonly enabled: boolean; readonly port: Option.Option<number> },
@@ -431,6 +494,18 @@ export const make = Effect.gen(function* () { · 188 unmodified lines
431 );494 );
432 return yield* SynchronizedRef.setAndGet(settingsRef, settings);495 return yield* SynchronizedRef.setAndGet(settingsRef, settings);
433 }).pipe(Effect.withSpan("desktop.settings.load")),496 }).pipe(Effect.withSpan("desktop.settings.load")),
497 setMainWindowBounds: (bounds, isMaximized) =>
498 persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)).pipe(
499 Effect.withSpan("desktop.settings.setMainWindowBounds", {
500 attributes: {
501 x: bounds.x,
502 y: bounds.y,
503 width: bounds.width,
504 height: bounds.height,
505 isMaximized,
506 },
507 }),
508 ),
434 setServerExposureMode: (mode) =>509 setServerExposureMode: (mode) =>
435 persist((settings) => setServerExposureMode(settings, mode)).pipe(510 persist((settings) => setServerExposureMode(settings, mode)).pipe(
436 Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),511 Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
@@ -488,6 +563,8 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET · 51 unmodified lines
488 return DesktopAppSettings.of({563 return DesktopAppSettings.of({
489 get: SynchronizedRef.get(settingsRef),564 get: SynchronizedRef.get(settingsRef),
490 load: SynchronizedRef.get(settingsRef),565 load: SynchronizedRef.get(settingsRef),
566 setMainWindowBounds: (bounds, isMaximized) =>
567 update((settings) => setMainWindowBounds(settings, bounds, isMaximized)),
491 setServerExposureMode: (mode) =>568 setServerExposureMode: (mode) =>
492 update((settings) => setServerExposureMode(settings, mode)),569 update((settings) => setServerExposureMode(settings, mode)),
493 setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),570 setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
apps/desktop/src/updates/DesktopUpdates.test.ts+50−0
@@ -38,6 +38,7 @@ const flushCallbacks = Effect.yieldNow; · 37 unmodified lines
38function makeHarness(options: UpdatesHarnessOptions = {}) {38function makeHarness(options: UpdatesHarnessOptions = {}) {
39 let checkCount = 0;39 let checkCount = 0;
40 let allowDowngrade = false;40 let allowDowngrade = false;
41 let fullChangelog = false;
41 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];42 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
42 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();43 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
43 const sentStates: DesktopUpdateState[] = [];44 const sentStates: DesktopUpdateState[] = [];
@@ -73,6 +74,10 @@ function makeHarness(options: UpdatesHarnessOptions = {}) { · 29 unmodified lines
73 Effect.sync(() => {74 Effect.sync(() => {
74 allowDowngrade = value;75 allowDowngrade = value;
75 }),76 }),
77 setFullChangelog: (value) =>
78 Effect.sync(() => {
79 fullChangelog = value;
80 }),
76 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,81 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
77 checkForUpdates: Effect.sync(() => {82 checkForUpdates: Effect.sync(() => {
78 checkCount += 1;83 checkCount += 1;
@@ -153,6 +158,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) { · 74 unmodified lines
153 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {158 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
154 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),159 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
155 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),160 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
161 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
156 setServerExposureMode: () => Effect.die("unexpected server exposure update"),162 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
157 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),163 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
158 setUpdateChannel: () => Effect.fail(setUpdateChannelError),164 setUpdateChannel: () => Effect.fail(setUpdateChannelError),
@@ -186,6 +192,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) { · 27 unmodified lines
186 layer,192 layer,
187 checkCount: () => checkCount,193 checkCount: () => checkCount,
188 feedUrls: () => feedUrls,194 feedUrls: () => feedUrls,
195 fullChangelog: () => fullChangelog,
189 listenerCount: () =>196 listenerCount: () =>
190 Array.from(listeners.values()).reduce(197 Array.from(listeners.values()).reduce(
191 (total, eventListeners) => total + eventListeners.size,198 (total, eventListeners) => total + eventListeners.size,
@@ -287,6 +294,49 @@ describe("DesktopUpdates", () => { · 95 unmodified lines
287 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));294 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
288 });295 });
289 296
297 it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
298 const harness = makeHarness();
299
300 return Effect.scoped(
301 Effect.gen(function* () {
302 const updates = yield* DesktopUpdates.DesktopUpdates;
303 yield* updates.configure;
304
305 yield* updates.setChannel("nightly");
306 assert.equal(harness.fullChangelog(), true);
307
308 harness.emit("update-available", {
309 version: "1.2.4-nightly.20260709.766",
310 releaseNotes: [
311 {
312 version: "1.2.4-nightly.20260709.766",
313 note: `<h2>What's Changed</h2><ul><li>feat(client): persist offline environment data by <a>@juliusmarminge</a> in <a>#3795</a></li></ul><h2>Full Changelog</h2>`,
314 },
315 {
316 version: "1.2.4-nightly.20260709.765",
317 note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
318 },
319 ],
320 });
321 yield* flushCallbacks;
322
323 const state = yield* updates.getState;
324 assert.equal(state.status, "available");
325 assert.deepEqual(state.releaseNotes, [
326 {
327 version: "1.2.4-nightly.20260709.766",
328 items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
329 },
330 {
331 version: "1.2.4-nightly.20260709.765",
332 items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
333 },
334 ]);
335 assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
336 }),
337 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
338 });
339
290 it.effect("keeps raw updater event failures out of update state", () => {340 it.effect("keeps raw updater event failures out of update state", () => {
291 const harness = makeHarness();341 const harness = makeHarness();
292 const cause = new Error(342 const cause = new Error(
apps/desktop/src/updates/DesktopUpdates.ts+13−2
@@ -27,6 +27,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts"; · 26 unmodified lines
27import * as ElectronWindow from "../electron/ElectronWindow.ts";27import * as ElectronWindow from "../electron/ElectronWindow.ts";
28import * as IpcChannels from "../ipc/channels.ts";28import * as IpcChannels from "../ipc/channels.ts";
29import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";29import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
30import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
30import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";31import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
31import {32import {
32 createInitialDesktopUpdateState,33 createInitialDesktopUpdateState,
@@ -49,6 +50,10 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type; · 16 unmodified lines
49 50
50const UpdateInfo = Schema.Struct({51const UpdateInfo = Schema.Struct({
51 version: Schema.String,52 version: Schema.String,
53 // Left unvalidated on purpose: a malformed release-notes payload must never
54 // fail the decode and block the update state transition. The shape is
55 // validated defensively in normalizeDesktopUpdateReleaseNotes.
56 releaseNotes: Schema.optional(Schema.Unknown),
52});57});
53 58
54const DownloadProgressInfo = Schema.Struct({59const DownloadProgressInfo = Schema.Struct({
@@ -330,10 +335,12 @@ export const make = Effect.gen(function* () { · 275 unmodified lines
330 yield* electronUpdater.setChannel(channel);335 yield* electronUpdater.setChannel(channel);
331 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);336 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
332 yield* electronUpdater.setAllowDowngrade(allowsPrerelease);337 yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
338 yield* electronUpdater.setFullChangelog(allowsPrerelease);
333 yield* logUpdaterInfo("using update channel", {339 yield* logUpdaterInfo("using update channel", {
334 channel,340 channel,
335 allowPrerelease: allowsPrerelease,341 allowPrerelease: allowsPrerelease,
336 allowDowngrade: allowsPrerelease,342 allowDowngrade: allowsPrerelease,
343 fullChangelog: allowsPrerelease,
337 });344 });
338 });345 });
339 346
@@ -567,11 +574,15 @@ export const make = Effect.gen(function* () { · 227 unmodified lines
567 }574 }
568 575
569 const checkedAt = yield* currentIsoTimestamp;576 const checkedAt = yield* currentIsoTimestamp;
577 const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
570 yield* setState(578 yield* setState(
571 reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),579 reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
572 );580 );
573 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);581 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
574 yield* logUpdaterInfo("update available", { version: info.version });582 yield* logUpdaterInfo("update available", {
583 version: info.version,
584 releaseNoteGroups: releaseNotes.length,
585 });
575 }),586 }),
576 ),587 ),
577 Effect.catchCause((cause) => {588 Effect.catchCause((cause) => {
apps/desktop/src/updates/releaseNotes.test.ts+67−0
@@ -0,0 +1,67 @@
1import { describe, expect, it } from "vite-plus/test";
2
3import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
4
5describe("normalizeDesktopUpdateReleaseNotes", () => {
6 it("splits a plain string note into items under the fallback version", () => {
7 const notes = normalizeDesktopUpdateReleaseNotes(
8 "## What's changed\n- First fix\n- Second fix",
9 "1.2.3",
10 );
11 expect(notes).toEqual([{ version: "1.2.3", items: ["First fix", "Second fix"] }]);
12 });
13
14 it("keeps per-version groups and drops empty ones", () => {
15 const notes = normalizeDesktopUpdateReleaseNotes(
16 [
17 { version: "1.2.3", note: "- Newer change" },
18 { version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" },
19 { version: "1.2.1", note: "- Older change" },
20 ],
21 "1.2.3",
22 );
23 expect(notes).toEqual([
24 { version: "1.2.3", items: ["Newer change"] },
25 { version: "1.2.1", items: ["Older change"] },
26 ]);
27 });
28
29 it("decodes valid HTML entities", () => {
30 const notes = normalizeDesktopUpdateReleaseNotes("- Fix &amp; polish &#128512;", "1.0.0");
31 expect(notes).toEqual([{ version: "1.0.0", items: ["Fix & polish 😀"] }]);
32 });
33
34 it("ignores malformed entries instead of throwing", () => {
35 const notes = normalizeDesktopUpdateReleaseNotes(
36 [
37 { version: "1.2.3", note: "- Valid change" },
38 { version: 42, note: "- Bad version type" },
39 { version: "1.2.1", note: { html: "<p>object note</p>" } },
40 "not an object",
41 null,
42 ],
43 "1.2.3",
44 );
45 expect(notes).toEqual([{ version: "1.2.3", items: ["Valid change"] }]);
46 });
47
48 it("returns non-empty groups even when preceded by many boilerplate-only groups", () => {
49 const boilerplate = Array.from({ length: 7 }, (_, index) => ({
50 version: `1.3.${9 - index}`,
51 note: "Full changelog: https://example.com/compare/x...y",
52 }));
53 const notes = normalizeDesktopUpdateReleaseNotes(
54 [...boilerplate, { version: "1.3.2", note: "- Older but real change" }],
55 "1.3.9",
56 );
57 expect(notes).toEqual([{ version: "1.3.2", items: ["Older but real change"] }]);
58 });
59
60 it("does not throw on out-of-range numeric entities and keeps the literal", () => {
61 expect(() =>
62 normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0"),
63 ).not.toThrow();
64 const notes = normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0");
65 expect(notes).toEqual([{ version: "1.0.0", items: ["Broken entity &#9999999999;"] }]);
66 });
67});
apps/desktop/src/updates/releaseNotes.ts+125−0
@@ -0,0 +1,125 @@
1import type { DesktopUpdateReleaseNote } from "@t3tools/contracts";
2
3interface ElectronReleaseNoteInfo {
4 readonly version: string;
5 readonly note: string | null | undefined;
6}
7
8function isElectronReleaseNoteInfo(value: unknown): value is ElectronReleaseNoteInfo {
9 if (typeof value !== "object" || value === null) return false;
10 const candidate = value as { readonly version?: unknown; readonly note?: unknown };
11 return (
12 typeof candidate.version === "string" &&
13 (typeof candidate.note === "string" || candidate.note === null || candidate.note === undefined)
14 );
15}
16
17const MAX_RELEASE_NOTE_GROUPS = 6;
18const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
19const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
20
21const HTML_ENTITY_REPLACEMENTS: Readonly<Record<string, string>> = {
22 amp: "&",
23 apos: "'",
24 gt: ">",
25 lt: "<",
26 nbsp: " ",
27 quot: '"',
28};
29
30function decodeCodePoint(codePoint: number, entity: string): string {
31 // String.fromCodePoint throws RangeError outside the valid Unicode range, and
32 // Number.isFinite alone lets oversized values (e.g. &#9999999999;) through.
33 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
34 return `&${entity};`;
35 }
36 return String.fromCodePoint(codePoint);
37}
38
39function decodeHtmlEntity(entity: string): string {
40 const named = HTML_ENTITY_REPLACEMENTS[entity];
41 if (named) return named;
42 if (entity.startsWith("#x")) {
43 return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
44 }
45 if (entity.startsWith("#")) {
46 return decodeCodePoint(Number.parseInt(entity.slice(1), 10), entity);
47 }
48 return `&${entity};`;
49}
50
51function decodeHtmlEntities(input: string): string {
52 return input.replace(/&([a-zA-Z]+|#\d+|#x[0-9a-fA-F]+);/g, (_, entity: string) =>
53 decodeHtmlEntity(entity),
54 );
55}
56
57function stripMarkup(input: string): string {
58 return decodeHtmlEntities(
59 input
60 .replace(/<br\s*\/?>/gi, "\n")
61 .replace(/<li\b[^>]*>/gi, "\n- ")
62 .replace(/<\/(?:p|div|li|h[1-6]|ul|ol|blockquote)>/gi, "\n")
63 .replace(/<[^>]*>/g, "")
64 .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
65 .replace(/\*\*([^*]+)\*\*/g, "$1"),
66 );
67}
68
69function truncateReleaseNoteItem(item: string): string {
70 if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item;
71 return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`;
72}
73
74function isIgnoredReleaseNoteLine(line: string): boolean {
75 const normalized = line
76 .toLowerCase()
77 .replace(/[*_`#]/g, "")
78 .trim();
79 return (
80 normalized === "" ||
81 normalized === "what's changed" ||
82 normalized === "whats changed" ||
83 normalized === "full changelog" ||
84 normalized === "new contributors" ||
85 normalized.startsWith("compare: ") ||
86 normalized.includes("/compare/")
87 );
88}
89
90function extractReleaseNoteItems(note: string | null | undefined): ReadonlyArray<string> {
91 if (!note) return [];
92
93 const items: string[] = [];
94 for (const rawLine of stripMarkup(note).split("\n")) {
95 const item = rawLine
96 .trim()
97 .replace(/^[-*]\s+/, "")
98 .replace(/^\d+[.)]\s+/, "")
99 .replace(/\s+/g, " ");
100 if (isIgnoredReleaseNoteLine(item)) continue;
101 items.push(truncateReleaseNoteItem(item));
102 if (items.length >= MAX_RELEASE_NOTE_ITEMS_PER_GROUP) break;
103 }
104 return items;
105}
106
107export function normalizeDesktopUpdateReleaseNotes(
108 releaseNotes: unknown,
109 fallbackVersion: string,
110): ReadonlyArray<DesktopUpdateReleaseNote> {
111 const rawNotes =
112 typeof releaseNotes === "string"
113 ? [{ version: fallbackVersion, note: releaseNotes }]
114 : Array.isArray(releaseNotes)
115 ? releaseNotes.filter(isElectronReleaseNoteInfo)
116 : [];
117
118 return rawNotes
119 .map((entry) => ({
120 version: entry.version,
121 items: extractReleaseNoteItems(entry.note),
122 }))
123 .filter((entry) => entry.items.length > 0)
124 .slice(0, MAX_RELEASE_NOTE_GROUPS);
125}
apps/desktop/src/updates/updateMachine.test.ts+24−0
@@ -118,6 +118,12 @@ describe("updateMachine", () => { · 117 unmodified lines
118 });118 });
119 119
120 it("tracks available, download start, and progress cleanly", () => {120 it("tracks available, download start, and progress cleanly", () => {
121 const releaseNotes = [
122 {
123 version: "1.1.0",
124 items: ["feat: add update release notes"],
125 },
126 ];
121 const available = reduceDesktopUpdateStateOnUpdateAvailable(127 const available = reduceDesktopUpdateStateOnUpdateAvailable(
122 {128 {
123 ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),129 ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
@@ -126,15 +132,33 @@ describe("updateMachine", () => { · 2 unmodified lines
126 },132 },
127 "1.1.0",133 "1.1.0",
128 "2026-03-04T00:00:00.000Z",134 "2026-03-04T00:00:00.000Z",
135 releaseNotes,
129 );136 );
130 const downloading = reduceDesktopUpdateStateOnDownloadStart(available);137 const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
131 const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);138 const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
132 139
133 expect(available.status).toBe("available");140 expect(available.status).toBe("available");
134 expect(available.channel).toBe("latest");141 expect(available.channel).toBe("latest");
142 expect(available.releaseNotes).toBe(releaseNotes);
143 expect(downloading.releaseNotes).toBe(releaseNotes);
135 expect(downloading.status).toBe("downloading");144 expect(downloading.status).toBe("downloading");
136 expect(downloading.downloadPercent).toBe(0);145 expect(downloading.downloadPercent).toBe(0);
137 expect(progress.downloadPercent).toBe(55.5);146 expect(progress.downloadPercent).toBe(55.5);
138 expect(progress.errorContext).toBeNull();147 expect(progress.errorContext).toBeNull();
139 });148 });
149
150 it("clears release notes when checking again", () => {
151 const state = reduceDesktopUpdateStateOnCheckStart(
152 {
153 ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"),
154 enabled: true,
155 status: "available",
156 availableVersion: "1.1.0-nightly.1",
157 releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"] }],
158 },
159 "2026-03-04T00:00:00.000Z",
160 );
161
162 expect(state.releaseNotes).toEqual([]);
163 });
140});164});
apps/desktop/src/updates/updateMachine.ts+6−0
@@ -1,6 +1,7 @@
1import type {1import type {
2 DesktopRuntimeInfo,2 DesktopRuntimeInfo,
3 DesktopUpdateChannel,3 DesktopUpdateChannel,
4 DesktopUpdateReleaseNote,
4 DesktopUpdateState,5 DesktopUpdateState,
5} from "@t3tools/contracts";6} from "@t3tools/contracts";
6 7
@@ -29,6 +30,7 @@ export function createInitialDesktopUpdateState( · 22 unmodified lines
29 runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,30 runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
30 availableVersion: null,31 availableVersion: null,
31 downloadedVersion: null,32 downloadedVersion: null,
33 releaseNotes: [],
32 downloadPercent: null,34 downloadPercent: null,
33 checkedAt: null,35 checkedAt: null,
34 message: null,36 message: null,
@@ -45,6 +47,7 @@ export function reduceDesktopUpdateStateOnCheckStart( · 10 unmodified lines
45 ...state,47 ...state,
46 status: "checking",48 status: "checking",
47 checkedAt,49 checkedAt,
50 releaseNotes: [],
48 message: null,51 message: null,
49 downloadPercent: null,52 downloadPercent: null,
50 errorContext: null,53 errorContext: null,
@@ -72,12 +75,14 @@ export function reduceDesktopUpdateStateOnUpdateAvailable( · 21 unmodified lines
72 state: DesktopUpdateState,75 state: DesktopUpdateState,
73 version: string,76 version: string,
74 checkedAt: string,77 checkedAt: string,
78 releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
75): DesktopUpdateState {79): DesktopUpdateState {
76 return {80 return {
77 ...state,81 ...state,
78 status: "available",82 status: "available",
79 availableVersion: version,83 availableVersion: version,
80 downloadedVersion: null,84 downloadedVersion: null,
85 releaseNotes,
81 downloadPercent: null,86 downloadPercent: null,
82 checkedAt,87 checkedAt,
83 message: null,88 message: null,
@@ -95,6 +100,7 @@ export function reduceDesktopUpdateStateOnNoUpdate( · 11 unmodified lines
95 status: "up-to-date",100 status: "up-to-date",
96 availableVersion: null,101 availableVersion: null,
97 downloadedVersion: null,102 downloadedVersion: null,
103 releaseNotes: [],
98 downloadPercent: null,104 downloadPercent: null,
99 checkedAt,105 checkedAt,
100 message: null,106 message: null,
apps/desktop/src/window/DesktopApplicationMenu.test.ts+1−0
@@ -76,6 +76,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) => · 75 unmodified lines
76 showConnectingSplash: Effect.void,76 showConnectingSplash: Effect.void,
77 handleBackendReady: () => Effect.void,77 handleBackendReady: () => Effect.void,
78 handleBackendNotReady: Effect.void,78 handleBackendNotReady: Effect.void,
79 flushMainWindowBounds: Effect.void,
79 dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),80 dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
80 syncAppearance: Effect.void,81 syncAppearance: Effect.void,
81 } satisfies DesktopWindow.DesktopWindow["Service"]);82 } satisfies DesktopWindow.DesktopWindow["Service"]);
apps/desktop/src/window/DesktopWindow.test.ts+554−4
@@ -1,12 +1,17 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";2import { assert, describe, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
4import * as Layer from "effect/Layer";6import * as Layer from "effect/Layer";
7import * as Logger from "effect/Logger";
5import * as Option from "effect/Option";8import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";9import * as Ref from "effect/Ref";
10import * as References from "effect/References";
11import * as Schema from "effect/Schema";
7import * as TestClock from "effect/testing/TestClock";12import * as TestClock from "effect/testing/TestClock";
8 13
9import type * as Electron from "electron";14import * as Electron from "electron";
10import { vi } from "vite-plus/test";15import { vi } from "vite-plus/test";
11 16
12vi.mock("electron", async (importOriginal) => ({17vi.mock("electron", async (importOriginal) => ({
@@ -18,17 +23,25 @@ vi.mock("electron", async (importOriginal) => ({ · 5 unmodified lines
18 setUserAgent: vi.fn(),23 setUserAgent: vi.fn(),
19 })),24 })),
20 },25 },
26 screen: {
27 getAllDisplays: vi.fn(() => [
28 {
29 bounds: { x: 0, y: 0, width: 1920, height: 1080 },
30 },
31 ]),
32 },
21}));33}));
22 34
23import * as DesktopAssets from "../app/DesktopAssets.ts";35import * as DesktopAssets from "../app/DesktopAssets.ts";
24import * as DesktopConfig from "../app/DesktopConfig.ts";36import * as DesktopConfig from "../app/DesktopConfig.ts";
25import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";37import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
26import * as DesktopState from "../app/DesktopState.ts";38import * as DesktopState from "../app/DesktopState.ts";
39import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
27import * as ElectronMenu from "../electron/ElectronMenu.ts";40import * as ElectronMenu from "../electron/ElectronMenu.ts";
28import * as ElectronShell from "../electron/ElectronShell.ts";41import * as ElectronShell from "../electron/ElectronShell.ts";
29import * as ElectronTheme from "../electron/ElectronTheme.ts";42import * as ElectronTheme from "../electron/ElectronTheme.ts";
30import * as ElectronWindow from "../electron/ElectronWindow.ts";43import * as ElectronWindow from "../electron/ElectronWindow.ts";
31import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";44import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
32import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";45import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
33import * as DesktopWindow from "./DesktopWindow.ts";46import * as DesktopWindow from "./DesktopWindow.ts";
34import * as PreviewManager from "../preview/Manager.ts";47import * as PreviewManager from "../preview/Manager.ts";
@@ -46,6 +59,7 @@ const environmentInput = { · 11 unmodified lines
46} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;59} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
47 60
48function makeFakeBrowserWindow() {61function makeFakeBrowserWindow() {
62 const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
49 const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();63 const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
50 const webContents = {64 const webContents = {
51 copyImageAt: vi.fn(),65 copyImageAt: vi.fn(),
@@ -65,12 +79,21 @@ function makeFakeBrowserWindow() { · 13 unmodified lines
65 const window = {79 const window = {
66 close: vi.fn(),80 close: vi.fn(),
67 focus: vi.fn(),81 focus: vi.fn(),
82 getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
83 getNormalBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
68 isDestroyed: vi.fn(() => false),84 isDestroyed: vi.fn(() => false),
85 isFullScreen: vi.fn(() => false),
86 isMaximized: vi.fn(() => false),
69 isMinimized: vi.fn(() => false),87 isMinimized: vi.fn(() => false),
70 isVisible: vi.fn(() => true),88 isVisible: vi.fn(() => true),
71 loadURL: vi.fn(() => Promise.resolve()),89 loadURL: vi.fn(() => Promise.resolve()),
72 on: vi.fn(),90 maximize: vi.fn(),
73 once: vi.fn(),91 on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
92 windowListeners.set(eventName, listener);
93 }),
94 once: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
95 windowListeners.set(eventName, listener);
96 }),
74 restore: vi.fn(),97 restore: vi.fn(),
75 setBackgroundColor: vi.fn(),98 setBackgroundColor: vi.fn(),
76 setAutoHideCursor: vi.fn(),99 setAutoHideCursor: vi.fn(),
@@ -82,12 +105,20 @@ function makeFakeBrowserWindow() { · 5 unmodified lines
82 105
83 return {106 return {
84 window: window as unknown as Electron.BrowserWindow,107 window: window as unknown as Electron.BrowserWindow,
108 getBounds: window.getBounds,
109 getNormalBounds: window.getNormalBounds,
110 isDestroyed: window.isDestroyed,
111 isFullScreen: window.isFullScreen,
112 isMaximized: window.isMaximized,
113 isMinimized: window.isMinimized,
85 loadURL: window.loadURL,114 loadURL: window.loadURL,
115 maximize: window.maximize,
86 openDevTools: webContents.openDevTools,116 openDevTools: webContents.openDevTools,
87 reload: webContents.reload,117 reload: webContents.reload,
88 send: webContents.send,118 send: webContents.send,
89 setAutoHideCursor: window.setAutoHideCursor,119 setAutoHideCursor: window.setAutoHideCursor,
90 webContentsListeners,120 webContentsListeners,
121 windowListeners,
91 };122 };
92}123}
93 124
@@ -139,13 +170,57 @@ const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe( · 45 unmodified lines
139 ),170 ),
140);171);
141 172
173const desktopWindowBoundsEquivalence = Schema.toEquivalence(
174 DesktopAppSettings.DesktopWindowBoundsSchema,
175);
176
142function makeTestLayer(input: {177function makeTestLayer(input: {
143 readonly window: Electron.BrowserWindow;178 readonly window: Electron.BrowserWindow;
144 readonly createCount: Ref.Ref<number>;179 readonly createCount: Ref.Ref<number>;
145 readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;180 readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
146 readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];181 readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
182 readonly desktopSettings?: DesktopAppSettings.DesktopSettings;
183 readonly mainWindowBoundsUpdates?: DesktopAppSettings.DesktopWindowBounds[];
184 readonly mainWindowMaximizedUpdates?: boolean[];
185 readonly beforeMainWindowBoundsUpdate?: (
186 bounds: DesktopAppSettings.DesktopWindowBounds,
187 ) => Effect.Effect<void>;
147 readonly openedExternalUrls?: unknown[];188 readonly openedExternalUrls?: unknown[];
148}) {189}) {
190 let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
191 const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
192 get: Effect.sync(() => desktopSettings),
193 load: Effect.sync(() => desktopSettings),
194 setMainWindowBounds: (bounds, isMaximized) =>
195 Effect.gen(function* () {
196 if (input.beforeMainWindowBoundsUpdate) {
197 yield* input.beforeMainWindowBoundsUpdate(bounds);
198 }
199 const changed =
200 desktopSettings.mainWindowBounds === null ||
201 !desktopWindowBoundsEquivalence(desktopSettings.mainWindowBounds, bounds) ||
202 desktopSettings.mainWindowMaximized !== isMaximized;
203 if (changed) {
204 desktopSettings = {
205 ...desktopSettings,
206 mainWindowBounds: bounds,
207 mainWindowMaximized: isMaximized,
208 };
209 input.mainWindowBoundsUpdates?.push(bounds);
210 input.mainWindowMaximizedUpdates?.push(isMaximized);
211 }
212 return { settings: desktopSettings, changed };
213 }),
214 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
215 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
216 setUpdateChannel: () => Effect.die("unexpected update channel change"),
217 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
218 setWslDistro: () => Effect.die("unexpected WSL distro change"),
219 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
220 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
221 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
222 } satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
223
149 const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {224 const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
150 create: (options) =>225 create: (options) =>
151 Effect.sync(() => {226 Effect.sync(() => {
@@ -170,6 +245,7 @@ function makeTestLayer(input: { · 18 unmodified lines
170 Layer.mergeAll(245 Layer.mergeAll(
171 desktopAssetsLayer,246 desktopAssetsLayer,
172 desktopEnvironmentLayer,247 desktopEnvironmentLayer,
248 desktopAppSettingsLayer,
173 desktopServerExposureLayer,249 desktopServerExposureLayer,
174 DesktopState.layer,250 DesktopState.layer,
175 electronMenuLayer,251 electronMenuLayer,
@@ -267,6 +343,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n · 91 unmodified lines
267 Layer.mergeAll(343 Layer.mergeAll(
268 desktopAssetsLayer,344 desktopAssetsLayer,
269 desktopEnvironmentLayer,345 desktopEnvironmentLayer,
346 DesktopAppSettings.layerTest(),
270 desktopServerExposureLayer,347 desktopServerExposureLayer,
271 electronMenuLayer,348 electronMenuLayer,
272 Layer.succeed(ElectronShell.ElectronShell, {349 Layer.succeed(ElectronShell.ElectronShell, {
@@ -289,6 +366,23 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n · 16 unmodified lines
289 });366 });
290 367
291describe("DesktopWindow", () => {368describe("DesktopWindow", () => {
369 it("restores bounds only when the window fits within a connected display", () => {
370 const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
371 const displays = [
372 { x: 0, y: 0, width: 1920, height: 1080 },
373 { x: 1920, y: 0, width: 2560, height: 1440 },
374 ];
375
376 assert.deepEqual(
377 DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, displays),
378 persistedBounds,
379 );
380 assert.deepEqual(
381 DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, [displays[0]!]),
382 DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE,
383 );
384 });
385
292 it("recognizes only same-origin renderer navigations", () => {386 it("recognizes only same-origin renderer navigations", () => {
293 assert.isTrue(387 assert.isTrue(
294 DesktopWindow.isSameOriginRendererNavigation({388 DesktopWindow.isSameOriginRendererNavigation({
@@ -330,6 +424,10 @@ describe("DesktopWindow", () => { · 35 unmodified lines
330 424
331 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));425 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
332 assert.equal(yield* Ref.get(createCount), 1);426 assert.equal(yield* Ref.get(createCount), 1);
427 assert.equal(createdWindowOptions[0]?.width, 1100);
428 assert.equal(createdWindowOptions[0]?.height, 780);
429 assert.isUndefined(createdWindowOptions[0]?.x);
430 assert.isUndefined(createdWindowOptions[0]?.y);
333 assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);431 assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
334 assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);432 assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
335 assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);433 assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
@@ -338,6 +436,458 @@ describe("DesktopWindow", () => { · 2 unmodified lines
338 }),436 }),
339 );437 );
340 438
439 it.effect("uses the persisted main window bounds when opening the window", () =>
440 Effect.gen(function* () {
441 const fakeWindow = makeFakeBrowserWindow();
442 const createCount = yield* Ref.make(0);
443 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
444 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
445 const layer = makeTestLayer({
446 window: fakeWindow.window,
447 createCount,
448 mainWindow,
449 createdWindowOptions,
450 desktopSettings: {
451 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
452 mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
453 },
454 });
455
456 yield* Effect.gen(function* () {
457 const desktopWindow = yield* DesktopWindow.DesktopWindow;
458 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
459
460 assert.equal(createdWindowOptions[0]?.width, 1320);
461 assert.equal(createdWindowOptions[0]?.height, 880);
462 assert.equal(createdWindowOptions[0]?.x, 120);
463 assert.equal(createdWindowOptions[0]?.y, 80);
464 }).pipe(Effect.provide(layer));
465 }),
466 );
467
468 it.effect("restores the persisted maximized state", () =>
469 Effect.gen(function* () {
470 const fakeWindow = makeFakeBrowserWindow();
471 const createCount = yield* Ref.make(0);
472 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
473 const layer = makeTestLayer({
474 window: fakeWindow.window,
475 createCount,
476 mainWindow,
477 desktopSettings: {
478 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
479 mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
480 mainWindowMaximized: true,
481 },
482 });
483
484 yield* Effect.gen(function* () {
485 const desktopWindow = yield* DesktopWindow.DesktopWindow;
486 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
487
488 assert.equal(fakeWindow.maximize.mock.calls.length, 0);
489 const readyToShow = fakeWindow.windowListeners.get("ready-to-show");
490 if (!readyToShow) {
491 return yield* Effect.die("window ready-to-show listener was not registered");
492 }
493 readyToShow();
494 assert.equal(fakeWindow.maximize.mock.calls.length, 1);
495 }).pipe(Effect.provide(layer));
496 }),
497 );
498
499 it.effect("debounces move and resize bounds updates", () =>
500 Effect.gen(function* () {
501 const fakeWindow = makeFakeBrowserWindow();
502 const createCount = yield* Ref.make(0);
503 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
504 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
505 const layer = makeTestLayer({
506 window: fakeWindow.window,
507 createCount,
508 mainWindow,
509 mainWindowBoundsUpdates,
510 });
511
512 yield* Effect.gen(function* () {
513 const desktopWindow = yield* DesktopWindow.DesktopWindow;
514 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
515
516 const move = fakeWindow.windowListeners.get("move");
517 const resize = fakeWindow.windowListeners.get("resize");
518 if (!move || !resize) {
519 return yield* Effect.die("window bounds listeners were not registered");
520 }
521
522 fakeWindow.getBounds.mockReturnValue({ x: 120, y: 80, width: 1280, height: 840 });
523 move();
524 yield* TestClock.adjust(250);
525
526 fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
527 resize();
528 yield* TestClock.adjust(499);
529 assert.deepEqual(mainWindowBoundsUpdates, []);
530
531 yield* TestClock.adjust(1);
532 yield* Effect.promise(() => Promise.resolve());
533 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
534 }).pipe(Effect.provide(layer));
535 }),
536 );
537
538 it.effect("persists normal bounds and state for a maximized window", () =>
539 Effect.gen(function* () {
540 const fakeWindow = makeFakeBrowserWindow();
541 fakeWindow.isMaximized.mockReturnValue(true);
542 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
543 fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
544 const createCount = yield* Ref.make(0);
545 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
546 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
547 const mainWindowMaximizedUpdates: boolean[] = [];
548 const layer = makeTestLayer({
549 window: fakeWindow.window,
550 createCount,
551 mainWindow,
552 mainWindowBoundsUpdates,
553 mainWindowMaximizedUpdates,
554 });
555
556 yield* Effect.gen(function* () {
557 const desktopWindow = yield* DesktopWindow.DesktopWindow;
558 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
559
560 const close = fakeWindow.windowListeners.get("close");
561 if (!close) {
562 return yield* Effect.die("window close listener was not registered");
563 }
564 close();
565 yield* Effect.promise(() => Promise.resolve());
566
567 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
568 assert.deepEqual(mainWindowMaximizedUpdates, [true]);
569 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
570 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
571 }).pipe(Effect.provide(layer));
572 }),
573 );
574
575 it.effect("persists normal bounds and state from the native maximize event", () =>
576 Effect.gen(function* () {
577 const fakeWindow = makeFakeBrowserWindow();
578 const createCount = yield* Ref.make(0);
579 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
580 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
581 const mainWindowMaximizedUpdates: boolean[] = [];
582 const layer = makeTestLayer({
583 window: fakeWindow.window,
584 createCount,
585 mainWindow,
586 mainWindowBoundsUpdates,
587 mainWindowMaximizedUpdates,
588 });
589
590 yield* Effect.gen(function* () {
591 const desktopWindow = yield* DesktopWindow.DesktopWindow;
592 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
593
594 const maximize = fakeWindow.windowListeners.get("maximize");
595 if (!maximize) {
596 return yield* Effect.die("window maximize listener was not registered");
597 }
598
599 fakeWindow.isMaximized.mockReturnValue(true);
600 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
601 fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
602 maximize();
603 yield* TestClock.adjust(500);
604 yield* Effect.promise(() => Promise.resolve());
605
606 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
607 assert.deepEqual(mainWindowMaximizedUpdates, [true]);
608 }).pipe(Effect.provide(layer));
609 }),
610 );
611
612 it.effect("does not persist bounds that fail the domain schema", () =>
613 Effect.gen(function* () {
614 const fakeWindow = makeFakeBrowserWindow();
615 fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
616 const createCount = yield* Ref.make(0);
617 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
618 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
619 const layer = makeTestLayer({
620 window: fakeWindow.window,
621 createCount,
622 mainWindow,
623 mainWindowBoundsUpdates,
624 });
625
626 yield* Effect.gen(function* () {
627 const desktopWindow = yield* DesktopWindow.DesktopWindow;
628 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
629
630 const resize = fakeWindow.windowListeners.get("resize");
631 if (!resize) {
632 return yield* Effect.die("window resize listener was not registered");
633 }
634 resize();
635 yield* TestClock.adjust(500);
636 yield* Effect.promise(() => Promise.resolve());
637
638 assert.deepEqual(mainWindowBoundsUpdates, []);
639 }).pipe(Effect.provide(layer));
640 }),
641 );
642
643 it.effect("preserves unrestorable bounds until the user changes the window", () =>
644 Effect.gen(function* () {
645 const fakeWindow = makeFakeBrowserWindow();
646 const createCount = yield* Ref.make(0);
647 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
648 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
649 const layer = makeTestLayer({
650 window: fakeWindow.window,
651 createCount,
652 mainWindow,
653 mainWindowBoundsUpdates,
654 desktopSettings: {
655 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
656 mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 },
657 },
658 });
659
660 yield* Effect.gen(function* () {
661 const desktopWindow = yield* DesktopWindow.DesktopWindow;
662 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
663
664 const close = fakeWindow.windowListeners.get("close");
665 const move = fakeWindow.windowListeners.get("move");
666 if (!close || !move) {
667 return yield* Effect.die("window lifecycle listeners were not registered");
668 }
669
670 close();
671 yield* Effect.promise(() => Promise.resolve());
672 assert.deepEqual(mainWindowBoundsUpdates, []);
673
674 fakeWindow.getBounds.mockReturnValue({ x: 80, y: 60, width: 1280, height: 840 });
675 move();
676 yield* TestClock.adjust(500);
677 yield* Effect.promise(() => Promise.resolve());
678 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 80, y: 60, width: 1280, height: 840 }]);
679 }).pipe(Effect.provide(layer));
680 }),
681 );
682
683 it.effect("flushes normal bounds when fullscreen before the debounce completes", () =>
684 Effect.gen(function* () {
685 const fakeWindow = makeFakeBrowserWindow();
686 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
687 fakeWindow.getNormalBounds.mockReturnValue({ x: 200, y: 130, width: 1400, height: 940 });
688 const createCount = yield* Ref.make(0);
689 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
690 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
691 const layer = makeTestLayer({
692 window: fakeWindow.window,
693 createCount,
694 mainWindow,
695 mainWindowBoundsUpdates,
696 });
697
698 yield* Effect.gen(function* () {
699 const desktopWindow = yield* DesktopWindow.DesktopWindow;
700 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
701
702 const resize = fakeWindow.windowListeners.get("resize");
703 if (!resize) {
704 return yield* Effect.die("window resize listener was not registered");
705 }
706 resize();
707 yield* TestClock.adjust(250);
708 fakeWindow.isFullScreen.mockReturnValue(true);
709
710 yield* desktopWindow.flushMainWindowBounds;
711
712 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 200, y: 130, width: 1400, height: 940 }]);
713 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
714 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
715 }).pipe(Effect.provide(layer));
716 }),
717 );
718
719 it.effect("flushes normal bounds when minimized before the debounce completes", () =>
720 Effect.gen(function* () {
721 const fakeWindow = makeFakeBrowserWindow();
722 fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 });
723 fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 });
724 const createCount = yield* Ref.make(0);
725 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
726 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
727 const layer = makeTestLayer({
728 window: fakeWindow.window,
729 createCount,
730 mainWindow,
731 mainWindowBoundsUpdates,
732 });
733
734 yield* Effect.gen(function* () {
735 const desktopWindow = yield* DesktopWindow.DesktopWindow;
736 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
737
738 const resize = fakeWindow.windowListeners.get("resize");
739 if (!resize) {
740 return yield* Effect.die("window resize listener was not registered");
741 }
742 resize();
743 yield* TestClock.adjust(250);
744 fakeWindow.isMinimized.mockReturnValue(true);
745
746 yield* desktopWindow.flushMainWindowBounds;
747
748 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]);
749 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
750 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
751 }).pipe(Effect.provide(layer));
752 }),
753 );
754
755 it.effect("logs display lookup failures before falling back to the default size", () =>
756 Effect.gen(function* () {
757 const displayLookupFailure = new Error("screen API unavailable");
758 vi.mocked(Electron.screen.getAllDisplays).mockImplementationOnce(() => {
759 throw displayLookupFailure;
760 });
761 const logRecords: Array<{
762 readonly message: unknown;
763 readonly annotations: Readonly<Record<string, unknown>>;
764 }> = [];
765 const logger = Logger.make(({ fiber, message }) => {
766 logRecords.push({
767 message,
768 annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
769 });
770 });
771 const fakeWindow = makeFakeBrowserWindow();
772 const createCount = yield* Ref.make(0);
773 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
774 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
775 const layer = makeTestLayer({
776 window: fakeWindow.window,
777 createCount,
778 mainWindow,
779 createdWindowOptions,
780 });
781
782 yield* Effect.gen(function* () {
783 const desktopWindow = yield* DesktopWindow.DesktopWindow;
784 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
785 }).pipe(
786 Effect.provide(Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false }))),
787 );
788
789 const warning = logRecords.find(
790 (record) =>
791 Array.isArray(record.message) &&
792 record.message[0] === "failed to read connected displays; using defaults",
793 );
794 assert.isDefined(warning);
795 assert.strictEqual(warning.annotations.cause, displayLookupFailure);
796 assert.equal(createdWindowOptions[0]?.width, 1100);
797 assert.equal(createdWindowOptions[0]?.height, 780);
798 assert.isUndefined(createdWindowOptions[0]?.x);
799 assert.isUndefined(createdWindowOptions[0]?.y);
800 }),
801 );
802
803 it.effect("persists the current main window bounds before the window closes", () =>
804 Effect.gen(function* () {
805 const fakeWindow = makeFakeBrowserWindow();
806 fakeWindow.getBounds.mockReturnValue({ x: 240, y: 160, width: 1410, height: 930 });
807 const createCount = yield* Ref.make(0);
808 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
809 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
810 const writeStarted = yield* Deferred.make<void>();
811 const allowWrite = yield* Deferred.make<void>();
812 const flushCompleted = yield* Deferred.make<void>();
813 const layer = makeTestLayer({
814 window: fakeWindow.window,
815 createCount,
816 mainWindow,
817 mainWindowBoundsUpdates,
818 beforeMainWindowBoundsUpdate: () =>
819 Deferred.succeed(writeStarted, undefined).pipe(
820 Effect.andThen(Deferred.await(allowWrite)),
821 Effect.asVoid,
822 ),
823 });
824
825 yield* Effect.gen(function* () {
826 const desktopWindow = yield* DesktopWindow.DesktopWindow;
827 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
828
829 const close = fakeWindow.windowListeners.get("close");
830 if (!close) {
831 return yield* Effect.die("window close listener was not registered");
832 }
833 close();
834 yield* Deferred.await(writeStarted);
835 fakeWindow.isDestroyed.mockReturnValue(true);
836
837 const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe(
838 Effect.andThen(Deferred.succeed(flushCompleted, undefined)),
839 Effect.forkChild({ startImmediately: true }),
840 );
841 yield* Effect.yieldNow;
842 assert.isFalse(yield* Deferred.isDone(flushCompleted));
843
844 yield* Deferred.succeed(allowWrite, undefined);
845 yield* Fiber.join(flushFiber);
846 assert.isTrue(yield* Deferred.isDone(flushCompleted));
847
848 assert.deepEqual(mainWindowBoundsUpdates, [
849 {
850 x: 240,
851 y: 160,
852 width: 1410,
853 height: 930,
854 },
855 ]);
856 }).pipe(Effect.provide(layer));
857 }),
858 );
859
860 it.effect("publishes native macOS fullscreen changes to the renderer", () =>
861 Effect.gen(function* () {
862 const fakeWindow = makeFakeBrowserWindow();
863 const createCount = yield* Ref.make(0);
864 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
865 const layer = makeTestLayer({
866 window: fakeWindow.window,
867 createCount,
868 mainWindow,
869 });
870
871 yield* Effect.gen(function* () {
872 const desktopWindow = yield* DesktopWindow.DesktopWindow;
873 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
874
875 const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
876 const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
877 if (!enterFullscreen || !leaveFullscreen) {
878 return yield* Effect.die("fullscreen listeners were not registered");
879 }
880
881 enterFullscreen();
882 leaveFullscreen();
883 assert.deepEqual(fakeWindow.send.mock.calls, [
884 [WINDOW_FULLSCREEN_STATE_CHANNEL, true],
885 [WINDOW_FULLSCREEN_STATE_CHANNEL, false],
886 ]);
887 }).pipe(Effect.provide(layer));
888 }),
889 );
890
341 it.effect("recovers when the development renderer is temporarily unreachable", () =>891 it.effect("recovers when the development renderer is temporarily unreachable", () =>
342 Effect.gen(function* () {892 Effect.gen(function* () {
343 const fakeWindow = makeFakeBrowserWindow();893 const fakeWindow = makeFakeBrowserWindow();
apps/desktop/src/window/DesktopWindow.ts+180−4
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer"; · 4 unmodified lines
5import * as Option from "effect/Option";5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";6import * as Ref from "effect/Ref";
7 7
8import type * as Electron from "electron";8import * as Electron from "electron";
9 9
10import * as DesktopAssets from "../app/DesktopAssets.ts";10import * as DesktopAssets from "../app/DesktopAssets.ts";
11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -15,13 +15,15 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts"; · 3 unmodified lines
15import * as ElectronShell from "../electron/ElectronShell.ts";15import * as ElectronShell from "../electron/ElectronShell.ts";
16import * as ElectronTheme from "../electron/ElectronTheme.ts";16import * as ElectronTheme from "../electron/ElectronTheme.ts";
17import * as ElectronWindow from "../electron/ElectronWindow.ts";17import * as ElectronWindow from "../electron/ElectronWindow.ts";
18import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";18import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
19import * as PreviewManager from "../preview/Manager.ts";19import * as PreviewManager from "../preview/Manager.ts";
20import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
20 21
21const TITLEBAR_HEIGHT = 40;22const TITLEBAR_HEIGHT = 40;
22const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux23const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
23const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";24const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
24const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";25const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
26const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
25const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;27const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
26const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([28const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
27 -2, // ERR_FAILED29 -2, // ERR_FAILED
@@ -41,6 +43,7 @@ type WindowTitleBarOptions = Pick< · 13 unmodified lines
41type DesktopWindowRuntimeServices =43type DesktopWindowRuntimeServices =
42 | DesktopEnvironment.DesktopEnvironment44 | DesktopEnvironment.DesktopEnvironment
43 | DesktopAssets.DesktopAssets45 | DesktopAssets.DesktopAssets
46 | DesktopAppSettings.DesktopAppSettings
44 | ElectronMenu.ElectronMenu47 | ElectronMenu.ElectronMenu
45 | ElectronShell.ElectronShell48 | ElectronShell.ElectronShell
46 | ElectronTheme.ElectronTheme49 | ElectronTheme.ElectronTheme
@@ -75,6 +78,7 @@ export class DesktopWindow extends Context.Service< · 28 unmodified lines
75 // window so a "macOS dock click" while the backend is down doesn't78 // window so a "macOS dock click" while the backend is down doesn't
76 // produce a stranded window pointing at nothing.79 // produce a stranded window pointing at nothing.
77 readonly handleBackendNotReady: Effect.Effect<void>;80 readonly handleBackendNotReady: Effect.Effect<void>;
81 readonly flushMainWindowBounds: Effect.Effect<void>;
78 readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;82 readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
79 readonly syncAppearance: Effect.Effect<void>;83 readonly syncAppearance: Effect.Effect<void>;
80 }84 }
@@ -99,6 +103,45 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string { · 18 unmodified lines
99 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";103 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
100}104}
101 105
106type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
107
108function windowFitsWithinDisplay(
109 windowBounds: DesktopAppSettings.DesktopWindowBounds,
110 displayBounds: DisplayBounds,
111): boolean {
112 return (
113 windowBounds.x >= displayBounds.x &&
114 windowBounds.y >= displayBounds.y &&
115 windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width &&
116 windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height
117 );
118}
119
120function windowBoundsEqual(
121 left: DesktopAppSettings.DesktopWindowBounds,
122 right: DesktopAppSettings.DesktopWindowBounds,
123): boolean {
124 return (
125 left.x === right.x &&
126 left.y === right.y &&
127 left.width === right.width &&
128 left.height === right.height
129 );
130}
131
132export function resolveInitialMainWindowBounds(
133 persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
134 displays: readonly DisplayBounds[],
135): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
136 if (
137 persistedBounds !== null &&
138 displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
139 ) {
140 return persistedBounds;
141 }
142 return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
143}
144
102// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only145// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
103// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as146// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
104// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.147// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
@@ -202,6 +245,7 @@ export const make = Effect.gen(function* () { · 97 unmodified lines
202 const electronTheme = yield* ElectronTheme.ElectronTheme;245 const electronTheme = yield* ElectronTheme.ElectronTheme;
203 const electronWindow = yield* ElectronWindow.ElectronWindow;246 const electronWindow = yield* ElectronWindow.ElectronWindow;
204 const previewManager = yield* PreviewManager.PreviewManager;247 const previewManager = yield* PreviewManager.PreviewManager;
248 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
205 // Window-side latch for the primary backend's readiness. Set by249 // Window-side latch for the primary backend's readiness. Set by
206 // handleBackendReady (driven by the pool's onReady callback), cleared250 // handleBackendReady (driven by the pool's onReady callback), cleared
207 // by handleBackendNotReady (driven by onShutdown). Only consumed by251 // by handleBackendNotReady (driven by onShutdown). Only consumed by
@@ -214,6 +258,7 @@ export const make = Effect.gen(function* () { · 6 unmodified lines
214 const context = yield* Effect.context<DesktopWindowRuntimeServices>();258 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
215 const runFork = Effect.runForkWith(context);259 const runFork = Effect.runForkWith(context);
216 const runPromise = Effect.runPromiseWith(context);260 const runPromise = Effect.runPromiseWith(context);
261 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
217 262
218 const dismissConnectingSplash = Effect.gen(function* () {263 const dismissConnectingSplash = Effect.gen(function* () {
219 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());264 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
@@ -250,9 +295,31 @@ export const make = Effect.gen(function* () { · 30 unmodified lines
250 const iconPaths = yield* assets.iconPaths;295 const iconPaths = yield* assets.iconPaths;
251 const iconOption = getIconOption(iconPaths, environment.platform);296 const iconOption = getIconOption(iconPaths, environment.platform);
252 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;297 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
298 const persistedSettings = yield* desktopSettings.get;
299 const persistedBounds = persistedSettings.mainWindowBounds;
300 const displayBoundsResult = yield* Effect.sync(() => {
301 try {
302 return {
303 _tag: "Success" as const,
304 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
305 };
306 } catch (cause) {
307 return { _tag: "Failure" as const, cause };
308 }
309 });
310 const displayBounds =
311 displayBoundsResult._tag === "Success"
312 ? displayBoundsResult.bounds
313 : yield* logWindowWarning("failed to read connected displays; using defaults", {
314 cause: displayBoundsResult.cause,
315 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
316 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
317 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
318 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
319 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
320 }
253 const window = yield* electronWindow.create({321 const window = yield* electronWindow.create({
254 width: 1100,322 ...initialBounds,
255 height: 780,
256 minWidth: 840,323 minWidth: 840,
257 minHeight: 620,324 minHeight: 620,
258 show: false,325 show: false,
@@ -274,6 +341,92 @@ export const make = Effect.gen(function* () { · 15 unmodified lines
274 if (environment.platform === "darwin") {341 if (environment.platform === "darwin") {
275 window.setAutoHideCursor(false);342 window.setAutoHideCursor(false);
276 }343 }
344 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
345 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
346 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
347 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
348 if (window.isDestroyed()) {
349 return null;
350 }
351 const bounds =
352 window.isFullScreen() || window.isMaximized() || window.isMinimized()
353 ? window.getNormalBounds()
354 : window.getBounds();
355 return DesktopAppSettings.normalizeMainWindowBounds({
356 x: Math.round(bounds.x),
357 y: Math.round(bounds.y),
358 width: Math.round(bounds.width),
359 height: Math.round(bounds.height),
360 });
361 };
362 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
363 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
364 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
365 if (!boundsPersistenceEnabled) {
366 return pendingBoundsPersistFiber;
367 }
368 const bounds = readPersistableBounds();
369 if (bounds === null) {
370 return pendingBoundsPersistFiber;
371 }
372 pendingBoundsPersistFiber = runFork(
373 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
374 Effect.asVoid,
375 Effect.catch((error) =>
376 logWindowWarning("failed to persist main window bounds", {
377 message: error.message,
378 }),
379 ),
380 ),
381 );
382 return pendingBoundsPersistFiber;
383 };
384 const scheduleBoundsPersist = () => {
385 if (!boundsPersistenceEnabled) {
386 const currentBounds = readPersistableBounds();
387 if (
388 currentBounds === null ||
389 (fallbackWindowBounds !== null &&
390 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
391 window.isMaximized() === fallbackWindowMaximized)
392 ) {
393 return;
394 }
395 }
396 boundsPersistenceEnabled = true;
397 if (boundsPersistFiber !== undefined) {
398 const fiber = boundsPersistFiber;
399 boundsPersistFiber = undefined;
400 runFork(Fiber.interrupt(fiber));
401 }
402 boundsPersistFiber = runFork(
403 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
404 Effect.andThen(
405 Effect.sync(() => {
406 boundsPersistFiber = undefined;
407 void persistCurrentBounds();
408 }),
409 ),
410 ),
411 );
412 };
413 const clearBoundsPersist = () => {
414 if (boundsPersistFiber === undefined) {
415 return;
416 }
417 const fiber = boundsPersistFiber;
418 boundsPersistFiber = undefined;
419 runFork(Fiber.interrupt(fiber));
420 };
421 const flushBoundsPersist = Effect.sync(() => {
422 clearBoundsPersist();
423 return persistCurrentBounds();
424 }).pipe(
425 Effect.flatMap((fiber) =>
426 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
427 ),
428 );
429 flushMainWindowBounds = flushBoundsPersist;
277 430
278 yield* previewManager.setMainWindow(window);431 yield* previewManager.setMainWindow(window);
279 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {432 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
@@ -364,6 +517,22 @@ export const make = Effect.gen(function* () { · 84 unmodified lines
364 event.preventDefault();517 event.preventDefault();
365 window.setTitle(environment.displayName);518 window.setTitle(environment.displayName);
366 });519 });
520 window.on("resize", scheduleBoundsPersist);
521 window.on("move", scheduleBoundsPersist);
522 window.on("maximize", scheduleBoundsPersist);
523 window.on("unmaximize", scheduleBoundsPersist);
524 window.on("close", () => {
525 runFork(flushBoundsPersist);
526 });
527
528 if (environment.platform === "darwin") {
529 window.on("enter-full-screen", () => {
530 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
531 });
532 window.on("leave-full-screen", () => {
533 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
534 });
535 }
367 536
368 let developmentLoadRetryIndex = 0;537 let developmentLoadRetryIndex = 0;
369 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;538 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
@@ -463,6 +632,9 @@ export const make = Effect.gen(function* () { · 93 unmodified lines
463 bindFirstRevealTrigger(revealSubscribers, () => {632 bindFirstRevealTrigger(revealSubscribers, () => {
464 // Reveal the real window, then close the connecting splash (if any) so the633 // Reveal the real window, then close the connecting splash (if any) so the
465 // two don't overlap and there's no blank gap between them.634 // two don't overlap and there's no blank gap between them.
635 if (persistedSettings.mainWindowMaximized) {
636 window.maximize();
637 }
466 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));638 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
467 });639 });
468 640
@@ -473,6 +645,7 @@ export const make = Effect.gen(function* () { · 4 unmodified lines
473 645
474 window.on("closed", () => {646 window.on("closed", () => {
475 clearDevelopmentLoadRetry();647 clearDevelopmentLoadRetry();
648 clearBoundsPersist();
476 void runPromise(electronWindow.clearMain(Option.some(window)));649 void runPromise(electronWindow.clearMain(Option.some(window)));
477 });650 });
478 651
@@ -589,6 +762,9 @@ export const make = Effect.gen(function* () { · 110 unmodified lines
589 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(762 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
590 Effect.withSpan("desktop.window.handleBackendNotReady"),763 Effect.withSpan("desktop.window.handleBackendNotReady"),
591 ),764 ),
765 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
766 Effect.withSpan("desktop.window.flushMainWindowBounds"),
767 ),
592 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {768 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
593 yield* Effect.annotateCurrentSpan({ action });769 yield* Effect.annotateCurrentSpan({ action });
594 const existingWindow = yield* focusedMainWindow;770 const existingWindow = yield* focusedMainWindow;
apps/desktop/src/wsl/DesktopWslEnvironment.test.ts+24−0
@@ -16,6 +16,7 @@ import { · 15 unmodified lines
16 formatNodePtyProbeFailureReason,16 formatNodePtyProbeFailureReason,
17 formatWslShellTransportFailureReason,17 formatWslShellTransportFailureReason,
18 parseNodePath,18 parseNodePath,
19 parseNodeVersion,
19 parseResolvedPath,20 parseResolvedPath,
20 parseToolchainReport,21 parseToolchainReport,
21 probeWslDistros,22 probeWslDistros,
@@ -173,6 +174,29 @@ describe("parseNodePath", () => { · 151 unmodified lines
173 });174 });
174});175});
175 176
177describe("parseNodeVersion", () => {
178 it("extracts the node version from a nodeVersion: line", () => {
179 expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
180 });
181
182 it("returns null when the version value is empty", () => {
183 expect(parseNodeVersion("nodeVersion:")).toBeNull();
184 });
185
186 it("returns null when there is no nodeVersion line at all", () => {
187 expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
188 });
189
190 it("ignores surrounding noise and trims whitespace", () => {
191 const stdout = [
192 "some preamble noise",
193 " nodeVersion:22.16.0 ",
194 "nodePath:/usr/bin/node",
195 ].join("\n");
196 expect(parseNodeVersion(stdout)).toBe("22.16.0");
197 });
198});
199
176describe("parseResolvedPath", () => {200describe("parseResolvedPath", () => {
177 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {201 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
178 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";202 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
apps/desktop/src/wsl/DesktopWslEnvironment.ts+42−4
@@ -32,7 +32,11 @@ export interface EnsureWslNodePtyOptions { · 31 unmodified lines
32}32}
33 33
34export type EnsureWslNodePtyResult =34export type EnsureWslNodePtyResult =
35 | { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }35 | {
36 readonly ok: true;
37 readonly nodePath: string;
38 readonly resolvedPath: string;
39 }
36 | {40 | {
37 readonly ok: false;41 readonly ok: false;
38 readonly reason: string;42 readonly reason: string;
@@ -222,6 +226,7 @@ export const formatNodePtyProbeFailureReason = (exitCode: number): string | null · 183 unmodified lines
222const NODE_PTY_PROBE_SCRIPT = (226const NODE_PTY_PROBE_SCRIPT = (
223 linuxServerDir: string,227 linuxServerDir: string,
224) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"228) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
229printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
225printf 'resolvedPath:%s\\n' "$PATH"230printf 'resolvedPath:%s\\n' "$PATH"
226cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1231cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
227// The server bundle externalizes its deps to node_modules, and the WSL Node232// The server bundle externalizes its deps to node_modules, and the WSL Node
@@ -318,6 +323,16 @@ export const parseNodePath = (stdout: string): string | null => { · 90 unmodified lines
318 return path ?? null;323 return path ?? null;
319};324};
320 325
326export const parseNodeVersion = (stdout: string): string | null => {
327 const version = stdout
328 .split("\n")
329 .map((line) => line.trim())
330 .filter((line) => line.startsWith("nodeVersion:"))
331 .map((line) => line.slice("nodeVersion:".length).trim())
332 .find((value) => value.length > 0);
333 return version ?? null;
334};
335
321// Captures the login-shell PATH after the shared resolver has loaded version336// Captures the login-shell PATH after the shared resolver has loaded version
322// managers. Preserve the value byte-for-byte apart from a Windows-style CR so337// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
323// paths containing spaces or apostrophes can be forwarded as one env argv.338// paths containing spaces or apostrophes can be forwarded as one env argv.
@@ -404,7 +419,11 @@ const ensureNodePtyImpl = ( · 80 unmodified lines
404 419
405 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);420 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
406 if (transportFailureReason !== null) {421 if (transportFailureReason !== null) {
407 return { ok: false, reason: transportFailureReason, fatal: false } as const;422 return {
423 ok: false,
424 reason: transportFailureReason,
425 fatal: false,
426 } as const;
408 }427 }
409 428
410 // No node at all, even after the shared resolver repaired PATH. Surface429 // No node at all, even after the shared resolver repaired PATH. Surface
@@ -457,12 +476,31 @@ const ensureNodePtyImpl = ( · 46 unmodified lines
457 } as const;476 } as const;
458 }477 }
459 478
460 if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;479 if (probe.exitCode === 0) {
480 const rawVersion = parseNodeVersion(probe.stdout);
481 if (
482 rawVersion !== null &&
483 options.nodeEngineRange &&
484 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
485 ) {
486 const range = options.nodeEngineRange.trim();
487 return {
488 ok: false,
489 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
490 fatal: true,
491 } as const;
492 }
493 return { ok: true, nodePath, resolvedPath } as const;
494 }
461 495
462 if (options.allowBuild !== true) {496 if (options.allowBuild !== true) {
463 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);497 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
464 if (packagedProbeFailure !== null) {498 if (packagedProbeFailure !== null) {
465 return { ok: false, reason: packagedProbeFailure, fatal: true } as const;499 return {
500 ok: false,
501 reason: packagedProbeFailure,
502 fatal: true,
503 } as const;
466 }504 }
467 }505 }
468 506
apps/marketing/public/harnesses/cursor_light.svg+1−1
@@ -1 +1 @@
1<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>1<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" fill="#EDECEC" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
apps/marketing/public/harnesses/grok-dark.svg+4−0
@@ -0,0 +1,4 @@
1<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
2 <path fill="#F5F5F5" d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
3 <path fill="#F5F5F5" d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
4</svg>
apps/marketing/src/components/LegalPage.astro+414−0
@@ -0,0 +1,414 @@
1---
2import Layout from "../layouts/Layout.astro";
3
4interface Props {
5 readonly title: string;
6 readonly description: string;
7 readonly heading: string;
8 readonly lede: string;
9 readonly effectiveDate: string;
10 readonly lastUpdated: string;
11 readonly sections: ReadonlyArray<readonly [id: string, label: string]>;
12}
13
14const { title, description, heading, lede, effectiveDate, lastUpdated, sections } = Astro.props;
15---
16
17<Layout title={title} description={description} pageClass="legal-document-page">
18 <div class="legal-page">
19 <a class="legal-index-link" href="/legal"><span aria-hidden="true">&#8592;</span> All legal documents</a>
20 <header class="legal-hero">
21 <p class="eyebrow">T3 Tools, Inc. / Legal</p>
22 <h1>{heading}</h1>
23 <p class="legal-lede">{lede}</p>
24 <dl class="legal-dates" aria-label="Document dates">
25 <div>
26 <dt>Effective Date</dt>
27 <dd>{effectiveDate}</dd>
28 </div>
29 <div>
30 <dt>Last Updated</dt>
31 <dd>{lastUpdated}</dd>
32 </div>
33 </dl>
34 </header>
35
36 <div class="legal-rule" aria-hidden="true"></div>
37
38 <div class="legal-layout">
39 <aside class="legal-nav" aria-label="On this page">
40 <p class="legal-nav-label">On this page</p>
41 <ol>
42 {sections.map(([id, label], index) => (
43 <li>
44 <a href={`#${id}`} data-legal-nav-link={id}>
45 <span>{String(index + 1).padStart(2, "0")}</span>
46 {label}
47 </a>
48 </li>
49 ))}
50 </ol>
51 </aside>
52
53 <article class="legal-copy">
54 <slot />
55 </article>
56 </div>
57 </div>
58</Layout>
59
60<script>
61 const navLinks = Array.from(
62 document.querySelectorAll<HTMLAnchorElement>("[data-legal-nav-link]"),
63 );
64 const sections = navLinks
65 .map((link) => {
66 const id = link.dataset.legalNavLink;
67 const section = id ? document.getElementById(id) : null;
68 return section ? { link, section } : null;
69 })
70 .filter((entry): entry is { link: HTMLAnchorElement; section: HTMLElement } => entry !== null);
71
72 let activeId = "";
73 let frame = 0;
74
75 const updateActiveSection = () => {
76 frame = 0;
77 const marker = Math.min(180, window.innerHeight * 0.28);
78 let active = sections[0];
79
80 for (const entry of sections) {
81 if (entry.section.getBoundingClientRect().top > marker) break;
82 active = entry;
83 }
84
85 if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) {
86 active = sections[sections.length - 1];
87 }
88
89 if (!active || active.section.id === activeId) return;
90 activeId = active.section.id;
91
92 for (const { link, section } of sections) {
93 if (section.id === activeId) {
94 link.setAttribute("aria-current", "location");
95 } else {
96 link.removeAttribute("aria-current");
97 }
98 }
99 };
100
101 const scheduleUpdate = () => {
102 if (frame) return;
103 frame = window.requestAnimationFrame(updateActiveSection);
104 };
105
106 updateActiveSection();
107 window.addEventListener("scroll", scheduleUpdate, { passive: true });
108 window.addEventListener("resize", scheduleUpdate);
109</script>
110
111<style is:global>
112 .legal-page {
113 width: min(1120px, calc(100% - 64px));
114 margin: 0 auto;
115 padding: clamp(72px, 10vw, 132px) 0 112px;
116 }
117
118 .legal-index-link {
119 display: none;
120 }
121
122 .legal-hero {
123 max-width: 820px;
124 animation: fade-in 0.8s ease-out both;
125 }
126
127 .legal-hero h1 {
128 margin-top: 18px;
129 font-size: clamp(3.4rem, 8vw, 7.4rem);
130 font-weight: 500;
131 letter-spacing: -0.02em;
132 line-height: 0.9;
133 }
134
135 .legal-lede {
136 max-width: 720px;
137 margin-top: 34px;
138 color: var(--fg-muted);
139 font-size: clamp(1.05rem, 1.8vw, 1.3rem);
140 line-height: 1.65;
141 letter-spacing: -0.012em;
142 }
143
144 .legal-dates {
145 display: flex;
146 flex-wrap: wrap;
147 gap: 36px;
148 margin-top: 38px;
149 }
150
151 .legal-dates div {
152 display: grid;
153 gap: 4px;
154 }
155
156 .legal-dates dt,
157 .legal-nav-label,
158 .section-number {
159 color: var(--fg-dim);
160 font-family: var(--font-mono);
161 font-size: 0.68rem;
162 font-weight: 500;
163 letter-spacing: 0.12em;
164 text-transform: uppercase;
165 }
166
167 .legal-dates dd {
168 color: var(--fg);
169 font-family: var(--font-mono);
170 font-size: 0.8rem;
171 }
172
173 .legal-rule {
174 height: 1px;
175 margin: 72px 0;
176 background: linear-gradient(90deg, var(--border-strong), var(--border) 65%, transparent);
177 }
178
179 .legal-layout {
180 display: grid;
181 grid-template-columns: 210px minmax(0, 720px);
182 gap: clamp(64px, 10vw, 140px);
183 align-items: start;
184 }
185
186 .legal-nav {
187 position: sticky;
188 top: 88px;
189 max-height: calc(100vh - 112px);
190 overflow-y: auto;
191 scrollbar-width: thin;
192 }
193
194 .legal-nav ol {
195 display: grid;
196 gap: 2px;
197 margin-top: 16px;
198 padding-bottom: 12px;
199 list-style: none;
200 }
201
202 .legal-nav a {
203 display: grid;
204 grid-template-columns: 24px 1fr;
205 gap: 9px;
206 margin-left: -10px;
207 padding: 7px 8px 7px 10px;
208 border-radius: 6px;
209 color: var(--fg-dim);
210 font-size: 0.78rem;
211 line-height: 1.35;
212 transition:
213 color 0.16s ease,
214 background-color 0.16s ease,
215 box-shadow 0.16s ease;
216 }
217
218 .legal-nav a span {
219 color: var(--fg-faint);
220 font-family: var(--font-mono);
221 font-size: 0.64rem;
222 line-height: 1.7;
223 }
224
225 .legal-nav a:hover {
226 color: var(--fg);
227 }
228
229 .legal-nav a[aria-current="location"] {
230 color: var(--fg);
231 background: color-mix(in srgb, var(--accent) 8%, transparent);
232 box-shadow: inset 2px 0 var(--accent);
233 }
234
235 .legal-nav a[aria-current="location"] span {
236 color: var(--accent);
237 }
238
239 .legal-copy {
240 min-width: 0;
241 }
242
243 .legal-copy section {
244 scroll-margin-top: 104px;
245 }
246
247 .legal-copy section + section {
248 margin-top: 82px;
249 padding-top: 82px;
250 border-top: 1px solid var(--border);
251 }
252
253 .section-number {
254 color: var(--accent);
255 }
256
257 .legal-copy h2 {
258 margin: 8px 0 28px;
259 color: var(--fg);
260 font-size: clamp(1.75rem, 3vw, 2.45rem);
261 font-weight: 500;
262 letter-spacing: -0.04em;
263 line-height: 1.1;
264 }
265
266 .legal-copy h3 {
267 margin: 32px 0 10px;
268 color: var(--fg);
269 font-size: 1rem;
270 font-weight: 600;
271 letter-spacing: -0.015em;
272 }
273
274 .legal-copy h4 {
275 margin: 24px 0 8px;
276 color: var(--fg);
277 font-size: 0.94rem;
278 font-weight: 600;
279 }
280
281 .legal-copy p,
282 .legal-copy li,
283 .legal-copy address {
284 color: var(--fg-muted);
285 font-size: 0.98rem;
286 font-style: normal;
287 line-height: 1.78;
288 }
289
290 .legal-copy p + p {
291 margin-top: 18px;
292 }
293
294 .legal-copy strong {
295 color: var(--fg);
296 font-weight: 600;
297 }
298
299 .legal-copy ul,
300 .legal-copy ol {
301 display: grid;
302 gap: 12px;
303 margin: 18px 0 20px;
304 padding-left: 1.2rem;
305 }
306
307 .legal-copy li {
308 padding-left: 7px;
309 }
310
311 .legal-copy li::marker {
312 color: var(--accent);
313 }
314
315 .legal-copy .provider-list {
316 gap: 28px;
317 }
318
319 .provider-list a,
320 .legal-copy a {
321 overflow-wrap: anywhere;
322 }
323
324 .legal-copy a {
325 color: var(--fg);
326 text-decoration: underline;
327 text-decoration-color: color-mix(in srgb, var(--accent) 55%, transparent);
328 text-underline-offset: 4px;
329 transition: text-decoration-color 0.16s ease;
330 }
331
332 .legal-copy a:hover {
333 text-decoration-color: var(--accent);
334 }
335
336 .legal-notice {
337 color: var(--fg) !important;
338 font-weight: 600;
339 }
340
341 .legal-copy address {
342 margin-top: 20px;
343 }
344
345 .contact-link {
346 display: inline-block;
347 margin-top: 18px;
348 font-family: var(--font-mono);
349 font-size: 0.9rem;
350 }
351
352 @media (max-width: 820px) {
353 .legal-index-link {
354 display: inline-flex;
355 align-items: center;
356 gap: 8px;
357 margin-bottom: 38px;
358 color: var(--fg-dim);
359 font-family: var(--font-mono);
360 font-size: 0.72rem;
361 letter-spacing: 0.04em;
362 text-transform: uppercase;
363 }
364
365 .legal-page {
366 width: min(100% - 40px, 720px);
367 padding-top: 56px;
368 padding-bottom: 80px;
369 }
370
371 .legal-hero h1 {
372 font-size: clamp(3.1rem, 16vw, 5rem);
373 }
374
375 .legal-rule {
376 margin: 52px 0;
377 }
378
379 .legal-layout {
380 display: block;
381 }
382
383 .legal-nav {
384 display: none;
385 }
386
387 .legal-copy section + section {
388 margin-top: 62px;
389 padding-top: 62px;
390 }
391 }
392
393 @media (max-width: 420px) {
394 .legal-page {
395 width: calc(100% - 32px);
396 padding-top: 42px;
397 }
398
399 .legal-lede {
400 margin-top: 26px;
401 font-size: 1rem;
402 }
403
404 .legal-dates {
405 gap: 24px;
406 }
407
408 .legal-copy p,
409 .legal-copy li,
410 .legal-copy address {
411 font-size: 0.94rem;
412 }
413 }
414</style>
apps/marketing/src/layouts/Layout.astro+31−2
@@ -4,11 +4,13 @@ import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site"; · 3 unmodified lines
4interface Props {4interface Props {
5 title?: string;5 title?: string;
6 description?: string;6 description?: string;
7 pageClass?: string;
7}8}
8 9
9const {10const {
10 title = "T3 Code",11 title = "T3 Code",
11 description = "T3 Code — The open-source control plane for coding agents.",12 description = "T3 Code — The open-source control plane for coding agents.",
13 pageClass,
12} = Astro.props;14} = Astro.props;
13---15---
14 16
@@ -30,7 +32,7 @@ const { · 15 unmodified lines
30 <title>{title}</title>32 <title>{title}</title>
31 </head>33 </head>
32 <body>34 <body>
33 <div class="page">35 <div class:list={["page", pageClass]}>
34 <nav class="nav">36 <nav class="nav">
35 <div class="nav-inner">37 <div class="nav-inner">
36 <a href="/" class="nav-brand" aria-label="T3 Code home">38 <a href="/" class="nav-brand" aria-label="T3 Code home">
@@ -67,6 +69,9 @@ const { · 30 unmodified lines
67 <a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>69 <a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
68 <a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>70 <a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
69 <a href="/download">Download</a>71 <a href="/download">Download</a>
72 <a href="/terms-of-service">Terms</a>
73 <a href="/privacy-policy">Privacy</a>
74 <a href="/security-policy">Security</a>
70 </div>75 </div>
71 </div>76 </div>
72 </footer>77 </footer>
@@ -279,7 +284,7 @@ const { · 206 unmodified lines
279 min-height: 100vh;284 min-height: 100vh;
280 display: flex;285 display: flex;
281 flex-direction: column;286 flex-direction: column;
282 overflow-x: hidden;287 overflow-x: clip;
283 }288 }
284 289
285 .nav {290 .nav {
@@ -402,6 +407,8 @@ const { · 116 unmodified lines
402 407
403 .footer-links {408 .footer-links {
404 display: flex;409 display: flex;
410 flex-wrap: wrap;
411 justify-content: flex-end;
405 gap: 20px;412 gap: 20px;
406 }413 }
407 414
@@ -421,6 +428,28 @@ const { · 13 unmodified lines
421 padding-left: 20px;428 padding-left: 20px;
422 padding-right: 20px;429 padding-right: 20px;
423 }430 }
431
432 .legal-document-page .nav {
433 display: none;
434 }
435
436 .footer {
437 padding-bottom: max(32px, env(safe-area-inset-bottom));
438 }
439
440 .footer-inner {
441 align-items: flex-start;
442 flex-direction: column;
443 gap: 28px;
444 }
445
446 .footer-links {
447 display: grid;
448 grid-template-columns: repeat(3, minmax(0, 1fr));
449 width: 100%;
450 gap: 14px 20px;
451 justify-content: initial;
452 }
424 }453 }
425 454
426 @media (max-width: 420px) {455 @media (max-width: 420px) {
apps/marketing/src/lib/site.ts+1−1
@@ -1,6 +1,6 @@
1export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";1export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
2 2
3export const MARKETING_STATS = {3export const MARKETING_STATS = {
4 githubStars: "12k+",4 githubStars: "14k+",
5 users: "100,000",5 users: "100,000",
6} as const;6} as const;
apps/marketing/src/pages/index.astro+44−10
@@ -33,6 +33,9 @@ const mobileEndorsementRows = [ · 32 unmodified lines
33 <span class="hero-float-mark hf-cursor" title="Cursor">33 <span class="hero-float-mark hf-cursor" title="Cursor">
34 <img src="/harnesses/cursor_light.svg" alt="" />34 <img src="/harnesses/cursor_light.svg" alt="" />
35 </span>35 </span>
36 <span class="hero-float-mark hf-grok" title="Grok">
37 <img src="/harnesses/grok-dark.svg" alt="" />
38 </span>
36 </div>39 </div>
37 40
38 <div class="container hero-inner">41 <div class="container hero-inner">
@@ -41,7 +44,7 @@ const mobileEndorsementRows = [ · 2 unmodified lines
41 </h1>44 </h1>
42 45
43 <p class="hero-sub">46 <p class="hero-sub">
44 Orchestrate Claude Code, Codex, OpenCode and Cursor from one surface.47 Orchestrate Claude Code, Codex, OpenCode, Cursor, and Grok from one surface.
45 Bring your own subscription. Fork the whole thing.48 Bring your own subscription. Fork the whole thing.
46 </p>49 </p>
47 50
@@ -173,7 +176,7 @@ const mobileEndorsementRows = [ · 125 unmodified lines
173 <h2>Bring your own sub</h2>176 <h2>Bring your own sub</h2>
174 <p>177 <p>
175 T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,178 T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,
176 or Cursor with the credentials you already have — we orchestrate179 Cursor, or Grok with the credentials you already have — we orchestrate
177 them, you keep your plan.180 them, you keep your plan.
178 </p>181 </p>
179 </div>182 </div>
@@ -207,6 +210,13 @@ const mobileEndorsementRows = [ · 27 unmodified lines
207 <div class="harness-tag">@cursor/sdk</div>210 <div class="harness-tag">@cursor/sdk</div>
208 </div>211 </div>
209 </div>212 </div>
213 <div class="harness">
214 <div class="harness-mark"><img src="/harnesses/grok-dark.svg" alt="" /></div>
215 <div class="harness-meta">
216 <div class="harness-name">Grok CLI</div>
217 <div class="harness-tag">grok login</div>
218 </div>
219 </div>
210 </div>220 </div>
211 221
212 <div class="harness-footer">222 <div class="harness-footer">
@@ -254,7 +264,7 @@ const mobileEndorsementRows = [ · 41 unmodified lines
254 <button class="pr-button">264 <button class="pr-button">
255 <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.2"/><circle cx="6" cy="18" r="2.2"/><circle cx="18" cy="6" r="2.2"/><path d="M6 8v8M18 8v5a3 3 0 01-3 3h-3M13 13l-2 3 2 3"/></svg>265 <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.2"/><circle cx="6" cy="18" r="2.2"/><circle cx="18" cy="6" r="2.2"/><path d="M6 8v8M18 8v5a3 3 0 01-3 3h-3M13 13l-2 3 2 3"/></svg>
256 Commit &amp; push266 Commit &amp; push
257 <span class="pr-button-kbd">⌘⏎</span>267 <span id="pr-button-kbd" class="pr-button-kbd">⌘⏎</span>
258 </button>268 </button>
259 </div>269 </div>
260 </div>270 </div>
@@ -403,12 +413,14 @@ const mobileEndorsementRows = [ · 142 unmodified lines
403 const label = document.getElementById("download-label");413 const label = document.getElementById("download-label");
404 const ctaBtn = document.getElementById("cta-download-btn") as HTMLAnchorElement | null;414 const ctaBtn = document.getElementById("cta-download-btn") as HTMLAnchorElement | null;
405 const ctaLabel = document.getElementById("cta-download-label");415 const ctaLabel = document.getElementById("cta-download-label");
416 const kbd = document.getElementById("pr-button-kbd");
406 417
407 const platform = detectPlatform();418 const platform = detectPlatform();
408 if (!platform) return;419 if (!platform) return;
409 document.documentElement.dataset.platform = platform.os;420 document.documentElement.dataset.platform = platform.os;
410 if (label) label.textContent = platform.label;421 if (label) label.textContent = platform.label;
411 if (ctaLabel) ctaLabel.textContent = platform.label;422 if (ctaLabel) ctaLabel.textContent = platform.label;
423 if (kbd && platform.os !== "mac") kbd.textContent = "Ctrl ⏎";
412 424
413 try {425 try {
414 const release = await fetchLatestRelease();426 const release = await fetchLatestRelease();
@@ -613,8 +625,9 @@ const mobileEndorsementRows = [ · 198 unmodified lines
613 625
614 .hero-float-mark.hf-claude { background: radial-gradient(circle at 30% 25%, rgba(217, 119, 87, 0.22), rgba(20, 20, 24, 0.92) 65%); top: 8%; left: 7%; animation-delay: 0s; transform: rotate(-8deg); }626 .hero-float-mark.hf-claude { background: radial-gradient(circle at 30% 25%, rgba(217, 119, 87, 0.22), rgba(20, 20, 24, 0.92) 65%); top: 8%; left: 7%; animation-delay: 0s; transform: rotate(-8deg); }
615 .hero-float-mark.hf-codex { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 6%; right: 7%; animation-delay: -2.5s; transform: rotate(6deg); }627 .hero-float-mark.hf-codex { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 6%; right: 7%; animation-delay: -2.5s; transform: rotate(6deg); }
616 .hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 32%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }628 .hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 30%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
617 .hero-float-mark.hf-cursor { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 30%; right: 5%; animation-delay: -7s; transform: rotate(-5deg); }629 .hero-float-mark.hf-cursor { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 30%; right: 5%; animation-delay: -7s; transform: rotate(-5deg); }
630 .hero-float-mark.hf-grok { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 52%; left: 6%; animation-delay: -1.2s; transform: rotate(3deg); }
618 631
619 @media (max-width: 1180px) {632 @media (max-width: 1180px) {
620 .hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }633 .hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }
@@ -623,6 +636,7 @@ const mobileEndorsementRows = [ · 2 unmodified lines
623 .hero-float-mark.hf-codex { top: 2%; right: 3%; }636 .hero-float-mark.hf-codex { top: 2%; right: 3%; }
624 .hero-float-mark.hf-opencode { top: 26%; left: 2%; }637 .hero-float-mark.hf-opencode { top: 26%; left: 2%; }
625 .hero-float-mark.hf-cursor { top: 24%; right: 2%; }638 .hero-float-mark.hf-cursor { top: 24%; right: 2%; }
639 .hero-float-mark.hf-grok { top: 48%; left: 2%; transform: rotate(3deg); }
626 }640 }
627 641
628 @media (max-width: 820px) {642 @media (max-width: 820px) {
@@ -657,17 +671,18 @@ const mobileEndorsementRows = [ · 28 unmodified lines
657 height: 44px;671 height: 44px;
658 }672 }
659 673
660 /* Two above the title, two flanking the call-to-action area. */674 /* Three stacked on the left, two on the right — keeps the center CTA clear. */
661 .hero-float-mark.hf-claude {675 .hero-float-mark.hf-claude {
662 top: 44px;676 top: 44px;
663 left: 10px;677 left: 10px;
664 transform: rotate(-10deg);678 transform: rotate(-10deg);
665 }679 }
666 680
667 .hero-float-mark.hf-codex {681 .hero-float-mark.hf-grok {
668 top: 44px;682 top: 240px;
669 right: 10px;683 left: 4px;
670 transform: rotate(8deg);684 right: auto;
685 transform: rotate(-4deg);
671 }686 }
672 687
673 .hero-float-mark.hf-opencode {688 .hero-float-mark.hf-opencode {
@@ -677,6 +692,12 @@ const mobileEndorsementRows = [ · 3 unmodified lines
677 transform: rotate(-6deg);692 transform: rotate(-6deg);
678 }693 }
679 694
695 .hero-float-mark.hf-codex {
696 top: 44px;
697 right: 10px;
698 transform: rotate(8deg);
699 }
700
680 .hero-float-mark.hf-cursor {701 .hero-float-mark.hf-cursor {
681 top: 474px;702 top: 474px;
682 right: 4px;703 right: 4px;
@@ -686,6 +707,14 @@ const mobileEndorsementRows = [ · 3 unmodified lines
686 }707 }
687 708
688 @media (max-width: 340px) {709 @media (max-width: 340px) {
710 .hero-float-mark.hf-grok {
711 top: 220px;
712 left: 0;
713 width: 52px;
714 height: 52px;
715 border-radius: 14px;
716 }
717
689 .hero-float-mark.hf-opencode,718 .hero-float-mark.hf-opencode,
690 .hero-float-mark.hf-cursor {719 .hero-float-mark.hf-cursor {
691 top: 580px;720 top: 580px;
@@ -702,6 +731,7 @@ const mobileEndorsementRows = [ · 10 unmodified lines
702 right: 0;731 right: 0;
703 }732 }
704 733
734 .hero-float-mark.hf-grok img,
705 .hero-float-mark.hf-opencode img,735 .hero-float-mark.hf-opencode img,
706 .hero-float-mark.hf-cursor img {736 .hero-float-mark.hf-cursor img {
707 width: 30px;737 width: 30px;
@@ -748,7 +778,7 @@ const mobileEndorsementRows = [ · 40 unmodified lines
748 778
749 .harness-grid {779 .harness-grid {
750 display: grid;780 display: grid;
751 grid-template-columns: repeat(4, 1fr);781 grid-template-columns: repeat(5, 1fr);
752 gap: 0;782 gap: 0;
753 border: 1px solid var(--border);783 border: 1px solid var(--border);
754 border-radius: var(--radius);784 border-radius: var(--radius);
@@ -1203,6 +1233,10 @@ const mobileEndorsementRows = [ · 448 unmodified lines
1203 .harness-grid { grid-template-columns: 1fr 1fr; }1233 .harness-grid { grid-template-columns: 1fr 1fr; }
1204 .harness { border-right: 0; border-bottom: 1px solid var(--border); }1234 .harness { border-right: 0; border-bottom: 1px solid var(--border); }
1205 .harness:nth-child(odd) { border-right: 1px solid var(--border); }1235 .harness:nth-child(odd) { border-right: 1px solid var(--border); }
1236 .harness:nth-child(5):last-child {
1237 grid-column: 1 / -1;
1238 border-right: 0;
1239 }
1206 .git-inner { grid-template-columns: 1fr; gap: 40px; }1240 .git-inner { grid-template-columns: 1fr; gap: 40px; }
1207 .open-grid { grid-template-columns: 1fr; }1241 .open-grid { grid-template-columns: 1fr; }
1208 }1242 }
apps/marketing/src/pages/legal.astro+172−0
@@ -0,0 +1,172 @@
1---
2import Layout from "../layouts/Layout.astro";
3
4const documents = [
5 {
6 number: "01",
7 title: "Privacy Policy",
8 description: "How T3 Code handles information, connected services, and your privacy choices.",
9 href: "/privacy-policy",
10 },
11 {
12 number: "02",
13 title: "Terms of Service",
14 description: "The terms that govern your use of T3 Code and T3 Tools-operated services.",
15 href: "/terms-of-service",
16 },
17 {
18 number: "03",
19 title: "Security Policy",
20 description: "Our security practices, responsible disclosure process, and shared responsibilities.",
21 href: "/security-policy",
22 },
23] as const;
24---
25
26<Layout
27 title="Legal — T3 Code"
28 description="Privacy, terms, and security documents for T3 Code."
29 pageClass="legal-document-page"
30>
31 <div class="legal-index">
32 <header class="legal-index-hero">
33 <p class="eyebrow">T3 Tools, Inc. / Legal</p>
34 <h1>Legal</h1>
35 <p>Policies and terms for T3 Code, collected in one place.</p>
36 </header>
37
38 <nav class="document-list" aria-label="Legal documents">
39 {documents.map((document) => (
40 <a href={document.href} class="document-card">
41 <span class="document-number">{document.number}</span>
42 <span class="document-copy">
43 <strong>{document.title}</strong>
44 <span>{document.description}</span>
45 </span>
46 <span class="document-arrow" aria-hidden="true">&#8599;</span>
47 </a>
48 ))}
49 </nav>
50 </div>
51</Layout>
52
53<style>
54 .legal-index {
55 width: min(960px, calc(100% - 64px));
56 margin: 0 auto;
57 padding: clamp(72px, 10vw, 132px) 0 112px;
58 }
59
60 .legal-index-hero {
61 max-width: 680px;
62 animation: fade-in 0.7s ease-out both;
63 }
64
65 .legal-index h1 {
66 margin-top: 18px;
67 font-size: clamp(4rem, 10vw, 7.4rem);
68 font-weight: 500;
69 letter-spacing: -0.04em;
70 line-height: 0.9;
71 }
72
73 .legal-index-hero > p:last-child {
74 margin-top: 30px;
75 color: var(--fg-muted);
76 font-size: clamp(1.05rem, 2vw, 1.3rem);
77 line-height: 1.65;
78 }
79
80 .document-list {
81 display: grid;
82 margin-top: clamp(64px, 9vw, 96px);
83 border-top: 1px solid var(--border);
84 }
85
86 .document-card {
87 display: grid;
88 grid-template-columns: 42px minmax(0, 1fr) auto;
89 gap: 24px;
90 align-items: center;
91 padding: 30px 8px;
92 border-bottom: 1px solid var(--border);
93 transition: background-color 0.18s ease, padding 0.18s ease;
94 }
95
96 .document-number {
97 color: var(--accent);
98 font-family: var(--font-mono);
99 font-size: 0.7rem;
100 letter-spacing: 0.1em;
101 }
102
103 .document-copy {
104 display: grid;
105 gap: 7px;
106 }
107
108 .document-copy strong {
109 color: var(--fg);
110 font-size: 1.2rem;
111 font-weight: 500;
112 letter-spacing: -0.02em;
113 }
114
115 .document-copy > span {
116 color: var(--fg-dim);
117 font-size: 0.9rem;
118 line-height: 1.55;
119 }
120
121 .document-arrow {
122 color: var(--fg-dim);
123 font-size: 1.25rem;
124 transition: color 0.18s ease, transform 0.18s ease;
125 }
126
127 @media (hover: hover) and (pointer: fine) {
128 .document-card:hover {
129 padding-left: 16px;
130 padding-right: 16px;
131 background: rgba(255, 255, 255, 0.025);
132 }
133
134 .document-card:hover .document-arrow {
135 color: var(--fg);
136 transform: translate(2px, -2px);
137 }
138 }
139
140 @media (max-width: 820px) {
141 .legal-index {
142 width: min(100% - 40px, 720px);
143 padding-top: 56px;
144 padding-bottom: 80px;
145 }
146
147 .document-card {
148 grid-template-columns: 30px minmax(0, 1fr) auto;
149 gap: 14px;
150 padding: 24px 4px;
151 }
152 }
153
154 @media (max-width: 420px) {
155 .legal-index {
156 width: calc(100% - 32px);
157 padding-top: 42px;
158 }
159
160 .legal-index h1 {
161 font-size: 4.4rem;
162 }
163
164 .document-copy strong {
165 font-size: 1.08rem;
166 }
167
168 .document-copy > span {
169 font-size: 0.84rem;
170 }
171 }
172</style>
apps/marketing/src/pages/privacy-policy.astro+445−0
@@ -0,0 +1,445 @@
1---
2import LegalPage from "../components/LegalPage.astro";
3
4const sections = [
5 ["introduction", "Introduction"],
6 ["information", "Personal information we collect"],
7 ["uses", "How we use your personal information"],
8 ["sharing", "How we share your personal information"],
9 ["choices", "Your choices regarding your personal information"],
10 ["security", "Security of your personal information"],
11 ["international", "International users"],
12 ["children", "Children"],
13 ["do-not-track", "Do Not Track"],
14 ["updates", "Updates to this Privacy Policy"],
15 ["contact", "Contact us"],
16] as const;
17---
18
19<LegalPage
20 title="Privacy Policy — T3 Code"
21 description="How T3 Tools, Inc. handles information when you use T3 Code, app.t3.codes, and t3.codes."
22 heading="T3 Code Privacy Policy"
23 lede="This Privacy Policy describes how T3 Tools, Inc. collects, uses, and shares personal information when you use the T3 Code desktop, mobile, and hosted web applications, visit the t3.codes marketing site, or use the optional T3 Connect service."
24 effectiveDate="2026-07-14"
25 lastUpdated="2026-07-14"
26 sections={sections}
27>
28 <section id="introduction">
29 <p class="section-number">01</p>
30 <h2>Introduction</h2>
31 <p>
32 This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3
33 Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3
34 Code desktop and mobile applications, the hosted T3 Code web application located at
35 {" "}<a href="https://app.t3.codes">https://app.t3.codes</a>, or the optional T3 Connect
36 service (together, the “Services”), or visit the T3 Code marketing website located at
37 {" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”). This Policy applies to
38 personal information we collect through the Site and the Services, as well as personal
39 information you provide to us directly.
40 </p>
41 <p>
42 By using the Site or the Services, you acknowledge the practices described in this
43 Policy. If you do not agree with this Policy, please do not use the Site or the Services.
44 This Policy does not govern third-party coding agents, artificial-intelligence providers,
45 identity providers, or environments that you choose to connect to T3 Code; those third
46 parties process information under their own terms and privacy policies.
47 </p>
48 </section>
49
50 <section id="information">
51 <p class="section-number">02</p>
52 <h2>Personal Information We Collect</h2>
53
54 <p>
55 We collect personal information about you in different ways depending on how you use
56 T3 Code and which optional features you enable.
57 </p>
58
59 <h3>Personal Information From Users of T3 Code</h3>
60
61 <p>
62 When you use T3 Code, we may collect the following categories of personal information:
63 </p>
64 <ul>
65 <li>
66 <strong>Account information.</strong> If you create or sign in to a T3 account, we
67 receive general identifiers and profile information from our authentication provider
68 and the identity provider you select. This may include your name, email address,
69 profile image, user ID, sign-in method, and authentication credentials or tokens.
70 </li>
71 <li>
72 <strong>Environment and device information.</strong> If you enable T3 Connect, we
73 process information needed to connect and secure your environments and devices,
74 including identifiers, labels you assign, public keys, connection endpoints,
75 credential hashes, connection status, app and operating-system versions, and
76 notification preferences.
77 </li>
78 <li>
79 <strong>Agent activity and notifications.</strong> If you enable notifications or Live
80 Activities, we process push tokens and limited activity information needed to provide
81 those features, such as project and thread titles, model name, status, and activity
82 headline.
83 </li>
84 <li>
85 <strong>Information you provide to us.</strong> We collect information that you choose
86 to provide when you request support, send feedback, or otherwise communicate with us.
87 </li>
88 </ul>
89
90 <h3>Personal Information From Users of Our Site Generally</h3>
91 <p>
92 When you visit the Site or use online portions of the Services, we and our service
93 providers may automatically log online identifiers and internet-activity information,
94 including your Internet Protocol (IP) address, device and operating-system type, browser
95 or app type and version, pages viewed, access times, request timestamps, connection
96 events, latency, error details, and diagnostic traces. The amount of information we
97 collect depends on the Services you use and your device and browser settings.
98 </p>
99 <p>
100 We use operational and diagnostic information to provide, secure, maintain, and
101 troubleshoot the Services, not for targeted advertising.
102 </p>
103
104 <h3>Information We Get From Others</h3>
105 <p>
106 We may receive personal information from service providers that help us operate the
107 Services, such as authentication and identity providers, app stores, device-platform
108 providers, and coding-agent providers you choose to use. We may combine this information
109 with information we collect through the Site and the Services.
110 </p>
111
112 <h3>Cookies and Local Storage</h3>
113 <p>
114 The Site and online portions of the Services may use cookies or similar technologies to
115 operate essential features, maintain sessions, remember preferences, and understand
116 whether the Services are functioning correctly. T3 Code also stores connection settings,
117 credentials, preferences, drafts, and cached thread, file, branch, and server metadata on
118 your device. Credentials and session tokens use platform-provided protected storage where
119 supported. Information stored only on your device is not collected by T3 Tools unless it
120 is transmitted as part of a feature you use.
121 </p>
122
123 <h3>Device Permissions</h3>
124 <ul>
125 <li>
126 <strong>Camera.</strong> Used when you choose to scan a pairing QR code. Camera frames
127 are processed on your device.
128 </li>
129 <li>
130 <strong>Photos and files.</strong> Items you select are accessed only to preview them or
131 attach them to a request you initiate.
132 </li>
133 <li>
134 <strong>Notifications.</strong> Used only if you enable agent-status notifications or
135 Live Activities.
136 </li>
137 <li>
138 <strong>Local network.</strong> Used to discover or connect to T3 Code environments
139 accessible from your machine over the network.
140 </li>
141 </ul>
142 </section>
143
144 <section id="uses">
145 <p class="section-number">03</p>
146 <h2>How We Use Your Personal Information</h2>
147 <p>
148 Subject to this Policy and applicable terms governing third-party applications and
149 services, we may use personal information for the following purposes:
150 </p>
151 <ul>
152 <li>To establish and verify your identity and authenticate your account;</li>
153 <li>To link and protect devices and environments and deliver optional notifications;</li>
154 <li>To process and fulfill requests you make through the Services;</li>
155 <li>To provide customer service and respond to support requests and feedback;</li>
156 <li>To communicate with you about the Services and your relationship with us;</li>
157 <li>To monitor reliability, prevent abuse, and investigate security incidents;</li>
158 <li>To comply with applicable law and enforce the terms governing the Services; and</li>
159 <li>
160 To analyze and improve T3 Code using aggregated, de-identified, or other anonymous
161 operational information.
162 </li>
163 </ul>
164
165 <h3>Training of AI Models</h3>
166 <p>
167 We do not use your personal information, source code, prompts, or agent responses to
168 train artificial-intelligence models.
169 </p>
170
171 <h3>Compliance and Protection</h3>
172 <p>We may use personal information to:</p>
173 <ul>
174 <li>Comply with applicable laws, lawful requests, and legal process;</li>
175 <li>Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;</li>
176 <li>Audit our internal processes for legal, contractual, and policy compliance;</li>
177 <li>Enforce the terms and conditions that govern the Site and the Services; and</li>
178 <li>
179 Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized,
180 unethical, or illegal activity, including cyberattacks and identity theft.
181 </li>
182 </ul>
183 <p>
184 We may also use personal information for other purposes consistent with this Policy or
185 explained to you when we collect the information.
186 </p>
187 </section>
188
189 <section id="sharing">
190 <p class="section-number">04</p>
191 <h2>How We Share Your Personal Information</h2>
192 <p>
193 We may disclose the categories of personal information described above to the following
194 categories of third parties:
195 </p>
196
197 <h3>Providers You Choose</h3>
198 <p>
199 At your direction, prompts, files, and related content are sent to coding agents and
200 artificial-intelligence providers configured in your environment. Because you bring and
201 configure your own coding-agent harness and provider, the applicable third parties vary.
202 Those providers process information under their own terms and privacy policies.
203 </p>
204
205 <h3>Third-Party Service Providers</h3>
206 <p>
207 We use third-party service providers to help provide the Services and operate our
208 business. Depending on the features you use, these providers may include:
209 </p>
210 <ul class="provider-list">
211 <li>
212 <strong>Clerk</strong> <em>(Clerk, Inc.)</em>.<br />
213 We use Clerk to provide account authentication.<br />
214 You can view Clerk's privacy policy here:{" "}<a href="https://clerk.com/legal/privacy"
215 >https://clerk.com/legal/privacy</a
216 >.
217 </li>
218 <li>
219 <strong>Cloudflare</strong> <em>(Cloudflare, Inc.)</em>.<br />
220 We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.<br />
221 You can view Cloudflare's privacy policy here:{" "}<a
222 href="https://www.cloudflare.com/policies/privacy/"
223 >https://www.cloudflare.com/policies/privacy/</a
224 >.
225 </li>
226 <li>
227 <strong>PlanetScale</strong> <em>(PlanetScale, Inc.)</em>.<br />
228 We use PlanetScale to host the database that supports T3 Connect.<br />
229 You can view PlanetScale's privacy policy here:{" "}<a
230 href="https://planetscale.com/legal/privacy"
231 >https://planetscale.com/legal/privacy</a
232 >.
233 </li>
234 <li>
235 <strong>Vercel</strong> <em>(Vercel Inc.)</em>.<br />
236 We use Vercel to host and deploy the T3 Code Site.<br />
237 You can view Vercel's privacy notice here:{" "}<a
238 href="https://vercel.com/legal/privacy-notice"
239 >https://vercel.com/legal/privacy-notice</a
240 >.
241 </li>
242 <li>
243 <strong>Axiom</strong> <em>(Axiom, Inc.)</em>.<br />
244 We use Axiom for operational diagnostics that help us maintain and troubleshoot the
245 Services.<br />
246 You can view Axiom's privacy policy here:{" "}<a
247 href="https://axiom.co/docs/legal/privacy">https://axiom.co/docs/legal/privacy</a
248 >.
249 </li>
250 <li>
251 <strong>Expo</strong> <em>(650 Industries, Inc.)</em>.<br />
252 We use Expo for application updates and related mobile-app services.<br />
253 You can view Expo's privacy policy here:{" "}<a href="https://expo.dev/privacy"
254 >https://expo.dev/privacy</a
255 >.
256 </li>
257 <li>
258 <strong>Apple</strong> <em>(Apple Inc.)</em>.<br />
259 We use Apple services for app distribution, optional authentication, and platform
260 notifications.<br />
261 You can view Apple's privacy policy here:{" "}<a
262 href="https://www.apple.com/legal/privacy/">https://www.apple.com/legal/privacy/</a
263 >.
264 </li>
265 <li>
266 <strong>Google</strong> <em>(Google LLC)</em>.<br />
267 We use Google services for app distribution and optional authentication.<br />
268 You can view Google's privacy policy here:{" "}<a
269 href="https://policies.google.com/privacy">https://policies.google.com/privacy</a
270 >.
271 </li>
272 </ul>
273 <p>
274 These providers process information for us under their own contractual and privacy
275 obligations.
276 </p>
277
278 <h3>Affiliates and Professional Advisors</h3>
279 <p>
280 We may share personal information with our affiliates for purposes consistent with this
281 Policy and with lawyers, accountants, bankers, and other professional advisors in the
282 course of the services they provide to us.
283 </p>
284
285 <h3>Corporate Restructuring</h3>
286 <p>
287 We may share some or all personal information in connection with or during negotiation of
288 a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of
289 assets, or similar transaction. If another company acquires T3 Tools or its assets, that
290 company may possess the personal information collected by us and assume the rights and
291 obligations described in this Policy.
292 </p>
293
294 <h3>Legal and Safety Disclosures</h3>
295 <p>
296 We may disclose personal information if we believe in good faith that disclosure is
297 necessary to comply with law or legal process; protect or defend the rights, property, or
298 safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent
299 fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the
300 Services. We may also share personal information at your direction, with your consent, or
301 as described to you when the information is collected.
302 </p>
303
304 <h3>No Sale of Personal Information</h3>
305 <p>
306 We do not sell your personal information or share it for cross-context behavioral or
307 targeted advertising.
308 </p>
309
310 <h3>Third-Party Websites and Services</h3>
311 <p>
312 The Site and the Services may contain links to third-party websites or services. When you
313 follow a third-party link or connect a third-party service, that third party may collect
314 personal information from you. We do not control and are not responsible for the privacy
315 practices or content of third parties.
316 </p>
317 </section>
318
319 <section id="choices">
320 <p class="section-number">05</p>
321 <h2>Your Choices Regarding Your Personal Information</h2>
322
323 <h3>Account and Connection Choices</h3>
324 <p>
325 You may use local or direct connections without signing in to a T3 account. You can
326 disconnect environments, sign out, disable optional notifications and Live Activities,
327 and clear local caches from Settings. You can grant or revoke camera, photo, local-network,
328 and notification permissions in your device settings.
329 </p>
330
331 <h3>Cookies and Local Data</h3>
332 <p>
333 You can use your browser settings to stop accepting or to delete cookies, although some
334 portions of the Site or the Services may not function correctly as a result. Information
335 stored only on your device remains there until you clear it, remove the relevant
336 connection, or uninstall the app. The mobile app provides cache controls under
337 {" "}<strong>Settings → App → Client Storage</strong>.
338 </p>
339
340 <h3>Retention and Deletion</h3>
341 <p>
342 We retain account, environment-link, device-registration, notification, and security
343 information while your account or the relevant feature is active and for as long as
344 reasonably necessary to provide the Services, protect them from abuse, comply with law,
345 and resolve disputes. Operational diagnostic traces are configured to expire after 30
346 days. Some records may remain longer in backups or where retention is required for
347 security, fraud prevention, or legal compliance.
348 </p>
349 <p>
350 To request deletion of your T3 account and associated T3 Connect data, email{" "}<a
351 href="mailto:privacy@t3.tools">privacy@t3.tools</a
352 >{" "}from the email address associated with your account. We may need to verify your
353 identity. Deleting a T3 account does not delete information held by an environment or
354 coding-agent provider you control; contact those providers or delete that information
355 directly.
356 </p>
357
358 <h3>Your Privacy Rights</h3>
359 <p>
360 Depending on where you live, you may have rights to request access to, correction of,
361 deletion of, or a portable copy of your personal information, or to restrict or object
362 to certain processing. You may also have the right to appeal our response or complain to
363 a data-protection authority. We will honor applicable rights after verifying your
364 request.
365 </p>
366 </section>
367
368 <section id="security">
369 <p class="section-number">06</p>
370 <h2>Security of Your Personal Information</h2>
371 <p>
372 T3 Tools is committed to protecting the security of your personal information. We use
373 administrative, technical, and organizational safeguards designed to protect personal
374 information from unauthorized access, use, or disclosure. These safeguards include
375 encrypted network transport, scoped and proof-bound access tokens for supported
376 connection flows, protected credential storage, and redaction of authorization headers
377 from relay diagnostics.
378 </p>
379 <p>
380 No method of transmission over the Internet or method of electronic storage is completely
381 secure. While we use reasonable efforts to protect personal information, we cannot
382 guarantee its absolute security. You are responsible for securing the environments,
383 coding-agent accounts, credentials, and networks that you connect to T3 Code.
384 </p>
385 </section>
386
387 <section id="international">
388 <p class="section-number">07</p>
389 <h2>International Users</h2>
390 <p>
391 The Site and the Services are provided from the United States and are governed by United
392 States law. If you use the Site or the Services from outside the United States, your
393 personal information may be transferred to and processed in the United States and other
394 countries where we or our service providers operate. Where required, we use lawful
395 safeguards for international transfers of personal information.
396 </p>
397 </section>
398
399 <section id="children">
400 <p class="section-number">08</p>
401 <h2>Children</h2>
402 <p>
403 The Site and the Services are not intended for children under 13 years of age, and you
404 must be at least 13 years old to use them. We do not knowingly collect, use, or disclose
405 personal information from children under 13. If you believe a child under 13 has provided
406 us with personal information, please contact us so that we can take appropriate action.
407 </p>
408 </section>
409
410 <section id="do-not-track">
411 <p class="section-number">09</p>
412 <h2>Do Not Track</h2>
413 <p>
414 We currently do not respond to browser “Do Not Track” signals. T3 Code does not use
415 personal information for cross-context behavioral or targeted advertising.
416 </p>
417 </section>
418
419 <section id="updates">
420 <p class="section-number">10</p>
421 <h2>Updates to This Privacy Policy</h2>
422 <p>
423 We reserve the right to update this Policy from time to time. If we make material changes,
424 we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date”
425 above, and provide any additional notice required by law. Except as otherwise indicated,
426 changes become effective when the revised Policy is posted.
427 </p>
428 </section>
429
430 <section id="contact">
431 <p class="section-number">11</p>
432 <h2>Contact Us</h2>
433 <p>
434 If you have questions about this Policy or wish to make a privacy or deletion request,
435 please contact us at:
436 </p>
437 <address>
438 <strong>T3 Tools, Inc.</strong><br />
439 2261 Market Street #5309<br />
440 San Francisco, CA 94114<br />
441 United States
442 </address>
443 <a class="contact-link" href="mailto:privacy@t3.tools">privacy@t3.tools</a>
444 </section>
445</LegalPage>
apps/marketing/src/pages/security-policy.astro+187−0
@@ -0,0 +1,187 @@
1---
2import LegalPage from "../components/LegalPage.astro";
3
4const sections = [
5 ["introduction", "Introduction"],
6 ["reporting", "Reporting security issues"],
7 ["safe-harbor", "Responsible research and safe harbor"],
8 ["practices", "Our security practices"],
9 ["responsibilities", "Your responsibilities"],
10 ["updates", "Updates to this policy"],
11 ["contact", "Contact us"],
12] as const;
13---
14
15<LegalPage
16 title="Security Policy — T3 Code"
17 description="How to report security issues in T3 Code and how T3 Tools approaches product security."
18 heading="T3 Code Security Policy"
19 lede="Security is a shared responsibility. This policy explains how to report a vulnerability, how we protect T3 Tools-operated services, and how you can secure the environments and providers you connect to T3 Code."
20 effectiveDate="2026-07-15"
21 lastUpdated="2026-07-15"
22 sections={sections}
23>
24 <section id="introduction">
25 <p class="section-number">01</p>
26 <h2>Introduction</h2>
27 <p>
28 This Security Policy describes the vulnerability-reporting process and security practices for
29 the T3 Code desktop and mobile applications, the hosted application at{" "}<a
30 href="https://app.t3.codes">https://app.t3.codes</a
31 >, the optional T3 Connect service, and the T3 Code website at{" "}<a href="https://t3.codes"
32 >https://t3.codes</a
33 >.
34 </p>
35 <p>
36 T3 Code connects software running on your devices and in environments you control with
37 coding-agent harnesses and providers you choose. We secure the software and infrastructure
38 operated by T3 Tools, but we do not control the security of your devices, environments,
39 repositories, networks, credentials, or third-party providers. Please review the shared
40 responsibilities below when assessing risk.
41 </p>
42 </section>
43
44 <section id="reporting">
45 <p class="section-number">02</p>
46 <h2>Reporting Security Issues</h2>
47 <p>
48 If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated
49 infrastructure, email{" "}<a href="mailto:security@ping.gg">security@ping.gg</a>. Please do not
50 disclose the issue publicly until we have had a reasonable opportunity to investigate and
51 remediate it.
52 </p>
53 <p>Please include, when available:</p>
54 <ul>
55 <li>A description of the issue and its potential impact;</li>
56 <li>The affected application, version, URL, endpoint, or component;</li>
57 <li>Clear reproduction steps or a minimal proof of concept;</li>
58 <li>Relevant logs, screenshots, or request and response details with secrets removed; and</li>
59 <li>Your preferred contact information and whether you want public credit.</li>
60 </ul>
61 <p>
62 We aim to acknowledge complete reports within one business day, keep reporters informed of
63 material progress, and coordinate disclosure after a fix is available. Resolution time varies
64 with severity, complexity, and dependencies on third parties.
65 </p>
66 </section>
67
68 <section id="safe-harbor">
69 <p class="section-number">03</p>
70 <h2>Responsible Research and Safe Harbor</h2>
71 <p>
72 We support good-faith security research. If you make a genuine effort to comply with this
73 policy, avoid harm, respect privacy, and report findings promptly, we will treat your research
74 as authorized and will not initiate legal action against you for accidental, good-faith
75 violations of this policy. If a third party initiates legal action concerning compliant
76 research, we will make our authorization known where appropriate.
77 </p>
78 <p>To remain within this safe harbor, you must:</p>
79 <ul>
80 <li>Test only accounts, data, and systems you own or have explicit permission to test;</li>
81 <li>Stop and report immediately if you encounter personal, confidential, or production data;</li>
82 <li>Access only the minimum information needed to demonstrate the issue;</li>
83 <li>Avoid disrupting availability, degrading performance, or damaging or deleting data;</li>
84 <li>Not use social engineering, phishing, physical attacks, or denial-of-service testing;</li>
85 <li>Not test third-party services or infrastructure outside T3 Tools’ control; and</li>
86 <li>Give us reasonable time to address the issue before public disclosure.</li>
87 </ul>
88 <p>
89 This safe harbor does not authorize violations of law or activity outside the scope of this
90 policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools
91 in its discretion.
92 </p>
93 </section>
94
95 <section id="practices">
96 <p class="section-number">04</p>
97 <h2>Our Security Practices</h2>
98 <p>
99 We use administrative, technical, and organizational safeguards designed for the nature of T3
100 Code and the information processed by T3 Tools-operated services. These practices include:
101 </p>
102 <ul>
103 <li>
104 <strong>Data minimization.</strong> T3 Code is designed so coding-session content can remain
105 between your clients, your environment, and the harnesses and providers you configure. We
106 process information through T3 Tools-operated infrastructure only when needed for a feature
107 you enable.
108 </li>
109 <li>
110 <strong>Encrypted transport.</strong> T3 Tools-operated network services use encrypted
111 transport. Supported connection flows use scoped credentials and security controls designed
112 to reduce unauthorized reuse.
113 </li>
114 <li>
115 <strong>Credential protection.</strong> T3 Code uses platform-provided protected storage for
116 credentials and session tokens where supported. We design operational logging to avoid
117 collecting secrets that are not needed to operate or troubleshoot the Services.
118 </li>
119 <li>
120 <strong>Access controls.</strong> Access to production systems and operational data is limited
121 according to job responsibilities and protected using authentication and authorization
122 controls.
123 </li>
124 <li>
125 <strong>Maintenance and monitoring.</strong> We monitor T3 Tools-operated services for
126 reliability and security events, review dependencies, and deploy updates and mitigations as
127 appropriate.
128 </li>
129 <li>
130 <strong>Established providers.</strong> We use specialized providers for services such as
131 authentication, hosting, and application distribution and evaluate the controls relevant to
132 their role.
133 </li>
134 </ul>
135 <p>
136 No system is completely secure. These practices reduce risk but do not guarantee that the Site
137 or Services will be free from vulnerabilities or unauthorized access.
138 </p>
139 </section>
140
141 <section id="responsibilities">
142 <p class="section-number">05</p>
143 <h2>Your Responsibilities</h2>
144 <p>
145 Because you control much of the T3 Code execution path, you play an important role in securing
146 it. You are responsible for:
147 </p>
148 <ul>
149 <li>Keeping T3 Code, your operating systems, and connected tools up to date;</li>
150 <li>Securing your devices, repositories, environments, networks, and backups;</li>
151 <li>Protecting account, provider, repository, and environment credentials;</li>
152 <li>Using multi-factor authentication where your identity and coding-agent providers support it;</li>
153 <li>Granting providers and integrations only the permissions they need;</li>
154 <li>Reviewing commands, source changes, and other agent output before applying or executing it;</li>
155 <li>Removing lost or unused devices and revoking credentials you believe may be compromised; and</li>
156 <li>Following the security policies of your selected harnesses, providers, and infrastructure.</li>
157 </ul>
158 <p>
159 Do not send passwords, API keys, access tokens, or private keys in a vulnerability report.
160 Revoke any secret that may have been exposed before sharing sanitized evidence with us.
161 </p>
162 </section>
163
164 <section id="updates">
165 <p class="section-number">06</p>
166 <h2>Updates to This Policy</h2>
167 <p>
168 We may update this Security Policy as T3 Code, our infrastructure, and security practices
169 evolve. We will post revisions at this URL and update the dates above. Material changes to the
170 vulnerability-reporting process or safe-harbor terms will apply prospectively.
171 </p>
172 </section>
173
174 <section id="contact">
175 <p class="section-number">07</p>
176 <h2>Contact Us</h2>
177 <p>
178 Report security issues or ask security-related questions at{" "}<a
179 href="mailto:security@ping.gg">security@ping.gg</a
180 >.
181 </p>
182 <p>
183 For general legal questions, contact{" "}<a href="mailto:legal@t3.tools">legal@t3.tools</a>.
184 For privacy requests, contact{" "}<a href="mailto:privacy@t3.tools">privacy@t3.tools</a>.
185 </p>
186 </section>
187</LegalPage>
apps/marketing/src/pages/terms-of-service.astro+396−0
@@ -0,0 +1,396 @@
1---
2import LegalPage from "../components/LegalPage.astro";
3
4const sections = [
5 ["introduction", "Introduction"],
6 ["accounts", "Accounts"],
7 ["content", "Your content and providers"],
8 ["rights", "T3 Code and proprietary rights"],
9 ["acceptable-use", "Acceptable use"],
10 ["availability", "Availability and changes"],
11 ["fees", "Fees"],
12 ["privacy", "Privacy"],
13 ["termination", "Suspension and termination"],
14 ["beta", "Beta services"],
15 ["disclaimers", "Disclaimers"],
16 ["liability", "Limitation of liability"],
17 ["indemnification", "Indemnification"],
18 ["copyright", "Copyright complaints"],
19 ["third-parties", "Third-party services"],
20 ["feedback", "Feedback"],
21 ["disputes", "Dispute resolution"],
22 ["miscellaneous", "Miscellaneous"],
23 ["changes", "Changes to these Terms"],
24 ["contact", "Contact us"],
25] as const;
26---
27
28<LegalPage
29 title="Terms of Service — T3 Code"
30 description="The terms that govern your use of T3 Code, app.t3.codes, T3 Connect, and t3.codes."
31 heading="T3 Code Terms of Service"
32 lede="These Terms govern your use of T3 Code, including its desktop, mobile, and hosted applications, the optional T3 Connect service, and the t3.codes website."
33 effectiveDate="2026-07-15"
34 lastUpdated="2026-07-15"
35 sections={sections}
36>
37 <section id="introduction">
38 <p class="section-number">01</p>
39 <h2>Introduction</h2>
40 <p>
41 These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc.
42 (“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop
43 and mobile applications, the hosted T3 Code application at{" "}<a href="https://app.t3.codes"
44 >https://app.t3.codes</a
45 >, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code
46 marketing website at{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”).
47 </p>
48 <p>
49 By accessing or using the Site or Services, you agree to these Terms. If you use the Services
50 for an organization, you represent that you have authority to bind that organization, and
51 “you” includes the organization. If you do not agree to these Terms, do not use the Site or
52 Services.
53 </p>
54 <p>
55 You must be at least 13 years old to use the Site or Services. If the law where you live
56 requires a greater age to enter into these Terms, you must meet that requirement or have a
57 parent or legal guardian agree on your behalf.
58 </p>
59 </section>
60
61 <section id="accounts">
62 <p class="section-number">02</p>
63 <h2>Accounts</h2>
64 <p>
65 You can use some T3 Code features without creating a T3 account. An account may be required
66 for account-backed features, including T3 Connect. You agree to provide accurate account
67 information, keep your credentials secure, and promptly notify us if you suspect unauthorized
68 access. You are responsible for activity performed through your account and connected devices,
69 except to the extent caused by our failure to use reasonable security measures.
70 </p>
71 <p>
72 You may not share credentials in a way that compromises the Services, impersonate another
73 person, or create accounts through unauthorized automated means. We may require reasonable
74 verification before restoring access or acting on an account request.
75 </p>
76 </section>
77
78 <section id="content">
79 <p class="section-number">03</p>
80 <h2>Your Content and Providers</h2>
81 <p>
82 T3 Code can help you send prompts, source files, images, attachments, review comments, and
83 instructions to coding-agent harnesses and providers you choose, and display their responses,
84 command output, file changes, source code, and diffs (collectively, “User Content”). You retain
85 all rights you have in your User Content.
86 </p>
87 <p>
88 You bring and configure your own coding-agent harness and provider. Your User Content is
89 ordinarily processed in the environment you control and by the providers you select, not by
90 T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User
91 Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and
92 process that content only as reasonably necessary to provide, secure, and troubleshoot that
93 feature. This license ends when the content is no longer needed for those purposes, subject to
94 reasonable backup, security, and legal-retention requirements.
95 </p>
96 <p>
97 You represent that you have the rights and permissions needed to use and submit User Content
98 and to direct its processing by your selected harnesses and providers. You are responsible for
99 reviewing those providers’ terms, privacy practices, data controls, and output before using
100 them with confidential, proprietary, regulated, or personal information.
101 </p>
102 </section>
103
104 <section id="rights">
105 <p class="section-number">04</p>
106 <h2>T3 Code and Proprietary Rights</h2>
107 <p>
108 T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted
109 infrastructure, documentation, and other materials, excluding User Content and third-party
110 materials. These Terms do not transfer ownership of either party’s intellectual property.
111 </p>
112 <p>
113 Portions of T3 Code are available as open-source software. Your use, copying, modification, and
114 distribution of that source code are governed by the license included with the applicable
115 repository or component. These Terms govern your use of the hosted Services and do not limit
116 rights granted to you by an applicable open-source license.
117 </p>
118 <p>
119 Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right
120 to access and use the Services for lawful personal or internal business purposes. You may not
121 use our trademarks, service marks, or trade dress without written permission.
122 </p>
123 </section>
124
125 <section id="acceptable-use">
126 <p class="section-number">05</p>
127 <h2>Acceptable Use</h2>
128 <p>You may not use the Site or Services to:</p>
129 <ul>
130 <li>Violate applicable law or another person’s rights;</li>
131 <li>Upload, transmit, or generate content you do not have the right to use;</li>
132 <li>Distribute malware, exploit code, or harmful content except in authorized security work;</li>
133 <li>Probe, attack, disrupt, or gain unauthorized access to the Services or another system;</li>
134 <li>Bypass rate limits, access controls, security measures, or usage restrictions;</li>
135 <li>Interfere with other users or place an unreasonable load on shared infrastructure;</li>
136 <li>Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or</li>
137 <li>Misrepresent that output or activity from a third-party agent was produced or endorsed by us.</li>
138 </ul>
139 <p>
140 Authorized security research must follow our{" "}<a href="/security-policy">Security Policy</a>.
141 We may investigate suspected violations and take proportionate action to protect users and the
142 Services.
143 </p>
144 </section>
145
146 <section id="availability">
147 <p class="section-number">06</p>
148 <h2>Availability and Changes</h2>
149 <p>
150 We may add, change, suspend, or discontinue features, integrations, or supported platforms. We
151 aim to provide reasonable notice when a change materially reduces an account-backed feature,
152 but urgent security, legal, or reliability changes may take effect immediately. The Services
153 may be unavailable because of maintenance, provider outages, network conditions, or events
154 outside our control.
155 </p>
156 <p>
157 T3 Code depends on software, environments, networks, and coding-agent providers that you
158 configure or that third parties operate. We do not control their availability, compatibility,
159 pricing, or behavior.
160 </p>
161 </section>
162
163 <section id="fees">
164 <p class="section-number">07</p>
165 <h2>Fees</h2>
166 <p>
167 T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state
168 otherwise for a feature. You remain responsible for charges from your coding-agent providers,
169 cloud infrastructure, network operators, app stores, and other third parties. If we introduce
170 a paid feature, we will present its price and applicable payment terms before you purchase it.
171 </p>
172 </section>
173
174 <section id="privacy">
175 <p class="section-number">08</p>
176 <h2>Privacy</h2>
177 <p>
178 Our{" "}<a href="/privacy-policy">Privacy Policy</a> explains how T3 Tools collects, uses, and
179 shares personal information when you use the Site and Services. Third-party environments,
180 harnesses, identity providers, and coding-agent providers process information under their own
181 terms and privacy policies.
182 </p>
183 </section>
184
185 <section id="termination">
186 <p class="section-number">09</p>
187 <h2>Suspension and Termination</h2>
188 <p>
189 You may stop using the Services at any time. You may disconnect environments and devices from
190 within T3 Code and may request deletion of an account as described in our Privacy Policy.
191 </p>
192 <p>
193 We may suspend or terminate access to account-backed or hosted features if we reasonably
194 believe you materially violated these Terms, created a security or legal risk, failed to pay an
195 applicable fee, or used the Services in a way that could harm other users or shared
196 infrastructure. When practicable, we will give notice and an opportunity to cure. We may act
197 immediately where needed to prevent harm or comply with law.
198 </p>
199 <p>
200 Provisions that by their nature should survive termination—including ownership, disclaimers,
201 limitations of liability, indemnification, and dispute terms—will survive.
202 </p>
203 </section>
204
205 <section id="beta">
206 <p class="section-number">10</p>
207 <h2>Beta Services</h2>
208 <p>
209 T3 Code is an early-stage product, and some or all features may be identified as alpha, beta,
210 preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete,
211 change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole
212 copy of important work, and review proposed commands and file changes before applying them.
213 </p>
214 </section>
215
216 <section id="disclaimers">
217 <p class="section-number">11</p>
218 <h2>Disclaimers</h2>
219 <p class="legal-notice">
220 TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SITE AND SERVICES ARE PROVIDED “AS IS” AND “AS
221 AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF
222 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
223 </p>
224 <p>
225 Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete,
226 or harmful output. You are responsible for reviewing output, commands, patches, and other
227 actions before relying on or executing them. We do not warrant that the Services or third-party
228 output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose.
229 </p>
230 <p>
231 Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not
232 apply to you.
233 </p>
234 </section>
235
236 <section id="liability">
237 <p class="section-number">12</p>
238 <h2>Limitation of Liability</h2>
239 <p class="legal-notice">
240 TO THE MAXIMUM EXTENT PERMITTED BY LAW, T3 TOOLS AND ITS AFFILIATES, OFFICERS, EMPLOYEES,
241 AGENTS, AND LICENSORS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,
242 EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS
243 OPPORTUNITIES, ARISING FROM OR RELATED TO THE SITE, SERVICES, OR THESE TERMS.
244 </p>
245 <p>
246 To the maximum extent permitted by law, our aggregate liability for all claims arising from or
247 relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount
248 you paid directly to T3 Tools for the Services during the 12 months before the event giving rise
249 to the claim. These limitations apply regardless of the legal theory and even if a remedy fails
250 of its essential purpose. They do not limit liability that cannot lawfully be limited.
251 </p>
252 </section>
253
254 <section id="indemnification">
255 <p class="section-number">13</p>
256 <h2>Indemnification</h2>
257 <p>
258 To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its
259 affiliates, officers, employees, and agents from third-party claims, damages, losses, and
260 reasonable legal fees arising from your User Content, your use of the Site or Services in
261 violation of these Terms or law, or your infringement of another person’s rights. We will
262 promptly notify you of a covered claim and reasonably cooperate in its defense. You may not
263 settle a claim in a way that admits fault by or imposes obligations on us without our written
264 consent.
265 </p>
266 </section>
267
268 <section id="copyright">
269 <p class="section-number">14</p>
270 <h2>Copyright Complaints</h2>
271 <p>
272 If you believe material available through a T3 Tools-operated part of the Site or Services
273 infringes your copyright, send a notice to{" "}<a href="mailto:legal@t3.tools">legal@t3.tools</a
274 >{" "}identifying the copyrighted work, the allegedly infringing material and its location, your
275 contact information, a statement of good-faith belief, a statement under penalty of perjury
276 that the notice is accurate and you are authorized to act, and your physical or electronic
277 signature.
278 </p>
279 <p>
280 T3 Tools does not control content stored only in a user’s environment or held by a user-selected
281 provider. Requests concerning that material should be directed to the operator that hosts it.
282 </p>
283 </section>
284
285 <section id="third-parties">
286 <p class="section-number">15</p>
287 <h2>Third-Party Services</h2>
288 <p>
289 The Services may connect to or display content from third-party coding agents, model providers,
290 identity providers, repositories, app stores, websites, and infrastructure. Your use of those
291 services is governed by their terms. We do not endorse or control third-party services and are
292 not responsible for their content, security, availability, output, or data practices.
293 </p>
294 <p>
295 Third-party and open-source software included with T3 Code is governed by its applicable
296 license notices. Where those licenses conflict with these Terms for that software, the
297 applicable open-source license controls.
298 </p>
299 </section>
300
301 <section id="feedback">
302 <p class="section-number">16</p>
303 <h2>Feedback</h2>
304 <p>
305 If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a
306 perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback
307 without restriction or compensation. This does not transfer ownership of your User Content.
308 </p>
309 </section>
310
311 <section id="disputes">
312 <p class="section-number">17</p>
313 <h2>Dispute Resolution</h2>
314 <p class="legal-notice">
315 PLEASE READ THIS SECTION CAREFULLY. IT REQUIRES MOST DISPUTES TO BE RESOLVED BY INDIVIDUAL
316 BINDING ARBITRATION AND WAIVES JURY TRIALS AND CLASS OR REPRESENTATIVE ACTIONS.
317 </p>
318 <h3>Informal Resolution</h3>
319 <p>
320 Before starting arbitration or a court proceeding, the party raising a dispute must send a
321 written notice describing the dispute and requested relief. Notices to us must be sent to{" "}<a
322 href="mailto:legal@t3.tools">legal@t3.tools</a
323 >. The parties will try in good faith to resolve the dispute for at least 30 days.
324 </p>
325 <h3>Binding Arbitration</h3>
326 <p>
327 Except for disputes eligible for small-claims court and requests for injunctive relief to
328 protect intellectual property or prevent unauthorized access, unresolved disputes will be
329 resolved by binding individual arbitration administered by JAMS under its applicable consumer
330 or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may
331 take place remotely unless the arbitrator determines that an in-person hearing is necessary.
332 </p>
333 <h3>No Class Actions</h3>
334 <p>
335 Disputes must be brought only on an individual basis. Neither party may participate in a class,
336 collective, consolidated, or representative action or arbitration to the extent permitted by
337 law.
338 </p>
339 <h3>Opt Out</h3>
340 <p>
341 You may opt out of this arbitration agreement by emailing{" "}<a href="mailto:legal@t3.tools"
342 >legal@t3.tools</a
343 > within 30 days after you first accept these Terms. Include your name, the email associated
344 with your account if any, and a clear statement that you opt out of arbitration.
345 </p>
346 <p>
347 If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the
348 state and federal courts located in San Francisco County, California, and each party consents
349 to those courts.
350 </p>
351 </section>
352
353 <section id="miscellaneous">
354 <p class="section-number">18</p>
355 <h2>Miscellaneous</h2>
356 <p>
357 California law governs these Terms without regard to conflict-of-law principles, except that
358 the Federal Arbitration Act governs the arbitration provisions. These Terms and documents
359 incorporated by reference are the entire agreement between you and us regarding the Site and
360 Services. If a provision is unenforceable, it will be modified to the minimum extent necessary
361 or severed, and the remaining provisions will continue in effect.
362 </p>
363 <p>
364 Our failure to enforce a provision is not a waiver. You may not assign these Terms without our
365 written consent. We may assign them in connection with a merger, acquisition, reorganization,
366 or sale of assets. We are not liable for delays or failures caused by events beyond our
367 reasonable control. Headings are for convenience only, and “including” means “including without
368 limitation.”
369 </p>
370 </section>
371
372 <section id="changes">
373 <p class="section-number">19</p>
374 <h2>Changes to These Terms</h2>
375 <p>
376 We may update these Terms from time to time. We will post updated Terms at this URL and update
377 the dates above. If a change materially affects your rights, we will provide additional notice
378 when reasonably practicable or as required by law. Changes apply prospectively from their
379 effective date. Your continued use of the Site or Services after that date means you accept the
380 updated Terms.
381 </p>
382 </section>
383
384 <section id="contact">
385 <p class="section-number">20</p>
386 <h2>Contact Us</h2>
387 <p>If you have questions about these Terms, contact us at:</p>
388 <address>
389 <strong>T3 Tools, Inc.</strong><br />
390 2261 Market Street #5309<br />
391 San Francisco, CA 94114<br />
392 United States
393 </address>
394 <a class="contact-link" href="mailto:legal@t3.tools">legal@t3.tools</a>
395 </section>
396</LegalPage>
apps/mobile/.swiftlint.yml+1−0
@@ -1,6 +1,7 @@
1included:1included:
2 - ios/T3Code2 - ios/T3Code
3 - modules/t3-composer-editor/ios3 - modules/t3-composer-editor/ios
4 - modules/t3-native-controls/ios
4 - modules/t3-terminal/ios5 - modules/t3-terminal/ios
5 - modules/t3-review-diff/ios6 - modules/t3-review-diff/ios
6 7
apps/mobile/README.md+24−0
@@ -34,6 +34,30 @@ Build and run the local iOS dev client: · 33 unmodified lines
34vp run ios:dev34vp run ios:dev
35```35```
36 36
37If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
38reduced-capability local build. Personal Team builds omit the widget and share extensions, push
39entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.
40
41```bash
42T3CODE_IOS_PERSONAL_TEAM=1 \
43T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code.dev \
44vp run ios:dev
45```
46
47Build and install a self-contained Release app that does not need Metro:
48
49```bash
50vp run ios:release
51```
52
53The Personal Team equivalent also needs a unique bundle identifier:
54
55```bash
56T3CODE_IOS_PERSONAL_TEAM=1 \
57T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code \
58vp run ios:release
59```
60
37Build and run the local iOS preview app:61Build and run the local iOS preview app:
38 62
39```bash63```bash
apps/mobile/app.config.ts+212−47
@@ -1,5 +1,6 @@
1import type { ExpoConfig } from "expo/config";1import type { ExpoConfig } from "expo/config";
2 2
3import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
3import { loadRepoEnv } from "../../scripts/lib/public-config.ts";4import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
4 5
5type AppVariant = "development" | "preview" | "production";6type AppVariant = "development" | "preview" | "production";
@@ -8,43 +9,82 @@ const repoEnv = loadRepoEnv(); · 2 unmodified lines
8Object.assign(process.env, repoEnv);9Object.assign(process.env, repoEnv);
9 10
10const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);11const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
12const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
11 13
12const VARIANT_CONFIG: Record<14const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
13 AppVariant,15const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
14 {16
15 readonly appName: string;17const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
16 readonly scheme: string;18
17 readonly iosIcon: string;19if (
18 readonly iosBundleIdentifier: string;20 isIosPersonalTeamBuild &&
19 readonly androidPackage: string;21 (!personalTeamBundleIdentifier ||
20 readonly relyingParty?: string;22 !IOS_BUNDLE_IDENTIFIER_PATTERN.test(personalTeamBundleIdentifier))
21 }23) {
22> = {24 throw new Error(
25 "T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID must be a reverse-DNS identifier such as com.example.t3code when T3CODE_IOS_PERSONAL_TEAM=1.",
26 );
27}
28
29const DEVELOPMENT_ASSETS = {
30 appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
31 iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject),
32 splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
33 androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.developmentUniversalIconPng),
34 androidAdaptiveBackgroundColor: "#00639B",
35 androidMonochromeIcon: "./assets/android-icon-mark.png",
36 androidNotificationIcon: "./assets/android-notification-icon.png",
37 androidNotificationColor: "#00639B",
38} as const;
39
40const PREVIEW_ASSETS = {
41 appIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
42 iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIconComposerProject),
43 splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
44 androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.nightlyLinuxIconPng),
45 androidAdaptiveBackgroundColor: "#111533",
46 androidMonochromeIcon: "./assets/android-icon-mark.png",
47 androidNotificationIcon: "./assets/android-notification-icon.png",
48 androidNotificationColor: "#7565C7",
49} as const;
50
51const RELEASE_ASSETS = {
52 appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
53 iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject),
54 splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
55 androidAdaptiveForeground: "./assets/android-icon-mark.png",
56 androidAdaptiveBackgroundColor: "#000000",
57 androidMonochromeIcon: "./assets/android-icon-mark.png",
58 androidNotificationIcon: "./assets/android-notification-icon.png",
59 androidNotificationColor: "#FFFFFF",
60} as const;
61
62const VARIANT_CONFIG = {
23 development: {63 development: {
24 appName: "T3 Code Dev",64 appName: "T3 Code Dev",
25 scheme: "t3code-dev",65 scheme: "t3code-dev",
26 iosIcon: "./assets/icon-composer-dev.icon",
27 iosBundleIdentifier: "com.t3tools.t3code.dev",66 iosBundleIdentifier: "com.t3tools.t3code.dev",
28 androidPackage: "com.t3tools.t3code.dev",67 androidPackage: "com.t3tools.t3code.dev",
29 relyingParty: "clerk.t3.codes",68 relyingParty: "clerk.t3.codes",
69 assets: DEVELOPMENT_ASSETS,
30 },70 },
31 preview: {71 preview: {
32 appName: "T3 Code Preview",72 appName: "T3 Code Preview",
33 scheme: "t3code-preview",73 scheme: "t3code-preview",
34 iosIcon: "./assets/icon-composer-prod.icon",
35 iosBundleIdentifier: "com.t3tools.t3code.preview",74 iosBundleIdentifier: "com.t3tools.t3code.preview",
36 androidPackage: "com.t3tools.t3code.preview",75 androidPackage: "com.t3tools.t3code.preview",
37 relyingParty: "clerk.t3.codes",76 relyingParty: "clerk.t3.codes",
77 assets: PREVIEW_ASSETS,
38 },78 },
39 production: {79 production: {
40 appName: "T3 Code",80 appName: "T3 Code",
41 scheme: "t3code",81 scheme: "t3code",
42 iosIcon: "./assets/icon-composer-prod.icon",
43 iosBundleIdentifier: "com.t3tools.t3code",82 iosBundleIdentifier: "com.t3tools.t3code",
44 androidPackage: "com.t3tools.t3code",83 androidPackage: "com.t3tools.t3code",
45 relyingParty: "clerk.t3.codes",84 relyingParty: "clerk.t3.codes",
85 assets: RELEASE_ASSETS,
46 },86 },
47};87} as const;
48 88
49function resolveAppVariant(value: string | undefined): AppVariant {89function resolveAppVariant(value: string | undefined): AppVariant {
50 switch (value) {90 switch (value) {
@@ -58,6 +98,63 @@ function resolveAppVariant(value: string | undefined): AppVariant { · 7 unmodified lines
58}98}
59 99
60const variant = VARIANT_CONFIG[APP_VARIANT];100const variant = VARIANT_CONFIG[APP_VARIANT];
101const iosBundleIdentifier = isIosPersonalTeamBuild
102 ? personalTeamBundleIdentifier!
103 : variant.iosBundleIdentifier;
104
105const dmSansFonts = {
106 regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
107 medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf",
108 bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf",
109} as const;
110
111const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
112 "expo-widgets",
113 {
114 bundleIdentifier: `${iosBundleIdentifier}.widgets`,
115 groupIdentifier: `group.${iosBundleIdentifier}`,
116 enablePushNotifications: true,
117 // Agent activity can update many times an hour; without the
118 // frequent-updates entitlement iOS throttles the update budget sooner.
119 frequentUpdates: true,
120 widgets: [
121 {
122 name: "AgentActivity",
123 displayName: "Agent Activity",
124 description: "Shows the current state of active T3 Code agents.",
125 supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
126 },
127 ],
128 },
129];
130
131const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
132 "expo-sharing",
133 {
134 ios: {
135 // Personal Teams cannot sign App Groups or extension targets. Keep the
136 // reduced-capability local build usable while release builds expose the
137 // real system share target.
138 enabled: !isIosPersonalTeamBuild,
139 extensionBundleIdentifier: `${iosBundleIdentifier}.sharing`,
140 appGroupId: `group.${iosBundleIdentifier}`,
141 activationRule: {
142 supportsText: true,
143 supportsWebUrlWithMaxCount: 1,
144 supportsImageWithMaxCount: 8,
145 },
146 },
147 android: {
148 enabled: true,
149 singleShareMimeTypes: ["text/plain", "image/*"],
150 multipleShareMimeTypes: ["image/*"],
151 },
152 },
153];
154
155// These aliases match the fonts' PostScript names on iOS. Register the same
156// names on Android so React Native and the native composer use one set of
157// family names without waiting for runtime font loading.
61 158
62const config: ExpoConfig = {159const config: ExpoConfig = {
63 name: variant.appName,160 name: variant.appName,
@@ -66,10 +163,14 @@ const config: ExpoConfig = { · 2 unmodified lines
66 scheme: variant.scheme,163 scheme: variant.scheme,
67 version: "0.1.0",164 version: "0.1.0",
68 runtimeVersion: {165 runtimeVersion: {
69 policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",166 // Fingerprint (not appVersion) so an OTA only reaches binaries whose native
167 // project — native deps, config plugins, AND patches/ — matches the update.
168 // With appVersion, every 0.1.0 build shares a runtime version, so a JS update
169 // could land on a binary missing the native changes it needs and crash.
170 policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
70 },171 },
71 orientation: "portrait",172 orientation: "portrait",
72 icon: "./assets/icon.png",173 icon: variant.assets.appIcon,
73 userInterfaceStyle: "automatic",174 userInterfaceStyle: "automatic",
74 updates: {175 updates: {
75 enabled: true,176 enabled: true,
@@ -78,9 +179,13 @@ const config: ExpoConfig = { · 2 unmodified lines
78 fallbackToCacheTimeout: 0,179 fallbackToCacheTimeout: 0,
79 },180 },
80 ios: {181 ios: {
81 icon: variant.iosIcon,182 icon: variant.assets.iosIcon,
82 supportsTablet: true,183 supportsTablet: true,
83 bundleIdentifier: variant.iosBundleIdentifier,184 bundleIdentifier: iosBundleIdentifier,
185 // Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
186 // does not fall back to a personal team (which cannot sign app groups,
187 // Sign in with Apple, or push notification entitlements).
188 appleTeamId: "ARK85ZXQ4Z",
84 associatedDomains: [189 associatedDomains: [
85 `applinks:${variant.relyingParty}`,190 `applinks:${variant.relyingParty}`,
86 `webcredentials:${variant.relyingParty}`,191 `webcredentials:${variant.relyingParty}`,
@@ -95,41 +200,94 @@ const config: ExpoConfig = { · 8 unmodified lines
95 },200 },
96 },201 },
97 android: {202 android: {
98 icon: "./assets/icon.png",203 icon: variant.assets.appIcon,
99 package: variant.androidPackage,204 package: variant.androidPackage,
100 adaptiveIcon: {205 adaptiveIcon: {
101 backgroundColor: "#E6F4FE",206 backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
102 foregroundImage: "./assets/android-icon-foreground.png",207 foregroundImage: variant.assets.androidAdaptiveForeground,
103 backgroundImage: "./assets/android-icon-background.png",208 monochromeImage: variant.assets.androidMonochromeIcon,
104 monochromeImage: "./assets/android-icon-monochrome.png",
105 },209 },
106 predictiveBackGestureEnabled: false,210 // Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
211 // JS back handling survives it via react-native's Android 16 shim plus
212 // withAndroidPredictiveBackCompat on Android 13-15.
213 predictiveBackGestureEnabled: true,
107 },214 },
108 web: {215 web: {
109 favicon: "./assets/favicon.png",216 favicon: variant.assets.appIcon,
110 },217 },
111 plugins: [218 plugins: [
112 "expo-router",219 "expo-asset",
113 "expo-font",220 [
221 "expo-font",
222 {
223 ios: {
224 fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold],
225 },
226 android: {
227 fonts: [
228 {
229 fontFamily: "DMSans-Regular",
230 fontDefinitions: [{ path: dmSansFonts.regular, weight: 400 }],
231 },
232 {
233 fontFamily: "DMSans-Medium",
234 fontDefinitions: [{ path: dmSansFonts.medium, weight: 500 }],
235 },
236 {
237 fontFamily: "DMSans-Bold",
238 fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }],
239 },
240 ],
241 },
242 },
243 ],
114 "expo-secure-store",244 "expo-secure-store",
115 ["@clerk/expo", { theme: "./clerk-theme.json" }],245 "expo-sqlite",
246 ...(isIosPersonalTeamBuild
247 ? [sharingPlugin]
248 : ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),
249 [
250 "expo-notifications",
251 {
252 icon: variant.assets.androidNotificationIcon,
253 color: variant.assets.androidNotificationColor,
254 mode: APP_VARIANT === "development" ? "development" : "production",
255 },
256 ],
257 // appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before
258 // plugins earlier in this array, so it cannot strip the entitlement Clerk would add.
259 ["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],
116 "expo-web-browser",260 "expo-web-browser",
261 [
262 "expo-quick-actions",
263 {
264 // Adaptive launcher-shortcut icon; referenced by resource name from
265 // the shortcut items set in src/features/shortcuts.
266 androidIcons: {
267 shortcut_icon: {
268 foregroundImage: variant.assets.androidAdaptiveForeground,
269 backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
270 },
271 },
272 },
273 ],
117 [274 [
118 "expo-camera",275 "expo-camera",
119 {276 {
120 cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",277 cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
121 barcodeScannerEnabled: true,278 barcodeScannerEnabled: true,
279 recordAudioAndroid: false,
122 },280 },
123 ],281 ],
124 [282 [
125 "expo-splash-screen",283 "expo-splash-screen",
126 {284 {
127 image: "./assets/splash-icon.png",285 image: variant.assets.splashIcon,
128 resizeMode: "contain",286 resizeMode: "contain",
129 backgroundColor: "#ffffff",287 backgroundColor: "#ffffff",
130 imageWidth: 220,288 imageWidth: 220,
131 dark: {289 dark: {
132 image: "./assets/splash-icon.png",290 image: variant.assets.splashIcon,
133 backgroundColor: "#0a0a0a",291 backgroundColor: "#0a0a0a",
134 },292 },
135 },293 },
@@ -147,26 +305,24 @@ const config: ExpoConfig = { · 11 unmodified lines
147 },305 },
148 },306 },
149 ],307 ],
150 [308 "./plugins/withIosCocoaPodsUuidCache.cjs",
151 "expo-widgets",309 // Must be listed BEFORE expo-widgets: same-type mods run last-registered-
152 {310 // first, so registering earlier makes this plugin's mods run AFTER
153 bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,311 // expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
154 groupIdentifier: `group.${variant.iosBundleIdentifier}`,312 // would delete the asset catalog) and its xcodeproj mod creates the widget
155 enablePushNotifications: true,313 // target (which must exist before the compile phase can be attached).
156 widgets: [314 ...(!isIosPersonalTeamBuild ? ["./plugins/withWidgetLogoAsset.cjs", widgetsPlugin] : []),
157 {315 "./plugins/withIosSceneLifecycle.cjs",
158 name: "AgentActivity",
159 displayName: "Agent Activity",
160 description: "Shows the current state of active T3 Code agents.",
161 supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
162 },
163 ],
164 },
165 ],
166 "./plugins/withAndroidCleartextTraffic.cjs",316 "./plugins/withAndroidCleartextTraffic.cjs",
317 "./plugins/withAndroidGradleHeap.cjs",
318 "./plugins/withAndroidModernPopupMenu.cjs",
319 "./plugins/withAndroidModernAlertDialog.cjs",
320 "./plugins/withAndroidPredictiveBackCompat.cjs",
321 ...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
167 ],322 ],
168 extra: {323 extra: {
169 appVariant: APP_VARIANT,324 appVariant: APP_VARIANT,
325 iosPersonalTeamBuild: isIosPersonalTeamBuild,
170 relay: {326 relay: {
171 url: repoEnv.T3CODE_RELAY_URL ?? null,327 url: repoEnv.T3CODE_RELAY_URL ?? null,
172 },328 },
@@ -174,6 +330,15 @@ const config: ExpoConfig = { · 1 unmodified line
174 publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,330 publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
175 jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,331 jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
176 },332 },
333 // Native Google sign-in credentials. @clerk/expo reads these from `extra`
334 // under their exact env-var names (not nested), and its config plugin reads
335 // the iOS URL scheme at prebuild to register it in Info.plist.
336 // Unset values must be omitted (not null): the public manifest serializes
337 // null to {}, which is truthy and would defeat Clerk's fallback checks.
338 EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
339 EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
340 EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
341 EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
177 observability: {342 observability: {
178 tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",343 tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
179 tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,344 tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
apps/mobile/assets/android-icon-background.png+0−0

Binary file not shown.

apps/mobile/assets/android-icon-foreground.png+0−0

Binary file not shown.

apps/mobile/assets/android-icon-mark.png+0−0

Binary file not shown.

apps/mobile/assets/android-icon-monochrome.png+0−0

Binary file not shown.

apps/mobile/assets/android-notification-icon.png+0−0

Binary file not shown.

apps/mobile/assets/favicon.png+0−0

Binary file not shown.

apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg+0−0

Binary file not shown.

apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png+0−0

Binary file not shown.

apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg+0−3
@@ -1,3 +0,0 @@
1<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
2<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
3</svg>
apps/mobile/assets/icon.png+0−0

Binary file not shown.

apps/mobile/assets/splash-icon.png+0−0

Binary file not shown.

apps/mobile/assets/widget/T3Mark.svg+3−0
@@ -0,0 +1,3 @@
1<svg width="111" height="74" viewBox="7 29 111 74" fill="none" xmlns="http://www.w3.org/2000/svg">
2<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="black"/>
3</svg>
apps/mobile/eas.json+16−5
@@ -6,25 +6,31 @@ · 5 unmodified lines
6 },6 },
7 "build": {7 "build": {
8 "development": {8 "development": {
9 "corepack": true,
9 "env": {10 "env": {
10 "APP_VARIANT": "development"11 "APP_VARIANT": "development",
12 "NODE_OPTIONS": "--max-old-space-size=4096"
11 },13 },
12 "channel": "development",14 "channel": "development",
13 "developmentClient": true,15 "developmentClient": true,
14 "distribution": "internal"16 "distribution": "internal"
15 },17 },
16 "preview": {18 "preview": {
19 "corepack": true,
17 "env": {20 "env": {
18 "APP_VARIANT": "preview"21 "APP_VARIANT": "preview",
22 "NODE_OPTIONS": "--max-old-space-size=4096"
19 },23 },
20 "channel": "preview",24 "channel": "preview",
21 "environment": "preview",25 "environment": "preview",
22 "distribution": "internal"26 "distribution": "internal"
23 },27 },
24 "preview:dev": {28 "preview:dev": {
29 "corepack": true,
25 "env": {30 "env": {
26 "APP_VARIANT": "preview",31 "APP_VARIANT": "preview",
27 "MOBILE_VERSION_POLICY": "fingerprint"32 "MOBILE_VERSION_POLICY": "fingerprint",
33 "NODE_OPTIONS": "--max-old-space-size=4096"
28 },34 },
29 "channel": "preview",35 "channel": "preview",
30 "environment": "preview",36 "environment": "preview",
@@ -35,8 +41,10 @@ · 4 unmodified lines
35 }41 }
36 },42 },
37 "production": {43 "production": {
44 "corepack": true,
38 "env": {45 "env": {
39 "APP_VARIANT": "production"46 "APP_VARIANT": "production",
47 "NODE_OPTIONS": "--max-old-space-size=4096"
40 },48 },
41 "channel": "production",49 "channel": "production",
42 "environment": "production",50 "environment": "production",
@@ -46,7 +54,10 @@ · 3 unmodified lines
46 "submit": {54 "submit": {
47 "production": {55 "production": {
48 "ios": {56 "ios": {
49 "ascAppId": "6761315631"57 "ascAppId": "6787819824"
58 },
59 "android": {
60 "track": "internal"
50 }61 }
51 }62 }
52 }63 }
apps/mobile/global.css+29−26
@@ -12,7 +12,7 @@ · 11 unmodified lines
12 /* Card / surface */12 /* Card / surface */
13 --color-card: #ffffff;13 --color-card: #ffffff;
14 --color-card-alt: #f5f5f5;14 --color-card-alt: #f5f5f5;
15 --color-card-translucent: rgba(255, 255, 255, 0.94);15 --color-card-translucent: rgba(255, 255, 255, 0.8);
16 16
17 /* Text */17 /* Text */
18 --color-foreground: #262626;18 --color-foreground: #262626;
@@ -51,6 +51,7 @@ · 32 unmodified lines
51 /* Inputs */51 /* Inputs */
52 --color-input: #ffffff;52 --color-input: #ffffff;
53 --color-input-border: rgba(0, 0, 0, 0.1);53 --color-input-border: rgba(0, 0, 0, 0.1);
54 --color-sidebar-search: rgba(118, 118, 128, 0.12);
54 --color-placeholder: #a3a3a3;55 --color-placeholder: #a3a3a3;
55 56
56 /* Icons */57 /* Icons */
@@ -105,7 +106,7 @@ · 48 unmodified lines
105 /* Card / surface */106 /* Card / surface */
106 --color-card: #171717;107 --color-card: #171717;
107 --color-card-alt: #1c1c1c;108 --color-card-alt: #1c1c1c;
108 --color-card-translucent: rgba(17, 17, 17, 0.94);109 --color-card-translucent: rgba(17, 17, 17, 0.8);
109 110
110 /* Text */111 /* Text */
111 --color-foreground: #f5f5f5;112 --color-foreground: #f5f5f5;
@@ -144,6 +145,7 @@ · 32 unmodified lines
144 /* Inputs */145 /* Inputs */
145 --color-input: #141414;146 --color-input: #141414;
146 --color-input-border: rgba(255, 255, 255, 0.08);147 --color-input-border: rgba(255, 255, 255, 0.08);
148 --color-sidebar-search: rgba(118, 118, 128, 0.24);
147 --color-placeholder: #8e8e93;149 --color-placeholder: #8e8e93;
148 150
149 /* Icons */151 /* Icons */
@@ -194,41 +196,42 @@ · 44 unmodified lines
194 196
195/* ─── Typography ────────────────────────────────────────────────────── */197/* ─── Typography ────────────────────────────────────────────────────── */
196@theme {198@theme {
197 --font-sans: "DMSans_400Regular";199 /* Keep these native family names aligned with app.config.ts. */
198 --font-medium: "DMSans_500Medium";200 --font-sans: "DMSans-Regular";
199 --font-bold: "DMSans_700Bold";201 --font-medium: "DMSans-Medium";
202 --font-bold: "DMSans-Bold";
200 203
201 /* Keep this scale aligned with src/lib/typography.ts for native style props. */204 /* Keep this scale aligned with src/lib/typography.ts for native style props. */
202 --text-3xs: 10px;205 --text-3xs: 11px;
203 --text-3xs--line-height: 13px;206 --text-3xs--line-height: 14px;
204 --text-2xs: 11px;207 --text-2xs: 12px;
205 --text-2xs--line-height: 15px;208 --text-2xs--line-height: 16px;
206 --text-xs: 12px;209 --text-xs: 13px;
207 --text-xs--line-height: 16px;210 --text-xs--line-height: 17px;
208 --text-sm: 13px;211 --text-sm: 14px;
209 --text-sm--line-height: 18px;212 --text-sm--line-height: 19px;
210 --text-base: 15px;213 --text-base: 16px;
211 --text-base--line-height: 22px;214 --text-base--line-height: 23px;
212 --text-lg: 17px;215 --text-lg: 18px;
213 --text-lg--line-height: 22px;216 --text-lg--line-height: 23px;
214 --text-xl: 20px;217 --text-xl: 21px;
215 --text-xl--line-height: 26px;218 --text-xl--line-height: 28px;
216 --text-2xl: 24px;219 --text-2xl: 26px;
217 --text-2xl--line-height: 30px;220 --text-2xl--line-height: 32px;
218 --text-3xl: 28px;221 --text-3xl: 30px;
219 --text-3xl--line-height: 34px;222 --text-3xl--line-height: 36px;
220}223}
221 224
222/* ─── Custom utilities ──────────────────────────────────────────────── */225/* ─── Custom utilities ──────────────────────────────────────────────── */
223@utility font-t3-medium {226@utility font-t3-medium {
224 font-family: "DMSans_500Medium";227 font-family: var(--font-medium);
225}228}
226 229
227@utility font-t3-bold {230@utility font-t3-bold {
228 font-family: "DMSans_700Bold";231 font-family: var(--font-bold);
229}232}
230 233
231@utility font-t3-extrabold {234@utility font-t3-extrabold {
232 font-family: "DMSans_700Bold";235 font-family: var(--font-bold);
233 font-weight: 800;236 font-weight: 800;
234}237}
apps/mobile/index.ts+15−1
@@ -1,2 +1,16 @@
1import { registerRootComponent } from "expo";
1import "react-native-gesture-handler";2import "react-native-gesture-handler";
2import "expo-router/entry";3import { LogBox } from "react-native";
4import { featureFlags } from "react-native-screens";
5
6import App from "./src/App";
7
8// Required for react-native-screens' iOS FormSheet sizing fix when a nested
9// native stack is rendered inside a non-fitToContents formSheet.
10featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
11
12if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
13 LogBox.ignoreAllLogs();
14}
15
16registerRootComponent(App);
apps/mobile/metro.config.js+9−0
@@ -6,6 +6,7 @@ const { withUniwindConfig } = require("uniwind/metro"); · 5 unmodified lines
6/** @type {import("expo/metro-config").MetroConfig} */6/** @type {import("expo/metro-config").MetroConfig} */
7const config = getDefaultConfig(__dirname);7const config = getDefaultConfig(__dirname);
8const workspaceRoot = path.resolve(__dirname, "../..");8const workspaceRoot = path.resolve(__dirname, "../..");
9const escapedWorkspaceRoot = workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] }));10const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] }));
10const resolveShikiDependencyRoot = (packageName) => {11const resolveShikiDependencyRoot = (packageName) => {
11 const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] });12 const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] });
@@ -25,6 +26,14 @@ const resolveShikiDependencyRoot = (packageName) => { · 13 unmodified lines
25config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];26config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
26config.resolver = {27config.resolver = {
27 ...config.resolver,28 ...config.resolver,
29 blockList: [
30 ...(Array.isArray(config.resolver?.blockList)
31 ? config.resolver.blockList
32 : config.resolver?.blockList
33 ? [config.resolver.blockList]
34 : []),
35 new RegExp(`${escapedWorkspaceRoot}[/\\\\]\\.t3[/\\\\].*`),
36 ],
28 extraNodeModules: {37 extraNodeModules: {
29 // oxlint-disable-next-line unicorn/no-useless-fallback-in-spread38 // oxlint-disable-next-line unicorn/no-useless-fallback-in-spread
30 ...(config.resolver?.extraNodeModules ?? {}),39 ...(config.resolver?.extraNodeModules ?? {}),
apps/mobile/modules/t3-composer-editor/android/build.gradle+19−0
@@ -0,0 +1,19 @@
1apply plugin: 'com.android.library'
2apply plugin: 'org.jetbrains.kotlin.android'
3
4group = 'com.t3tools.composereditor'
5version = '0.0.0'
6
7android {
8 namespace 'expo.modules.t3composereditor'
9 compileSdk rootProject.ext.compileSdkVersion
10
11 defaultConfig {
12 minSdkVersion rootProject.ext.minSdkVersion
13 targetSdkVersion rootProject.ext.targetSdkVersion
14 }
15}
16
17dependencies {
18 implementation project(':expo-modules-core')
19}
apps/mobile/modules/t3-composer-editor/android/src/main/AndroidManifest.xml+1−0
@@ -0,0 +1 @@
1<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt+72−0
@@ -0,0 +1,72 @@
1package expo.modules.t3composereditor
2
3import expo.modules.kotlin.modules.Module
4import expo.modules.kotlin.modules.ModuleDefinition
5
6class T3ComposerEditorModule : Module() {
7 override fun definition() = ModuleDefinition {
8 Name("T3ComposerEditor")
9
10 View(T3ComposerEditorView::class) {
11 Prop("controlledDocumentJson") { view: T3ComposerEditorView, documentJson: String ->
12 view.setControlledDocumentJson(documentJson)
13 }
14 Prop("themeJson") { view: T3ComposerEditorView, themeJson: String ->
15 view.setThemeJson(themeJson)
16 }
17 Prop("placeholder") { view: T3ComposerEditorView, placeholder: String ->
18 view.setPlaceholder(placeholder)
19 }
20 Prop("fontFamily") { view: T3ComposerEditorView, fontFamily: String ->
21 view.setFontFamily(fontFamily)
22 }
23 Prop("fontSize") { view: T3ComposerEditorView, fontSize: Double ->
24 view.setFontSize(fontSize.toFloat())
25 }
26 Prop("lineHeight") { view: T3ComposerEditorView, lineHeight: Double ->
27 view.setLineHeight(lineHeight.toFloat())
28 }
29 Prop("contentInsetVertical") { view: T3ComposerEditorView, contentInsetVertical: Double ->
30 view.setContentInsetVertical(contentInsetVertical.toInt())
31 }
32
33 Prop("singleLineCentered") { view: T3ComposerEditorView, singleLineCentered: Boolean ->
34 view.setSingleLineCentered(singleLineCentered)
35 }
36 Prop("editable") { view: T3ComposerEditorView, editable: Boolean ->
37 view.setEditable(editable)
38 }
39 Prop("scrollEnabled") { view: T3ComposerEditorView, scrollEnabled: Boolean ->
40 view.setScrollEnabled(scrollEnabled)
41 }
42 Prop("autoFocus") { view: T3ComposerEditorView, autoFocus: Boolean ->
43 view.setAutoFocus(autoFocus)
44 }
45 Prop("autoCorrect") { view: T3ComposerEditorView, autoCorrect: Boolean ->
46 view.setAutoCorrect(autoCorrect)
47 }
48 Prop("spellCheck") { view: T3ComposerEditorView, spellCheck: Boolean ->
49 view.setSpellCheck(spellCheck)
50 }
51
52 Events(
53 "onComposerChange",
54 "onComposerSelectionChange",
55 "onComposerFocus",
56 "onComposerBlur",
57 "onComposerPasteImages",
58 "onComposerContentSizeChange",
59 )
60
61 AsyncFunction("focus") { view: T3ComposerEditorView ->
62 view.focusEditor()
63 }
64 AsyncFunction("blur") { view: T3ComposerEditorView ->
65 view.blurEditor()
66 }
67 AsyncFunction("setSelection") { view: T3ComposerEditorView, start: Int, end: Int ->
68 view.setSelection(start, end)
69 }
70 }
71 }
72}
apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt+480−0
@@ -0,0 +1,480 @@
1package expo.modules.t3composereditor
2
3import android.content.Context
4import android.content.ClipboardManager
5import android.graphics.Color
6import android.graphics.Canvas
7import android.graphics.Paint
8import android.graphics.RectF
9import android.graphics.Typeface
10import android.text.Editable
11import android.text.InputType
12import android.text.Spanned
13import android.text.TextWatcher
14import android.text.style.ReplacementSpan
15import android.view.Gravity
16import android.view.ViewGroup
17import android.view.inputmethod.InputMethodManager
18import android.widget.EditText
19import expo.modules.kotlin.AppContext
20import expo.modules.kotlin.viewevent.EventDispatcher
21import expo.modules.kotlin.views.ExpoView
22import org.json.JSONObject
23import kotlin.math.max
24
25class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
26 context,
27 appContext
28) {
29 private val editor = SelectionAwareEditText(context)
30 private val onComposerChange by EventDispatcher()
31 private val onComposerSelectionChange by EventDispatcher()
32 private val onComposerFocus by EventDispatcher()
33 private val onComposerBlur by EventDispatcher()
34 private val onComposerPasteImages by EventDispatcher()
35 private val onComposerContentSizeChange by EventDispatcher()
36 private var applyingNativeValue = false
37 private var desiredLineHeightPx = 0
38 private var lastContentHeight = 0
39 private var contentInsetVertical = 0
40 private var tokensJson = "[]"
41 private var tokens: List<ComposerToken> = emptyList()
42 private var chipTheme = ComposerChipTheme.default()
43 private var autoCorrect = true
44 private var spellCheck = true
45 private var nativeEventCount = 0
46
47 init {
48 editor.setBackgroundColor(Color.TRANSPARENT)
49 editor.gravity = Gravity.TOP or Gravity.START
50 editor.includeFontPadding = false
51 editor.isSingleLine = false
52 editor.minLines = 1
53 editor.inputType =
54 InputType.TYPE_CLASS_TEXT or
55 InputType.TYPE_TEXT_FLAG_MULTI_LINE or
56 InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
57 editor.setTextColor(Color.BLACK)
58 editor.setHintTextColor(Color.GRAY)
59 editor.setPadding(0, 0, 0, 0)
60 editor.selectionListener = { start, end ->
61 if (!applyingNativeValue) {
62 emitSelectionChange(start, end)
63 }
64 }
65 editor.pasteImagesListener = { uris ->
66 onComposerPasteImages(mapOf("uris" to uris))
67 }
68 editor.setOnFocusChangeListener { _, hasFocus ->
69 if (hasFocus) {
70 onComposerFocus(emptyMap<String, Any>())
71 } else {
72 onComposerBlur(emptyMap<String, Any>())
73 }
74 }
75 editor.addTextChangedListener(
76 object : TextWatcher {
77 override fun beforeTextChanged(
78 text: CharSequence?,
79 start: Int,
80 count: Int,
81 after: Int
82 ) = Unit
83 override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) = Unit
84
85 override fun afterTextChanged(editable: Editable?) {
86 if (applyingNativeValue) return
87 val nextValue = editable.toString()
88 val selection = currentSelectionPayload()
89 nativeEventCount += 1
90 onComposerChange(
91 mapOf(
92 "value" to nextValue,
93 "selection" to selection,
94 "eventCount" to nativeEventCount,
95 ),
96 )
97 emitContentSizeIfNeeded()
98 }
99 },
100 )
101 editor.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> emitContentSizeIfNeeded() }
102 addView(
103 editor,
104 LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
105 )
106 }
107
108 @Suppress("ReturnCount")
109 fun setControlledDocumentJson(documentJson: String) {
110 val document = try {
111 JSONObject(documentJson)
112 } catch (_: Exception) {
113 return
114 }
115 val mostRecentEventCount = document.optInt("mostRecentEventCount", -1)
116 if (mostRecentEventCount < nativeEventCount) return
117
118 val value = document.optString("value")
119 if (document.optBoolean("isNativeEcho") && editor.text.toString() != value) return
120
121 val nextTokensJson = document.optString("tokensJson", "[]")
122 val nextTokens = if (nextTokensJson == tokensJson) tokens else parseTokens(nextTokensJson)
123 val requestedSelection = document.optJSONObject("selection")
124 val previousSelectionStart = editor.selectionStart.coerceAtLeast(0)
125 val previousSelectionEnd = editor.selectionEnd.coerceAtLeast(0)
126 val valueChanged = editor.text.toString() != value
127
128 applyingNativeValue = true
129 try {
130 if (valueChanged) {
131 editor.setText(value)
132 }
133 tokensJson = nextTokensJson
134 tokens = nextTokens
135 applyTokenSpans()
136 if (requestedSelection != null) {
137 applySelection(
138 requestedSelection.optInt("start", previousSelectionStart),
139 requestedSelection.optInt("end", previousSelectionEnd),
140 )
141 } else if (valueChanged) {
142 applySelection(previousSelectionStart, previousSelectionEnd)
143 }
144 } finally {
145 applyingNativeValue = false
146 }
147 emitContentSizeIfNeeded()
148 }
149
150 fun setThemeJson(themeJson: String) {
151 try {
152 val theme = JSONObject(themeJson)
153 editor.setTextColor(parseColor(theme.optString("text"), Color.BLACK))
154 editor.setHintTextColor(parseColor(theme.optString("placeholder"), Color.GRAY))
155 chipTheme = ComposerChipTheme(
156 chipBackground = parseColor(theme.optString("chipBackground"), chipTheme.chipBackground),
157 chipBorder = parseColor(theme.optString("chipBorder"), chipTheme.chipBorder),
158 chipText = parseColor(theme.optString("chipText"), chipTheme.chipText),
159 skillBackground = parseColor(
160 theme.optString("skillBackground"),
161 chipTheme.skillBackground,
162 ),
163 skillBorder = parseColor(theme.optString("skillBorder"), chipTheme.skillBorder),
164 skillText = parseColor(theme.optString("skillText"), chipTheme.skillText),
165 )
166 applyTokenSpans()
167 } catch (_: Exception) {
168 }
169 }
170
171 fun setPlaceholder(placeholder: String) {
172 editor.hint = placeholder
173 }
174
175 fun setFontFamily(fontFamily: String) {
176 editor.typeface = if (fontFamily.contains("Mono", ignoreCase = true)) {
177 Typeface.MONOSPACE
178 } else {
179 Typeface.DEFAULT
180 }
181 }
182
183 fun setFontSize(fontSize: Float) {
184 editor.textSize = fontSize
185 applyLineHeight()
186 }
187
188 fun setLineHeight(lineHeight: Float) {
189 desiredLineHeightPx = (lineHeight * resources.displayMetrics.density).toInt()
190 applyLineHeight()
191 }
192
193 fun setSingleLineCentered(centered: Boolean) {
194 editor.gravity = if (centered) {
195 Gravity.CENTER_VERTICAL or Gravity.START
196 } else {
197 Gravity.TOP or Gravity.START
198 }
199 }
200
201 fun setContentInsetVertical(contentInsetVertical: Int) {
202 this.contentInsetVertical =
203 max(0, (contentInsetVertical * resources.displayMetrics.density).toInt())
204 editor.setPadding(0, this.contentInsetVertical, 0, this.contentInsetVertical)
205 emitContentSizeIfNeeded()
206 }
207
208 fun setEditable(editable: Boolean) {
209 editor.isEnabled = editable
210 editor.isFocusable = editable
211 editor.isFocusableInTouchMode = editable
212 editor.isCursorVisible = editable
213 }
214
215 fun setScrollEnabled(scrollEnabled: Boolean) {
216 editor.isVerticalScrollBarEnabled = scrollEnabled
217 }
218
219 fun setAutoFocus(autoFocus: Boolean) {
220 if (autoFocus) {
221 post { focusEditor() }
222 }
223 }
224
225 fun setAutoCorrect(autoCorrect: Boolean) {
226 this.autoCorrect = autoCorrect
227 updateInputFlags()
228 }
229
230 fun setSpellCheck(spellCheck: Boolean) {
231 this.spellCheck = spellCheck
232 updateInputFlags()
233 }
234
235 fun focusEditor() {
236 editor.requestFocus()
237 val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
238 imm?.showSoftInput(editor, InputMethodManager.SHOW_IMPLICIT)
239 }
240
241 fun blurEditor() {
242 editor.clearFocus()
243 val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
244 imm?.hideSoftInputFromWindow(editor.windowToken, 0)
245 }
246
247 fun setSelection(start: Int, end: Int) {
248 applySelection(start, end)
249 }
250
251 private fun applySelection(start: Int, end: Int) {
252 val textLength = editor.text?.length ?: 0
253 val safeStart = start.coerceIn(0, textLength)
254 val safeEnd = end.coerceIn(0, textLength)
255 editor.setSelection(safeStart, safeEnd)
256 }
257
258 private fun updateInputFlags() {
259 var flags =
260 InputType.TYPE_CLASS_TEXT or
261 InputType.TYPE_TEXT_FLAG_MULTI_LINE or
262 InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
263 flags = if (autoCorrect && spellCheck) {
264 flags or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
265 } else {
266 flags or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
267 }
268 editor.inputType = flags
269 }
270
271 private fun applyLineHeight() {
272 if (desiredLineHeightPx <= 0) return
273 val fontHeight = editor.paint.fontMetricsInt.descent - editor.paint.fontMetricsInt.ascent
274 editor.setLineSpacing(max(0, desiredLineHeightPx - fontHeight).toFloat(), 1f)
275 }
276
277 private fun currentSelectionPayload(): Map<String, Int> =
278 mapOf(
279 "start" to editor.selectionStart.coerceAtLeast(0),
280 "end" to editor.selectionEnd.coerceAtLeast(0),
281 )
282
283 private fun emitSelectionChange(start: Int, end: Int) {
284 onComposerSelectionChange(
285 mapOf(
286 "value" to editor.text.toString(),
287 "selection" to mapOf("start" to start, "end" to end),
288 "eventCount" to nativeEventCount,
289 ),
290 )
291 }
292
293 private fun emitContentSizeIfNeeded() {
294 val height = editor.layout?.height ?: editor.measuredHeight
295 val contentHeight = height + contentInsetVertical * 2
296 if (contentHeight == lastContentHeight) return
297 lastContentHeight = contentHeight
298 onComposerContentSizeChange(
299 mapOf("height" to contentHeight / resources.displayMetrics.density),
300 )
301 }
302
303 private fun applyTokenSpans() {
304 val editable = editor.text ?: return
305 editable.getSpans(
306 0,
307 editable.length,
308 ComposerChipSpan::class.java
309 ).forEach(editable::removeSpan)
310 tokens.forEach { token ->
311 if (token.start < 0 || token.end <= token.start || token.end > editable.length) return@forEach
312 val expectedSource = editable.substring(token.start, token.end)
313 if (expectedSource != token.source) return@forEach
314 editable.setSpan(
315 ComposerChipSpan(
316 token.label,
317 token.type == "skill",
318 chipTheme,
319 resources.displayMetrics.density
320 ),
321 token.start,
322 token.end,
323 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
324 )
325 }
326 editor.invalidate()
327 }
328
329 private fun parseColor(value: String, fallback: Int): Int =
330 try {
331 Color.parseColor(value)
332 } catch (_: Exception) {
333 fallback
334 }
335}
336
337private data class ComposerToken(
338 val type: String,
339 val source: String,
340 val label: String,
341 val start: Int,
342 val end: Int
343)
344
345private data class ComposerChipTheme(
346 val chipBackground: Int,
347 val chipBorder: Int,
348 val chipText: Int,
349 val skillBackground: Int,
350 val skillBorder: Int,
351 val skillText: Int
352) {
353 companion object {
354 fun default() = ComposerChipTheme(
355 chipBackground = Color.rgb(238, 240, 243),
356 chipBorder = Color.rgb(210, 214, 220),
357 chipText = Color.rgb(35, 39, 45),
358 skillBackground = Color.rgb(233, 239, 255),
359 skillBorder = Color.rgb(185, 200, 245),
360 skillText = Color.rgb(45, 72, 155),
361 )
362 }
363}
364
365private class ComposerChipSpan(
366 private val label: String,
367 private val skill: Boolean,
368 private val theme: ComposerChipTheme,
369 density: Float
370) : ReplacementSpan() {
371 private val horizontalPadding = 7f * density
372 private val verticalPadding = 2f * density
373 private val cornerRadius = 6f * density
374 private val borderWidth = density
375
376 override fun getSize(
377 paint: Paint,
378 text: CharSequence,
379 start: Int,
380 end: Int,
381 fontMetrics: Paint.FontMetricsInt?
382 ): Int {
383 fontMetrics?.let {
384 val extra = verticalPadding.toInt()
385 val base = paint.fontMetricsInt
386 it.top = base.top - extra
387 it.ascent = base.ascent - extra
388 it.descent = base.descent + extra
389 it.bottom = base.bottom + extra
390 }
391 return (paint.measureText(label) + horizontalPadding * 2).toInt()
392 }
393
394 override fun draw(
395 canvas: Canvas,
396 text: CharSequence,
397 start: Int,
398 end: Int,
399 x: Float,
400 top: Int,
401 y: Int,
402 bottom: Int,
403 paint: Paint
404 ) {
405 val width = paint.measureText(label) + horizontalPadding * 2
406 val metrics = paint.fontMetrics
407 val rect = RectF(
408 x,
409 y + metrics.ascent - verticalPadding,
410 x + width,
411 y + metrics.descent + verticalPadding,
412 )
413 val originalColor = paint.color
414 val originalStyle = paint.style
415 val originalStrokeWidth = paint.strokeWidth
416
417 paint.color = if (skill) theme.skillBackground else theme.chipBackground
418 paint.style = Paint.Style.FILL
419 canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
420 paint.color = if (skill) theme.skillBorder else theme.chipBorder
421 paint.style = Paint.Style.STROKE
422 paint.strokeWidth = borderWidth
423 canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
424 paint.color = if (skill) theme.skillText else theme.chipText
425 paint.style = Paint.Style.FILL
426 canvas.drawText(label, x + horizontalPadding, y.toFloat(), paint)
427
428 paint.color = originalColor
429 paint.style = originalStyle
430 paint.strokeWidth = originalStrokeWidth
431 }
432}
433
434private fun parseTokens(value: String): List<ComposerToken> = try {
435 val array = org.json.JSONArray(value)
436 List(array.length()) { index ->
437 val token = array.getJSONObject(index)
438 ComposerToken(
439 type = token.optString("type"),
440 source = token.optString("source"),
441 label = token.optString("label"),
442 start = token.optInt("start"),
443 end = token.optInt("end"),
444 )
445 }
446} catch (_: Exception) {
447 emptyList()
448}
449
450private class SelectionAwareEditText(context: Context) : EditText(context) {
451 var selectionListener: ((Int, Int) -> Unit)? = null
452 var pasteImagesListener: ((List<String>) -> Unit)? = null
453
454 override fun onSelectionChanged(selStart: Int, selEnd: Int) {
455 super.onSelectionChanged(selStart, selEnd)
456 selectionListener?.invoke(selStart, selEnd)
457 }
458
459 override fun onTextContextMenuItem(id: Int): Boolean {
460 if (id == android.R.id.paste || id == android.R.id.pasteAsPlainText) {
461 val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
462 val clip = clipboard?.primaryClip
463 val imageUris = buildList {
464 if (clip != null) {
465 for (index in 0 until clip.itemCount) {
466 clip.getItemAt(index).uri?.let { uri ->
467 val mimeType = context.contentResolver.getType(uri)
468 if (mimeType?.startsWith("image/") == true) add(uri.toString())
469 }
470 }
471 }
472 }
473 if (imageUris.isNotEmpty()) {
474 pasteImagesListener?.invoke(imageUris)
475 return true
476 }
477 }
478 return super.onTextContextMenuItem(id)
479 }
480}
apps/mobile/modules/t3-composer-editor/expo-module.config.json+4−1
@@ -1,6 +1,9 @@
1{1{
2 "platforms": ["apple"],2 "platforms": ["apple", "android"],
3 "apple": {3 "apple": {
4 "modules": ["T3ComposerEditorModule"]4 "modules": ["T3ComposerEditorModule"]
5 },
6 "android": {
7 "modules": ["expo.modules.t3composereditor.T3ComposerEditorModule"]
5 }8 }
6}9}
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift+1−0
@@ -47,6 +47,7 @@ public class T3ComposerEditorModule: Module { · 46 unmodified lines
47 "onComposerSelectionChange",47 "onComposerSelectionChange",
48 "onComposerFocus",48 "onComposerFocus",
49 "onComposerBlur",49 "onComposerBlur",
50 "onComposerSubmit",
50 "onComposerPasteImages",51 "onComposerPasteImages",
51 "onComposerContentSizeChange"52 "onComposerContentSizeChange"
52 )53 )
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift+24−2
@@ -63,6 +63,24 @@ private final class ComposerTextView: UITextView { · 62 unmodified lines
63 63
64 var onPasteImages: (([String]) -> Void)?64 var onPasteImages: (([String]) -> Void)?
65 var onAttributedMutation: (() -> Void)?65 var onAttributedMutation: (() -> Void)?
66 var onSubmit: (() -> Void)?
67
68 override var keyCommands: [UIKeyCommand]? {
69 var commands = super.keyCommands ?? []
70 let submit = UIKeyCommand(
71 input: "\r",
72 modifierFlags: .command,
73 action: #selector(submitMessage(_:))
74 )
75 submit.discoverabilityTitle = "Send Message"
76 submit.wantsPriorityOverSystemBehavior = true
77 commands.append(submit)
78 return commands
79 }
80
81 @objc private func submitMessage(_ sender: UIKeyCommand) {
82 onSubmit?()
83 }
66 84
67 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {85 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
68 if action == #selector(paste(_:)) {86 if action == #selector(paste(_:)) {
@@ -282,7 +300,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { · 213 unmodified lines
282 skillText: "#a21caf",300 skillText: "#a21caf",
283 fileTint: "#737373"301 fileTint: "#737373"
284 )302 )
285 private var fontFamily = "DMSans_400Regular"303 private var fontFamily = "DMSans-Regular"
286 private var fontSize: CGFloat = 14304 private var fontSize: CGFloat = 14
287 private var lineHeight: CGFloat = 20305 private var lineHeight: CGFloat = 20
288 private var contentInsetVertical: CGFloat = 0306 private var contentInsetVertical: CGFloat = 0
@@ -299,6 +317,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { · 10 unmodified lines
299 let onComposerSelectionChange = EventDispatcher()317 let onComposerSelectionChange = EventDispatcher()
300 let onComposerFocus = EventDispatcher()318 let onComposerFocus = EventDispatcher()
301 let onComposerBlur = EventDispatcher()319 let onComposerBlur = EventDispatcher()
320 let onComposerSubmit = EventDispatcher()
302 let onComposerPasteImages = EventDispatcher()321 let onComposerPasteImages = EventDispatcher()
303 let onComposerContentSizeChange = EventDispatcher()322 let onComposerContentSizeChange = EventDispatcher()
304 323
@@ -320,6 +339,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { · 15 unmodified lines
320 textView.onAttributedMutation = { [weak self] in339 textView.onAttributedMutation = { [weak self] in
321 self?.emitTextChange()340 self?.emitTextChange()
322 }341 }
342 textView.onSubmit = { [weak self] in
343 self?.onComposerSubmit([:])
344 }
323 addSubview(textView)345 addSubview(textView)
324 346
325 placeholderLabel.numberOfLines = 0347 placeholderLabel.numberOfLines = 0
@@ -586,7 +608,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { · 260 unmodified lines
586 iconImage: UIImage?,608 iconImage: UIImage?,
587 style: ComposerChipStyle609 style: ComposerChipStyle
588 ) -> UIImage {610 ) -> UIImage {
589 let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))611 let font = UIFont(name: "DMSans-Medium", size: max(12, fontSize - 2))
590 ?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)612 ?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
591 let fallbackIcon = UIImage(613 let fallbackIcon = UIImage(
592 systemName: iconName,614 systemName: iconName,
apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx+14−5
@@ -26,6 +26,15 @@ function nodeKey(node: MarkdownNode, index: number): string { · 25 unmodified lines
26 return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;26 return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
27}27}
28 28
29/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
30function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
31 return Math.max(10, Math.round(textStyle.fontSize * 0.8));
32}
33
34function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
35 return codeBlockFontSize(textStyle) + 6;
36}
37
29function nodeText(node: MarkdownNode): string {38function nodeText(node: MarkdownNode): string {
30 if (node.content !== undefined) {39 if (node.content !== undefined) {
31 return node.content;40 return node.content;
@@ -161,8 +170,8 @@ function HighlightedCodeText(props: { · 129 unmodified lines
161 style={{170 style={{
162 color: props.textStyle.codeColor,171 color: props.textStyle.codeColor,
163 fontFamily: "ui-monospace",172 fontFamily: "ui-monospace",
164 fontSize: 12,173 fontSize: codeBlockFontSize(props.textStyle),
165 lineHeight: 18,174 lineHeight: codeBlockLineHeight(props.textStyle),
166 }}175 }}
167 >176 >
168 {props.content}177 {props.content}
@@ -196,8 +205,8 @@ function HighlightedCodeText(props: { · 27 unmodified lines
196 style={{205 style={{
197 color: props.textStyle.codeColor,206 color: props.textStyle.codeColor,
198 fontFamily: "ui-monospace",207 fontFamily: "ui-monospace",
199 fontSize: 12,208 fontSize: codeBlockFontSize(props.textStyle),
200 lineHeight: 18,209 lineHeight: codeBlockLineHeight(props.textStyle),
201 }}210 }}
202 >211 >
203 {keyedLines.map((line, lineIndex) => (212 {keyedLines.map((line, lineIndex) => (
@@ -264,7 +273,7 @@ function NativeCodeBlock(props: { · 60 unmodified lines
264 flex: 1,273 flex: 1,
265 color: props.textStyle.mutedColor,274 color: props.textStyle.mutedColor,
266 fontFamily: "ui-monospace",275 fontFamily: "ui-monospace",
267 fontSize: 12,276 fontSize: codeBlockFontSize(props.textStyle),
268 }}277 }}
269 >278 >
270 {languageLabel}279 {languageLabel}
apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx+21−4
@@ -32,11 +32,25 @@ function runKeySignature(run: NativeMarkdownTextRun): string { · 31 unmodified lines
32 ].join(":");32 ].join(":");
33}33}
34 34
35const DEFAULT_BODY_FONT_SIZE = 15;
36const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
37
38function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
39 const index = Math.max(0, Math.min(5, headingLevel - 1));
40 const configured = textStyle.headingFontSizes?.[index];
41 if (typeof configured === "number" && Number.isFinite(configured)) {
42 return configured;
43 }
44
45 const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
46 return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
47}
48
35function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {49function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
36 const isFile = run.fileIcon != null;50 const isFile = run.fileIcon != null;
37 const isSkill = run.skillName != null;51 const isSkill = run.skillName != null;
38 const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));52 const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
39 const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;53 const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
40 const isHeading = run.role === "heading";54 const isHeading = run.role === "heading";
41 const isCodeBlock = run.role === "code-block" || run.role === "code-language";55 const isCodeBlock = run.role === "code-block" || run.role === "code-language";
42 const hasParagraphStyle = run.headIndent !== undefined;56 const hasParagraphStyle = run.headIndent !== undefined;
@@ -88,7 +102,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle · 45 unmodified lines
88 : isHeading102 : isHeading
89 ? headingFontSize103 ? headingFontSize
90 : run.role === "code-language"104 : run.role === "code-language"
91 ? 11105 ? Math.max(10, Math.round(textStyle.fontSize * 0.73))
92 : run.code || isCodeBlock106 : run.code || isCodeBlock
93 ? Math.max(12, textStyle.fontSize - 2)107 ? Math.max(12, textStyle.fontSize - 2)
94 : textStyle.fontSize,108 : textStyle.fontSize,
@@ -98,9 +112,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle · 3 unmodified lines
98 : run.role === "list-break"112 : run.role === "list-break"
99 ? textStyle.lineHeight + (run.spacing ?? 0)113 ? textStyle.lineHeight + (run.spacing ?? 0)
100 : isHeading114 : isHeading
101 ? Math.max(headingFontSize + 6, 20)115 ? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
102 : isCodeBlock116 : isCodeBlock
103 ? 18117 ? Math.max(16, textStyle.lineHeight - 2)
104 : textStyle.lineHeight,118 : textStyle.lineHeight,
105 fontStyle: run.italic ? "italic" : "normal",119 fontStyle: run.italic ? "italic" : "normal",
106 fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",120 fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
@@ -148,6 +162,9 @@ export function NativeMarkdownSelectableText(props: { · 41 unmodified lines
148 // color-only child update can otherwise leave the previous appearance cached.162 // color-only child update can otherwise leave the previous appearance cached.
149 const appearanceKey = [163 const appearanceKey = [
150 colorScheme ?? "unspecified",164 colorScheme ?? "unspecified",
165 props.textStyle.fontSize,
166 props.textStyle.lineHeight,
167 props.textStyle.headingFontSizes?.join(","),
151 props.textStyle.color,168 props.textStyle.color,
152 props.textStyle.strongColor,169 props.textStyle.strongColor,
153 props.textStyle.mutedColor,170 props.textStyle.mutedColor,
apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts+1−0
@@ -16,6 +16,7 @@ export interface NativeMarkdownTextStyle { · 15 unmodified lines
16 readonly fontFamily: string;16 readonly fontFamily: string;
17 readonly headingFontFamily: string;17 readonly headingFontFamily: string;
18 readonly boldFontFamily: string;18 readonly boldFontFamily: string;
19 readonly headingFontSizes?: ReadonlyArray<number>;
19}20}
20 21
21export interface MarkdownHighlightedToken {22export interface MarkdownHighlightedToken {
apps/mobile/modules/t3-native-controls/android/build.gradle+19−0
@@ -0,0 +1,19 @@
1apply plugin: 'com.android.library'
2apply plugin: 'org.jetbrains.kotlin.android'
3
4group = 'com.t3tools.nativecontrols'
5version = '0.0.0'
6
7android {
8 namespace 'expo.modules.t3nativecontrols'
9 compileSdk rootProject.ext.compileSdkVersion
10
11 defaultConfig {
12 minSdkVersion rootProject.ext.minSdkVersion
13 targetSdkVersion rootProject.ext.targetSdkVersion
14 }
15}
16
17dependencies {
18 implementation project(':expo-modules-core')
19}
apps/mobile/modules/t3-native-controls/android/src/main/AndroidManifest.xml+1−0
@@ -0,0 +1 @@
1<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3HeaderButtonView.kt+97−0
@@ -0,0 +1,97 @@
1package expo.modules.t3nativecontrols
2
3import android.content.Context
4import android.graphics.Canvas
5import android.graphics.Color
6import android.graphics.Paint
7import android.view.View
8import expo.modules.kotlin.AppContext
9import expo.modules.kotlin.viewevent.EventDispatcher
10import expo.modules.kotlin.views.ExpoView
11
12class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
13 private val iconView = HeaderIconView(context)
14 private val onTriggered by EventDispatcher()
15
16 init {
17 isClickable = true
18 isFocusable = true
19 setOnClickListener {
20 onTriggered(emptyMap<String, Any>())
21 }
22 addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
23 }
24
25 fun setLabel(label: String) {
26 contentDescription = label
27 }
28
29 fun setSystemImage(systemImage: String) {
30 iconView.systemImage = systemImage
31 }
32}
33
34private class HeaderIconView(context: Context) : View(context) {
35 private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
36 color = Color.parseColor("#6B7280")
37 strokeCap = Paint.Cap.ROUND
38 strokeJoin = Paint.Join.ROUND
39 strokeWidth = 3f * resources.displayMetrics.density
40 style = Paint.Style.STROKE
41 }
42
43 var systemImage: String = "gearshape"
44 set(value) {
45 field = value
46 invalidate()
47 }
48
49 override fun onDraw(canvas: Canvas) {
50 super.onDraw(canvas)
51 val cx = width / 2f
52 val cy = height / 2f
53 val size = minOf(width, height).toFloat()
54 if (systemImage == "square.and.pencil") {
55 drawNewTask(canvas, cx, cy, size)
56 } else {
57 drawSettings(canvas, cx, cy, size)
58 }
59 }
60
61 private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
62 val radius = size * 0.12f
63 canvas.drawCircle(cx, cy, radius, paint)
64 for (index in 0 until 8) {
65 val angle = Math.PI * index / 4.0
66 val inner = size * 0.19f
67 val outer = size * 0.27f
68 val sx = cx + kotlin.math.cos(angle).toFloat() * inner
69 val sy = cy + kotlin.math.sin(angle).toFloat() * inner
70 val ex = cx + kotlin.math.cos(angle).toFloat() * outer
71 val ey = cy + kotlin.math.sin(angle).toFloat() * outer
72 canvas.drawLine(sx, sy, ex, ey, paint)
73 }
74 }
75
76 private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
77 val left = cx - size * 0.2f
78 val top = cy - size * 0.16f
79 val right = cx + size * 0.14f
80 val bottom = cy + size * 0.2f
81 canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
82 canvas.drawLine(
83 cx - size * 0.02f,
84 cy + size * 0.13f,
85 cx + size * 0.24f,
86 cy - size * 0.13f,
87 paint
88 )
89 canvas.drawLine(
90 cx + size * 0.17f,
91 cy - size * 0.2f,
92 cx + size * 0.24f,
93 cy - size * 0.13f,
94 paint
95 )
96 }
97}
apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt+47−0
@@ -0,0 +1,47 @@
1package expo.modules.t3nativecontrols
2
3import expo.modules.kotlin.modules.Module
4import expo.modules.kotlin.modules.ModuleDefinition
5
6class T3NativeControlsModule : Module() {
7 override fun definition() = ModuleDefinition {
8 Name("T3NativeControls")
9
10 Function("getShowcasePairingUrl") {
11 appContext.currentActivity?.intent?.getStringExtra("showcasePairingUrl")
12 }
13
14 Function("getShowcaseScene") {
15 val storedScene = appContext.reactContext
16 ?.filesDir
17 ?.resolve("t3-showcase-scene")
18 ?.takeIf { it.isFile }
19 ?.readText()
20 ?.trim()
21 ?.takeIf { it.isNotEmpty() }
22 storedScene ?: appContext.currentActivity?.intent?.getStringExtra("showcaseScene")
23 }
24
25 Function("prepareShowcaseCapture") {
26 // Android app data is cleared by the host runner before launch.
27 }
28
29 Function("markShowcaseReady") { scene: String ->
30 appContext.reactContext
31 ?.filesDir
32 ?.resolve("t3-showcase-ready")
33 ?.writeText(scene)
34 }
35
36 View(T3HeaderButtonView::class) {
37 Prop("label") { view: T3HeaderButtonView, label: String ->
38 view.setLabel(label)
39 }
40 Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
41 view.setSystemImage(systemImage)
42 }
43
44 Events("onTriggered")
45 }
46 }
47}
apps/mobile/modules/t3-native-controls/expo-module.config.json+9−0
@@ -0,0 +1,9 @@
1{
2 "platforms": ["apple", "android"],
3 "apple": {
4 "modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
5 },
6 "android": {
7 "modules": ["expo.modules.t3nativecontrols.T3NativeControlsModule"]
8 }
9}
apps/mobile/modules/t3-native-controls/ios/T3HeaderButtonView.swift+62−0
@@ -0,0 +1,62 @@
1import ExpoModulesCore
2import UIKit
3
4public final class T3HeaderButtonView: ExpoView {
5 private static let size: CGFloat = 44
6 private static let symbolSize: CGFloat = 18
7
8 private let button = UIButton(type: .system)
9 private var systemImage = "circle"
10
11 let onTriggered = EventDispatcher()
12
13 public required init(appContext: AppContext? = nil) {
14 super.init(appContext: appContext)
15
16 isAccessibilityElement = false
17 button.frame = bounds
18 button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
19 button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
20 addSubview(button)
21 applyConfiguration()
22 }
23
24 public override var intrinsicContentSize: CGSize {
25 CGSize(width: Self.size, height: Self.size)
26 }
27
28 public func setLabel(_ label: String) {
29 button.accessibilityLabel = label
30 }
31
32 public func setSystemImage(_ systemImage: String) {
33 guard self.systemImage != systemImage else {
34 return
35 }
36 self.systemImage = systemImage
37 applyConfiguration()
38 }
39
40 private func applyConfiguration() {
41 var configuration: UIButton.Configuration
42 if #available(iOS 26.0, *) {
43 configuration = .glass()
44 configuration.cornerStyle = .capsule
45 } else {
46 configuration = .plain()
47 }
48
49 configuration.baseForegroundColor = .label
50 configuration.contentInsets = .zero
51 configuration.image = UIImage(systemName: systemImage)
52 configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
53 pointSize: Self.symbolSize,
54 weight: .regular
55 )
56 button.configuration = configuration
57 }
58
59 @objc private func handlePress() {
60 onTriggered()
61 }
62}
apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift+131−0
@@ -0,0 +1,131 @@
1import ExpoModulesCore
2import UIKit
3
4public final class T3KeyboardCommandsModule: Module {
5 public func definition() -> ModuleDefinition {
6 Name("T3KeyboardCommands")
7
8 View(T3KeyboardCommandsView.self) {
9 Prop("enabledCommands") { (view: T3KeyboardCommandsView, commands: [String]) in
10 view.setEnabledCommands(commands)
11 }
12 Events("onCommand")
13 }
14 }
15}
16
17public final class T3KeyboardCommandsView: ExpoView {
18 let onCommand = EventDispatcher()
19 private var enabledCommands = Set<String>()
20
21 public override var canBecomeFirstResponder: Bool { true }
22
23 public override var keyCommands: [UIKeyCommand]? {
24 [
25 enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"),
26 enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"),
27 enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"),
28 enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"),
29 enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"),
30 enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"),
31 enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"),
32 enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
33 ].compactMap { $0 }
34 }
35
36 func setEnabledCommands(_ commands: [String]) {
37 enabledCommands = Set(commands)
38 if isFirstResponder {
39 resignFirstResponder()
40 }
41 reclaimFirstResponderIfAvailable()
42 }
43
44 private func enabledCommand(
45 _ identifier: String,
46 input: String,
47 modifiers: UIKeyModifierFlags,
48 action: Selector,
49 title: String
50 ) -> UIKeyCommand? {
51 guard enabledCommands.contains(identifier) else { return nil }
52 return command(input, modifiers: modifiers, action: action, title: title)
53 }
54
55 public required init(appContext: AppContext? = nil) {
56 super.init(appContext: appContext)
57 NotificationCenter.default.addObserver(
58 self,
59 selector: #selector(reclaimFirstResponderIfAvailable),
60 name: UITextView.textDidEndEditingNotification,
61 object: nil
62 )
63 NotificationCenter.default.addObserver(
64 self,
65 selector: #selector(reclaimFirstResponderIfAvailable),
66 name: UITextField.textDidEndEditingNotification,
67 object: nil
68 )
69 NotificationCenter.default.addObserver(
70 self,
71 selector: #selector(reclaimFirstResponderIfAvailable),
72 name: UIApplication.didBecomeActiveNotification,
73 object: nil
74 )
75 }
76
77 deinit {
78 NotificationCenter.default.removeObserver(self)
79 }
80
81 public override func didMoveToWindow() {
82 super.didMoveToWindow()
83 reclaimFirstResponderIfAvailable()
84 }
85
86 public override func layoutSubviews() {
87 super.layoutSubviews()
88 reclaimFirstResponderIfAvailable()
89 }
90
91 private func command(
92 _ input: String,
93 modifiers: UIKeyModifierFlags,
94 action: Selector,
95 title: String
96 ) -> UIKeyCommand {
97 let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
98 command.discoverabilityTitle = title
99 command.wantsPriorityOverSystemBehavior = true
100 return command
101 }
102
103 @objc private func newTask() { emit("newTask") }
104 @objc private func focusSearch() { emit("focusSearch") }
105 @objc private func goBack() { emit("back") }
106 @objc private func openFiles() { emit("files") }
107 @objc private func openTerminal() { emit("terminal") }
108 @objc private func openReview() { emit("review") }
109 @objc private func handleToggleSidebar() { emit("toggleSidebar") }
110
111 private func emit(_ command: String) {
112 onCommand(["command": command])
113 }
114
115 @objc private func reclaimFirstResponderIfAvailable() {
116 DispatchQueue.main.async { [weak self] in
117 guard let self, self.window?.t3FirstResponder == nil else { return }
118 self.becomeFirstResponder()
119 }
120 }
121}
122
123private extension UIView {
124 var t3FirstResponder: UIResponder? {
125 if isFirstResponder { return self }
126 for subview in subviews {
127 if let responder = subview.t3FirstResponder { return responder }
128 }
129 return nil
130 }
131}
apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec+19−0
@@ -0,0 +1,19 @@
1Pod::Spec.new do |s|
2 s.name = 'T3NativeControls'
3 s.version = '1.0.0'
4 s.summary = 'Native UIKit controls for T3 Code mobile.'
5 s.description = 'UIKit-backed controls that match native iOS navigation chrome.'
6 s.author = 'T3 Tools'
7 s.homepage = 'https://t3tools.com'
8 s.platforms = {
9 :ios => '18.0',
10 }
11 s.source = { :path => '.' }
12 s.static_framework = true
13
14 s.dependency 'ExpoModulesCore'
15 s.pod_target_xcconfig = {
16 'DEFINES_MODULE' => 'YES',
17 }
18 s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
19end
apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift+57−0
@@ -0,0 +1,57 @@
1import ExpoModulesCore
2import Security
3
4public final class T3NativeControlsModule: Module {
5 public func definition() -> ModuleDefinition {
6 Name("T3NativeControls")
7
8 Function("getShowcasePairingUrl") {
9 let arguments = ProcessInfo.processInfo.arguments
10 guard
11 let flagIndex = arguments.firstIndex(of: "--showcasePairingUrl"),
12 arguments.indices.contains(flagIndex + 1)
13 else {
14 return nil as String?
15 }
16 return arguments[flagIndex + 1]
17 }
18
19 Function("getShowcaseScene") { () -> String? in
20 let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
21 if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
22 .trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
23 return storedScene
24 }
25 let arguments = ProcessInfo.processInfo.arguments
26 guard
27 let flagIndex = arguments.firstIndex(of: "--showcaseScene"),
28 arguments.indices.contains(flagIndex + 1)
29 else {
30 return nil as String?
31 }
32 return arguments[flagIndex + 1]
33 }
34
35 Function("prepareShowcaseCapture") {
36 for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
37 SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
38 }
39 }
40
41 Function("markShowcaseReady") { (scene: String) in
42 let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
43 try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
44 }
45
46 View(T3HeaderButtonView.self) {
47 Prop("label") { (view: T3HeaderButtonView, label: String) in
48 view.setLabel(label)
49 }
50 Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
51 view.setSystemImage(systemImage)
52 }
53
54 Events("onTriggered")
55 }
56 }
57}
apps/mobile/modules/t3-review-diff/android/build.gradle+19−0
@@ -0,0 +1,19 @@
1apply plugin: 'com.android.library'
2apply plugin: 'org.jetbrains.kotlin.android'
3
4group = 'com.t3tools.reviewdiff'
5version = '0.0.0'
6
7android {
8 namespace 'expo.modules.t3reviewdiff'
9 compileSdk rootProject.ext.compileSdkVersion
10
11 defaultConfig {
12 minSdkVersion rootProject.ext.minSdkVersion
13 targetSdkVersion rootProject.ext.targetSdkVersion
14 }
15}
16
17dependencies {
18 implementation project(':expo-modules-core')
19}
apps/mobile/modules/t3-review-diff/android/src/main/AndroidManifest.xml+1−0
@@ -0,0 +1 @@
1<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt+315−0
@@ -0,0 +1,315 @@
1package expo.modules.t3reviewdiff
2
3import android.content.Context
4import android.graphics.Canvas
5import android.graphics.Color
6import android.graphics.LinearGradient
7import android.graphics.Paint
8import android.graphics.Path
9import android.graphics.RectF
10import android.graphics.Shader
11import android.graphics.Typeface
12import kotlin.math.max
13import kotlin.math.min
14
15internal class ReviewDiffCanvasDrawing(context: Context) {
16 private val density = context.resources.displayMetrics.density
17 var theme: DiffTheme = DiffTheme.fallback("light")
18
19 val backgroundPaint = Paint()
20 val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
21 val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
22 hinting = Paint.HINTING_ON
23 isSubpixelText = false
24 clearShadowLayer()
25 }
26 val uiPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
27 hinting = Paint.HINTING_ON
28 isSubpixelText = false
29 clearShadowLayer()
30 }
31
32 private val italicCodeTypeface by lazy {
33 Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC)
34 }
35 private val boldItalicCodeTypeface by lazy {
36 Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC)
37 }
38
39 init {
40 textPaint.typeface = ReviewDiffTypefaces.regular
41 uiPaint.typeface = Typeface.DEFAULT_BOLD
42 }
43
44 fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF {
45 val centerY = (top + bottom) / 2f
46 val left = style.fileHeaderHorizontalPaddingPx
47 return RectF(left, centerY - 10f * density, left + 20f * density, centerY + 10f * density)
48 }
49
50 fun fileHeaderIconRect(top: Int, bottom: Int, style: DiffStyle): RectF {
51 val chevron = fileHeaderChevronRect(top, bottom, style)
52 return RectF(
53 chevron.right + 8f * density,
54 chevron.top,
55 chevron.right + 28f * density,
56 chevron.bottom,
57 )
58 }
59
60 fun fileHeaderCheckboxRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF {
61 val centerY = (top + bottom) / 2f
62 val right = width - style.fileHeaderHorizontalPaddingPx
63 return RectF(
64 right - 20f * density,
65 centerY - 10f * density,
66 right,
67 centerY + 10f * density,
68 )
69 }
70
71 fun drawDisclosureChevron(
72 canvas: Canvas,
73 rect: RectF,
74 color: Int,
75 collapsed: Boolean
76 ) {
77 borderPaint.style = Paint.Style.STROKE
78 borderPaint.color = color
79 borderPaint.strokeWidth = 2f * density
80 borderPaint.strokeCap = Paint.Cap.ROUND
81 borderPaint.strokeJoin = Paint.Join.ROUND
82 val path = Path()
83 if (collapsed) {
84 path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f)
85 path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY())
86 path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f)
87 } else {
88 path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
89 path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f)
90 path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
91 }
92 canvas.drawPath(path, borderPaint)
93 borderPaint.style = Paint.Style.FILL
94 }
95
96 fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) {
97 val color = when (changeType) {
98 "new" -> theme.addText
99 "deleted" -> theme.deleteText
100 else -> theme.hunkText
101 }
102 borderPaint.style = Paint.Style.STROKE
103 borderPaint.color = color
104 borderPaint.strokeWidth = 2f * density
105 canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
106
107 if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") {
108 drawRenameChevronIcon(canvas, rect, color)
109 } else {
110 backgroundPaint.color = color
111 canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint)
112 }
113 borderPaint.style = Paint.Style.FILL
114 }
115
116 fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) {
117 if (checked) {
118 backgroundPaint.color = theme.hunkText
119 canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint)
120 }
121 borderPaint.style = Paint.Style.STROKE
122 borderPaint.color = if (checked) theme.hunkText else theme.mutedText
123 borderPaint.strokeWidth = 1.8f * density
124 canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
125 if (checked) {
126 borderPaint.color = theme.background
127 borderPaint.strokeWidth = 2f * density
128 borderPaint.strokeCap = Paint.Cap.ROUND
129 borderPaint.strokeJoin = Paint.Join.ROUND
130 val path = Path().apply {
131 moveTo(rect.left + rect.width() * 0.28f, rect.centerY())
132 lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f)
133 lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f)
134 }
135 canvas.drawPath(path, borderPaint)
136 }
137 borderPaint.style = Paint.Style.FILL
138 }
139
140 fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) {
141 borderPaint.style = Paint.Style.STROKE
142 borderPaint.color = color
143 borderPaint.strokeWidth = 1.7f * density
144 borderPaint.strokeCap = Paint.Cap.ROUND
145 canvas.drawOval(rect, borderPaint)
146 canvas.drawLine(
147 rect.centerX(),
148 rect.top + rect.height() * 0.3f,
149 rect.centerX(),
150 rect.top + rect.height() * 0.58f,
151 borderPaint,
152 )
153 borderPaint.style = Paint.Style.FILL
154 canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint)
155 }
156
157 fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) {
158 paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
159 configureTextPaint(paint, color, size)
160 }
161
162 fun configureMonospacePaint(color: Int, size: Float, weight: String) {
163 textPaint.typeface = ReviewDiffTypefaces.forWeight(weight)
164 configureTextPaint(textPaint, color, size)
165 }
166
167 fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) {
168 val tokenBold = fontStyle and 2 != 0
169 val italic = fontStyle and 1 != 0
170 textPaint.typeface = when {
171 tokenBold && italic -> boldItalicCodeTypeface
172 tokenBold -> ReviewDiffTypefaces.bold
173 italic -> italicCodeTypeface
174 else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight)
175 }
176 configureTextPaint(textPaint, color, style.codeFontSizePx)
177 textPaint.isUnderlineText = fontStyle and 4 != 0
178 }
179
180 fun lineNumberColor(change: String): Int = when (change) {
181 "add" -> theme.addText
182 "delete" -> theme.deleteText
183 else -> theme.mutedText
184 }
185
186 fun drawDeleteStripes(
187 canvas: Canvas,
188 top: Int,
189 bottom: Int,
190 width: Float,
191 color: Int
192 ) {
193 backgroundPaint.color = color
194 var y = top.toFloat()
195 while (y < bottom) {
196 canvas.drawRect(0f, y, width, min(bottom.toFloat(), y + density), backgroundPaint)
197 y += 2f * density
198 }
199 }
200
201 fun drawWordDiffRanges(
202 canvas: Canvas,
203 row: DiffRow,
204 codeX: Float,
205 top: Int,
206 bottom: Int
207 ) {
208 if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return
209 val color = if (row.change == "add") theme.addBar else theme.deleteBar
210 backgroundPaint.color = withAlpha(color, 71)
211 val characterWidth = textPaint.measureText("M")
212 val fontHeight = textPaint.fontMetrics.run { descent - ascent }
213 val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight))
214 val highlightTop = (top + bottom - highlightHeight) / 2f
215 row.wordDiffRanges.forEach { range ->
216 val left = codeX + range.start * characterWidth
217 val right = max(left + 2f * density, codeX + range.end * characterWidth)
218 canvas.drawRoundRect(
219 RectF(left, highlightTop, right, highlightTop + highlightHeight),
220 3f * density,
221 3f * density,
222 backgroundPaint,
223 )
224 }
225 }
226
227 fun drawFileHeaderPathScrollFades(
228 canvas: Canvas,
229 pathRect: RectF,
230 horizontalOffset: Int,
231 maxOffset: Int
232 ) {
233 if (maxOffset <= 0 || pathRect.width() <= 0f) return
234 val fadeWidth = min(28f * density, pathRect.width() / 3f)
235 if (horizontalOffset > 0) {
236 drawHorizontalFade(
237 canvas,
238 RectF(pathRect.left, pathRect.top, pathRect.left + fadeWidth, pathRect.bottom),
239 fadesToRight = false,
240 )
241 }
242 if (horizontalOffset < maxOffset) {
243 drawHorizontalFade(
244 canvas,
245 RectF(pathRect.right - fadeWidth, pathRect.top, pathRect.right, pathRect.bottom),
246 fadesToRight = true,
247 )
248 }
249 }
250
251 private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) {
252 borderPaint.style = Paint.Style.STROKE
253 borderPaint.color = color
254 borderPaint.strokeWidth = 1.8f * density
255 borderPaint.strokeCap = Paint.Cap.ROUND
256 borderPaint.strokeJoin = Paint.Join.ROUND
257 val chevronWidth = 3.6f * density
258 val chevronHeight = 8f * density
259 val gap = 2.4f * density
260 val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f
261 val path = Path()
262 for (x in listOf(startX, startX + chevronWidth + gap)) {
263 path.moveTo(x, rect.centerY() - chevronHeight / 2f)
264 path.lineTo(x + chevronWidth, rect.centerY())
265 path.lineTo(x, rect.centerY() + chevronHeight / 2f)
266 }
267 canvas.drawPath(path, borderPaint)
268 }
269
270 private fun configureTextPaint(paint: Paint, color: Int, size: Float) {
271 paint.textSize = size
272 paint.color = color
273 paint.style = Paint.Style.FILL
274 paint.textAlign = Paint.Align.LEFT
275 paint.isUnderlineText = false
276 paint.isFakeBoldText = false
277 paint.clearShadowLayer()
278 }
279
280 private fun drawHorizontalFade(canvas: Canvas, rect: RectF, fadesToRight: Boolean) {
281 val opaque = theme.headerBackground
282 val transparent = Color.argb(0, Color.red(opaque), Color.green(opaque), Color.blue(opaque))
283 backgroundPaint.shader = LinearGradient(
284 rect.left,
285 rect.centerY(),
286 rect.right,
287 rect.centerY(),
288 if (fadesToRight) transparent else opaque,
289 if (fadesToRight) opaque else transparent,
290 Shader.TileMode.CLAMP,
291 )
292 canvas.drawRect(rect, backgroundPaint)
293 backgroundPaint.shader = null
294 }
295
296 private fun isBoldFontWeight(weight: String): Boolean = when (weight.lowercase()) {
297 "medium", "semibold", "semi-bold", "bold", "heavy", "black" -> true
298 else -> false
299 }
300
301 private fun withAlpha(color: Int, alpha: Int): Int =
302 Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
303}
304
305private object ReviewDiffTypefaces {
306 val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL)
307 private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL)
308 val bold: Typeface = Typeface.create("monospace", Typeface.BOLD)
309
310 fun forWeight(weight: String): Typeface = when (weight.lowercase()) {
311 "medium", "semibold", "semi-bold" -> medium
312 "bold", "heavy", "black" -> bold
313 else -> regular
314 }
315}
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt+78−0
@@ -0,0 +1,78 @@
1package expo.modules.t3reviewdiff
2
3import expo.modules.kotlin.modules.Module
4import expo.modules.kotlin.modules.ModuleDefinition
5
6class T3ReviewDiffModule : Module() {
7 override fun definition() = ModuleDefinition {
8 Name("T3ReviewDiffSurface")
9
10 View(T3ReviewDiffView::class) {
11 Prop("tokensResetKey") { view: T3ReviewDiffView, tokensResetKey: String ->
12 view.setTokensResetKey(tokensResetKey)
13 }
14 Prop("contentResetKey") { view: T3ReviewDiffView, contentResetKey: String ->
15 view.setContentResetKey(contentResetKey)
16 }
17 Prop("collapsedFileIdsJson") { view: T3ReviewDiffView, collapsedFileIdsJson: String ->
18 view.setCollapsedFileIdsJson(collapsedFileIdsJson)
19 }
20 Prop("viewedFileIdsJson") { view: T3ReviewDiffView, viewedFileIdsJson: String ->
21 view.setViewedFileIdsJson(viewedFileIdsJson)
22 }
23 Prop("selectedRowIdsJson") { view: T3ReviewDiffView, selectedRowIdsJson: String ->
24 view.setSelectedRowIdsJson(selectedRowIdsJson)
25 }
26 Prop("collapsedCommentIdsJson") { view: T3ReviewDiffView, collapsedCommentIdsJson: String ->
27 view.setCollapsedCommentIdsJson(collapsedCommentIdsJson)
28 }
29 Prop("appearanceScheme") { view: T3ReviewDiffView, appearanceScheme: String ->
30 view.setAppearanceScheme(appearanceScheme)
31 }
32 Prop("themeJson") { view: T3ReviewDiffView, themeJson: String ->
33 view.setThemeJson(themeJson)
34 }
35 Prop("styleJson") { view: T3ReviewDiffView, styleJson: String ->
36 view.setStyleJson(styleJson)
37 }
38 Prop("rowHeight") { view: T3ReviewDiffView, rowHeight: Double ->
39 view.setRowHeight(rowHeight.toFloat())
40 }
41 Prop("contentWidth") { view: T3ReviewDiffView, contentWidth: Double ->
42 view.setContentWidth(contentWidth.toFloat())
43 }
44 Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double ->
45 view.setInitialRowIndex(initialRowIndex)
46 }
47
48 Events(
49 "onDebug",
50 "onVisibleFileChange",
51 "onToggleFile",
52 "onToggleViewedFile",
53 "onPressLine",
54 "onToggleComment",
55 )
56
57 AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean ->
58 view.scrollToFile(fileId, animated)
59 }
60 AsyncFunction("scrollToTop") { view: T3ReviewDiffView, animated: Boolean ->
61 view.scrollToTop(animated)
62 }
63 AsyncFunction("setRowsJson") { view: T3ReviewDiffView, rowsJson: String ->
64 view.setRowsJson(rowsJson)
65 }
66 AsyncFunction("setTokensJson") { view: T3ReviewDiffView, tokensJson: String ->
67 view.setTokensJson(tokensJson)
68 }
69 AsyncFunction("setTokensPatchJson") { view: T3ReviewDiffView, tokensPatchJson: String ->
70 view.setTokensPatchJson(tokensPatchJson)
71 }
72
73 OnViewDestroys { view: T3ReviewDiffView ->
74 view.cleanup()
75 }
76 }
77 }
78}
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt+1429−0
@@ -0,0 +1,1429 @@
1package expo.modules.t3reviewdiff
2
3import android.content.Context
4import android.graphics.Canvas
5import android.graphics.Color
6import android.graphics.Paint
7import android.graphics.RectF
8import android.view.GestureDetector
9import android.view.MotionEvent
10import android.view.VelocityTracker
11import android.view.View
12import android.view.ViewGroup
13import android.view.ViewConfiguration
14import android.widget.OverScroller
15import expo.modules.kotlin.AppContext
16import expo.modules.kotlin.viewevent.EventDispatcher
17import expo.modules.kotlin.views.ExpoView
18import org.json.JSONArray
19import org.json.JSONObject
20import java.util.concurrent.Executors
21import kotlin.math.abs
22import kotlin.math.ceil
23import kotlin.math.max
24import kotlin.math.min
25
26class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
27 private val canvasView = DiffCanvasView(context)
28 private val onDebug by EventDispatcher()
29 private val onVisibleFileChange by EventDispatcher()
30 private val onToggleFile by EventDispatcher()
31 private val onToggleViewedFile by EventDispatcher()
32 private val onPressLine by EventDispatcher()
33 private val onToggleComment by EventDispatcher()
34 private var rows: List<DiffRow> = emptyList()
35 private var visibleRows: List<DiffRow> = emptyList()
36 private var collapsedFileIds: Set<String> = emptySet()
37 private var viewedFileIds: Set<String> = emptySet()
38 private var selectedRowIds: Set<String> = emptySet()
39 private var collapsedCommentIds: Set<String> = emptySet()
40 private var initialRowIndex = 0
41 private var pendingInitialScroll = false
42 private var lastVisibleFileId: String? = null
43 private var tokensResetKey = ""
44 private var contentResetKey = ""
45 private var rowsDecodeGeneration = 0
46 private var tokensDecodeGeneration = 0
47 private val payloadDecodeExecutor = Executors.newSingleThreadExecutor()
48 private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
49 private val minimumFlingVelocity = ViewConfiguration.get(context).scaledMinimumFlingVelocity
50 private val verticalScroller = OverScroller(context)
51 private val horizontalScroller = OverScroller(context)
52 private var dragAxis: DragAxis? = null
53 private var horizontalDragTarget: HorizontalPanTarget? = null
54 private var lastTouchX = 0f
55 private var lastTouchY = 0f
56 private var velocityTracker: VelocityTracker? = null
57
58 init {
59 canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) }
60 canvasView.onVisibleRowsChanged = { first, last ->
61 onDebug(
62 mapOf(
63 "message" to "visible-range",
64 "firstRowIndex" to first,
65 "lastRowIndex" to last,
66 ),
67 )
68 emitVisibleFile(first)
69 }
70
71 addView(
72 canvasView,
73 LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
74 )
75 }
76
77 fun setTokensResetKey(value: String) {
78 if (tokensResetKey == value) return
79 tokensResetKey = value
80 canvasView.tokensByRowId = emptyMap()
81 }
82
83 fun setContentResetKey(value: String) {
84 if (contentResetKey == value) return
85 contentResetKey = value
86 tokensDecodeGeneration += 1
87 canvasView.tokensByRowId = emptyMap()
88 lastVisibleFileId = null
89 pendingInitialScroll = true
90 canvasView.setVerticalOffset(0)
91 canvasView.resetHorizontalOffsets()
92 applyPendingInitialScroll()
93 }
94
95 fun setCollapsedFileIdsJson(value: String) {
96 collapsedFileIds = parseStringSet(value)
97 canvasView.collapsedFileIds = collapsedFileIds
98 rebuildVisibleRows()
99 }
100
101 fun setViewedFileIdsJson(value: String) {
102 viewedFileIds = parseStringSet(value)
103 canvasView.viewedFileIds = viewedFileIds
104 }
105
106 fun setSelectedRowIdsJson(value: String) {
107 selectedRowIds = parseStringSet(value)
108 canvasView.selectedRowIds = selectedRowIds
109 }
110
111 fun setCollapsedCommentIdsJson(value: String) {
112 collapsedCommentIds = parseStringSet(value)
113 canvasView.collapsedCommentIds = collapsedCommentIds
114 rebuildVisibleRows()
115 }
116
117 fun setAppearanceScheme(value: String) {
118 canvasView.theme = DiffTheme.fallback(value)
119 }
120
121 fun setThemeJson(value: String) {
122 canvasView.theme = DiffTheme.fromJson(value, canvasView.theme)
123 }
124
125 fun setStyleJson(value: String) {
126 canvasView.style = DiffStyle.fromJson(value, canvasView.style, resources.displayMetrics.density)
127 }
128
129 fun setRowHeight(value: Float) {
130 canvasView.style = canvasView.style.copy(rowHeightPx = dp(value))
131 }
132
133 fun setContentWidth(value: Float) {
134 canvasView.contentWidthPx = max(width, dp(value).toInt())
135 }
136
137 fun setInitialRowIndex(value: Double) {
138 initialRowIndex = value.toInt().coerceAtLeast(0)
139 pendingInitialScroll = true
140 applyPendingInitialScroll()
141 }
142
143 fun setRowsJson(value: String) {
144 rowsDecodeGeneration += 1
145 val generation = rowsDecodeGeneration
146 payloadDecodeExecutor.execute {
147 val decodedRows = parseRows(value)
148 post {
149 if (generation != rowsDecodeGeneration) return@post
150 rows = decodedRows
151 lastVisibleFileId = null
152 rebuildVisibleRows()
153 }
154 }
155 }
156
157 fun setTokensJson(value: String) {
158 tokensDecodeGeneration += 1
159 val generation = tokensDecodeGeneration
160 payloadDecodeExecutor.execute {
161 val decodedTokens = parseTokensObject(value)
162 post {
163 if (generation != tokensDecodeGeneration) return@post
164 canvasView.tokensByRowId = decodedTokens
165 }
166 }
167 }
168
169 fun setTokensPatchJson(value: String) {
170 payloadDecodeExecutor.execute {
171 try {
172 val payload = JSONObject(value)
173 val resetKey = payload.optString("resetKey")
174 val decodedTokens = parseTokensObject(
175 payload.optJSONObject("tokensByRowId") ?: JSONObject(),
176 )
177 post {
178 if (resetKey.isNotEmpty() && resetKey != tokensResetKey) return@post
179 if (decodedTokens.isNotEmpty()) {
180 canvasView.tokensByRowId = canvasView.tokensByRowId + decodedTokens
181 }
182 }
183 } catch (_: Exception) {
184 }
185 }
186 }
187
188 fun cleanup() {
189 payloadDecodeExecutor.shutdownNow()
190 }
191
192 fun scrollToFile(fileId: String, animated: Boolean) {
193 val index = visibleRows.indexOfFirst { it.kind == "file" && it.resolvedFileId == fileId }
194 if (index < 0) return
195 scrollToY(canvasView.rowTop(index), animated)
196 }
197
198 fun scrollToTop(animated: Boolean) {
199 scrollToY(0, animated)
200 }
201
202 @Suppress("NestedBlockDepth", "ReturnCount")
203 override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
204 when (event.actionMasked) {
205 MotionEvent.ACTION_DOWN -> {
206 verticalScroller.forceFinished(true)
207 horizontalScroller.forceFinished(true)
208 dragAxis = null
209 horizontalDragTarget = canvasView.horizontalPanTarget(event.y)
210 lastTouchX = event.x
211 lastTouchY = event.y
212 parent?.requestDisallowInterceptTouchEvent(true)
213 return false
214 }
215 MotionEvent.ACTION_MOVE -> {
216 if (dragAxis == null) {
217 val deltaX = event.x - lastTouchX
218 val deltaY = event.y - lastTouchY
219 if (max(abs(deltaX), abs(deltaY)) > touchSlop) {
220 dragAxis = if (abs(deltaY) >= abs(deltaX)) {
221 DragAxis.VERTICAL
222 } else {
223 horizontalDragTarget
224 ?.takeIf { canvasView.maxHorizontalOffset(it) > 0 }
225 ?.let { DragAxis.HORIZONTAL }
226 }
227 }
228 }
229 return dragAxis != null
230 }
231 MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> return dragAxis != null
232 }
233 return false
234 }
235
236 override fun dispatchTouchEvent(event: MotionEvent): Boolean {
237 if (event.actionMasked == MotionEvent.ACTION_DOWN) {
238 velocityTracker?.recycle()
239 velocityTracker = VelocityTracker.obtain()
240 }
241 velocityTracker?.addMovement(event)
242 val handled = super.dispatchTouchEvent(event)
243 if (
244 (
245 event.actionMasked == MotionEvent.ACTION_UP ||
246 event.actionMasked == MotionEvent.ACTION_CANCEL
247 ) &&
248 dragAxis == null
249 ) {
250 velocityTracker?.recycle()
251 velocityTracker = null
252 horizontalDragTarget = null
253 parent?.requestDisallowInterceptTouchEvent(false)
254 }
255 return handled
256 }
257
258 @Suppress("NestedBlockDepth")
259 override fun onTouchEvent(event: MotionEvent): Boolean {
260 val axis = dragAxis ?: return false
261 when (event.actionMasked) {
262 MotionEvent.ACTION_MOVE -> {
263 val deltaX = (lastTouchX - event.x).toInt()
264 val deltaY = (lastTouchY - event.y).toInt()
265 if (axis == DragAxis.VERTICAL) {
266 canvasView.scrollByVertical(deltaY)
267 } else {
268 horizontalDragTarget?.let { canvasView.scrollByHorizontal(deltaX, it) }
269 }
270 lastTouchX = event.x
271 lastTouchY = event.y
272 }
273 MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
274 if (event.actionMasked == MotionEvent.ACTION_UP) {
275 velocityTracker?.computeCurrentVelocity(1000)
276 if (axis == DragAxis.VERTICAL) {
277 val velocity = -(velocityTracker?.yVelocity ?: 0f).toInt()
278 if (abs(velocity) >= minimumFlingVelocity) {
279 verticalScroller.fling(
280 0,
281 canvasView.verticalOffset(),
282 0,
283 velocity,
284 0,
285 0,
286 0,
287 canvasView.maxVerticalOffset(),
288 )
289 postInvalidateOnAnimation()
290 }
291 } else if (horizontalDragTarget?.kind == HorizontalPanKind.CODE) {
292 val velocity = -(velocityTracker?.xVelocity ?: 0f).toInt()
293 if (abs(velocity) >= minimumFlingVelocity) {
294 horizontalScroller.fling(
295 canvasView.horizontalOffset(),
296 0,
297 velocity,
298 0,
299 0,
300 canvasView.maxHorizontalOffset(),
301 0,
302 0,
303 )
304 postInvalidateOnAnimation()
305 }
306 }
307 }
308 dragAxis = null
309 horizontalDragTarget = null
310 velocityTracker?.recycle()
311 velocityTracker = null
312 parent?.requestDisallowInterceptTouchEvent(false)
313 }
314 }
315 return true
316 }
317
318 override fun computeScroll() {
319 var animating = false
320 if (verticalScroller.computeScrollOffset()) {
321 canvasView.setVerticalOffset(verticalScroller.currY)
322 animating = true
323 }
324 if (horizontalScroller.computeScrollOffset()) {
325 canvasView.setHorizontalOffset(horizontalScroller.currX)
326 animating = true
327 }
328 if (animating) {
329 postInvalidateOnAnimation()
330 }
331 }
332
333 private fun rebuildVisibleRows() {
334 val filtered = ArrayList<DiffRow>(rows.size)
335 var currentFileCollapsed = false
336 rows.forEach { row ->
337 if (row.kind == "file") {
338 currentFileCollapsed = collapsedFileIds.contains(row.resolvedFileId)
339 filtered.add(row)
340 } else if (!currentFileCollapsed) {
341 filtered.add(row)
342 }
343 }
344 visibleRows = filtered
345 canvasView.rows = filtered
346 canvasView.viewedFileIds = viewedFileIds
347 canvasView.selectedRowIds = selectedRowIds
348 applyPendingInitialScroll()
349 }
350
351 private fun handleRowTap(row: DiffRow, gesture: String, target: RowTapTarget) {
352 when (row.kind) {
353 "file" -> {
354 if (gesture != "tap") return
355 if (target == RowTapTarget.VIEWED_CHECKBOX) {
356 onToggleViewedFile(mapOf("fileId" to row.resolvedFileId))
357 } else {
358 onToggleFile(mapOf("fileId" to row.resolvedFileId))
359 }
360 }
361 "comment" -> onToggleComment(mapOf("commentId" to row.id))
362 "line" -> {
363 val payload = mutableMapOf<String, Any>(
364 "rowId" to row.id,
365 "fileId" to row.resolvedFileId,
366 "gesture" to gesture,
367 "change" to row.change,
368 )
369 row.oldLineNumber?.let { payload["oldLineNumber"] = it }
370 row.newLineNumber?.let { payload["newLineNumber"] = it }
371 onPressLine(payload)
372 }
373 }
374 }
375
376 @Suppress("ReturnCount")
377 private fun emitVisibleFile(firstVisibleIndex: Int) {
378 if (visibleRows.isEmpty()) return
379 val start = firstVisibleIndex.coerceIn(0, visibleRows.lastIndex)
380 val fileId = (start downTo 0)
381 .asSequence()
382 .map { visibleRows[it].resolvedFileId }
383 .firstOrNull { it.isNotEmpty() }
384 ?: return
385 if (fileId == lastVisibleFileId) return
386 lastVisibleFileId = fileId
387 onVisibleFileChange(mapOf("fileId" to fileId))
388 }
389
390 private fun applyPendingInitialScroll() {
391 if (!pendingInitialScroll || visibleRows.isEmpty()) return
392 pendingInitialScroll = false
393 val index = initialRowIndex.coerceIn(0, visibleRows.lastIndex)
394 post { canvasView.setVerticalOffset(canvasView.rowTop(index)) }
395 }
396
397 private fun scrollToY(y: Int, animated: Boolean) {
398 val target = y.coerceIn(0, canvasView.maxVerticalOffset())
399 if (animated) {
400 verticalScroller.startScroll(
401 0,
402 canvasView.verticalOffset(),
403 0,
404 target - canvasView.verticalOffset(),
405 250,
406 )
407 postInvalidateOnAnimation()
408 } else {
409 canvasView.setVerticalOffset(target)
410 }
411 }
412
413 private fun dp(value: Float): Float = value * resources.displayMetrics.density
414
415 private enum class DragAxis {
416 VERTICAL,
417 HORIZONTAL
418 }
419}
420
421private enum class RowTapTarget {
422 ROW,
423 VIEWED_CHECKBOX
424}
425
426private enum class HorizontalPanKind {
427 CODE,
428 FILE_HEADER_PATH
429}
430
431private data class HorizontalPanTarget(
432 val fileId: String,
433 val kind: HorizontalPanKind
434)
435
436internal data class DiffRow(
437 val kind: String,
438 val id: String,
439 val fileId: String,
440 val filePath: String,
441 val previousPath: String?,
442 val changeType: String,
443 val additions: Int,
444 val deletions: Int,
445 val text: String,
446 val content: String,
447 val change: String,
448 val oldLineNumber: Int?,
449 val newLineNumber: Int?,
450 val wordDiffRanges: List<DiffWordDiffRange>,
451 val commentText: String,
452 val commentRangeLabel: String,
453 val commentSectionTitle: String
454) {
455 val resolvedFileId: String get() = fileId.ifEmpty { id }
456}
457
458internal data class DiffWordDiffRange(
459 val start: Int,
460 val end: Int
461)
462
463private data class DiffToken(
464 val content: String,
465 val color: Int?,
466 val fontStyle: Int
467)
468
469internal data class DiffTheme(
470 val background: Int,
471 val text: Int,
472 val mutedText: Int,
473 val headerBackground: Int,
474 val border: Int,
475 val hunkBackground: Int,
476 val hunkText: Int,
477 val addBackground: Int,
478 val deleteBackground: Int,
479 val addBar: Int,
480 val deleteBar: Int,
481 val addText: Int,
482 val deleteText: Int
483) {
484 companion object {
485 fun fallback(scheme: String): DiffTheme = if (scheme == "dark") {
486 DiffTheme(
487 background = Color.rgb(20, 22, 25),
488 text = Color.rgb(236, 238, 240),
489 mutedText = Color.rgb(153, 160, 170),
490 headerBackground = Color.rgb(26, 29, 33),
491 border = Color.rgb(52, 57, 64),
492 hunkBackground = Color.rgb(7, 31, 40),
493 hunkText = Color.rgb(0, 159, 255),
494 addBackground = Color.rgb(13, 47, 40),
495 deleteBackground = Color.rgb(57, 20, 21),
496 addBar = Color.rgb(0, 202, 177),
497 deleteBar = Color.rgb(255, 46, 63),
498 addText = Color.rgb(94, 204, 113),
499 deleteText = Color.rgb(255, 103, 98),
500 )
501 } else {
502 DiffTheme(
503 background = Color.WHITE,
504 text = Color.rgb(7, 7, 7),
505 mutedText = Color.rgb(102, 106, 115),
506 headerBackground = Color.WHITE,
507 border = Color.rgb(222, 224, 228),
508 hunkBackground = Color.rgb(224, 242, 255),
509 hunkText = Color.rgb(0, 130, 220),
510 addBackground = Color.rgb(229, 248, 245),
511 deleteBackground = Color.rgb(255, 230, 231),
512 addBar = Color.rgb(0, 172, 151),
513 deleteBar = Color.rgb(213, 44, 54),
514 addText = Color.rgb(25, 130, 67),
515 deleteText = Color.rgb(190, 38, 48),
516 )
517 }
518
519 fun fromJson(value: String, fallback: DiffTheme): DiffTheme = try {
520 val json = JSONObject(value)
521 DiffTheme(
522 background = color(json, "background", fallback.background),
523 text = color(json, "text", fallback.text),
524 mutedText = color(json, "mutedText", fallback.mutedText),
525 headerBackground = color(json, "headerBackground", fallback.headerBackground),
526 border = color(json, "border", fallback.border),
527 hunkBackground = color(json, "hunkBackground", fallback.hunkBackground),
528 hunkText = color(json, "hunkText", fallback.hunkText),
529 addBackground = color(json, "addBackground", fallback.addBackground),
530 deleteBackground = color(json, "deleteBackground", fallback.deleteBackground),
531 addBar = color(json, "addBar", fallback.addBar),
532 deleteBar = color(json, "deleteBar", fallback.deleteBar),
533 addText = color(json, "addText", fallback.addText),
534 deleteText = color(json, "deleteText", fallback.deleteText),
535 )
536 } catch (_: Exception) {
537 fallback
538 }
539
540 private fun color(json: JSONObject, key: String, fallback: Int): Int =
541 parseColor(json.optString(key), fallback)
542 }
543}
544
545internal data class DiffStyle(
546 val rowHeightPx: Float,
547 val gutterWidthPx: Float,
548 val codePaddingPx: Float,
549 val changeBarWidthPx: Float,
550 val fileHeaderHeightPx: Float,
551 val fileHeaderHorizontalPaddingPx: Float,
552 val codeFontSizePx: Float,
553 val codeFontWeight: String,
554 val lineNumberFontSizePx: Float,
555 val lineNumberFontWeight: String,
556 val hunkFontSizePx: Float,
557 val hunkFontWeight: String,
558 val fileHeaderFontSizePx: Float,
559 val fileHeaderFontWeight: String,
560 val fileHeaderMetaFontSizePx: Float,
561 val fileHeaderMetaFontWeight: String,
562 val fileHeaderSubtextFontSizePx: Float,
563 val fileHeaderSubtextFontWeight: String
564) {
565 companion object {
566 fun defaults(density: Float): DiffStyle = DiffStyle(
567 rowHeightPx = 20f * density,
568 gutterWidthPx = 72f * density,
569 codePaddingPx = 10f * density,
570 changeBarWidthPx = 3f * density,
571 fileHeaderHeightPx = 44f * density,
572 fileHeaderHorizontalPaddingPx = 10f * density,
573 codeFontSizePx = 12f * density,
574 codeFontWeight = "regular",
575 lineNumberFontSizePx = 10f * density,
576 lineNumberFontWeight = "regular",
577 hunkFontSizePx = 11f * density,
578 hunkFontWeight = "medium",
579 fileHeaderFontSizePx = 11f * density,
580 fileHeaderFontWeight = "semibold",
581 fileHeaderMetaFontSizePx = 10f * density,
582 fileHeaderMetaFontWeight = "semibold",
583 fileHeaderSubtextFontSizePx = 11f * density,
584 fileHeaderSubtextFontWeight = "medium",
585 )
586
587 fun fromJson(value: String, fallback: DiffStyle, density: Float): DiffStyle = try {
588 val json = JSONObject(value)
589 DiffStyle(
590 rowHeightPx = json.floatDp("rowHeight", fallback.rowHeightPx, density),
591 gutterWidthPx = json.floatDp("gutterWidth", fallback.gutterWidthPx, density),
592 codePaddingPx = json.floatDp("codePadding", fallback.codePaddingPx, density),
593 changeBarWidthPx = json.floatDp("changeBarWidth", fallback.changeBarWidthPx, density),
594 fileHeaderHeightPx = json.floatDp("fileHeaderHeight", fallback.fileHeaderHeightPx, density),
595 fileHeaderHorizontalPaddingPx = json.floatDp(
596 "fileHeaderHorizontalPadding",
597 fallback.fileHeaderHorizontalPaddingPx,
598 density,
599 ),
600 codeFontSizePx = json.floatSp("codeFontSize", fallback.codeFontSizePx, density),
601 codeFontWeight = json.optString("codeFontWeight", fallback.codeFontWeight),
602 lineNumberFontSizePx = json.floatSp(
603 "lineNumberFontSize",
604 fallback.lineNumberFontSizePx,
605 density,
606 ),
607 lineNumberFontWeight = json.optString(
608 "lineNumberFontWeight",
609 fallback.lineNumberFontWeight,
610 ),
611 hunkFontSizePx = json.floatSp("hunkFontSize", fallback.hunkFontSizePx, density),
612 hunkFontWeight = json.optString("hunkFontWeight", fallback.hunkFontWeight),
613 fileHeaderFontSizePx = json.floatSp(
614 "fileHeaderFontSize",
615 fallback.fileHeaderFontSizePx,
616 density,
617 ),
618 fileHeaderFontWeight = json.optString(
619 "fileHeaderFontWeight",
620 fallback.fileHeaderFontWeight,
621 ),
622 fileHeaderMetaFontSizePx = json.floatSp(
623 "fileHeaderMetaFontSize",
624 fallback.fileHeaderMetaFontSizePx,
625 density,
626 ),
627 fileHeaderMetaFontWeight = json.optString(
628 "fileHeaderMetaFontWeight",
629 fallback.fileHeaderMetaFontWeight,
630 ),
631 fileHeaderSubtextFontSizePx = json.floatSp(
632 "fileHeaderSubtextFontSize",
633 fallback.fileHeaderSubtextFontSizePx,
634 density,
635 ),
636 fileHeaderSubtextFontWeight = json.optString(
637 "fileHeaderSubtextFontWeight",
638 fallback.fileHeaderSubtextFontWeight,
639 ),
640 )
641 } catch (_: Exception) {
642 fallback
643 }
644 }
645}
646
647private class DiffCanvasView(context: Context) : View(context) {
648 private val density = resources.displayMetrics.density
649 private val drawing = ReviewDiffCanvasDrawing(context)
650 private val backgroundPaint = drawing.backgroundPaint
651 private val borderPaint = drawing.borderPaint
652 private val textPaint = drawing.textPaint
653 private val boldTextPaint = drawing.uiPaint
654 private val gestureDetector = GestureDetector(
655 context,
656 object : GestureDetector.SimpleOnGestureListener() {
657 override fun onDown(event: MotionEvent): Boolean = true
658
659 override fun onSingleTapUp(event: MotionEvent): Boolean {
660 rowHitAt(event.y)?.let { hit ->
661 val target = if (
662 hit.row.kind == "file" &&
663 drawing.fileHeaderCheckboxRect(
664 hit.top,
665 hit.bottom,
666 width,
667 style
668 ).contains(event.x, event.y)
669 ) {
670 RowTapTarget.VIEWED_CHECKBOX
671 } else {
672 RowTapTarget.ROW
673 }
674 onRowTap?.invoke(hit.row, "tap", target)
675 }
676 return true
677 }
678
679 override fun onLongPress(event: MotionEvent) {
680 rowHitAt(event.y)?.row
681 ?.takeIf { it.kind == "line" }
682 ?.let { onRowTap?.invoke(it, "longPress", RowTapTarget.ROW) }
683 }
684 },
685 )
686 private var rowOffsets = intArrayOf(0)
687 private var verticalOffset = 0
688 private var horizontalOffset = 0
689 private val headerPathOffsetsByFileId = mutableMapOf<String, Int>()
690 private var lastVisibleRange: Pair<Int, Int>? = null
691 var rows: List<DiffRow> = emptyList()
692 set(value) {
693 field = value
694 headerPathOffsetsByFileId.keys.retainAll(
695 value.asSequence().filter { it.kind == "file" }.map { it.resolvedFileId }.toSet(),
696 )
697 rebuildOffsets()
698 }
699 var tokensByRowId: Map<String, List<DiffToken>> = emptyMap()
700 set(value) {
701 field = value
702 invalidate()
703 }
704 var viewedFileIds: Set<String> = emptySet()
705 set(value) {
706 field = value
707 invalidate()
708 }
709 var collapsedFileIds: Set<String> = emptySet()
710 set(value) {
711 field = value
712 invalidate()
713 }
714 var collapsedCommentIds: Set<String> = emptySet()
715 set(value) {
716 field = value
717 rebuildOffsets()
718 }
719 var selectedRowIds: Set<String> = emptySet()
720 set(value) {
721 field = value
722 invalidate()
723 }
724 var theme: DiffTheme = DiffTheme.fallback("light")
725 set(value) {
726 field = value
727 drawing.theme = value
728 invalidate()
729 }
730 var style: DiffStyle = DiffStyle.defaults(density)
731 set(value) {
732 field = value
733 rebuildOffsets()
734 }
735 var contentWidthPx: Int = (1200 * density).toInt()
736 set(value) {
737 field = max(value, suggestedMinimumWidth)
738 setHorizontalOffset(horizontalOffset)
739 clampHeaderPathOffsets()
740 invalidate()
741 }
742 var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null
743 var onVisibleRowsChanged: ((Int, Int) -> Unit)? = null
744
745 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
746 setMeasuredDimension(
747 MeasureSpec.getSize(widthMeasureSpec),
748 MeasureSpec.getSize(heightMeasureSpec),
749 )
750 }
751
752 override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
753 super.onSizeChanged(width, height, oldWidth, oldHeight)
754 setVerticalOffset(verticalOffset)
755 setHorizontalOffset(horizontalOffset)
756 clampHeaderPathOffsets()
757 }
758
759 override fun onDraw(canvas: Canvas) {
760 super.onDraw(canvas)
761 canvas.drawColor(theme.background)
762 if (rows.isEmpty()) return
763 val first = rowIndexAt(max(0, verticalOffset + canvas.clipBounds.top))
764 val last = rowIndexAt(
765 min(max(0, rowOffsets.last() - 1), verticalOffset + canvas.clipBounds.bottom),
766 ).coerceAtLeast(first)
767 for (index in first..last.coerceAtMost(rows.lastIndex)) {
768 drawRow(
769 canvas,
770 rows[index],
771 rowOffsets[index] - verticalOffset,
772 rowOffsets[index + 1] - verticalOffset,
773 )
774 }
775 drawStickyFileHeader(canvas, first)
776 drawHorizontalScrollIndicator(canvas)
777 emitVisibleRange()
778 }
779
780 override fun onTouchEvent(event: MotionEvent): Boolean = gestureDetector.onTouchEvent(event)
781
782 fun rowTop(index: Int): Int = rowOffsets[index.coerceIn(0, max(0, rowOffsets.size - 2))]
783
784 fun setVerticalOffset(value: Int) {
785 val maxOffset = max(0, (rowOffsets.lastOrNull() ?: 0) - height)
786 val nextOffset = value.coerceIn(0, maxOffset)
787 if (verticalOffset == nextOffset) return
788 verticalOffset = nextOffset
789 invalidate()
790 emitVisibleRange()
791 }
792
793 fun scrollByVertical(delta: Int) {
794 setVerticalOffset(verticalOffset + delta)
795 }
796
797 fun verticalOffset(): Int = verticalOffset
798
799 fun maxVerticalOffset(): Int = max(0, (rowOffsets.lastOrNull() ?: 0) - height)
800
801 fun setHorizontalOffset(value: Int) {
802 val nextOffset = value.coerceIn(0, maxHorizontalOffset())
803 if (horizontalOffset == nextOffset) return
804 horizontalOffset = nextOffset
805 invalidate()
806 }
807
808 fun scrollByHorizontal(delta: Int, target: HorizontalPanTarget) {
809 if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
810 setHeaderPathOffset(
811 target.fileId,
812 (headerPathOffsetsByFileId[target.fileId] ?: 0) + delta,
813 )
814 } else {
815 setHorizontalOffset(horizontalOffset + delta)
816 }
817 }
818
819 fun horizontalOffset(): Int = horizontalOffset
820
821 fun maxHorizontalOffset(): Int = max(0, contentWidthPx - width)
822
823 fun maxHorizontalOffset(target: HorizontalPanTarget): Int =
824 if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
825 maxHeaderPathOffset(target.fileId)
826 } else {
827 maxHorizontalOffset()
828 }
829
830 fun horizontalPanTarget(y: Float): HorizontalPanTarget? {
831 val row = rowHitAt(y)?.row ?: return null
832 return HorizontalPanTarget(
833 fileId = row.resolvedFileId,
834 kind = if (row.kind == "file") HorizontalPanKind.FILE_HEADER_PATH else HorizontalPanKind.CODE,
835 )
836 }
837
838 fun resetHorizontalOffsets() {
839 setHorizontalOffset(0)
840 if (headerPathOffsetsByFileId.isNotEmpty()) {
841 headerPathOffsetsByFileId.clear()
842 invalidate()
843 }
844 }
845
846 private fun rebuildOffsets() {
847 rowOffsets = IntArray(rows.size + 1)
848 rows.forEachIndexed { index, row ->
849 rowOffsets[index + 1] = rowOffsets[index] + rowHeight(row)
850 }
851 setVerticalOffset(verticalOffset)
852 clampHeaderPathOffsets()
853 requestLayout()
854 invalidate()
855 }
856
857 private fun rowHeight(row: DiffRow): Int = when (row.kind) {
858 "file" -> style.fileHeaderHeightPx.toInt()
859 "notice" -> max((style.rowHeightPx * 2f).toInt(), (44 * density).toInt())
860 "comment" -> if (collapsedCommentIds.contains(row.id)) {
861 (44 * density).toInt()
862 } else {
863 (124 * density).toInt()
864 }
865 else -> style.rowHeightPx.toInt()
866 }.coerceAtLeast(1)
867
868 @Suppress("ReturnCount")
869 private fun rowIndexAt(y: Int): Int {
870 if (rows.isEmpty()) return 0
871 var low = 0
872 var high = rows.lastIndex
873 while (low <= high) {
874 val middle = (low + high) ushr 1
875 when {
876 y < rowOffsets[middle] -> high = middle - 1
877 y >= rowOffsets[middle + 1] -> low = middle + 1
878 else -> return middle
879 }
880 }
881 return low.coerceIn(0, rows.lastIndex)
882 }
883
884 private fun rowHitAt(y: Float): RowHit? {
885 stickyFileHeader(firstVisibleRow())?.let { sticky ->
886 if (y >= max(0, sticky.top).toFloat() && y < sticky.bottom.toFloat()) {
887 return rows.getOrNull(sticky.index)?.let { RowHit(it, sticky.top, sticky.bottom) }
888 }
889 }
890 val index = rowIndexAt(verticalOffset + y.toInt())
891 return rows.getOrNull(index)?.let {
892 RowHit(
893 row = it,
894 top = rowOffsets[index] - verticalOffset,
895 bottom = rowOffsets[index + 1] - verticalOffset,
896 )
897 }
898 }
899
900 private fun firstVisibleRow(): Int = rowIndexAt(verticalOffset)
901
902 private fun emitVisibleRange() {
903 if (rows.isEmpty()) return
904 val first = rowIndexAt(verticalOffset)
905 val last = rowIndexAt(verticalOffset + max(1, height))
906 val range = first to last
907 if (range == lastVisibleRange) return
908 lastVisibleRange = range
909 onVisibleRowsChanged?.invoke(first, last)
910 }
911
912 private fun drawRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
913 when (row.kind) {
914 "file" -> drawFileRow(canvas, row, top, bottom)
915 "hunk" -> drawHunkRow(canvas, row, top, bottom)
916 "notice" -> drawNoticeRow(canvas, row, top, bottom)
917 "comment" -> drawCommentRow(canvas, row, top, bottom)
918 else -> drawLineRow(canvas, row, top, bottom)
919 }
920 }
921
922 private fun drawFileRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
923 fill(canvas, theme.headerBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
924
925 val chevronRect = drawing.fileHeaderChevronRect(top, bottom, style)
926 val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
927 val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
928 drawing.drawDisclosureChevron(
929 canvas,
930 chevronRect,
931 theme.mutedText,
932 collapsed = collapsedFileIds.contains(row.resolvedFileId),
933 )
934 drawing.drawFileIcon(canvas, iconRect, row.changeType)
935 drawing.drawViewedCheckbox(
936 canvas,
937 checkboxRect,
938 viewedFileIds.contains(row.resolvedFileId),
939 )
940
941 drawing.configureUiPaint(
942 paint = boldTextPaint,
943 color = theme.deleteText,
944 size = style.fileHeaderMetaFontSizePx,
945 weight = style.fileHeaderMetaFontWeight,
946 )
947 val deleteText = "-${row.deletions}"
948 val deleteWidth = boldTextPaint.measureText(deleteText)
949 val addText = "+${row.additions}"
950 val addWidth = boldTextPaint.measureText(addText)
951 val countGap = 4f * density
952 val countsX = checkboxRect.left - 10f * density - deleteWidth - countGap - addWidth
953 val baseline = centeredBaseline(top, bottom, boldTextPaint)
954 canvas.drawText(deleteText, countsX, baseline, boldTextPaint)
955 boldTextPaint.color = theme.addText
956 canvas.drawText(addText, countsX + deleteWidth + countGap, baseline, boldTextPaint)
957
958 val pathLayout = fileHeaderPathLayout(row, top, bottom, iconRect, countsX)
959 val maxPathOffset = maxHeaderPathOffset(pathLayout)
960 val pathOffset = (headerPathOffsetsByFileId[row.resolvedFileId] ?: 0)
961 .coerceIn(0, maxPathOffset)
962 canvas.save()
963 canvas.clipRect(pathLayout.rect)
964 canvas.drawText(
965 pathLayout.displayPath,
966 pathLayout.rect.left - pathOffset,
967 centeredBaseline(top, bottom, boldTextPaint),
968 boldTextPaint,
969 )
970 canvas.restore()
971 drawing.drawFileHeaderPathScrollFades(
972 canvas,
973 pathLayout.rect,
974 pathOffset,
975 maxPathOffset,
976 )
977 drawBottomBorder(canvas, bottom)
978 }
979
980 private fun fileHeaderPathLayout(
981 row: DiffRow,
982 top: Int,
983 bottom: Int,
984 iconRect: RectF,
985 countsX: Float
986 ): FileHeaderPathLayout {
987 drawing.configureUiPaint(
988 paint = boldTextPaint,
989 color = theme.text,
990 size = style.fileHeaderFontSizePx,
991 weight = style.fileHeaderFontWeight,
992 )
993 val pathX = iconRect.right + 10f * density
994 val pathWidth = max(24f * density, countsX - pathX - 12f * density)
995 val centerY = (top + bottom) / 2f
996 val displayPath = if (
997 !row.previousPath.isNullOrEmpty() && row.previousPath != row.filePath
998 ) {
999 "${row.previousPath} -> ${row.filePath}"
1000 } else {
1001 row.filePath
1002 }
1003 return FileHeaderPathLayout(
1004 displayPath = displayPath,
1005 rect = RectF(pathX, centerY - 10f * density, pathX + pathWidth, centerY + 10f * density),
1006 )
1007 }
1008
1009 private fun maxHeaderPathOffset(fileId: String): Int {
1010 val row = rows.firstOrNull { it.kind == "file" && it.resolvedFileId == fileId } ?: return 0
1011 val top = 0
1012 val bottom = rowHeight(row)
1013 val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
1014 val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
1015 drawing.configureUiPaint(
1016 paint = boldTextPaint,
1017 color = theme.deleteText,
1018 size = style.fileHeaderMetaFontSizePx,
1019 weight = style.fileHeaderMetaFontWeight,
1020 )
1021 val countsX = checkboxRect.left - 10f * density -
1022 boldTextPaint.measureText("-${row.deletions}") - 4f * density -
1023 boldTextPaint.measureText("+${row.additions}")
1024 return maxHeaderPathOffset(fileHeaderPathLayout(row, top, bottom, iconRect, countsX))
1025 }
1026
1027 private fun maxHeaderPathOffset(layout: FileHeaderPathLayout): Int = max(
1028 0,
1029 ceil(boldTextPaint.measureText(layout.displayPath) - layout.rect.width()).toInt(),
1030 )
1031
1032 private fun setHeaderPathOffset(fileId: String, value: Int) {
1033 val nextOffset = value.coerceIn(0, maxHeaderPathOffset(fileId))
1034 if ((headerPathOffsetsByFileId[fileId] ?: 0) == nextOffset) return
1035 headerPathOffsetsByFileId[fileId] = nextOffset
1036 invalidate()
1037 }
1038
1039 private fun clampHeaderPathOffsets() {
1040 headerPathOffsetsByFileId.keys.toList().forEach { fileId ->
1041 val nextOffset = (headerPathOffsetsByFileId[fileId] ?: 0)
1042 .coerceIn(0, maxHeaderPathOffset(fileId))
1043 if (nextOffset == 0) {
1044 headerPathOffsetsByFileId.remove(fileId)
1045 } else {
1046 headerPathOffsetsByFileId[fileId] = nextOffset
1047 }
1048 }
1049 }
1050
1051 private fun drawHunkRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
1052 fill(canvas, theme.hunkBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
1053 drawing.configureMonospacePaint(
1054 color = theme.hunkText,
1055 size = style.hunkFontSizePx,
1056 weight = style.hunkFontWeight,
1057 )
1058 drawScrollableCode(canvas, top, bottom) { codeX ->
1059 canvas.drawText(
1060 row.text.ifEmpty { row.content },
1061 codeX,
1062 centeredBaseline(top, bottom, textPaint),
1063 textPaint,
1064 )
1065 }
1066 }
1067
1068 private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
1069 fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
1070 val iconSize = 16f * density
1071 val iconRect = RectF(
1072 style.fileHeaderHorizontalPaddingPx + 2f * density,
1073 (top + bottom - iconSize) / 2f,
1074 style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize,
1075 (top + bottom + iconSize) / 2f,
1076 )
1077 drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText)
1078 drawing.configureUiPaint(
1079 paint = textPaint,
1080 color = theme.mutedText,
1081 size = style.fileHeaderSubtextFontSizePx,
1082 weight = style.fileHeaderSubtextFontWeight,
1083 )
1084 val textX = iconRect.right + 10f * density
1085 canvas.drawText(
1086 ellipsize(row.text, textPaint, width - textX - style.fileHeaderHorizontalPaddingPx),
1087 textX,
1088 centeredBaseline(top, bottom, textPaint),
1089 textPaint,
1090 )
1091 drawBottomBorder(canvas, bottom)
1092 }
1093
1094 private fun drawCommentRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
1095 fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
1096 val cardRect = RectF(
1097 8f * density,
1098 top + 5f * density,
1099 width - 8f * density,
1100 bottom - 5f * density,
1101 )
1102 backgroundPaint.color = theme.headerBackground
1103 canvas.drawRoundRect(cardRect, 10f * density, 10f * density, backgroundPaint)
1104 borderPaint.style = Paint.Style.STROKE
1105 borderPaint.color = withAlpha(theme.border, 217)
1106 borderPaint.strokeWidth = density
1107 canvas.drawRoundRect(cardRect, 10f * density, 10f * density, borderPaint)
1108 borderPaint.style = Paint.Style.FILL
1109
1110 val collapsed = collapsedCommentIds.contains(row.id)
1111 val chevronRect = RectF(
1112 cardRect.left + 10f * density,
1113 cardRect.top + 11f * density,
1114 cardRect.left + 26f * density,
1115 cardRect.top + 27f * density,
1116 )
1117 drawing.drawDisclosureChevron(canvas, chevronRect, theme.mutedText, collapsed)
1118 drawing.configureUiPaint(
1119 paint = textPaint,
1120 color = theme.mutedText,
1121 size = style.fileHeaderSubtextFontSizePx,
1122 weight = style.fileHeaderSubtextFontWeight,
1123 )
1124 val title = "Comment on ${row.commentRangeLabel.ifEmpty { "line" }}"
1125 canvas.drawText(
1126 ellipsize(title, textPaint, cardRect.right - chevronRect.right - 20f * density),
1127 chevronRect.right + 10f * density,
1128 cardRect.top + 22f * density,
1129 textPaint,
1130 )
1131 if (!collapsed) {
1132 textPaint.color = theme.text
1133 val bodyX = cardRect.left + 18f * density
1134 canvas.drawText(
1135 ellipsize(
1136 row.commentText.ifEmpty { "Comment" },
1137 textPaint,
1138 cardRect.right - bodyX - 18f * density
1139 ),
1140 bodyX,
1141 cardRect.top + 58f * density,
1142 textPaint,
1143 )
1144 }
1145 }
1146
1147 @Suppress("CyclomaticComplexMethod")
1148 private fun drawLineRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
1149 val background = when (row.change) {
1150 "add" -> theme.addBackground
1151 "delete" -> theme.deleteBackground
1152 else -> theme.background
1153 }
1154 fill(canvas, background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
1155 if (style.changeBarWidthPx > 0) {
1156 when (row.change) {
1157 "add" -> fill(
1158 canvas,
1159 theme.addBar,
1160 0f,
1161 top.toFloat(),
1162 style.changeBarWidthPx,
1163 bottom.toFloat()
1164 )
1165 "delete" -> drawing.drawDeleteStripes(
1166 canvas,
1167 top,
1168 bottom,
1169 style.changeBarWidthPx,
1170 theme.deleteBar,
1171 )
1172 }
1173 }
1174 val selected = selectedRowIds.contains(row.id)
1175 if (selected) {
1176 fill(
1177 canvas,
1178 withAlpha(theme.hunkText, 56),
1179 0f,
1180 top.toFloat(),
1181 width.toFloat(),
1182 bottom.toFloat(),
1183 )
1184 fill(
1185 canvas,
1186 withAlpha(theme.hunkText, 242),
1187 0f,
1188 top.toFloat(),
1189 style.changeBarWidthPx,
1190 bottom.toFloat()
1191 )
1192 }
1193
1194 val tokens = tokensByRowId[row.id]
1195 drawScrollableCode(canvas, top, bottom) { codeX ->
1196 drawing.configureCodePaint(theme.text, 0, style)
1197 drawing.drawWordDiffRanges(canvas, row, codeX, top, bottom)
1198 if (tokens.isNullOrEmpty()) {
1199 canvas.drawText(row.content, codeX, centeredBaseline(top, bottom, textPaint), textPaint)
1200 } else {
1201 var x = codeX
1202 tokens.forEach { token ->
1203 drawing.configureCodePaint(token.color ?: theme.text, token.fontStyle, style)
1204 canvas.drawText(token.content, x, centeredBaseline(top, bottom, textPaint), textPaint)
1205 x += textPaint.measureText(token.content)
1206 }
1207 }
1208 }
1209
1210 drawLineNumber(canvas, row, top, bottom)
1211 }
1212
1213 private fun drawLineNumber(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
1214 val lineNumber = row.newLineNumber ?: row.oldLineNumber ?: return
1215 drawing.configureMonospacePaint(
1216 color = drawing.lineNumberColor(row.change),
1217 size = style.lineNumberFontSizePx,
1218 weight = style.lineNumberFontWeight,
1219 )
1220 textPaint.textAlign = Paint.Align.RIGHT
1221 canvas.drawText(
1222 lineNumber.toString(),
1223 style.changeBarWidthPx + style.gutterWidthPx - style.codePaddingPx,
1224 centeredBaseline(top, bottom, textPaint),
1225 textPaint,
1226 )
1227 textPaint.textAlign = Paint.Align.LEFT
1228 }
1229
1230 private fun drawScrollableCode(
1231 canvas: Canvas,
1232 top: Int,
1233 bottom: Int,
1234 draw: (Float) -> Unit
1235 ) {
1236 val gutterEnd = style.changeBarWidthPx + style.gutterWidthPx
1237 canvas.save()
1238 canvas.clipRect(gutterEnd, top.toFloat(), width.toFloat(), bottom.toFloat())
1239 draw(gutterEnd + style.codePaddingPx - horizontalOffset)
1240 canvas.restore()
1241 }
1242
1243 private fun drawStickyFileHeader(canvas: Canvas, firstVisibleIndex: Int) {
1244 val sticky = stickyFileHeader(firstVisibleIndex) ?: return
1245 val naturalTop = rowOffsets[sticky.index] - verticalOffset
1246 if (naturalTop == sticky.top) return
1247 drawFileRow(canvas, rows[sticky.index], sticky.top, sticky.bottom)
1248 }
1249
1250 @Suppress("ReturnCount")
1251 private fun stickyFileHeader(firstVisibleIndex: Int): StickyFileHeader? {
1252 if (rows.isEmpty()) return null
1253 val fileIndex = (firstVisibleIndex.coerceIn(0, rows.lastIndex) downTo 0)
1254 .firstOrNull { rows[it].kind == "file" }
1255 ?: return null
1256 val headerHeight = rowHeight(rows[fileIndex])
1257 val nextFileIndex = ((fileIndex + 1)..rows.lastIndex).firstOrNull { rows[it].kind == "file" }
1258 val top = nextFileIndex
1259 ?.let { min(0, rowOffsets[it] - verticalOffset - headerHeight) }
1260 ?: 0
1261 return StickyFileHeader(fileIndex, top, top + headerHeight)
1262 }
1263
1264 private fun drawHorizontalScrollIndicator(canvas: Canvas) {
1265 val maxOffset = maxHorizontalOffset()
1266 if (maxOffset <= 0 || width <= 0) return
1267 val trackWidth = width.toFloat()
1268 val thumbWidth = max(24f * density, trackWidth * trackWidth / contentWidthPx)
1269 val thumbTravel = trackWidth - thumbWidth
1270 val left = thumbTravel * horizontalOffset / maxOffset
1271 fill(
1272 canvas,
1273 withAlpha(theme.mutedText, 110),
1274 left,
1275 height - 2f * density,
1276 left + thumbWidth,
1277 height.toFloat(),
1278 )
1279 }
1280
1281 @Suppress("LongParameterList")
1282 private fun fill(
1283 canvas: Canvas,
1284 color: Int,
1285 left: Float,
1286 top: Float,
1287 right: Float,
1288 bottom: Float
1289 ) {
1290 backgroundPaint.color = color
1291 canvas.drawRect(left, top, right, bottom, backgroundPaint)
1292 }
1293
1294 private fun drawBottomBorder(canvas: Canvas, bottom: Int) {
1295 borderPaint.color = theme.border
1296 borderPaint.strokeWidth = density
1297 canvas.drawLine(0f, bottom - density / 2f, width.toFloat(), bottom - density / 2f, borderPaint)
1298 }
1299
1300 private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float {
1301 val metrics = paint.fontMetrics
1302 return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f
1303 }
1304
1305 private fun ellipsize(value: String, paint: Paint, width: Float): String {
1306 if (paint.measureText(value) <= width) return value
1307 val suffix = "..."
1308 val available = max(0f, width - paint.measureText(suffix))
1309 var end = value.length
1310 while (end > 0 && paint.measureText(value, 0, end) > available) end -= 1
1311 return value.substring(0, end) + suffix
1312 }
1313
1314 private data class StickyFileHeader(
1315 val index: Int,
1316 val top: Int,
1317 val bottom: Int
1318 )
1319
1320 private data class RowHit(
1321 val row: DiffRow,
1322 val top: Int,
1323 val bottom: Int
1324 )
1325
1326 private data class FileHeaderPathLayout(
1327 val displayPath: String,
1328 val rect: RectF
1329 )
1330}
1331
1332private fun withAlpha(color: Int, alpha: Int): Int =
1333 Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
1334
1335private fun parseRows(value: String): List<DiffRow> = try {
1336 val array = JSONArray(value)
1337 List(array.length()) { index ->
1338 val row = array.getJSONObject(index)
1339 DiffRow(
1340 kind = row.optString("kind"),
1341 id = row.optString("id"),
1342 fileId = row.optString("fileId"),
1343 filePath = row.optString("filePath"),
1344 previousPath = row.optNullableString("previousPath"),
1345 changeType = row.optString("changeType"),
1346 additions = row.optInt("additions"),
1347 deletions = row.optInt("deletions"),
1348 text = row.optString("text"),
1349 content = row.optString("content"),
1350 change = row.optString("change", "context"),
1351 oldLineNumber = row.optNullableInt("oldLineNumber"),
1352 newLineNumber = row.optNullableInt("newLineNumber"),
1353 wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),
1354 commentText = row.optString("commentText"),
1355 commentRangeLabel = row.optString("commentRangeLabel"),
1356 commentSectionTitle = row.optString("commentSectionTitle"),
1357 )
1358 }
1359} catch (_: Exception) {
1360 emptyList()
1361}
1362
1363private fun parseWordDiffRanges(value: JSONArray): List<DiffWordDiffRange> = buildList {
1364 for (index in 0 until value.length()) {
1365 val range = value.optJSONObject(index) ?: continue
1366 val start = range.optInt("start", -1)
1367 val end = range.optInt("end", -1)
1368 if (start >= 0 && end > start) {
1369 add(DiffWordDiffRange(start = start, end = end))
1370 }
1371 }
1372}
1373
1374private fun parseTokensObject(value: String): Map<String, List<DiffToken>> = try {
1375 parseTokensObject(JSONObject(value))
1376} catch (_: Exception) {
1377 emptyMap()
1378}
1379
1380private fun parseTokensObject(value: JSONObject): Map<String, List<DiffToken>> {
1381 val result = LinkedHashMap<String, List<DiffToken>>()
1382 val keys = value.keys()
1383 while (keys.hasNext()) {
1384 val rowId = keys.next()
1385 val array = value.optJSONArray(rowId) ?: continue
1386 result[rowId] = List(array.length()) { index ->
1387 val token = array.getJSONObject(index)
1388 DiffToken(
1389 content = token.optString("content"),
1390 color = token.optNullableString("color")?.let(::parseColorOrNull),
1391 fontStyle = token.optInt("fontStyle"),
1392 )
1393 }
1394 }
1395 return result
1396}
1397
1398private fun parseStringSet(value: String): Set<String> = try {
1399 val array = JSONArray(value)
1400 buildSet {
1401 for (index in 0 until array.length()) add(array.getString(index))
1402 }
1403} catch (_: Exception) {
1404 emptySet()
1405}
1406
1407private fun parseColor(value: String, fallback: Int): Int = try {
1408 Color.parseColor(value)
1409} catch (_: Exception) {
1410 fallback
1411}
1412
1413private fun parseColorOrNull(value: String): Int? = try {
1414 Color.parseColor(value)
1415} catch (_: Exception) {
1416 null
1417}
1418
1419private fun JSONObject.optNullableString(key: String): String? =
1420 if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
1421
1422private fun JSONObject.optNullableInt(key: String): Int? =
1423 if (isNull(key) || !has(key)) null else optInt(key)
1424
1425private fun JSONObject.floatDp(key: String, fallbackPx: Float, density: Float): Float =
1426 if (has(key)) optDouble(key).toFloat() * density else fallbackPx
1427
1428private fun JSONObject.floatSp(key: String, fallbackPx: Float, density: Float): Float =
1429 if (has(key)) optDouble(key).toFloat() * density else fallbackPx
apps/mobile/modules/t3-review-diff/expo-module.config.json+4−1
@@ -1,7 +1,10 @@
1{1{
2 "platforms": ["apple"],2 "platforms": ["apple", "android"],
3 "apple": {3 "apple": {
4 "modules": ["T3ReviewDiffModule"],4 "modules": ["T3ReviewDiffModule"],
5 "podspecPath": "T3ReviewDiffNative.podspec"5 "podspecPath": "T3ReviewDiffNative.podspec"
6 },
7 "android": {
8 "modules": ["expo.modules.t3reviewdiff.T3ReviewDiffModule"]
6 }9 }
7}10}
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift+40−13
@@ -5,22 +5,14 @@ public class T3ReviewDiffModule: Module { · 4 unmodified lines
5 Name("T3ReviewDiffSurface")5 Name("T3ReviewDiffSurface")
6 6
7 View(T3ReviewDiffView.self) {7 View(T3ReviewDiffView.self) {
8 Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
9 view.setRowsJson(rowsJson)
10 }
11
12 Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
13 view.setTokensJson(tokensJson)
14 }
15
16 Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
17 view.setTokensPatchJson(tokensPatchJson)
18 }
19
20 Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in8 Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
21 view.setTokensResetKey(tokensResetKey)9 view.setTokensResetKey(tokensResetKey)
22 }10 }
23 11
12 Prop("contentResetKey") { (view: T3ReviewDiffView, contentResetKey: String) in
13 view.setContentResetKey(contentResetKey)
14 }
15
24 Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in16 Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
25 view.setCollapsedFileIdsJson(collapsedFileIdsJson)17 view.setCollapsedFileIdsJson(collapsedFileIdsJson)
26 }18 }
@@ -61,7 +53,42 @@ public class T3ReviewDiffModule: Module { · 34 unmodified lines
61 view.setInitialRowIndex(initialRowIndex)53 view.setInitialRowIndex(initialRowIndex)
62 }54 }
63 55
64 Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")56 Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in
57 view.setRefreshing(refreshing)
58 }
59
60 Events(
61 "onDebug",
62 "onVisibleFileChange",
63 "onToggleFile",
64 "onToggleViewedFile",
65 "onPressLine",
66 "onToggleComment",
67 "onPullToRefresh"
68 )
69
70 AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
71 view.scrollToFile(fileId, animated: animated)
72 }
73
74 AsyncFunction("scrollToTop") { (view: T3ReviewDiffView, animated: Bool) in
75 view.scrollToTop(animated: animated)
76 }
77
78 // Large, frequently changing JSON values cannot be regular Fabric props. Expo's
79 // prop adapter compares strings on the main thread before invoking a setter, which
80 // makes a syntax-token patch capable of blocking a frame by itself.
81 AsyncFunction("setRowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
82 view.setRowsJson(rowsJson)
83 }
84
85 AsyncFunction("setTokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
86 view.setTokensJson(tokensJson)
87 }
88
89 AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
90 view.setTokensPatchJson(tokensPatchJson)
91 }
65 }92 }
66 }93 }
67}94}
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift+270−60
@@ -1,7 +1,7 @@
1import ExpoModulesCore1import ExpoModulesCore
2import UIKit2import UIKit
3 3
4private struct ReviewDiffNativeRow: Decodable {4private struct ReviewDiffNativeRow: Decodable, Sendable {
5 let kind: String5 let kind: String
6 let id: String6 let id: String
7 let fileId: String?7 let fileId: String?
@@ -21,18 +21,18 @@ private struct ReviewDiffNativeRow: Decodable { · 13 unmodified lines
21 let commentSectionTitle: String?21 let commentSectionTitle: String?
22}22}
23 23
24private struct ReviewDiffNativeWordDiffRange: Decodable {24private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
25 let start: Int25 let start: Int
26 let end: Int26 let end: Int
27}27}
28 28
29private struct ReviewDiffNativeToken: Decodable {29private struct ReviewDiffNativeToken: Decodable, Sendable {
30 let content: String30 let content: String
31 let color: String?31 let color: String?
32 let fontStyle: Int?32 let fontStyle: Int?
33}33}
34 34
35private struct ReviewDiffNativeTokenPatch: Decodable {35private struct ReviewDiffNativeTokenPatch: Decodable, Sendable {
36 let resetKey: String?36 let resetKey: String?
37 let chunkIndex: Int?37 let chunkIndex: Int?
38 let tokensByRowId: [String: [ReviewDiffNativeToken]]?38 let tokensByRowId: [String: [ReviewDiffNativeToken]]?
@@ -312,6 +312,10 @@ private struct ReviewDiffNativeStyle { · 273 unmodified lines
312}312}
313 313
314public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {314public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
315 private let payloadDecodeQueue = DispatchQueue(
316 label: "com.t3tools.review-diff.payload-decode",
317 qos: .userInitiated
318 )
315 private let scrollView = UIScrollView()319 private let scrollView = UIScrollView()
316 private let contentView = ReviewDiffContentView()320 private let contentView = ReviewDiffContentView()
317 private var rows: [ReviewDiffNativeRow] = []321 private var rows: [ReviewDiffNativeRow] = []
@@ -323,14 +327,25 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 5 unmodified lines
323 private var lastMetricsDebugKey = ""327 private var lastMetricsDebugKey = ""
324 private var lastVisibleRangeDebugKey = ""328 private var lastVisibleRangeDebugKey = ""
325 private var tokensResetKey = ""329 private var tokensResetKey = ""
330 private var contentResetKey = ""
326 private var initialRowIndex: Int?331 private var initialRowIndex: Int?
327 private var hasAppliedInitialRowIndex = false332 private var hasAppliedInitialRowIndex = false
333 private var lastVisibleFileId: String?
334 private var pendingScrollFileId: String?
335 private var pendingScrollAnimated = false
336 private var isProgrammaticScrollActive = false
337 private var rowsDecodeGeneration = 0
338 private var tokensDecodeGeneration = 0
328 339
329 let onDebug = EventDispatcher()340 let onDebug = EventDispatcher()
341 let onVisibleFileChange = EventDispatcher()
330 let onToggleFile = EventDispatcher()342 let onToggleFile = EventDispatcher()
331 let onToggleViewedFile = EventDispatcher()343 let onToggleViewedFile = EventDispatcher()
332 let onPressLine = EventDispatcher()344 let onPressLine = EventDispatcher()
333 let onToggleComment = EventDispatcher()345 let onToggleComment = EventDispatcher()
346 let onPullToRefresh = EventDispatcher()
347
348 private let pullRefreshControl = UIRefreshControl()
334 349
335 public required init(appContext: AppContext? = nil) {350 public required init(appContext: AppContext? = nil) {
336 super.init(appContext: appContext)351 super.init(appContext: appContext)
@@ -345,6 +360,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 8 unmodified lines
345 scrollView.showsVerticalScrollIndicator = true360 scrollView.showsVerticalScrollIndicator = true
346 scrollView.showsHorizontalScrollIndicator = false361 scrollView.showsHorizontalScrollIndicator = false
347 scrollView.backgroundColor = contentView.theme.background362 scrollView.backgroundColor = contentView.theme.background
363 pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
364 scrollView.refreshControl = pullRefreshControl
348 addSubview(scrollView)365 addSubview(scrollView)
349 366
350 contentView.backgroundColor = contentView.theme.background367 contentView.backgroundColor = contentView.theme.background
@@ -379,6 +396,13 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 28 unmodified lines
379 updateViewportFrame()396 updateViewportFrame()
380 }397 }
381 398
399 public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
400 // A direct gesture takes ownership from any interrupted programmatic jump.
401 // Resume visible-file events immediately so the inspector follows the finger.
402 isProgrammaticScrollActive = false
403 contentView.isVerticalScrollActive = true
404 }
405
382 public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {406 public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
383 guard !decelerate else {407 guard !decelerate else {
384 return408 return
@@ -396,77 +420,125 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 11 unmodified lines
396 }420 }
397 421
398 func setRowsJson(_ rowsJson: String) {422 func setRowsJson(_ rowsJson: String) {
399 guard let data = rowsJson.data(using: .utf8) else {423 rowsDecodeGeneration += 1
400 return424 let generation = rowsDecodeGeneration
401 }
402 425
403 do {426 payloadDecodeQueue.async { [weak self] in
404 rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)427 guard let data = rowsJson.data(using: .utf8) else {
405 contentView.rows = rows428 return
406 hasAppliedInitialRowIndex = false429 }
407 emitDebug("rows-decoded", [430
408 "rows": rows.count,431 do {
409 "firstKind": rows.first?.kind ?? "none",432 let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
410 ])433 DispatchQueue.main.async { [weak self] in
411 updateContentMetrics()434 guard let self, generation == self.rowsDecodeGeneration else {
412 } catch {435 return
413 rows = []436 }
414 contentView.rows = []437 self.rows = decodedRows
415 hasAppliedInitialRowIndex = false438 self.contentView.rows = decodedRows
416 updateContentMetrics()439 self.hasAppliedInitialRowIndex = false
417 emitDebug("rows-decode-failed", [440 self.lastVisibleFileId = nil
418 "error": error.localizedDescription,441 self.emitDebug("rows-decoded", [
419 ])442 "rows": decodedRows.count,
443 "firstKind": decodedRows.first?.kind ?? "none",
444 ])
445 self.updateContentMetrics()
446 self.applyPendingScrollIfNeeded()
447 }
448 } catch {
449 let message = error.localizedDescription
450 DispatchQueue.main.async { [weak self] in
451 guard let self, generation == self.rowsDecodeGeneration else {
452 return
453 }
454 self.rows = []
455 self.contentView.rows = []
456 self.hasAppliedInitialRowIndex = false
457 self.lastVisibleFileId = nil
458 self.pendingScrollFileId = nil
459 self.updateContentMetrics()
460 self.emitDebug("rows-decode-failed", ["error": message])
461 }
462 }
420 }463 }
421 }464 }
422 465
423 func setTokensJson(_ tokensJson: String) {466 func setTokensJson(_ tokensJson: String) {
424 guard let data = tokensJson.data(using: .utf8) else {467 tokensDecodeGeneration += 1
425 return468 let generation = tokensDecodeGeneration
426 }
427 469
428 do {470 payloadDecodeQueue.async { [weak self] in
429 contentView.tokensByRowId = try JSONDecoder().decode(471 guard let data = tokensJson.data(using: .utf8) else {
430 [String: [ReviewDiffNativeToken]].self,472 return
431 from: data473 }
432 )474
433 } catch {475 do {
434 contentView.tokensByRowId = [:]476 let decodedTokens = try JSONDecoder().decode(
435 emitDebug("tokens-decode-failed", [477 [String: [ReviewDiffNativeToken]].self,
436 "error": error.localizedDescription,478 from: data
437 ])479 )
480 DispatchQueue.main.async { [weak self] in
481 guard let self, generation == self.tokensDecodeGeneration else {
482 return
483 }
484 self.contentView.tokensByRowId = decodedTokens
485 }
486 } catch {
487 let message = error.localizedDescription
488 DispatchQueue.main.async { [weak self] in
489 guard let self, generation == self.tokensDecodeGeneration else {
490 return
491 }
492 self.contentView.tokensByRowId = [:]
493 self.emitDebug("tokens-decode-failed", ["error": message])
494 }
495 }
438 }496 }
439 }497 }
440 498
441 func setTokensPatchJson(_ tokensPatchJson: String) {499 func setTokensPatchJson(_ tokensPatchJson: String) {
442 guard let data = tokensPatchJson.data(using: .utf8) else {500 let contentResetKey = self.contentResetKey
443 return
444 }
445 501
446 do {502 payloadDecodeQueue.async { [weak self] in
447 let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)503 guard let data = tokensPatchJson.data(using: .utf8) else {
448 if let resetKey = patch.resetKey, resetKey != tokensResetKey {
449 tokensResetKey = resetKey
450 contentView.tokensByRowId = [:]
451 }
452
453 let tokensByRowId = patch.tokensByRowId ?? [:]
454 if tokensByRowId.isEmpty {
455 return504 return
456 }505 }
457 506
458 contentView.mergeTokensByRowId(tokensByRowId)507 do {
459 if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {508 let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
460 emitDebug("tokens-patch-decoded", [509 DispatchQueue.main.async { [weak self] in
461 "chunkIndex": chunkIndex,510 guard let self else {
462 "rows": tokensByRowId.count,511 return
463 "totalRows": contentView.tokensByRowId.count,512 }
464 ])513 guard contentResetKey == self.contentResetKey else {
514 return
515 }
516 // A highlighter request from the previous file can finish after the view has
517 // already reset. Never let that stale patch roll the native token state back.
518 if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
519 return
520 }
521
522 let tokensByRowId = patch.tokensByRowId ?? [:]
523 if tokensByRowId.isEmpty {
524 return
525 }
526
527 self.contentView.mergeTokensByRowId(tokensByRowId)
528 if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
529 self.emitDebug("tokens-patch-decoded", [
530 "chunkIndex": chunkIndex,
531 "rows": tokensByRowId.count,
532 "totalRows": self.contentView.tokensByRowId.count,
533 ])
534 }
535 }
536 } catch {
537 let message = error.localizedDescription
538 DispatchQueue.main.async { [weak self] in
539 self?.emitDebug("tokens-patch-decode-failed", ["error": message])
540 }
465 }541 }
466 } catch {
467 emitDebug("tokens-patch-decode-failed", [
468 "error": error.localizedDescription,
469 ])
470 }542 }
471 }543 }
472 544
@@ -482,6 +554,27 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 9 unmodified lines
482 ])554 ])
483 }555 }
484 556
557 func setContentResetKey(_ contentResetKey: String) {
558 guard contentResetKey != self.contentResetKey else {
559 return
560 }
561
562 self.contentResetKey = contentResetKey
563 rowsDecodeGeneration += 1
564 tokensDecodeGeneration += 1
565 contentView.tokensByRowId = [:]
566 rows = []
567 contentView.rows = []
568 hasAppliedInitialRowIndex = false
569 pendingScrollFileId = nil
570 isProgrammaticScrollActive = false
571 scrollView.setContentOffset(.zero, animated: false)
572 updateContentMetrics()
573 updateViewportFrame()
574 lastVisibleFileId = nil
575 applyInitialRowIndexIfNeeded()
576 }
577
485 func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {578 func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {
486 let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)579 let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)
487 let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)580 let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)
@@ -573,6 +666,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 85 unmodified lines
573 contentView.invalidateVisibleViewport()666 contentView.invalidateVisibleViewport()
574 contentView.setNeedsDisplay()667 contentView.setNeedsDisplay()
575 applyInitialRowIndexIfNeeded()668 applyInitialRowIndexIfNeeded()
669 applyPendingScrollIfNeeded()
670 emitVisibleFileIfNeeded()
576 671
577 let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"672 let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
578 if debugKey != lastMetricsDebugKey {673 if debugKey != lastMetricsDebugKey {
@@ -596,11 +691,41 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 17 unmodified lines
596 }691 }
597 692
598 private func finishVerticalScroll() {693 private func finishVerticalScroll() {
694 isProgrammaticScrollActive = false
599 contentView.isVerticalScrollActive = false695 contentView.isVerticalScrollActive = false
600 updateViewportFrame()696 updateViewportFrame()
601 emitVisibleRange(reason: "scroll-end")697 emitVisibleRange(reason: "scroll-end")
602 }698 }
603 699
700 private func emitVisibleFileIfNeeded() {
701 // Keep the explicit destination selected while UIKit animates through the files
702 // between the old and new offsets. Emitting every intermediate header forces a
703 // React render per crossing and makes the navigator visibly flash.
704 guard !isProgrammaticScrollActive else {
705 return
706 }
707
708 // The top of the combined diff is the explicit "All files" destination.
709 // Treat it as a first-class selection instead of immediately resolving the
710 // first file header and undoing the navigator's optimistic selection.
711 if scrollView.contentOffset.y <= 0.5 {
712 guard lastVisibleFileId != nil else {
713 return
714 }
715 lastVisibleFileId = nil
716 onVisibleFileChange(["fileId": NSNull()])
717 return
718 }
719
720 guard let fileId = contentView.visibleFileId(atVerticalOffset: scrollView.contentOffset.y),
721 fileId != lastVisibleFileId else {
722 return
723 }
724
725 lastVisibleFileId = fileId
726 onVisibleFileChange(["fileId": fileId])
727 }
728
604 private func emitVisibleRange(reason: String) {729 private func emitVisibleRange(reason: String) {
605 guard let range = contentView.currentVisibleRowRange() else {730 guard let range = contentView.currentVisibleRowRange() else {
606 return731 return
@@ -670,6 +795,33 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 63 unmodified lines
670 applyInitialRowIndexIfNeeded()795 applyInitialRowIndexIfNeeded()
671 }796 }
672 797
798 func scrollToFile(_ fileId: String, animated: Bool) {
799 pendingScrollFileId = fileId
800 pendingScrollAnimated = animated
801 applyPendingScrollIfNeeded()
802 }
803
804 func scrollToTop(animated: Bool) {
805 pendingScrollFileId = nil
806 pendingScrollAnimated = false
807 setVerticalContentOffset(0, animated: animated)
808 }
809
810 @objc private func handlePullToRefresh() {
811 onPullToRefresh([:])
812 }
813
814 /// Driven from JS: set to false once the reload completes to dismiss the spinner.
815 func setRefreshing(_ refreshing: Bool) {
816 if refreshing {
817 if !pullRefreshControl.isRefreshing {
818 pullRefreshControl.beginRefreshing()
819 }
820 } else if pullRefreshControl.isRefreshing {
821 pullRefreshControl.endRefreshing()
822 }
823 }
824
673 private func applyStyle() {825 private func applyStyle() {
674 contentView.style = ReviewDiffNativeStyle826 contentView.style = ReviewDiffNativeStyle
675 .resolve(stylePayload)827 .resolve(stylePayload)
@@ -686,6 +838,38 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { · 10 unmodified lines
686 )838 )
687 contentView.verticalOffset = scrollView.contentOffset.y839 contentView.verticalOffset = scrollView.contentOffset.y
688 contentView.invalidateVisibleViewport()840 contentView.invalidateVisibleViewport()
841 emitVisibleFileIfNeeded()
842 }
843
844 private func applyPendingScrollIfNeeded() {
845 guard let fileId = pendingScrollFileId,
846 bounds.height > 0 else {
847 return
848 }
849
850 guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else {
851 if !rows.isEmpty {
852 pendingScrollFileId = nil
853 }
854 return
855 }
856
857 let animated = pendingScrollAnimated
858 pendingScrollFileId = nil
859 pendingScrollAnimated = false
860 setVerticalContentOffset(headerOffset, animated: animated)
861 }
862
863 private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) {
864 let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
865 let clampedOffset = min(max(targetOffset, 0), maxOffset)
866 let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5
867 isProgrammaticScrollActive = shouldAnimate
868 contentView.isVerticalScrollActive = shouldAnimate
869 scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
870 if !shouldAnimate {
871 updateViewportFrame()
872 }
689 }873 }
690 874
691 private func applyInitialRowIndexIfNeeded() {875 private func applyInitialRowIndexIfNeeded() {
@@ -1255,6 +1439,32 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { · 563 unmodified lines
1255 return rowOffsets[rowIndex]1439 return rowOffsets[rowIndex]
1256 }1440 }
1257 1441
1442 func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? {
1443 guard let firstHeaderRowIndex = fileHeaderRowIndices.first else {
1444 return nil
1445 }
1446
1447 var lowerBound = 0
1448 var upperBound = fileHeaderRowIndices.count
1449 while lowerBound < upperBound {
1450 let midpoint = (lowerBound + upperBound) / 2
1451 let rowIndex = fileHeaderRowIndices[midpoint]
1452 if rowOffsets[rowIndex] <= verticalOffset + 0.5 {
1453 lowerBound = midpoint + 1
1454 } else {
1455 upperBound = midpoint
1456 }
1457 }
1458
1459 let rowIndex = lowerBound > 0
1460 ? fileHeaderRowIndices[lowerBound - 1]
1461 : firstHeaderRowIndex
1462 guard rows.indices.contains(rowIndex) else {
1463 return nil
1464 }
1465 return resolvedFileId(for: rows[rowIndex])
1466 }
1467
1258 private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {1468 private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {
1259 fileHeaderRowIndices.first { rowIndex in1469 fileHeaderRowIndices.first { rowIndex in
1260 rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId1470 rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId
apps/mobile/modules/t3-review-diff/package.json+5−0
@@ -7,6 +7,11 @@ · 6 unmodified lines
7 "modules": [7 "modules": [
8 "T3ReviewDiffModule"8 "T3ReviewDiffModule"
9 ]9 ]
10 },
11 "android": {
12 "modules": [
13 "expo.modules.t3reviewdiff.T3ReviewDiffModule"
14 ]
10 }15 }
11 }16 }
12}17}
apps/mobile/modules/t3-terminal/README.md+15−3
@@ -18,9 +18,9 @@ uses that callback I/O model: · 17 unmodified lines
184. send user input back to JS with the write callback184. send user input back to JS with the write callback
195. emit Ghostty's measured terminal size through `onResize`195. emit Ghostty's measured terminal size through `onResize`
20 20
21Android currently implements the same view name (`T3TerminalSurface`) and event payloads so the21Android implements the same view contract with upstream `libghostty-vt` for terminal state, parsing,
22React Native screen and RPC code stay platform-neutral. The renderer backend can be replaced with a22reflow, and scrollback. An Android Canvas view renders compact snapshots produced by the JNI bridge,
23future Android Ghostty build without changing JS.23so the React Native screen and RPC code stay platform-neutral.
24 24
25Vendored Ghostty revision and license details are in `THIRD_PARTY_NOTICES.md`.25Vendored Ghostty revision and license details are in `THIRD_PARTY_NOTICES.md`.
26 26
@@ -36,3 +36,15 @@ apps/mobile/modules/t3-terminal/scripts/build-libghostty-ios16.sh · 9 unmodified lines
36The script builds Ghostty with Zig 0.15.2, strips the iOS archives, and replaces only the36The script builds Ghostty with Zig 0.15.2, strips the iOS archives, and replaces only the
37`ios-arm64` and `ios-arm64-simulator` slices. Xcode's Metal toolchain must be installed; if `metal`37`ios-arm64` and `ios-arm64-simulator` slices. Xcode's Metal toolchain must be installed; if `metal`
38fails, run `xcodebuild -downloadComponent MetalToolchain`.38fails, run `xcodebuild -downloadComponent MetalToolchain`.
39
40## Rebuilding libghostty-vt for Android
41
42The checked-in Android shared libraries and headers are pinned to the revision recorded in
43`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
44
45```bash
46apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
47```
48
49The script downloads Zig 0.15.2 when needed, checks out the pinned upstream Ghostty revision, and
50rebuilds all four Android ABIs with 16 KB page-size support.
apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md+18−0
@@ -14,3 +14,21 @@ iOS 16 support fork. That fork was created from VVTerm's custom-I/O Ghostty fork · 13 unmodified lines
14 14
15Ghostty's MIT license applies to the vendored framework. Keep this notice in sync when updating15Ghostty's MIT license applies to the vendored framework. Keep this notice in sync when updating
16`Vendor/libghostty`.16`Vendor/libghostty`.
17
18## Ghostty / libghostty-vt
19
20The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
21
22- Upstream project: https://github.com/ghostty-org/ghostty
23- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
24- License: MIT
25
26Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
27updating `Vendor/libghostty-vt`.
28
29## MesloLGS NF (Android terminal font)
30
31- Files: `android/src/main/assets/fonts/MesloLGS-NF-{Regular,Bold}.ttf`
32- Source: https://github.com/romkatv/powerlevel10k-media (Meslo LG patched with Nerd Fonts glyphs)
33- Upstream: Meslo LG by André Berg (customization of Apple's Menlo), Nerd Fonts patcher
34- License: Apache License 2.0
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/LICENSE+21−0
@@ -0,0 +1,21 @@
1MIT License
2
3Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors
4
5Permission is hereby granted, free of charge, to any person obtaining a copy
6of this software and associated documentation files (the "Software"), to deal
7in the Software without restriction, including without limitation the rights
8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9copies of the Software, and to permit persons to whom the Software is
10furnished to do so, subject to the following conditions:
11
12The above copyright notice and this permission notice shall be included in all
13copies or substantial portions of the Software.
14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21SOFTWARE.
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/VERSION+1−0
@@ -0,0 +1 @@
19f62873bf195e4d8a762d768a1405a5f2f7b1697
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt.h+154−0
@@ -0,0 +1,154 @@
1/**
2 * @file vt.h
3 *
4 * libghostty-vt - Virtual terminal emulator library
5 *
6 * This library provides functionality for parsing and handling terminal
7 * escape sequences as well as maintaining terminal state such as styles,
8 * cursor position, screen, scrollback, and more.
9 *
10 * WARNING: This is an incomplete, work-in-progress API. It is not yet
11 * stable and is definitely going to change.
12 */
13
14/**
15 * @mainpage libghostty-vt - Virtual Terminal Emulator Library
16 *
17 * libghostty-vt is a C library which implements a modern terminal emulator,
18 * extracted from the [Ghostty](https://ghostty.org) terminal emulator.
19 *
20 * libghostty-vt contains the logic for handling the core parts of a terminal
21 * emulator: parsing terminal escape sequences, maintaining terminal state,
22 * encoding input events, etc. It can handle scrollback, line wrapping,
23 * reflow on resize, and more.
24 *
25 * @warning This library is currently in development and the API is not yet stable.
26 * Breaking changes are expected in future versions. Use with caution in production code.
27 *
28 * @section groups_sec API Reference
29 *
30 * The API is organized into the following groups:
31 * - @ref terminal "Terminal" - Complete terminal emulator state and rendering
32 * - @ref render "Render State" - Incremental render state updates for custom renderers
33 * - @ref formatter "Formatter" - Format terminal content as plain text, VT sequences, or HTML
34 * - @ref osc "OSC Parser" - Parse OSC (Operating System Command) sequences
35 * - @ref sgr "SGR Parser" - Parse SGR (Select Graphic Rendition) sequences
36 * - @ref paste "Paste Utilities" - Validate paste data safety
37 * - @ref build_info "Build Info" - Query compile-time build configuration
38 * - @ref allocator "Memory Management" - Memory management and custom allocators
39 * - @ref wasm "WebAssembly Utilities" - WebAssembly convenience functions
40 *
41 * Encoding related APIs:
42 * - @ref focus "Focus Encoding" - Encode focus in/out events into terminal sequences
43 * - @ref key "Key Encoding" - Encode key events into terminal sequences
44 * - @ref mouse "Mouse Encoding" - Encode mouse events into terminal sequences
45 *
46 * @section examples_sec Examples
47 *
48 * Complete working examples:
49 * - @ref c-vt-build-info/src/main.c - Build info query example
50 * - @ref c-vt/src/main.c - OSC parser example
51 * - @ref c-vt-encode-key/src/main.c - Key encoding example
52 * - @ref c-vt-encode-mouse/src/main.c - Mouse encoding example
53 * - @ref c-vt-paste/src/main.c - Paste safety check example
54 * - @ref c-vt-sgr/src/main.c - SGR parser example
55 * - @ref c-vt-formatter/src/main.c - Terminal formatter example
56 * - @ref c-vt-grid-traverse/src/main.c - Grid traversal example using grid refs
57 * - @ref c-vt-grid-ref-tracked/src/main.c - Tracked grid ref example
58 *
59 */
60
61/** @example c-vt-build-info/src/main.c
62 * This example demonstrates how to query compile-time build configuration
63 * such as SIMD support, Kitty graphics, and tmux control mode availability.
64 */
65
66/** @example c-vt/src/main.c
67 * This example demonstrates how to use the OSC parser to parse an OSC sequence,
68 * extract command information, and retrieve command-specific data like window titles.
69 */
70
71/** @example c-vt-encode-key/src/main.c
72 * This example demonstrates how to use the key encoder to convert key events
73 * into terminal escape sequences using the Kitty keyboard protocol.
74 */
75
76/** @example c-vt-encode-mouse/src/main.c
77 * This example demonstrates how to use the mouse encoder to convert mouse events
78 * into terminal escape sequences using the SGR mouse format.
79 */
80
81/** @example c-vt-paste/src/main.c
82 * This example demonstrates how to use the paste utilities to check if
83 * paste data is safe before sending it to the terminal.
84 */
85
86/** @example c-vt-sgr/src/main.c
87 * This example demonstrates how to use the SGR parser to parse terminal
88 * styling sequences and extract text attributes like colors and underline styles.
89 */
90
91/** @example c-vt-formatter/src/main.c
92 * This example demonstrates how to use the terminal and formatter APIs to
93 * create a terminal, write VT-encoded content into it, and format the screen
94 * contents as plain text.
95 */
96
97/** @example c-vt-grid-traverse/src/main.c
98 * This example demonstrates how to traverse the entire terminal grid using
99 * grid refs to inspect cell codepoints, row wrap state, and cell styles.
100 */
101
102/** @example c-vt-grid-ref-tracked/src/main.c
103 * This example demonstrates how to track a grid ref as the terminal scrolls,
104 * detect when it loses its value, and move it to a new point.
105 */
106
107/** @example c-vt-selection-gesture/src/main.c
108 * This example demonstrates how to use synthetic selection gesture events to
109 * derive drag and deep-press selection snapshots.
110 */
111
112/** @example c-vt-kitty-graphics/src/main.c
113 * This example demonstrates how to use the system interface to install a
114 * PNG decoder callback and send a Kitty Graphics Protocol image.
115 */
116
117#ifndef GHOSTTY_VT_H
118#define GHOSTTY_VT_H
119
120#ifdef __cplusplus
121extern "C" {
122#endif
123
124#include <ghostty/vt/types.h>
125#include <ghostty/vt/allocator.h>
126#include <ghostty/vt/build_info.h>
127#include <ghostty/vt/color.h>
128#include <ghostty/vt/device.h>
129#include <ghostty/vt/focus.h>
130#include <ghostty/vt/formatter.h>
131#include <ghostty/vt/render.h>
132#include <ghostty/vt/terminal.h>
133#include <ghostty/vt/grid_ref.h>
134#include <ghostty/vt/grid_ref_tracked.h>
135#include <ghostty/vt/osc.h>
136#include <ghostty/vt/sgr.h>
137#include <ghostty/vt/style.h>
138#include <ghostty/vt/sys.h>
139#include <ghostty/vt/key.h>
140#include <ghostty/vt/kitty_graphics.h>
141#include <ghostty/vt/modes.h>
142#include <ghostty/vt/mouse.h>
143#include <ghostty/vt/paste.h>
144#include <ghostty/vt/point.h>
145#include <ghostty/vt/screen.h>
146#include <ghostty/vt/selection.h>
147#include <ghostty/vt/size_report.h>
148#include <ghostty/vt/wasm.h>
149
150#ifdef __cplusplus
151}
152#endif
153
154#endif /* GHOSTTY_VT_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/allocator.h+255−0
@@ -0,0 +1,255 @@
1/**
2 * @file allocator.h
3 *
4 * Memory management interface for libghostty-vt.
5 */
6
7#ifndef GHOSTTY_VT_ALLOCATOR_H
8#define GHOSTTY_VT_ALLOCATOR_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/types.h>
14
15/** @defgroup allocator Memory Management
16 *
17 * libghostty-vt does require memory allocation for various operations,
18 * but is resilient to allocation failures and will gracefully handle
19 * out-of-memory situations by returning error codes.
20 *
21 * The exact memory management semantics are documented in the relevant
22 * functions and data structures.
23 *
24 * libghostty-vt uses explicit memory allocation via an allocator
25 * interface provided by GhosttyAllocator. The interface is based on the
26 * [Zig](https://ziglang.org) allocator interface, since this has been
27 * shown to be a flexible and powerful interface in practice and enables
28 * a wide variety of allocation strategies.
29 *
30 * **For the common case, you can pass NULL as the allocator for any
31 * function that accepts one,** and libghostty will use a default allocator.
32 * The default allocator will be libc malloc/free if libc is linked.
33 * Otherwise, a custom allocator is used (currently Zig's SMP allocator)
34 * that doesn't require any external dependencies.
35 *
36 * ## Basic Usage
37 *
38 * For simple use cases, you can ignore this interface entirely by passing NULL
39 * as the allocator parameter to functions that accept one. This will use the
40 * default allocator (typically libc malloc/free, if libc is linked, but
41 * we provide our own default allocator if libc isn't linked).
42 *
43 * To use a custom allocator:
44 * 1. Implement the GhosttyAllocatorVtable function pointers
45 * 2. Create a GhosttyAllocator struct with your vtable and context
46 * 3. Pass the allocator to functions that accept one
47 *
48 * ## Alloc/Free Helpers
49 *
50 * ghostty_alloc() and ghostty_free() provide a simple malloc/free-style
51 * interface for allocating and freeing byte buffers through the library's
52 * allocator. These are useful when:
53 *
54 * - You need to allocate a buffer to pass into a libghostty-vt function
55 * (e.g. preparing input data for ghostty_terminal_vt_write()).
56 * - You need to free a buffer returned by a libghostty-vt function
57 * (e.g. the output of ghostty_formatter_format_alloc()).
58 * - You are on a platform where the library's internal allocator differs
59 * from the consumer's C runtime (e.g. Windows, where Zig's libc and
60 * MSVC's CRT maintain separate heaps), so calling the standard C
61 * free() on library-allocated memory would be undefined behavior.
62 *
63 * Always use the same allocator (or NULL) for both the allocation and
64 * the corresponding free.
65 *
66 * @{
67 */
68
69/**
70 * Function table for custom memory allocator operations.
71 *
72 * This vtable defines the interface for a custom memory allocator. All
73 * function pointers must be valid and non-NULL.
74 *
75 * @ingroup allocator
76 *
77 * If you're not going to use a custom allocator, you can ignore all of
78 * this. All functions that take an allocator pointer allow NULL to use a
79 * default allocator.
80 *
81 * The interface is based on the Zig allocator interface. I'll say up front
82 * that it is easy to look at this interface and think "wow, this is really
83 * overcomplicated". The reason for this complexity is well thought out by
84 * the Zig folks, and it enables a diverse set of allocation strategies
85 * as shown by the Zig ecosystem. As a consolation, please note that many
86 * of the arguments are only needed for advanced use cases and can be
87 * safely ignored in simple implementations. For example, if you look at
88 * the Zig implementation of the libc allocator in `lib/std/heap.zig`
89 * (search for CAllocator), you'll see it is very simple.
90 *
91 * We chose to align with the Zig allocator interface because:
92 *
93 * 1. It is a proven interface that serves a wide variety of use cases
94 * in the real world via the Zig ecosystem. It's shown to work.
95 *
96 * 2. Our core implementation itself is Zig, and this lets us very
97 * cheaply and easily convert between C and Zig allocators.
98 *
99 * NOTE(mitchellh): In the future, we can have default implementations of
100 * resize/remap and allow those to be null.
101 */
102typedef struct {
103 /**
104 * Return a pointer to `len` bytes with specified `alignment`, or return
105 * `NULL` indicating the allocation failed.
106 *
107 * @param ctx The allocator context
108 * @param len Number of bytes to allocate
109 * @param alignment Required alignment for the allocation. Guaranteed to
110 * be a power of two between 1 and 16 inclusive.
111 * @param ret_addr First return address of the allocation call stack (0 if not provided)
112 * @return Pointer to allocated memory, or NULL if allocation failed
113 */
114 void* (*alloc)(void *ctx, size_t len, uint8_t alignment, uintptr_t ret_addr);
115
116 /**
117 * Attempt to expand or shrink memory in place.
118 *
119 * `memory_len` must equal the length requested from the most recent
120 * successful call to `alloc`, `resize`, or `remap`. `alignment` must
121 * equal the same value that was passed as the `alignment` parameter to
122 * the original `alloc` call.
123 *
124 * `new_len` must be greater than zero.
125 *
126 * @param ctx The allocator context
127 * @param memory Pointer to the memory block to resize
128 * @param memory_len Current size of the memory block
129 * @param alignment Alignment (must match original allocation)
130 * @param new_len New requested size
131 * @param ret_addr First return address of the allocation call stack (0 if not provided)
132 * @return true if resize was successful in-place, false if relocation would be required
133 */
134 bool (*resize)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr);
135
136 /**
137 * Attempt to expand or shrink memory, allowing relocation.
138 *
139 * `memory_len` must equal the length requested from the most recent
140 * successful call to `alloc`, `resize`, or `remap`. `alignment` must
141 * equal the same value that was passed as the `alignment` parameter to
142 * the original `alloc` call.
143 *
144 * A non-`NULL` return value indicates the resize was successful. The
145 * allocation may have same address, or may have been relocated. In either
146 * case, the allocation now has size of `new_len`. A `NULL` return value
147 * indicates that the resize would be equivalent to allocating new memory,
148 * copying the bytes from the old memory, and then freeing the old memory.
149 * In such case, it is more efficient for the caller to perform the copy.
150 *
151 * `new_len` must be greater than zero.
152 *
153 * @param ctx The allocator context
154 * @param memory Pointer to the memory block to remap
155 * @param memory_len Current size of the memory block
156 * @param alignment Alignment (must match original allocation)
157 * @param new_len New requested size
158 * @param ret_addr First return address of the allocation call stack (0 if not provided)
159 * @return Pointer to resized memory (may be relocated), or NULL if manual copy is needed
160 */
161 void* (*remap)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr);
162
163 /**
164 * Free and invalidate a region of memory.
165 *
166 * `memory_len` must equal the length requested from the most recent
167 * successful call to `alloc`, `resize`, or `remap`. `alignment` must
168 * equal the same value that was passed as the `alignment` parameter to
169 * the original `alloc` call.
170 *
171 * @param ctx The allocator context
172 * @param memory Pointer to the memory block to free
173 * @param memory_len Size of the memory block
174 * @param alignment Alignment (must match original allocation)
175 * @param ret_addr First return address of the allocation call stack (0 if not provided)
176 */
177 void (*free)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, uintptr_t ret_addr);
178} GhosttyAllocatorVtable;
179
180/**
181 * Custom memory allocator.
182 *
183 * For functions that take an allocator pointer, a NULL pointer indicates
184 * that the default allocator should be used. The default allocator will
185 * be libc malloc/free if we're linking to libc. If libc isn't linked,
186 * a custom allocator is used (currently Zig's SMP allocator).
187 *
188 * @ingroup allocator
189 *
190 * Usage example:
191 * @code
192 * GhosttyAllocator allocator = {
193 * .vtable = &my_allocator_vtable,
194 * .ctx = my_allocator_state
195 * };
196 * @endcode
197 */
198typedef struct GhosttyAllocator {
199 /**
200 * Opaque context pointer passed to all vtable functions.
201 * This allows the allocator implementation to maintain state
202 * or reference external resources needed for memory management.
203 */
204 void *ctx;
205
206 /**
207 * Pointer to the allocator's vtable containing function pointers
208 * for memory operations (alloc, resize, remap, free).
209 */
210 const GhosttyAllocatorVtable *vtable;
211} GhosttyAllocator;
212
213/**
214 * Allocate a buffer of `len` bytes.
215 *
216 * Uses the provided allocator, or the default allocator if NULL is passed.
217 * The returned buffer must be freed with ghostty_free() using the same
218 * allocator.
219 *
220 * @param allocator Pointer to the allocator to use, or NULL for the default
221 * @param len Number of bytes to allocate
222 * @return Pointer to the allocated buffer, or NULL if allocation failed
223 *
224 * @ingroup allocator
225 */
226GHOSTTY_API uint8_t* ghostty_alloc(const GhosttyAllocator* allocator, size_t len);
227
228/**
229 * Free memory that was allocated by a libghostty-vt function.
230 *
231 * Use this to free buffers returned by functions such as
232 * ghostty_formatter_format_alloc(). Pass the same allocator that was
233 * used for the allocation, or NULL if the default allocator was used.
234 *
235 * On platforms where the library's internal allocator differs from the
236 * consumer's C runtime (e.g. Windows, where Zig's libc and MSVC's CRT
237 * maintain separate heaps), calling the standard C free() on memory
238 * allocated by the library causes undefined behavior. This function
239 * guarantees the correct allocator is used regardless of platform.
240 *
241 * It is safe to pass a NULL pointer; the call is a no-op in that case.
242 *
243 * @param allocator Pointer to the allocator that was used to allocate the
244 * memory, or NULL if the default allocator was used
245 * @param ptr Pointer to the memory to free (may be NULL)
246 * @param len Length of the allocation in bytes (must match the original
247 * allocation size)
248 *
249 * @ingroup allocator
250 */
251GHOSTTY_API void ghostty_free(const GhosttyAllocator* allocator, uint8_t* ptr, size_t len);
252
253/** @} */
254
255#endif /* GHOSTTY_VT_ALLOCATOR_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/build_info.h+150−0
@@ -0,0 +1,150 @@
1/**
2 * @file build_info.h
3 *
4 * Build info - query compile-time build configuration of libghostty-vt.
5 */
6
7#ifndef GHOSTTY_VT_BUILD_INFO_H
8#define GHOSTTY_VT_BUILD_INFO_H
9
10/** @defgroup build_info Build Info
11 *
12 * Query compile-time build configuration of libghostty-vt.
13 *
14 * These values reflect the options the library was built with and are
15 * constant for the lifetime of the process.
16 *
17 * ## Basic Usage
18 *
19 * Use ghostty_build_info() to query individual build options:
20 *
21 * @snippet c-vt-build-info/src/main.c build-info-query
22 *
23 * @{
24 */
25
26#include <stddef.h>
27#include <stdbool.h>
28
29#include <ghostty/vt/types.h>
30
31#ifdef __cplusplus
32extern "C" {
33#endif
34
35/**
36 * Build optimization mode.
37 */
38typedef enum GHOSTTY_ENUM_TYPED {
39 GHOSTTY_OPTIMIZE_DEBUG = 0,
40 GHOSTTY_OPTIMIZE_RELEASE_SAFE = 1,
41 GHOSTTY_OPTIMIZE_RELEASE_SMALL = 2,
42 GHOSTTY_OPTIMIZE_RELEASE_FAST = 3,
43 GHOSTTY_OPTIMIZE_MODE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
44} GhosttyOptimizeMode;
45
46/**
47 * Build info data types that can be queried.
48 *
49 * Each variant documents the expected output pointer type.
50 */
51typedef enum GHOSTTY_ENUM_TYPED {
52 /** Invalid data type. Never results in any data extraction. */
53 GHOSTTY_BUILD_INFO_INVALID = 0,
54
55 /**
56 * Whether SIMD-accelerated code paths are enabled.
57 *
58 * Output type: bool *
59 */
60 GHOSTTY_BUILD_INFO_SIMD = 1,
61
62 /**
63 * Whether Kitty graphics protocol support is available.
64 *
65 * Output type: bool *
66 */
67 GHOSTTY_BUILD_INFO_KITTY_GRAPHICS = 2,
68
69 /**
70 * Whether tmux control mode support is available.
71 *
72 * Output type: bool *
73 */
74 GHOSTTY_BUILD_INFO_TMUX_CONTROL_MODE = 3,
75
76 /**
77 * The optimization mode the library was built with.
78 *
79 * Output type: GhosttyOptimizeMode *
80 */
81 GHOSTTY_BUILD_INFO_OPTIMIZE = 4,
82
83 /**
84 * The full version string (e.g. "1.2.3" or "1.2.3-dev+abcdef").
85 *
86 * Output type: GhosttyString *
87 */
88 GHOSTTY_BUILD_INFO_VERSION_STRING = 5,
89
90 /**
91 * The major version number.
92 *
93 * Output type: size_t *
94 */
95 GHOSTTY_BUILD_INFO_VERSION_MAJOR = 6,
96
97 /**
98 * The minor version number.
99 *
100 * Output type: size_t *
101 */
102 GHOSTTY_BUILD_INFO_VERSION_MINOR = 7,
103
104 /**
105 * The patch version number.
106 *
107 * Output type: size_t *
108 */
109 GHOSTTY_BUILD_INFO_VERSION_PATCH = 8,
110
111 /**
112 * The pre metadata string (e.g. "alpha", "beta", "dev"). Has zero length if
113 * no pre metadata is present.
114 *
115 * Output type: GhosttyString *
116 */
117 GHOSTTY_BUILD_INFO_VERSION_PRE = 9,
118
119 /**
120 * The build metadata string (e.g. commit hash). Has zero length if
121 * no build metadata is present.
122 *
123 * Output type: GhosttyString *
124 */
125 GHOSTTY_BUILD_INFO_VERSION_BUILD = 10,
126 GHOSTTY_BUILD_INFO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
127} GhosttyBuildInfo;
128
129/**
130 * Query a compile-time build configuration value.
131 *
132 * The caller must pass a pointer to the correct output type for the
133 * requested data (see GhosttyBuildInfo variants for types).
134 *
135 * @param data The build info field to query
136 * @param out Pointer to store the result (type depends on data parameter)
137 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
138 * data type is invalid
139 *
140 * @ingroup build_info
141 */
142GHOSTTY_API GhosttyResult ghostty_build_info(GhosttyBuildInfo data, void *out);
143
144#ifdef __cplusplus
145}
146#endif
147
148/** @} */
149
150#endif /* GHOSTTY_VT_BUILD_INFO_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/color.h+97−0
@@ -0,0 +1,97 @@
1/**
2 * @file color.h
3 *
4 * Color types and utilities.
5 */
6
7#ifndef GHOSTTY_VT_COLOR_H
8#define GHOSTTY_VT_COLOR_H
9
10#include <stdint.h>
11#include <ghostty/vt/types.h>
12
13#ifdef __cplusplus
14extern "C" {
15#endif
16
17/**
18 * RGB color value.
19 *
20 * @ingroup sgr
21 */
22typedef struct {
23 uint8_t r; /**< Red component (0-255) */
24 uint8_t g; /**< Green component (0-255) */
25 uint8_t b; /**< Blue component (0-255) */
26} GhosttyColorRgb;
27
28/**
29 * Palette color index (0-255).
30 *
31 * @ingroup sgr
32 */
33typedef uint8_t GhosttyColorPaletteIndex;
34
35/** @addtogroup sgr
36 * @{
37 */
38
39/** Black color (0) @ingroup sgr */
40#define GHOSTTY_COLOR_NAMED_BLACK 0
41/** Red color (1) @ingroup sgr */
42#define GHOSTTY_COLOR_NAMED_RED 1
43/** Green color (2) @ingroup sgr */
44#define GHOSTTY_COLOR_NAMED_GREEN 2
45/** Yellow color (3) @ingroup sgr */
46#define GHOSTTY_COLOR_NAMED_YELLOW 3
47/** Blue color (4) @ingroup sgr */
48#define GHOSTTY_COLOR_NAMED_BLUE 4
49/** Magenta color (5) @ingroup sgr */
50#define GHOSTTY_COLOR_NAMED_MAGENTA 5
51/** Cyan color (6) @ingroup sgr */
52#define GHOSTTY_COLOR_NAMED_CYAN 6
53/** White color (7) @ingroup sgr */
54#define GHOSTTY_COLOR_NAMED_WHITE 7
55/** Bright black color (8) @ingroup sgr */
56#define GHOSTTY_COLOR_NAMED_BRIGHT_BLACK 8
57/** Bright red color (9) @ingroup sgr */
58#define GHOSTTY_COLOR_NAMED_BRIGHT_RED 9
59/** Bright green color (10) @ingroup sgr */
60#define GHOSTTY_COLOR_NAMED_BRIGHT_GREEN 10
61/** Bright yellow color (11) @ingroup sgr */
62#define GHOSTTY_COLOR_NAMED_BRIGHT_YELLOW 11
63/** Bright blue color (12) @ingroup sgr */
64#define GHOSTTY_COLOR_NAMED_BRIGHT_BLUE 12
65/** Bright magenta color (13) @ingroup sgr */
66#define GHOSTTY_COLOR_NAMED_BRIGHT_MAGENTA 13
67/** Bright cyan color (14) @ingroup sgr */
68#define GHOSTTY_COLOR_NAMED_BRIGHT_CYAN 14
69/** Bright white color (15) @ingroup sgr */
70#define GHOSTTY_COLOR_NAMED_BRIGHT_WHITE 15
71
72/** @} */
73
74/**
75 * Get the RGB color components.
76 *
77 * This function extracts the individual red, green, and blue components
78 * from a GhosttyColorRgb value. Primarily useful in WebAssembly environments
79 * where accessing struct fields directly is difficult.
80 *
81 * @param color The RGB color value
82 * @param r Pointer to store the red component (0-255)
83 * @param g Pointer to store the green component (0-255)
84 * @param b Pointer to store the blue component (0-255)
85 *
86 * @ingroup sgr
87 */
88GHOSTTY_API void ghostty_color_rgb_get(GhosttyColorRgb color,
89 uint8_t* r,
90 uint8_t* g,
91 uint8_t* b);
92
93#ifdef __cplusplus
94}
95#endif
96
97#endif /* GHOSTTY_VT_COLOR_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/device.h+151−0
@@ -0,0 +1,151 @@
1/**
2 * @file device.h
3 *
4 * Device types used by the terminal for device status and device attribute
5 * queries.
6 */
7
8#ifndef GHOSTTY_VT_DEVICE_H
9#define GHOSTTY_VT_DEVICE_H
10
11#include <stddef.h>
12#include <stdint.h>
13
14/* DA1 conformance levels (Pp parameter). */
15#define GHOSTTY_DA_CONFORMANCE_VT100 1
16#define GHOSTTY_DA_CONFORMANCE_VT101 1
17#define GHOSTTY_DA_CONFORMANCE_VT102 6
18#define GHOSTTY_DA_CONFORMANCE_VT125 12
19#define GHOSTTY_DA_CONFORMANCE_VT131 7
20#define GHOSTTY_DA_CONFORMANCE_VT132 4
21#define GHOSTTY_DA_CONFORMANCE_VT220 62
22#define GHOSTTY_DA_CONFORMANCE_VT240 62
23#define GHOSTTY_DA_CONFORMANCE_VT320 63
24#define GHOSTTY_DA_CONFORMANCE_VT340 63
25#define GHOSTTY_DA_CONFORMANCE_VT420 64
26#define GHOSTTY_DA_CONFORMANCE_VT510 65
27#define GHOSTTY_DA_CONFORMANCE_VT520 65
28#define GHOSTTY_DA_CONFORMANCE_VT525 65
29#define GHOSTTY_DA_CONFORMANCE_LEVEL_2 62
30#define GHOSTTY_DA_CONFORMANCE_LEVEL_3 63
31#define GHOSTTY_DA_CONFORMANCE_LEVEL_4 64
32#define GHOSTTY_DA_CONFORMANCE_LEVEL_5 65
33
34/* DA1 feature codes (Ps parameters). */
35#define GHOSTTY_DA_FEATURE_COLUMNS_132 1
36#define GHOSTTY_DA_FEATURE_PRINTER 2
37#define GHOSTTY_DA_FEATURE_REGIS 3
38#define GHOSTTY_DA_FEATURE_SIXEL 4
39#define GHOSTTY_DA_FEATURE_SELECTIVE_ERASE 6
40#define GHOSTTY_DA_FEATURE_USER_DEFINED_KEYS 8
41#define GHOSTTY_DA_FEATURE_NATIONAL_REPLACEMENT 9
42#define GHOSTTY_DA_FEATURE_TECHNICAL_CHARACTERS 15
43#define GHOSTTY_DA_FEATURE_LOCATOR 16
44#define GHOSTTY_DA_FEATURE_TERMINAL_STATE 17
45#define GHOSTTY_DA_FEATURE_WINDOWING 18
46#define GHOSTTY_DA_FEATURE_HORIZONTAL_SCROLLING 21
47#define GHOSTTY_DA_FEATURE_ANSI_COLOR 22
48#define GHOSTTY_DA_FEATURE_RECTANGULAR_EDITING 28
49#define GHOSTTY_DA_FEATURE_ANSI_TEXT_LOCATOR 29
50#define GHOSTTY_DA_FEATURE_CLIPBOARD 52
51
52/* DA2 device type identifiers (Pp parameter). */
53#define GHOSTTY_DA_DEVICE_TYPE_VT100 0
54#define GHOSTTY_DA_DEVICE_TYPE_VT220 1
55#define GHOSTTY_DA_DEVICE_TYPE_VT240 2
56#define GHOSTTY_DA_DEVICE_TYPE_VT330 18
57#define GHOSTTY_DA_DEVICE_TYPE_VT340 19
58#define GHOSTTY_DA_DEVICE_TYPE_VT320 24
59#define GHOSTTY_DA_DEVICE_TYPE_VT382 32
60#define GHOSTTY_DA_DEVICE_TYPE_VT420 41
61#define GHOSTTY_DA_DEVICE_TYPE_VT510 61
62#define GHOSTTY_DA_DEVICE_TYPE_VT520 64
63#define GHOSTTY_DA_DEVICE_TYPE_VT525 65
64
65#ifdef __cplusplus
66extern "C" {
67#endif
68
69/**
70 * Color scheme reported in response to a CSI ? 996 n query.
71 *
72 * @ingroup terminal
73 */
74typedef enum GHOSTTY_ENUM_TYPED {
75 GHOSTTY_COLOR_SCHEME_LIGHT = 0,
76 GHOSTTY_COLOR_SCHEME_DARK = 1,
77 GHOSTTY_COLOR_SCHEME_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
78} GhosttyColorScheme;
79
80/**
81 * Primary device attributes (DA1) response data.
82 *
83 * Returned as part of GhosttyDeviceAttributes in response to a CSI c query.
84 * The conformance_level is the Pp parameter and features contains the Ps
85 * feature codes.
86 *
87 * @ingroup terminal
88 */
89typedef struct {
90 /** Conformance level (Pp parameter). E.g. 62 for VT220. */
91 uint16_t conformance_level;
92
93 /** DA1 feature codes. Only the first num_features entries are valid. */
94 uint16_t features[64];
95
96 /** Number of valid entries in the features array. */
97 size_t num_features;
98} GhosttyDeviceAttributesPrimary;
99
100/**
101 * Secondary device attributes (DA2) response data.
102 *
103 * Returned as part of GhosttyDeviceAttributes in response to a CSI > c query.
104 * Response format: CSI > Pp ; Pv ; Pc c
105 *
106 * @ingroup terminal
107 */
108typedef struct {
109 /** Terminal type identifier (Pp). E.g. 1 for VT220. */
110 uint16_t device_type;
111
112 /** Firmware/patch version number (Pv). */
113 uint16_t firmware_version;
114
115 /** ROM cartridge registration number (Pc). Always 0 for emulators. */
116 uint16_t rom_cartridge;
117} GhosttyDeviceAttributesSecondary;
118
119/**
120 * Tertiary device attributes (DA3) response data.
121 *
122 * Returned as part of GhosttyDeviceAttributes in response to a CSI = c query.
123 * Response format: DCS ! | D...D ST (DECRPTUI).
124 *
125 * @ingroup terminal
126 */
127typedef struct {
128 /** Unit ID encoded as 8 uppercase hex digits in the response. */
129 uint32_t unit_id;
130} GhosttyDeviceAttributesTertiary;
131
132/**
133 * Device attributes response data for all three DA levels.
134 *
135 * Filled by the device_attributes callback in response to CSI c,
136 * CSI > c, or CSI = c queries. The terminal uses whichever sub-struct
137 * matches the request type.
138 *
139 * @ingroup terminal
140 */
141typedef struct {
142 GhosttyDeviceAttributesPrimary primary;
143 GhosttyDeviceAttributesSecondary secondary;
144 GhosttyDeviceAttributesTertiary tertiary;
145} GhosttyDeviceAttributes;
146
147#ifdef __cplusplus
148}
149#endif
150
151#endif /* GHOSTTY_VT_DEVICE_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/focus.h+76−0
@@ -0,0 +1,76 @@
1/**
2 * @file focus.h
3 *
4 * Focus encoding - encode focus in/out events into terminal escape sequences.
5 */
6
7#ifndef GHOSTTY_VT_FOCUS_H
8#define GHOSTTY_VT_FOCUS_H
9
10/** @defgroup focus Focus Encoding
11 *
12 * Utilities for encoding focus gained/lost events into terminal escape
13 * sequences (CSI I / CSI O) for focus reporting mode (mode 1004).
14 *
15 * ## Basic Usage
16 *
17 * Use ghostty_focus_encode() to encode a focus event into a caller-provided
18 * buffer. If the buffer is too small, the function returns
19 * GHOSTTY_OUT_OF_SPACE and sets the required size in the output parameter.
20 *
21 * ## Example
22 *
23 * @snippet c-vt-encode-focus/src/main.c focus-encode
24 *
25 * @{
26 */
27
28#include <stddef.h>
29#include <ghostty/vt/types.h>
30
31#ifdef __cplusplus
32extern "C" {
33#endif
34
35/**
36 * Focus event types for focus reporting mode (mode 1004).
37 */
38typedef enum GHOSTTY_ENUM_TYPED {
39 /** Terminal window gained focus */
40 GHOSTTY_FOCUS_GAINED = 0,
41 /** Terminal window lost focus */
42 GHOSTTY_FOCUS_LOST = 1,
43 GHOSTTY_FOCUS_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
44} GhosttyFocusEvent;
45
46/**
47 * Encode a focus event into a terminal escape sequence.
48 *
49 * Encodes a focus gained (CSI I) or focus lost (CSI O) report into the
50 * provided buffer.
51 *
52 * If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
53 * and writes the required buffer size to @p out_written. The caller can
54 * then retry with a sufficiently sized buffer.
55 *
56 * @param event The focus event to encode
57 * @param buf Output buffer to write the encoded sequence into (may be NULL)
58 * @param buf_len Size of the output buffer in bytes
59 * @param[out] out_written On success, the number of bytes written. On
60 * GHOSTTY_OUT_OF_SPACE, the required buffer size.
61 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
62 * is too small
63 */
64GHOSTTY_API GhosttyResult ghostty_focus_encode(
65 GhosttyFocusEvent event,
66 char* buf,
67 size_t buf_len,
68 size_t* out_written);
69
70#ifdef __cplusplus
71}
72#endif
73
74/** @} */
75
76#endif /* GHOSTTY_VT_FOCUS_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/formatter.h+207−0
@@ -0,0 +1,207 @@
1/**
2 * @file formatter.h
3 *
4 * Format terminal content as plain text, VT sequences, or HTML.
5 */
6
7#ifndef GHOSTTY_VT_FORMATTER_H
8#define GHOSTTY_VT_FORMATTER_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/allocator.h>
14#include <ghostty/vt/selection.h>
15#include <ghostty/vt/types.h>
16#include <ghostty/vt/terminal.h>
17
18#ifdef __cplusplus
19extern "C" {
20#endif
21
22/** @defgroup formatter Formatter
23 *
24 * Format terminal content as plain text, VT sequences, or HTML.
25 *
26 * A formatter captures a reference to a terminal and formatting options.
27 * It can be used repeatedly to produce output that reflects the current
28 * terminal state at the time of each format call.
29 *
30 * The terminal must outlive the formatter.
31 *
32 * @{
33 */
34
35/**
36 * Extra screen state to include in styled output.
37 *
38 * @ingroup formatter
39 */
40typedef struct {
41 /** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterScreenExtra). */
42 size_t size;
43
44 /** Emit cursor position using CUP (CSI H). */
45 bool cursor;
46
47 /** Emit current SGR style state based on the cursor's active style_id. */
48 bool style;
49
50 /** Emit current hyperlink state using OSC 8 sequences. */
51 bool hyperlink;
52
53 /** Emit character protection mode using DECSCA. */
54 bool protection;
55
56 /** Emit Kitty keyboard protocol state using CSI > u and CSI = sequences. */
57 bool kitty_keyboard;
58
59 /** Emit character set designations and invocations. */
60 bool charsets;
61} GhosttyFormatterScreenExtra;
62
63/**
64 * Extra terminal state to include in styled output.
65 *
66 * @ingroup formatter
67 */
68typedef struct {
69 /** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalExtra). */
70 size_t size;
71
72 /** Emit the palette using OSC 4 sequences. */
73 bool palette;
74
75 /** Emit terminal modes that differ from their defaults using CSI h/l. */
76 bool modes;
77
78 /** Emit scrolling region state using DECSTBM and DECSLRM sequences. */
79 bool scrolling_region;
80
81 /** Emit tabstop positions by clearing all tabs and setting each one. */
82 bool tabstops;
83
84 /** Emit the present working directory using OSC 7. */
85 bool pwd;
86
87 /** Emit keyboard modes such as ModifyOtherKeys. */
88 bool keyboard;
89
90 /** Screen-level extras. */
91 GhosttyFormatterScreenExtra screen;
92} GhosttyFormatterTerminalExtra;
93
94/**
95 * Options for creating a terminal formatter.
96 *
97 * @ingroup formatter
98 */
99typedef struct {
100 /** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalOptions). */
101 size_t size;
102
103 /** Output format to emit. */
104 GhosttyFormatterFormat emit;
105
106 /** Whether to unwrap soft-wrapped lines. */
107 bool unwrap;
108
109 /** Whether to trim trailing whitespace on non-blank lines. */
110 bool trim;
111
112 /** Extra terminal state to include in styled output. */
113 GhosttyFormatterTerminalExtra extra;
114
115 /** Optional selection to restrict output to a range.
116 * If NULL, the entire screen is formatted. */
117 const GhosttySelection *selection;
118} GhosttyFormatterTerminalOptions;
119
120/**
121 * Create a formatter for a terminal's active screen.
122 *
123 * The terminal must outlive the formatter. The formatter stores a borrowed
124 * reference to the terminal and reads its current state on each format call.
125 *
126 * @param allocator Pointer to allocator, or NULL to use the default allocator
127 * @param formatter Pointer to store the created formatter handle
128 * @param terminal The terminal to format (must not be NULL)
129 * @param options Formatting options
130 * @return GHOSTTY_SUCCESS on success, or an error code on failure
131 *
132 * @ingroup formatter
133 */
134GHOSTTY_API GhosttyResult ghostty_formatter_terminal_new(
135 const GhosttyAllocator* allocator,
136 GhosttyFormatter* formatter,
137 GhosttyTerminal terminal,
138 GhosttyFormatterTerminalOptions options);
139
140/**
141 * Run the formatter and produce output into the caller-provided buffer.
142 *
143 * Each call formats the current terminal state. Pass NULL for buf to
144 * query the required buffer size without writing any output; in that case
145 * out_written receives the required size and the return value is
146 * GHOSTTY_OUT_OF_SPACE.
147 *
148 * If the buffer is too small, returns GHOSTTY_OUT_OF_SPACE and sets
149 * out_written to the required size. The caller can then retry with a
150 * larger buffer.
151 *
152 * @param formatter The formatter handle (must not be NULL)
153 * @param buf Pointer to the output buffer, or NULL to query size
154 * @param buf_len Length of the output buffer in bytes
155 * @param out_written Pointer to receive the number of bytes written,
156 * or the required size on failure
157 * @return GHOSTTY_SUCCESS on success, or an error code on failure
158 *
159 * @ingroup formatter
160 */
161GHOSTTY_API GhosttyResult ghostty_formatter_format_buf(GhosttyFormatter formatter,
162 uint8_t* buf,
163 size_t buf_len,
164 size_t* out_written);
165
166/**
167 * Run the formatter and return an allocated buffer with the output.
168 *
169 * Each call formats the current terminal state. The buffer is allocated
170 * using the provided allocator (or the default allocator if NULL).
171 * The caller is responsible for freeing the returned buffer with
172 * ghostty_free(), passing the same allocator (or NULL for the default)
173 * that was used for the allocation.
174 *
175 * @param formatter The formatter handle (must not be NULL)
176 * @param allocator Pointer to allocator, or NULL to use the default allocator
177 * @param out_ptr Pointer to receive the allocated buffer
178 * @param out_len Pointer to receive the length of the output in bytes
179 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
180 * failure
181 *
182 * @ingroup formatter
183 */
184GHOSTTY_API GhosttyResult ghostty_formatter_format_alloc(GhosttyFormatter formatter,
185 const GhosttyAllocator* allocator,
186 uint8_t** out_ptr,
187 size_t* out_len);
188
189/**
190 * Free a formatter instance.
191 *
192 * Releases all resources associated with the formatter. After this call,
193 * the formatter handle becomes invalid.
194 *
195 * @param formatter The formatter handle to free (may be NULL)
196 *
197 * @ingroup formatter
198 */
199GHOSTTY_API void ghostty_formatter_free(GhosttyFormatter formatter);
200
201/** @} */
202
203#ifdef __cplusplus
204}
205#endif
206
207#endif /* GHOSTTY_VT_FORMATTER_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref.h+212−0
@@ -0,0 +1,212 @@
1/**
2 * @file grid_ref.h
3 *
4 * Terminal grid reference type for referencing a resolved position in the
5 * terminal grid.
6 */
7
8#ifndef GHOSTTY_VT_GRID_REF_H
9#define GHOSTTY_VT_GRID_REF_H
10
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/types.h>
14#include <ghostty/vt/screen.h>
15#include <ghostty/vt/style.h>
16
17#ifdef __cplusplus
18extern "C" {
19#endif
20
21/** @defgroup grid_ref Grid Reference
22 *
23 * A grid reference is a reference to a specific cell position in the
24 * terminal. Obtain a grid reference from `ghostty_terminal_grid_ref`
25 * for untracked or `ghostty_terminal_grid_ref_track` for tracked. Untracked
26 * vs tracked is explained next.
27 *
28 * Important: The grid reference APIs are not meant to be used as the core of a render
29 * loop. They are not built to sustain the framerates needed for rendering large
30 * screens. Use the render state API for that.
31 *
32 * ## Untracked vs Tracked References
33 *
34 * ### Untracked Reference
35 *
36 * An untracked grid reference is a value type that snapshots a specific
37 * cell. It is only valid until the next update to the terminal instance.
38 * There is no guarantee that it will remain valid after any operation,
39 * even if a seemingly unrelated part of the grid is changed. These are meant
40 * to be read and have their values cached immediately after obtaining it.
41 *
42 * An untracked grid reference has a performance cost in its initial lookup,
43 * but doesn't affect the ongoing performance of the terminal in any way,
44 * since it is a one-time snapshot.
45 *
46 * ### Tracked Reference
47 *
48 * A tracked grid reference follows its cell across normal screen operations.
49 * For example scrolling, scrollback pruning, resize/reflow, and other
50 * terminal mutations update the tracked reference automatically.
51 *
52 * A tracked reference can still lose its original semantic location. This can
53 * happen when the underlying grid is reset, pruned, or otherwise discarded in a
54 * way that cannot be mapped to a meaningful new cell. In that state,
55 * ghostty_tracked_grid_ref_has_value() returns false and
56 * ghostty_tracked_grid_ref_snapshot() / ghostty_tracked_grid_ref_point() return
57 * GHOSTTY_NO_VALUE. The handle remains valid, and callers may move it to a new
58 * point with ghostty_tracked_grid_ref_set().
59 *
60 * To read cell data from a tracked reference, first snapshot it with
61 * ghostty_tracked_grid_ref_snapshot(). The returned `GhosttyGridRef` is again
62 * an untracked reference and follows the same short lifetime rules as any other
63 * untracked grid reference.
64 *
65 * A tracked reference belongs to the terminal screen/page-list that was active
66 * when it was created or last set. Converting it to a point uses that owning
67 * screen/page-list, even if the terminal has since switched between primary and
68 * alternate screens. Calling ghostty_tracked_grid_ref_set() resolves the new
69 * point against the terminal's currently active screen/page-list and may move
70 * the tracked reference between screens.
71 *
72 * Tracked references are owned by the caller and must be freed with
73 * ghostty_tracked_grid_ref_free(). If the terminal that created a tracked
74 * reference is freed first, the handle remains valid only for tracked-grid-ref
75 * APIs: it reports no value and can still be freed.
76 *
77 * Each tracked reference adds bookkeeping to terminal mutations. Use them
78 * sparingly for long-lived anchors such as selections, search state, marks,
79 * or application-side bookmarks.
80 *
81 * ## Lifetime
82 *
83 * An untracked reference is a snapshot. It doesn't need to be freed.
84 * The safety of accessing the value is documented explicitly above: it
85 * is only safe to access any data until the next terminal mutating
86 * operation (including free).
87 *
88 * A tracked reference is allocated and must be freed when it is no
89 * longer needed. A tracked reference may outlive the terminal that created it;
90 * after terminal free, it reports no value and can still be freed.
91 *
92 * ## Examples
93 *
94 * @snippet c-vt-grid-traverse/src/main.c grid-ref-traverse
95 * @snippet c-vt-grid-ref-tracked/src/main.c grid-ref-tracked
96 *
97 * @{
98 */
99
100/**
101 * A resolved reference to a terminal cell position.
102 *
103 * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
104 *
105 * @ingroup grid_ref
106 */
107typedef struct {
108 size_t size;
109 void *node;
110 uint16_t x;
111 uint16_t y;
112} GhosttyGridRef;
113
114/**
115 * Get the cell from a grid reference.
116 *
117 * @param ref Pointer to the grid reference
118 * @param[out] out_cell On success, set to the cell at the ref's position (may be NULL)
119 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
120 * node is NULL
121 *
122 * @ingroup grid_ref
123 */
124GHOSTTY_API GhosttyResult ghostty_grid_ref_cell(const GhosttyGridRef *ref,
125 GhosttyCell *out_cell);
126
127/**
128 * Get the row from a grid reference.
129 *
130 * @param ref Pointer to the grid reference
131 * @param[out] out_row On success, set to the row at the ref's position (may be NULL)
132 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
133 * node is NULL
134 *
135 * @ingroup grid_ref
136 */
137GHOSTTY_API GhosttyResult ghostty_grid_ref_row(const GhosttyGridRef *ref,
138 GhosttyRow *out_row);
139
140/**
141 * Get the grapheme cluster codepoints for the cell at the grid reference's
142 * position.
143 *
144 * Writes the full grapheme cluster (the cell's primary codepoint followed by
145 * any combining codepoints) into the provided buffer. If the cell has no text,
146 * out_len is set to 0 and GHOSTTY_SUCCESS is returned.
147 *
148 * If the buffer is too small (or NULL), the function returns
149 * GHOSTTY_OUT_OF_SPACE and writes the required number of codepoints to
150 * out_len. The caller can then retry with a sufficiently sized buffer.
151 *
152 * @param ref Pointer to the grid reference
153 * @param buf Output buffer of uint32_t codepoints (may be NULL)
154 * @param buf_len Number of uint32_t elements in the buffer
155 * @param[out] out_len On success, the number of codepoints written. On
156 * GHOSTTY_OUT_OF_SPACE, the required buffer size in codepoints.
157 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
158 * node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
159 *
160 * @ingroup grid_ref
161 */
162GHOSTTY_API GhosttyResult ghostty_grid_ref_graphemes(const GhosttyGridRef *ref,
163 uint32_t *buf,
164 size_t buf_len,
165 size_t *out_len);
166
167/**
168 * Get the hyperlink URI for the cell at the grid reference's position.
169 *
170 * Writes the URI bytes into the provided buffer. If the cell has no
171 * hyperlink, out_len is set to 0 and GHOSTTY_SUCCESS is returned.
172 *
173 * If the buffer is too small (or NULL), the function returns
174 * GHOSTTY_OUT_OF_SPACE and writes the required number of bytes to
175 * out_len. The caller can then retry with a sufficiently sized buffer.
176 *
177 * @param ref Pointer to the grid reference
178 * @param buf Output buffer for the URI bytes (may be NULL)
179 * @param buf_len Size of the output buffer in bytes
180 * @param[out] out_len On success, the number of bytes written. On
181 * GHOSTTY_OUT_OF_SPACE, the required buffer size in bytes.
182 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
183 * node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
184 *
185 * @ingroup grid_ref
186 */
187GHOSTTY_API GhosttyResult ghostty_grid_ref_hyperlink_uri(
188 const GhosttyGridRef *ref,
189 uint8_t *buf,
190 size_t buf_len,
191 size_t *out_len);
192
193/**
194 * Get the style of the cell at the grid reference's position.
195 *
196 * @param ref Pointer to the grid reference
197 * @param[out] out_style On success, set to the cell's style (may be NULL)
198 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
199 * node is NULL
200 *
201 * @ingroup grid_ref
202 */
203GHOSTTY_API GhosttyResult ghostty_grid_ref_style(const GhosttyGridRef *ref,
204 GhosttyStyle *out_style);
205
206/** @} */
207
208#ifdef __cplusplus
209}
210#endif
211
212#endif /* GHOSTTY_VT_GRID_REF_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref_tracked.h+139−0
@@ -0,0 +1,139 @@
1/**
2 * @file grid_ref_tracked.h
3 *
4 * Tracked terminal grid references.
5 */
6
7#ifndef GHOSTTY_VT_GRID_REF_TRACKED_H
8#define GHOSTTY_VT_GRID_REF_TRACKED_H
9
10#include <stdbool.h>
11#include <ghostty/vt/types.h>
12#include <ghostty/vt/grid_ref.h>
13#include <ghostty/vt/point.h>
14
15#ifdef __cplusplus
16extern "C" {
17#endif
18
19/**
20 * Tracked grid references are owned grid references that move with the
21 * terminal. See @ref grid_ref for the full overview of tracked and untracked
22 * grid reference behavior.
23 *
24 * @ingroup grid_ref
25 */
26
27/**
28 * Free a tracked grid reference.
29 *
30 * Passing NULL is allowed and has no effect. A tracked reference may be freed
31 * after the terminal that created it is freed.
32 *
33 * @param ref Tracked grid reference to free.
34 *
35 * @ingroup grid_ref
36 */
37GHOSTTY_API void ghostty_tracked_grid_ref_free(GhosttyTrackedGridRef ref);
38
39/**
40 * Return whether a tracked grid reference currently has a meaningful value.
41 *
42 * If the terminal that created the tracked reference has been freed, this
43 * returns false.
44 *
45 * @param ref Tracked grid reference.
46 * @return true if the reference currently has a meaningful value.
47 *
48 * @ingroup grid_ref
49 */
50GHOSTTY_API bool ghostty_tracked_grid_ref_has_value(
51 GhosttyTrackedGridRef ref);
52
53/**
54 * Convert a tracked grid reference to a point in the requested coordinate
55 * space.
56 *
57 * This is the tracked equivalent of ghostty_terminal_point_from_grid_ref().
58 * Unlike snapshotting, this does not expose an intermediate untracked
59 * GhosttyGridRef.
60 *
61 * A tracked reference is resolved against the terminal screen/page-list that
62 * currently owns the reference. If the terminal has switched between primary
63 * and alternate screens since the reference was created or last set, this may
64 * be different from the terminal's currently active screen.
65 *
66 * If the tracked reference no longer has a meaningful value, this returns
67 * GHOSTTY_NO_VALUE. GHOSTTY_NO_VALUE is also returned when the reference cannot
68 * be represented in the requested coordinate space, including after the
69 * terminal that created the tracked reference has been freed.
70 *
71 * @param ref Tracked grid reference.
72 * @param tag Coordinate space to convert into.
73 * @param[out] out_point On success, receives the coordinate. May be NULL.
74 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
75 * or GHOSTTY_NO_VALUE if there is no representable value.
76 *
77 * @ingroup grid_ref
78 */
79GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_point(
80 GhosttyTrackedGridRef ref,
81 GhosttyPointTag tag,
82 GhosttyPointCoordinate *out_point);
83
84/**
85 * Move an existing tracked grid reference to a new terminal point.
86 *
87 * On success, the tracked reference begins tracking the new point and any prior
88 * "no value" state is cleared. On GHOSTTY_OUT_OF_MEMORY, the original tracked
89 * reference is left unchanged.
90 *
91 * The terminal must be the same terminal that created the tracked reference.
92 * The point is resolved against the terminal screen/page-list that is active at
93 * the time this function is called. If the terminal has switched between
94 * primary and alternate screens, this may move the tracked reference from one
95 * screen/page-list to the other.
96 *
97 * @param ref Tracked grid reference.
98 * @param terminal Terminal instance that owns the reference.
99 * @param point New point to track.
100 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref, terminal,
101 * or point is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation fails.
102 *
103 * @ingroup grid_ref
104 */
105GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_set(
106 GhosttyTrackedGridRef ref,
107 GhosttyTerminal terminal,
108 GhosttyPoint point);
109
110/**
111 * Snapshot a tracked grid reference into a regular GhosttyGridRef.
112 *
113 * The returned GhosttyGridRef is an untracked snapshot and has the same
114 * lifetime rules as ghostty_terminal_grid_ref(): it is only valid until the
115 * next terminal update. Snapshot immediately before calling
116 * ghostty_grid_ref_cell(), ghostty_grid_ref_row(),
117 * ghostty_grid_ref_graphemes(), ghostty_grid_ref_hyperlink_uri(), or
118 * ghostty_grid_ref_style().
119 *
120 * If the tracked reference no longer has a meaningful value, this returns
121 * GHOSTTY_NO_VALUE. This includes references whose owning terminal has been
122 * freed.
123 *
124 * @param ref Tracked grid reference.
125 * @param[out] out_ref On success, receives an untracked snapshot. May be NULL.
126 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
127 * or GHOSTTY_NO_VALUE if the tracked location was discarded.
128 *
129 * @ingroup grid_ref
130 */
131GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_snapshot(
132 GhosttyTrackedGridRef ref,
133 GhosttyGridRef *out_ref);
134
135#ifdef __cplusplus
136}
137#endif
138
139#endif /* GHOSTTY_VT_GRID_REF_TRACKED_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key.h+73−0
@@ -0,0 +1,73 @@
1/**
2 * @file key.h
3 *
4 * Key encoding module - encode key events into terminal escape sequences.
5 */
6
7#ifndef GHOSTTY_VT_KEY_H
8#define GHOSTTY_VT_KEY_H
9
10/** @defgroup key Key Encoding
11 *
12 * Utilities for encoding key events into terminal escape sequences,
13 * supporting both legacy encoding as well as Kitty Keyboard Protocol.
14 *
15 * ## Basic Usage
16 *
17 * 1. Create an encoder instance with ghostty_key_encoder_new()
18 * 2. Configure encoder options with ghostty_key_encoder_setopt()
19 * or ghostty_key_encoder_setopt_from_terminal() if you have a
20 * GhosttyTerminal.
21 * 3. For each key event:
22 * - Create a key event with ghostty_key_event_new()
23 * - Set event properties (action, key, modifiers, etc.)
24 * - Encode with ghostty_key_encoder_encode()
25 * - Free the event with ghostty_key_event_free()
26 * - Note: You can also reuse the same key event multiple times by
27 * changing its properties.
28 * 4. Free the encoder with ghostty_key_encoder_free() when done
29 *
30 * For a complete working example, see example/c-vt-encode-key in the
31 * repository.
32 *
33 * ## Example
34 *
35 * @snippet c-vt-encode-key/src/main.c key-encode
36 *
37 * ## Example: Encoding with Terminal State
38 *
39 * When you have a GhosttyTerminal, you can sync its modes (cursor key
40 * application, Kitty flags, etc.) into the encoder automatically:
41 *
42 * @code{.c}
43 * // Create a terminal and feed it some VT data that changes modes
44 * GhosttyTerminal terminal;
45 * ghostty_terminal_new(NULL, &terminal,
46 * (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0});
47 *
48 * // Application might write data that enables Kitty keyboard protocol, etc.
49 * ghostty_terminal_vt_write(terminal, vt_data, vt_len);
50 *
51 * // Create an encoder and sync its options from the terminal
52 * GhosttyKeyEncoder encoder;
53 * ghostty_key_encoder_new(NULL, &encoder);
54 * ghostty_key_encoder_setopt_from_terminal(encoder, terminal);
55 *
56 * // Encode a key event using the terminal-derived options
57 * char buf[128];
58 * size_t written = 0;
59 * ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);
60 *
61 * ghostty_key_encoder_free(encoder);
62 * ghostty_terminal_free(terminal);
63 * @endcode
64 *
65 * @{
66 */
67
68#include <ghostty/vt/key/event.h>
69#include <ghostty/vt/key/encoder.h>
70
71/** @} */
72
73#endif /* GHOSTTY_VT_KEY_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/encoder.h+255−0
@@ -0,0 +1,255 @@
1/**
2 * @file encoder.h
3 *
4 * Key event encoding to terminal escape sequences.
5 */
6
7#ifndef GHOSTTY_VT_KEY_ENCODER_H
8#define GHOSTTY_VT_KEY_ENCODER_H
9
10#include <stddef.h>
11#include <stdint.h>
12#include <ghostty/vt/types.h>
13#include <ghostty/vt/allocator.h>
14#include <ghostty/vt/terminal.h>
15#include <ghostty/vt/key/event.h>
16
17/**
18 * Opaque handle to a key encoder instance.
19 *
20 * This handle represents a key encoder that converts key events into terminal
21 * escape sequences.
22 *
23 * @ingroup key
24 */
25typedef struct GhosttyKeyEncoderImpl *GhosttyKeyEncoder;
26
27/**
28 * Kitty keyboard protocol flags.
29 *
30 * Bitflags representing the various modes of the Kitty keyboard protocol.
31 * These can be combined using bitwise OR operations. Valid values all
32 * start with `GHOSTTY_KITTY_KEY_`.
33 *
34 * @ingroup key
35 */
36typedef uint8_t GhosttyKittyKeyFlags;
37
38/** Kitty keyboard protocol disabled (all flags off) */
39#define GHOSTTY_KITTY_KEY_DISABLED 0
40
41/** Disambiguate escape codes */
42#define GHOSTTY_KITTY_KEY_DISAMBIGUATE (1 << 0)
43
44/** Report key press and release events */
45#define GHOSTTY_KITTY_KEY_REPORT_EVENTS (1 << 1)
46
47/** Report alternate key codes */
48#define GHOSTTY_KITTY_KEY_REPORT_ALTERNATES (1 << 2)
49
50/** Report all key events including those normally handled by the terminal */
51#define GHOSTTY_KITTY_KEY_REPORT_ALL (1 << 3)
52
53/** Report associated text with key events */
54#define GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED (1 << 4)
55
56/** All Kitty keyboard protocol flags enabled */
57#define GHOSTTY_KITTY_KEY_ALL (GHOSTTY_KITTY_KEY_DISAMBIGUATE | GHOSTTY_KITTY_KEY_REPORT_EVENTS | GHOSTTY_KITTY_KEY_REPORT_ALTERNATES | GHOSTTY_KITTY_KEY_REPORT_ALL | GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED)
58
59/**
60 * macOS option key behavior.
61 *
62 * Determines whether the "option" key on macOS is treated as "alt" or not.
63 * See the Ghostty `macos-option-as-alt` configuration option for more details.
64 *
65 * @ingroup key
66 */
67typedef enum GHOSTTY_ENUM_TYPED {
68 /** Option key is not treated as alt */
69 GHOSTTY_OPTION_AS_ALT_FALSE = 0,
70 /** Option key is treated as alt */
71 GHOSTTY_OPTION_AS_ALT_TRUE = 1,
72 /** Only left option key is treated as alt */
73 GHOSTTY_OPTION_AS_ALT_LEFT = 2,
74 /** Only right option key is treated as alt */
75 GHOSTTY_OPTION_AS_ALT_RIGHT = 3,
76 GHOSTTY_OPTION_AS_ALT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
77} GhosttyOptionAsAlt;
78
79/**
80 * Key encoder option identifiers.
81 *
82 * These values are used with ghostty_key_encoder_setopt() to configure
83 * the behavior of the key encoder.
84 *
85 * @ingroup key
86 */
87typedef enum GHOSTTY_ENUM_TYPED {
88 /** Terminal DEC mode 1: cursor key application mode (value: bool) */
89 GHOSTTY_KEY_ENCODER_OPT_CURSOR_KEY_APPLICATION = 0,
90
91 /** Terminal DEC mode 66: keypad key application mode (value: bool) */
92 GHOSTTY_KEY_ENCODER_OPT_KEYPAD_KEY_APPLICATION = 1,
93
94 /** Terminal DEC mode 1035: ignore keypad with numlock (value: bool) */
95 GHOSTTY_KEY_ENCODER_OPT_IGNORE_KEYPAD_WITH_NUMLOCK = 2,
96
97 /** Terminal DEC mode 1036: alt sends escape prefix (value: bool) */
98 GHOSTTY_KEY_ENCODER_OPT_ALT_ESC_PREFIX = 3,
99
100 /** xterm modifyOtherKeys mode 2 (value: bool) */
101 GHOSTTY_KEY_ENCODER_OPT_MODIFY_OTHER_KEYS_STATE_2 = 4,
102
103 /** Kitty keyboard protocol flags (value: GhosttyKittyKeyFlags bitmask) */
104 GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS = 5,
105
106 /** macOS option-as-alt setting (value: GhosttyOptionAsAlt) */
107 GHOSTTY_KEY_ENCODER_OPT_MACOS_OPTION_AS_ALT = 6,
108
109 /** Backarrow key mode (value: bool)
110 * See https://vt100.net/dec/ek-vt3xx-tp-002.pdf page 170
111 * If `false` (the default), `backspace` emits 0x7f
112 * If `true`, `backspace` emits 0x08
113 */
114 GHOSTTY_KEY_ENCODER_OPT_BACKARROW_KEY_MODE = 7,
115
116 GHOSTTY_KEY_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
117} GhosttyKeyEncoderOption;
118
119/**
120 * Create a new key encoder instance.
121 *
122 * Creates a new key encoder with default options. The encoder can be configured
123 * using ghostty_key_encoder_setopt() and must be freed using
124 * ghostty_key_encoder_free() when no longer needed.
125 *
126 * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
127 * @param encoder Pointer to store the created encoder handle
128 * @return GHOSTTY_SUCCESS on success, or an error code on failure
129 *
130 * @ingroup key
131 */
132GHOSTTY_API GhosttyResult ghostty_key_encoder_new(const GhosttyAllocator *allocator, GhosttyKeyEncoder *encoder);
133
134/**
135 * Free a key encoder instance.
136 *
137 * Releases all resources associated with the key encoder. After this call,
138 * the encoder handle becomes invalid and must not be used.
139 *
140 * @param encoder The encoder handle to free (may be NULL)
141 *
142 * @ingroup key
143 */
144GHOSTTY_API void ghostty_key_encoder_free(GhosttyKeyEncoder encoder);
145
146/**
147 * Set an option on the key encoder.
148 *
149 * Configures the behavior of the key encoder. Options control various aspects
150 * of encoding such as terminal modes (cursor key application mode, keypad mode),
151 * protocol selection (Kitty keyboard protocol flags), and platform-specific
152 * behaviors (macOS option-as-alt).
153 *
154 * If you are using a terminal instance, you can set the key encoding
155 * options based on the active terminal state (e.g. legacy vs Kitty mode
156 * and associated flags) with ghostty_key_encoder_setopt_from_terminal().
157 *
158 * A null pointer value does nothing. It does not reset the value to the
159 * default. The setopt call will do nothing.
160 *
161 * @param encoder The encoder handle, must not be NULL
162 * @param option The option to set
163 * @param value Pointer to the value to set (type depends on the option)
164 *
165 * @ingroup key
166 */
167GHOSTTY_API void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value);
168
169/**
170 * Set encoder options from a terminal's current state.
171 *
172 * Reads the terminal's current modes and flags and applies them to the
173 * encoder's options. This sets cursor key application mode, keypad mode,
174 * alt escape prefix, modifyOtherKeys state, and Kitty keyboard protocol
175 * flags from the terminal state.
176 *
177 * Note that the `macos_option_as_alt` option cannot be determined from
178 * terminal state and is reset to `GHOSTTY_OPTION_AS_ALT_FALSE` by this
179 * call. Use ghostty_key_encoder_setopt() to set it afterward if needed.
180 *
181 * @param encoder The encoder handle, must not be NULL
182 * @param terminal The terminal handle, must not be NULL
183 *
184 * @ingroup key
185 */
186GHOSTTY_API void ghostty_key_encoder_setopt_from_terminal(GhosttyKeyEncoder encoder, GhosttyTerminal terminal);
187
188/**
189 * Encode a key event into a terminal escape sequence.
190 *
191 * Converts a key event into the appropriate terminal escape sequence based on
192 * the encoder's current options. The sequence is written to the provided buffer.
193 *
194 * Not all key events produce output. For example, unmodified modifier keys
195 * typically don't generate escape sequences. Check the out_len parameter to
196 * determine if any data was written.
197 *
198 * If the output buffer is too small, this function returns GHOSTTY_OUT_OF_SPACE
199 * and out_len will contain the required buffer size. The caller can then
200 * allocate a larger buffer and call the function again.
201 *
202 * @param encoder The encoder handle, must not be NULL
203 * @param event The key event to encode, must not be NULL
204 * @param out_buf Buffer to write the encoded sequence to
205 * @param out_buf_size Size of the output buffer in bytes
206 * @param out_len Pointer to store the number of bytes written (may be NULL)
207 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer too small, or other error code
208 *
209 * ## Example: Calculate required buffer size
210 *
211 * @code{.c}
212 * // Query the required size with a NULL buffer (always returns OUT_OF_SPACE)
213 * size_t required = 0;
214 * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required);
215 * assert(result == GHOSTTY_OUT_OF_SPACE);
216 *
217 * // Allocate buffer of required size
218 * char *buf = malloc(required);
219 *
220 * // Encode with properly sized buffer
221 * size_t written = 0;
222 * result = ghostty_key_encoder_encode(encoder, event, buf, required, &written);
223 * assert(result == GHOSTTY_SUCCESS);
224 *
225 * // Use the encoded sequence...
226 *
227 * free(buf);
228 * @endcode
229 *
230 * ## Example: Direct encoding with static buffer
231 *
232 * @code{.c}
233 * // Most escape sequences are short, so a static buffer often suffices
234 * char buf[128];
235 * size_t written = 0;
236 * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);
237 *
238 * if (result == GHOSTTY_SUCCESS) {
239 * // Write the encoded sequence to the terminal
240 * write(pty_fd, buf, written);
241 * } else if (result == GHOSTTY_OUT_OF_SPACE) {
242 * // Buffer too small, written contains required size
243 * char *dynamic_buf = malloc(written);
244 * result = ghostty_key_encoder_encode(encoder, event, dynamic_buf, written, &written);
245 * assert(result == GHOSTTY_SUCCESS);
246 * write(pty_fd, dynamic_buf, written);
247 * free(dynamic_buf);
248 * }
249 * @endcode
250 *
251 * @ingroup key
252 */
253GHOSTTY_API GhosttyResult ghostty_key_encoder_encode(GhosttyKeyEncoder encoder, GhosttyKeyEvent event, char *out_buf, size_t out_buf_size, size_t *out_len);
254
255#endif /* GHOSTTY_VT_KEY_ENCODER_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/event.h+482−0
@@ -0,0 +1,482 @@
1/**
2 * @file event.h
3 *
4 * Key event representation and manipulation.
5 */
6
7#ifndef GHOSTTY_VT_KEY_EVENT_H
8#define GHOSTTY_VT_KEY_EVENT_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/types.h>
14#include <ghostty/vt/allocator.h>
15
16/**
17 * Opaque handle to a key event.
18 *
19 * This handle represents a keyboard input event containing information about
20 * the physical key pressed, modifiers, and generated text.
21 *
22 * @ingroup key
23 */
24typedef struct GhosttyKeyEventImpl *GhosttyKeyEvent;
25
26/**
27 * Keyboard input event types.
28 *
29 * @ingroup key
30 */
31typedef enum GHOSTTY_ENUM_TYPED {
32 /** Key was released */
33 GHOSTTY_KEY_ACTION_RELEASE = 0,
34 /** Key was pressed */
35 GHOSTTY_KEY_ACTION_PRESS = 1,
36 /** Key is being repeated (held down) */
37 GHOSTTY_KEY_ACTION_REPEAT = 2,
38 GHOSTTY_KEY_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
39} GhosttyKeyAction;
40
41/**
42 * Keyboard modifier keys bitmask.
43 *
44 * A bitmask representing all keyboard modifiers. This tracks which modifier keys
45 * are pressed and, where supported by the platform, which side (left or right)
46 * of each modifier is active.
47 *
48 * Use the GHOSTTY_MODS_* constants to test and set individual modifiers.
49 *
50 * Modifier side bits are only meaningful when the corresponding modifier bit is set.
51 * Not all platforms support distinguishing between left and right modifier
52 * keys and Ghostty is built to expect that some platforms may not provide this
53 * information.
54 *
55 * @ingroup key
56 */
57typedef uint16_t GhosttyMods;
58
59/** Shift key is pressed */
60#define GHOSTTY_MODS_SHIFT (1 << 0)
61/** Control key is pressed */
62#define GHOSTTY_MODS_CTRL (1 << 1)
63/** Alt/Option key is pressed */
64#define GHOSTTY_MODS_ALT (1 << 2)
65/** Super/Command/Windows key is pressed */
66#define GHOSTTY_MODS_SUPER (1 << 3)
67/** Caps Lock is active */
68#define GHOSTTY_MODS_CAPS_LOCK (1 << 4)
69/** Num Lock is active */
70#define GHOSTTY_MODS_NUM_LOCK (1 << 5)
71
72/**
73 * Right shift is pressed (0 = left, 1 = right).
74 * Only meaningful when GHOSTTY_MODS_SHIFT is set.
75 */
76#define GHOSTTY_MODS_SHIFT_SIDE (1 << 6)
77/**
78 * Right ctrl is pressed (0 = left, 1 = right).
79 * Only meaningful when GHOSTTY_MODS_CTRL is set.
80 */
81#define GHOSTTY_MODS_CTRL_SIDE (1 << 7)
82/**
83 * Right alt is pressed (0 = left, 1 = right).
84 * Only meaningful when GHOSTTY_MODS_ALT is set.
85 */
86#define GHOSTTY_MODS_ALT_SIDE (1 << 8)
87/**
88 * Right super is pressed (0 = left, 1 = right).
89 * Only meaningful when GHOSTTY_MODS_SUPER is set.
90 */
91#define GHOSTTY_MODS_SUPER_SIDE (1 << 9)
92
93/**
94 * Physical key codes.
95 *
96 * The set of key codes that Ghostty is aware of. These represent physical keys
97 * on the keyboard and are layout-independent. For example, the "a" key on a US
98 * keyboard is the same as the "ф" key on a Russian keyboard, but both will
99 * report the same key_a value.
100 *
101 * Layout-dependent strings are provided separately as UTF-8 text and are produced
102 * by the platform. These values are based on the W3C UI Events KeyboardEvent code
103 * standard. See: https://www.w3.org/TR/uievents-code
104 *
105 * @ingroup key
106 */
107typedef enum GHOSTTY_ENUM_TYPED {
108 GHOSTTY_KEY_UNIDENTIFIED = 0,
109
110 // Writing System Keys (W3C § 3.1.1)
111 GHOSTTY_KEY_BACKQUOTE,
112 GHOSTTY_KEY_BACKSLASH,
113 GHOSTTY_KEY_BRACKET_LEFT,
114 GHOSTTY_KEY_BRACKET_RIGHT,
115 GHOSTTY_KEY_COMMA,
116 GHOSTTY_KEY_DIGIT_0,
117 GHOSTTY_KEY_DIGIT_1,
118 GHOSTTY_KEY_DIGIT_2,
119 GHOSTTY_KEY_DIGIT_3,
120 GHOSTTY_KEY_DIGIT_4,
121 GHOSTTY_KEY_DIGIT_5,
122 GHOSTTY_KEY_DIGIT_6,
123 GHOSTTY_KEY_DIGIT_7,
124 GHOSTTY_KEY_DIGIT_8,
125 GHOSTTY_KEY_DIGIT_9,
126 GHOSTTY_KEY_EQUAL,
127 GHOSTTY_KEY_INTL_BACKSLASH,
128 GHOSTTY_KEY_INTL_RO,
129 GHOSTTY_KEY_INTL_YEN,
130 GHOSTTY_KEY_A,
131 GHOSTTY_KEY_B,
132 GHOSTTY_KEY_C,
133 GHOSTTY_KEY_D,
134 GHOSTTY_KEY_E,
135 GHOSTTY_KEY_F,
136 GHOSTTY_KEY_G,
137 GHOSTTY_KEY_H,
138 GHOSTTY_KEY_I,
139 GHOSTTY_KEY_J,
140 GHOSTTY_KEY_K,
141 GHOSTTY_KEY_L,
142 GHOSTTY_KEY_M,
143 GHOSTTY_KEY_N,
144 GHOSTTY_KEY_O,
145 GHOSTTY_KEY_P,
146 GHOSTTY_KEY_Q,
147 GHOSTTY_KEY_R,
148 GHOSTTY_KEY_S,
149 GHOSTTY_KEY_T,
150 GHOSTTY_KEY_U,
151 GHOSTTY_KEY_V,
152 GHOSTTY_KEY_W,
153 GHOSTTY_KEY_X,
154 GHOSTTY_KEY_Y,
155 GHOSTTY_KEY_Z,
156 GHOSTTY_KEY_MINUS,
157 GHOSTTY_KEY_PERIOD,
158 GHOSTTY_KEY_QUOTE,
159 GHOSTTY_KEY_SEMICOLON,
160 GHOSTTY_KEY_SLASH,
161
162 // Functional Keys (W3C § 3.1.2)
163 GHOSTTY_KEY_ALT_LEFT,
164 GHOSTTY_KEY_ALT_RIGHT,
165 GHOSTTY_KEY_BACKSPACE,
166 GHOSTTY_KEY_CAPS_LOCK,
167 GHOSTTY_KEY_CONTEXT_MENU,
168 GHOSTTY_KEY_CONTROL_LEFT,
169 GHOSTTY_KEY_CONTROL_RIGHT,
170 GHOSTTY_KEY_ENTER,
171 GHOSTTY_KEY_META_LEFT,
172 GHOSTTY_KEY_META_RIGHT,
173 GHOSTTY_KEY_SHIFT_LEFT,
174 GHOSTTY_KEY_SHIFT_RIGHT,
175 GHOSTTY_KEY_SPACE,
176 GHOSTTY_KEY_TAB,
177 GHOSTTY_KEY_CONVERT,
178 GHOSTTY_KEY_KANA_MODE,
179 GHOSTTY_KEY_NON_CONVERT,
180
181 // Control Pad Section (W3C § 3.2)
182 GHOSTTY_KEY_DELETE,
183 GHOSTTY_KEY_END,
184 GHOSTTY_KEY_HELP,
185 GHOSTTY_KEY_HOME,
186 GHOSTTY_KEY_INSERT,
187 GHOSTTY_KEY_PAGE_DOWN,
188 GHOSTTY_KEY_PAGE_UP,
189
190 // Arrow Pad Section (W3C § 3.3)
191 GHOSTTY_KEY_ARROW_DOWN,
192 GHOSTTY_KEY_ARROW_LEFT,
193 GHOSTTY_KEY_ARROW_RIGHT,
194 GHOSTTY_KEY_ARROW_UP,
195
196 // Numpad Section (W3C § 3.4)
197 GHOSTTY_KEY_NUM_LOCK,
198 GHOSTTY_KEY_NUMPAD_0,
199 GHOSTTY_KEY_NUMPAD_1,
200 GHOSTTY_KEY_NUMPAD_2,
201 GHOSTTY_KEY_NUMPAD_3,
202 GHOSTTY_KEY_NUMPAD_4,
203 GHOSTTY_KEY_NUMPAD_5,
204 GHOSTTY_KEY_NUMPAD_6,
205 GHOSTTY_KEY_NUMPAD_7,
206 GHOSTTY_KEY_NUMPAD_8,
207 GHOSTTY_KEY_NUMPAD_9,
208 GHOSTTY_KEY_NUMPAD_ADD,
209 GHOSTTY_KEY_NUMPAD_BACKSPACE,
210 GHOSTTY_KEY_NUMPAD_CLEAR,
211 GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY,
212 GHOSTTY_KEY_NUMPAD_COMMA,
213 GHOSTTY_KEY_NUMPAD_DECIMAL,
214 GHOSTTY_KEY_NUMPAD_DIVIDE,
215 GHOSTTY_KEY_NUMPAD_ENTER,
216 GHOSTTY_KEY_NUMPAD_EQUAL,
217 GHOSTTY_KEY_NUMPAD_MEMORY_ADD,
218 GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR,
219 GHOSTTY_KEY_NUMPAD_MEMORY_RECALL,
220 GHOSTTY_KEY_NUMPAD_MEMORY_STORE,
221 GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT,
222 GHOSTTY_KEY_NUMPAD_MULTIPLY,
223 GHOSTTY_KEY_NUMPAD_PAREN_LEFT,
224 GHOSTTY_KEY_NUMPAD_PAREN_RIGHT,
225 GHOSTTY_KEY_NUMPAD_SUBTRACT,
226 GHOSTTY_KEY_NUMPAD_SEPARATOR,
227 GHOSTTY_KEY_NUMPAD_UP,
228 GHOSTTY_KEY_NUMPAD_DOWN,
229 GHOSTTY_KEY_NUMPAD_RIGHT,
230 GHOSTTY_KEY_NUMPAD_LEFT,
231 GHOSTTY_KEY_NUMPAD_BEGIN,
232 GHOSTTY_KEY_NUMPAD_HOME,
233 GHOSTTY_KEY_NUMPAD_END,
234 GHOSTTY_KEY_NUMPAD_INSERT,
235 GHOSTTY_KEY_NUMPAD_DELETE,
236 GHOSTTY_KEY_NUMPAD_PAGE_UP,
237 GHOSTTY_KEY_NUMPAD_PAGE_DOWN,
238
239 // Function Section (W3C § 3.5)
240 GHOSTTY_KEY_ESCAPE,
241 GHOSTTY_KEY_F1,
242 GHOSTTY_KEY_F2,
243 GHOSTTY_KEY_F3,
244 GHOSTTY_KEY_F4,
245 GHOSTTY_KEY_F5,
246 GHOSTTY_KEY_F6,
247 GHOSTTY_KEY_F7,
248 GHOSTTY_KEY_F8,
249 GHOSTTY_KEY_F9,
250 GHOSTTY_KEY_F10,
251 GHOSTTY_KEY_F11,
252 GHOSTTY_KEY_F12,
253 GHOSTTY_KEY_F13,
254 GHOSTTY_KEY_F14,
255 GHOSTTY_KEY_F15,
256 GHOSTTY_KEY_F16,
257 GHOSTTY_KEY_F17,
258 GHOSTTY_KEY_F18,
259 GHOSTTY_KEY_F19,
260 GHOSTTY_KEY_F20,
261 GHOSTTY_KEY_F21,
262 GHOSTTY_KEY_F22,
263 GHOSTTY_KEY_F23,
264 GHOSTTY_KEY_F24,
265 GHOSTTY_KEY_F25,
266 GHOSTTY_KEY_FN,
267 GHOSTTY_KEY_FN_LOCK,
268 GHOSTTY_KEY_PRINT_SCREEN,
269 GHOSTTY_KEY_SCROLL_LOCK,
270 GHOSTTY_KEY_PAUSE,
271
272 // Media Keys (W3C § 3.6)
273 GHOSTTY_KEY_BROWSER_BACK,
274 GHOSTTY_KEY_BROWSER_FAVORITES,
275 GHOSTTY_KEY_BROWSER_FORWARD,
276 GHOSTTY_KEY_BROWSER_HOME,
277 GHOSTTY_KEY_BROWSER_REFRESH,
278 GHOSTTY_KEY_BROWSER_SEARCH,
279 GHOSTTY_KEY_BROWSER_STOP,
280 GHOSTTY_KEY_EJECT,
281 GHOSTTY_KEY_LAUNCH_APP_1,
282 GHOSTTY_KEY_LAUNCH_APP_2,
283 GHOSTTY_KEY_LAUNCH_MAIL,
284 GHOSTTY_KEY_MEDIA_PLAY_PAUSE,
285 GHOSTTY_KEY_MEDIA_SELECT,
286 GHOSTTY_KEY_MEDIA_STOP,
287 GHOSTTY_KEY_MEDIA_TRACK_NEXT,
288 GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS,
289 GHOSTTY_KEY_POWER,
290 GHOSTTY_KEY_SLEEP,
291 GHOSTTY_KEY_AUDIO_VOLUME_DOWN,
292 GHOSTTY_KEY_AUDIO_VOLUME_MUTE,
293 GHOSTTY_KEY_AUDIO_VOLUME_UP,
294 GHOSTTY_KEY_WAKE_UP,
295
296 // Legacy, Non-standard, and Special Keys (W3C § 3.7)
297 GHOSTTY_KEY_COPY,
298 GHOSTTY_KEY_CUT,
299 GHOSTTY_KEY_PASTE,
300 GHOSTTY_KEY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
301} GhosttyKey;
302
303/**
304 * Create a new key event instance.
305 *
306 * Creates a new key event with default values. The event must be freed using
307 * ghostty_key_event_free() when no longer needed.
308 *
309 * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
310 * @param event Pointer to store the created key event handle
311 * @return GHOSTTY_SUCCESS on success, or an error code on failure
312 *
313 * @ingroup key
314 */
315GHOSTTY_API GhosttyResult ghostty_key_event_new(const GhosttyAllocator *allocator, GhosttyKeyEvent *event);
316
317/**
318 * Free a key event instance.
319 *
320 * Releases all resources associated with the key event. After this call,
321 * the event handle becomes invalid and must not be used.
322 *
323 * @param event The key event handle to free (may be NULL)
324 *
325 * @ingroup key
326 */
327GHOSTTY_API void ghostty_key_event_free(GhosttyKeyEvent event);
328
329/**
330 * Set the key action (press, release, repeat).
331 *
332 * @param event The key event handle, must not be NULL
333 * @param action The action to set
334 *
335 * @ingroup key
336 */
337GHOSTTY_API void ghostty_key_event_set_action(GhosttyKeyEvent event, GhosttyKeyAction action);
338
339/**
340 * Get the key action (press, release, repeat).
341 *
342 * @param event The key event handle, must not be NULL
343 * @return The key action
344 *
345 * @ingroup key
346 */
347GHOSTTY_API GhosttyKeyAction ghostty_key_event_get_action(GhosttyKeyEvent event);
348
349/**
350 * Set the physical key code.
351 *
352 * @param event The key event handle, must not be NULL
353 * @param key The physical key code to set
354 *
355 * @ingroup key
356 */
357GHOSTTY_API void ghostty_key_event_set_key(GhosttyKeyEvent event, GhosttyKey key);
358
359/**
360 * Get the physical key code.
361 *
362 * @param event The key event handle, must not be NULL
363 * @return The physical key code
364 *
365 * @ingroup key
366 */
367GHOSTTY_API GhosttyKey ghostty_key_event_get_key(GhosttyKeyEvent event);
368
369/**
370 * Set the modifier keys bitmask.
371 *
372 * @param event The key event handle, must not be NULL
373 * @param mods The modifier keys bitmask to set
374 *
375 * @ingroup key
376 */
377GHOSTTY_API void ghostty_key_event_set_mods(GhosttyKeyEvent event, GhosttyMods mods);
378
379/**
380 * Get the modifier keys bitmask.
381 *
382 * @param event The key event handle, must not be NULL
383 * @return The modifier keys bitmask
384 *
385 * @ingroup key
386 */
387GHOSTTY_API GhosttyMods ghostty_key_event_get_mods(GhosttyKeyEvent event);
388
389/**
390 * Set the consumed modifiers bitmask.
391 *
392 * @param event The key event handle, must not be NULL
393 * @param consumed_mods The consumed modifiers bitmask to set
394 *
395 * @ingroup key
396 */
397GHOSTTY_API void ghostty_key_event_set_consumed_mods(GhosttyKeyEvent event, GhosttyMods consumed_mods);
398
399/**
400 * Get the consumed modifiers bitmask.
401 *
402 * @param event The key event handle, must not be NULL
403 * @return The consumed modifiers bitmask
404 *
405 * @ingroup key
406 */
407GHOSTTY_API GhosttyMods ghostty_key_event_get_consumed_mods(GhosttyKeyEvent event);
408
409/**
410 * Set whether the key event is part of a composition sequence.
411 *
412 * @param event The key event handle, must not be NULL
413 * @param composing Whether the key event is part of a composition sequence
414 *
415 * @ingroup key
416 */
417GHOSTTY_API void ghostty_key_event_set_composing(GhosttyKeyEvent event, bool composing);
418
419/**
420 * Get whether the key event is part of a composition sequence.
421 *
422 * @param event The key event handle, must not be NULL
423 * @return Whether the key event is part of a composition sequence
424 *
425 * @ingroup key
426 */
427GHOSTTY_API bool ghostty_key_event_get_composing(GhosttyKeyEvent event);
428
429/**
430 * Set the UTF-8 text generated by the key for the current keyboard layout.
431 *
432 * Must contain the unmodified character before any Ctrl/Meta transformations.
433 * The encoder derives modifier sequences from the logical key and mods
434 * bitmask, not from this text. Do not pass C0 control characters
435 * (U+0000-U+001F, U+007F) or platform function key codes (e.g. macOS PUA
436 * U+F700-U+F8FF); pass NULL instead and let the encoder use the logical key.
437 *
438 * The key event does NOT take ownership of the text pointer. The caller
439 * must ensure the string remains valid for the lifetime needed by the event.
440 *
441 * @param event The key event handle, must not be NULL
442 * @param utf8 The UTF-8 text to set (or NULL for empty)
443 * @param len Length of the UTF-8 text in bytes
444 *
445 * @ingroup key
446 */
447GHOSTTY_API void ghostty_key_event_set_utf8(GhosttyKeyEvent event, const char *utf8, size_t len);
448
449/**
450 * Get the UTF-8 text generated by the key event.
451 *
452 * The returned pointer is valid until the event is freed or the UTF-8 text is modified.
453 *
454 * @param event The key event handle, must not be NULL
455 * @param len Pointer to store the length of the UTF-8 text in bytes (may be NULL)
456 * @return The UTF-8 text (or NULL for empty)
457 *
458 * @ingroup key
459 */
460GHOSTTY_API const char *ghostty_key_event_get_utf8(GhosttyKeyEvent event, size_t *len);
461
462/**
463 * Set the unshifted Unicode codepoint.
464 *
465 * @param event The key event handle, must not be NULL
466 * @param codepoint The unshifted Unicode codepoint to set
467 *
468 * @ingroup key
469 */
470GHOSTTY_API void ghostty_key_event_set_unshifted_codepoint(GhosttyKeyEvent event, uint32_t codepoint);
471
472/**
473 * Get the unshifted Unicode codepoint.
474 *
475 * @param event The key event handle, must not be NULL
476 * @return The unshifted Unicode codepoint
477 *
478 * @ingroup key
479 */
480GHOSTTY_API uint32_t ghostty_key_event_get_unshifted_codepoint(GhosttyKeyEvent event);
481
482#endif /* GHOSTTY_VT_KEY_EVENT_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/kitty_graphics.h+775−0
@@ -0,0 +1,775 @@
1/**
2 * @file kitty_graphics.h
3 *
4 * Kitty graphics protocol
5 *
6 * See @ref kitty_graphics for a full usage guide.
7 */
8
9#ifndef GHOSTTY_VT_KITTY_GRAPHICS_H
10#define GHOSTTY_VT_KITTY_GRAPHICS_H
11
12#include <stdbool.h>
13#include <stdint.h>
14#include <ghostty/vt/allocator.h>
15#include <ghostty/vt/selection.h>
16#include <ghostty/vt/types.h>
17
18#ifdef __cplusplus
19extern "C" {
20#endif
21
22/** @defgroup kitty_graphics Kitty Graphics
23 *
24 * API for inspecting images and placements stored via the
25 * [Kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/).
26 *
27 * The central object is @ref GhosttyKittyGraphics, an opaque handle to
28 * the image storage associated with a terminal's active screen. From it
29 * you can iterate over placements and look up individual images.
30 *
31 * ## Obtaining a KittyGraphics Handle
32 *
33 * A @ref GhosttyKittyGraphics handle is obtained from a terminal via
34 * ghostty_terminal_get() with @ref GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS.
35 * The handle is borrowed from the terminal and remains valid until the
36 * next mutating terminal call (e.g. ghostty_terminal_vt_write() or
37 * ghostty_terminal_reset()).
38 *
39 * Before images can be stored, Kitty graphics must be enabled on the
40 * terminal by setting a non-zero storage limit with
41 * @ref GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT, and a PNG
42 * decoder callback must be installed via ghostty_sys_set() with
43 * @ref GHOSTTY_SYS_OPT_DECODE_PNG.
44 *
45 * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png
46 *
47 * ## Iterating Placements
48 *
49 * Placements are inspected through a @ref GhosttyKittyGraphicsPlacementIterator.
50 * The typical workflow is:
51 *
52 * 1. Create an iterator with ghostty_kitty_graphics_placement_iterator_new().
53 * 2. Populate it from the storage with ghostty_kitty_graphics_get() using
54 * @ref GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
55 * 3. Optionally filter by z-layer with
56 * ghostty_kitty_graphics_placement_iterator_set().
57 * 4. Advance with ghostty_kitty_graphics_placement_next() and read
58 * per-placement data with ghostty_kitty_graphics_placement_get().
59 * 5. For each placement, look up its image with
60 * ghostty_kitty_graphics_image() to access pixel data and dimensions.
61 * 6. Free the iterator with ghostty_kitty_graphics_placement_iterator_free().
62 *
63 * ## Looking Up Images
64 *
65 * Given an image ID (obtained from a placement via
66 * @ref GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID), call
67 * ghostty_kitty_graphics_image() to get a @ref GhosttyKittyGraphicsImage
68 * handle. From this handle, ghostty_kitty_graphics_image_get() provides
69 * the image dimensions, pixel format, compression, and a borrowed pointer
70 * to the raw pixel data.
71 *
72 * ## Rendering Helpers
73 *
74 * Several functions assist with rendering a placement:
75 *
76 * - ghostty_kitty_graphics_placement_pixel_size() — rendered pixel
77 * dimensions accounting for source rect and aspect ratio.
78 * - ghostty_kitty_graphics_placement_grid_size() — number of grid
79 * columns and rows the placement occupies.
80 * - ghostty_kitty_graphics_placement_viewport_pos() — viewport-relative
81 * grid position (may be negative for partially scrolled placements).
82 * - ghostty_kitty_graphics_placement_source_rect() — resolved source
83 * rectangle in pixels, clamped to image bounds.
84 * - ghostty_kitty_graphics_placement_rect() — bounding rectangle as a
85 * @ref GhosttySelection.
86 *
87 * ## Lifetime and Thread Safety
88 *
89 * All handles borrowed from the terminal (GhosttyKittyGraphics,
90 * GhosttyKittyGraphicsImage) are invalidated by any mutating terminal
91 * call. The placement iterator is independently owned and must be freed
92 * by the caller, but the data it yields is only valid while the
93 * underlying terminal is not mutated.
94 *
95 * ## Example
96 *
97 * The following example creates a terminal, sends a Kitty graphics
98 * image, then iterates placements and prints image metadata:
99 *
100 * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main
101 *
102 * @{
103 */
104
105/**
106 * Queryable data kinds for ghostty_kitty_graphics_get().
107 *
108 * @ingroup kitty_graphics
109 */
110typedef enum GHOSTTY_ENUM_TYPED {
111 /** Invalid / sentinel value. */
112 GHOSTTY_KITTY_GRAPHICS_DATA_INVALID = 0,
113
114 /**
115 * Populate a pre-allocated placement iterator with placement data from
116 * the storage. Iterator data is only valid as long as the underlying
117 * terminal is not mutated.
118 *
119 * Output type: GhosttyKittyGraphicsPlacementIterator *
120 */
121 GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR = 1,
122 GHOSTTY_KITTY_GRAPHICS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
123} GhosttyKittyGraphicsData;
124
125/**
126 * Queryable data kinds for ghostty_kitty_graphics_placement_get().
127 *
128 * @ingroup kitty_graphics
129 */
130typedef enum GHOSTTY_ENUM_TYPED {
131 /** Invalid / sentinel value. */
132 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_INVALID = 0,
133
134 /**
135 * The image ID this placement belongs to.
136 *
137 * Output type: uint32_t *
138 */
139 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID = 1,
140
141 /**
142 * The placement ID.
143 *
144 * Output type: uint32_t *
145 */
146 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_PLACEMENT_ID = 2,
147
148 /**
149 * Whether this is a virtual placement (unicode placeholder).
150 *
151 * Output type: bool *
152 */
153 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IS_VIRTUAL = 3,
154
155 /**
156 * Pixel offset from the left edge of the cell.
157 *
158 * Output type: uint32_t *
159 */
160 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_X_OFFSET = 4,
161
162 /**
163 * Pixel offset from the top edge of the cell.
164 *
165 * Output type: uint32_t *
166 */
167 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Y_OFFSET = 5,
168
169 /**
170 * Source rectangle x origin in pixels.
171 *
172 * Output type: uint32_t *
173 */
174 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_X = 6,
175
176 /**
177 * Source rectangle y origin in pixels.
178 *
179 * Output type: uint32_t *
180 */
181 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_Y = 7,
182
183 /**
184 * Source rectangle width in pixels (0 = full image width).
185 *
186 * Output type: uint32_t *
187 */
188 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_WIDTH = 8,
189
190 /**
191 * Source rectangle height in pixels (0 = full image height).
192 *
193 * Output type: uint32_t *
194 */
195 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_HEIGHT = 9,
196
197 /**
198 * Number of columns this placement occupies.
199 *
200 * Output type: uint32_t *
201 */
202 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_COLUMNS = 10,
203
204 /**
205 * Number of rows this placement occupies.
206 *
207 * Output type: uint32_t *
208 */
209 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_ROWS = 11,
210
211 /**
212 * Z-index for this placement.
213 *
214 * Output type: int32_t *
215 */
216 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Z = 12,
217
218 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
219} GhosttyKittyGraphicsPlacementData;
220
221/**
222 * Z-layer classification for kitty graphics placements.
223 *
224 * Based on the kitty protocol z-index conventions:
225 * - BELOW_BG: z < INT32_MIN/2 (drawn below cell background)
226 * - BELOW_TEXT: INT32_MIN/2 <= z < 0 (above background, below text)
227 * - ABOVE_TEXT: z >= 0 (above text)
228 * - ALL: no filtering (current behavior)
229 *
230 * @ingroup kitty_graphics
231 */
232typedef enum GHOSTTY_ENUM_TYPED {
233 GHOSTTY_KITTY_PLACEMENT_LAYER_ALL = 0,
234 GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_BG = 1,
235 GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_TEXT = 2,
236 GHOSTTY_KITTY_PLACEMENT_LAYER_ABOVE_TEXT = 3,
237 GHOSTTY_KITTY_PLACEMENT_LAYER_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
238} GhosttyKittyPlacementLayer;
239
240/**
241 * Settable options for ghostty_kitty_graphics_placement_iterator_set().
242 *
243 * @ingroup kitty_graphics
244 */
245typedef enum GHOSTTY_ENUM_TYPED {
246 /**
247 * Set the z-layer filter for the iterator.
248 *
249 * Input type: GhosttyKittyPlacementLayer *
250 */
251 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER = 0,
252 GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
253} GhosttyKittyGraphicsPlacementIteratorOption;
254
255/**
256 * Pixel format of a Kitty graphics image.
257 *
258 * @ingroup kitty_graphics
259 */
260typedef enum GHOSTTY_ENUM_TYPED {
261 GHOSTTY_KITTY_IMAGE_FORMAT_RGB = 0,
262 GHOSTTY_KITTY_IMAGE_FORMAT_RGBA = 1,
263 GHOSTTY_KITTY_IMAGE_FORMAT_PNG = 2,
264 GHOSTTY_KITTY_IMAGE_FORMAT_GRAY_ALPHA = 3,
265 GHOSTTY_KITTY_IMAGE_FORMAT_GRAY = 4,
266 GHOSTTY_KITTY_IMAGE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
267} GhosttyKittyImageFormat;
268
269/**
270 * Compression of a Kitty graphics image.
271 *
272 * @ingroup kitty_graphics
273 */
274typedef enum GHOSTTY_ENUM_TYPED {
275 GHOSTTY_KITTY_IMAGE_COMPRESSION_NONE = 0,
276 GHOSTTY_KITTY_IMAGE_COMPRESSION_ZLIB_DEFLATE = 1,
277 GHOSTTY_KITTY_IMAGE_COMPRESSION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
278} GhosttyKittyImageCompression;
279
280/**
281 * Queryable data kinds for ghostty_kitty_graphics_image_get().
282 *
283 * @ingroup kitty_graphics
284 */
285typedef enum GHOSTTY_ENUM_TYPED {
286 /** Invalid / sentinel value. */
287 GHOSTTY_KITTY_IMAGE_DATA_INVALID = 0,
288
289 /**
290 * The image ID.
291 *
292 * Output type: uint32_t *
293 */
294 GHOSTTY_KITTY_IMAGE_DATA_ID = 1,
295
296 /**
297 * The image number.
298 *
299 * Output type: uint32_t *
300 */
301 GHOSTTY_KITTY_IMAGE_DATA_NUMBER = 2,
302
303 /**
304 * Image width in pixels.
305 *
306 * Output type: uint32_t *
307 */
308 GHOSTTY_KITTY_IMAGE_DATA_WIDTH = 3,
309
310 /**
311 * Image height in pixels.
312 *
313 * Output type: uint32_t *
314 */
315 GHOSTTY_KITTY_IMAGE_DATA_HEIGHT = 4,
316
317 /**
318 * Pixel format of the image.
319 *
320 * Output type: GhosttyKittyImageFormat *
321 */
322 GHOSTTY_KITTY_IMAGE_DATA_FORMAT = 5,
323
324 /**
325 * Compression of the image.
326 *
327 * Output type: GhosttyKittyImageCompression *
328 */
329 GHOSTTY_KITTY_IMAGE_DATA_COMPRESSION = 6,
330
331 /**
332 * Borrowed pointer to the raw pixel data. Valid as long as the
333 * underlying terminal is not mutated.
334 *
335 * Output type: const uint8_t **
336 */
337 GHOSTTY_KITTY_IMAGE_DATA_DATA_PTR = 7,
338
339 /**
340 * Length of the raw pixel data in bytes.
341 *
342 * Output type: size_t *
343 */
344 GHOSTTY_KITTY_IMAGE_DATA_DATA_LEN = 8,
345
346 GHOSTTY_KITTY_IMAGE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
347} GhosttyKittyGraphicsImageData;
348
349/**
350 * Combined rendering geometry for a placement in a single sized struct.
351 *
352 * Combines the results of ghostty_kitty_graphics_placement_pixel_size(),
353 * ghostty_kitty_graphics_placement_grid_size(),
354 * ghostty_kitty_graphics_placement_viewport_pos(), and
355 * ghostty_kitty_graphics_placement_source_rect() into one call. This is
356 * an optimization over calling those four functions individually,
357 * particularly useful in environments with high per-call overhead such
358 * as FFI or Cgo.
359 *
360 * This struct uses the sized-struct ABI pattern. Initialize with
361 * GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo) before calling
362 * ghostty_kitty_graphics_placement_render_info().
363 *
364 * @ingroup kitty_graphics
365 */
366typedef struct {
367 /** Size of this struct in bytes. Must be set to sizeof(GhosttyKittyGraphicsPlacementRenderInfo). */
368 size_t size;
369 /** Rendered width in pixels. */
370 uint32_t pixel_width;
371 /** Rendered height in pixels. */
372 uint32_t pixel_height;
373 /** Number of grid columns the placement occupies. */
374 uint32_t grid_cols;
375 /** Number of grid rows the placement occupies. */
376 uint32_t grid_rows;
377 /** Viewport-relative column (may be negative for partially visible placements). */
378 int32_t viewport_col;
379 /** Viewport-relative row (may be negative for partially visible placements). */
380 int32_t viewport_row;
381 /** False when the placement is fully off-screen or virtual. */
382 bool viewport_visible;
383 /** Resolved source rectangle x origin in pixels. */
384 uint32_t source_x;
385 /** Resolved source rectangle y origin in pixels. */
386 uint32_t source_y;
387 /** Resolved source rectangle width in pixels. */
388 uint32_t source_width;
389 /** Resolved source rectangle height in pixels. */
390 uint32_t source_height;
391} GhosttyKittyGraphicsPlacementRenderInfo;
392
393/**
394 * Get data from a kitty graphics storage instance.
395 *
396 * The output pointer must be of the appropriate type for the requested
397 * data kind.
398 *
399 * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
400 *
401 * @param graphics The kitty graphics handle
402 * @param data The type of data to extract
403 * @param[out] out Pointer to store the extracted data
404 * @return GHOSTTY_SUCCESS on success
405 *
406 * @ingroup kitty_graphics
407 */
408GHOSTTY_API GhosttyResult ghostty_kitty_graphics_get(
409 GhosttyKittyGraphics graphics,
410 GhosttyKittyGraphicsData data,
411 void* out);
412
413/**
414 * Look up a Kitty graphics image by its image ID.
415 *
416 * Returns NULL if no image with the given ID exists or if Kitty graphics
417 * are disabled at build time.
418 *
419 * @param graphics The kitty graphics handle
420 * @param image_id The image ID to look up
421 * @return An opaque image handle, or NULL if not found
422 *
423 * @ingroup kitty_graphics
424 */
425GHOSTTY_API GhosttyKittyGraphicsImage ghostty_kitty_graphics_image(
426 GhosttyKittyGraphics graphics,
427 uint32_t image_id);
428
429/**
430 * Get data from a Kitty graphics image.
431 *
432 * The output pointer must be of the appropriate type for the requested
433 * data kind.
434 *
435 * @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
436 * @param data The data kind to query
437 * @param[out] out Pointer to receive the queried value
438 * @return GHOSTTY_SUCCESS on success
439 *
440 * @ingroup kitty_graphics
441 */
442GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get(
443 GhosttyKittyGraphicsImage image,
444 GhosttyKittyGraphicsImageData data,
445 void* out);
446
447/**
448 * Get multiple data fields from a Kitty graphics image in a single call.
449 *
450 * This is an optimization over calling ghostty_kitty_graphics_image_get()
451 * repeatedly, particularly useful in environments with high per-call
452 * overhead such as FFI or Cgo.
453 *
454 * Each element in the keys array specifies a data kind, and the
455 * corresponding element in the values array receives the result.
456 * The type of each values[i] pointer must match the output type
457 * documented for keys[i].
458 *
459 * Processing stops at the first error; on success out_written
460 * is set to count, on error it is set to the index of the
461 * failing key (i.e. the number of values successfully written).
462 *
463 * @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
464 * @param count Number of key/value pairs
465 * @param keys Array of data kinds to query
466 * @param values Array of output pointers (types must match each key's
467 * documented output type)
468 * @param[out] out_written On return, receives the number of values
469 * successfully written (may be NULL)
470 * @return GHOSTTY_SUCCESS if all queries succeed
471 *
472 * @ingroup kitty_graphics
473 */
474GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get_multi(
475 GhosttyKittyGraphicsImage image,
476 size_t count,
477 const GhosttyKittyGraphicsImageData* keys,
478 void** values,
479 size_t* out_written);
480
481/**
482 * Create a new placement iterator instance.
483 *
484 * All fields except the allocator are left undefined until populated
485 * via ghostty_kitty_graphics_get() with
486 * GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
487 *
488 * @param allocator Pointer to allocator, or NULL to use the default allocator
489 * @param[out] out_iterator On success, receives the created iterator handle
490 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
491 * failure
492 *
493 * @ingroup kitty_graphics
494 */
495GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_new(
496 const GhosttyAllocator* allocator,
497 GhosttyKittyGraphicsPlacementIterator* out_iterator);
498
499/**
500 * Free a placement iterator.
501 *
502 * @param iterator The iterator handle to free (may be NULL)
503 *
504 * @ingroup kitty_graphics
505 */
506GHOSTTY_API void ghostty_kitty_graphics_placement_iterator_free(
507 GhosttyKittyGraphicsPlacementIterator iterator);
508
509/**
510 * Set an option on a placement iterator.
511 *
512 * Use GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER with a
513 * GhosttyKittyPlacementLayer value to filter placements by z-layer.
514 * The filter is applied during iteration: ghostty_kitty_graphics_placement_next()
515 * will skip placements that do not match the configured layer.
516 *
517 * The default layer is GHOSTTY_KITTY_PLACEMENT_LAYER_ALL (no filtering).
518 *
519 * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
520 * @param option The option to set
521 * @param value Pointer to the value (type depends on option; NULL returns
522 * GHOSTTY_INVALID_VALUE)
523 * @return GHOSTTY_SUCCESS on success
524 *
525 * @ingroup kitty_graphics
526 */
527GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_set(
528 GhosttyKittyGraphicsPlacementIterator iterator,
529 GhosttyKittyGraphicsPlacementIteratorOption option,
530 const void* value);
531
532/**
533 * Advance the placement iterator to the next placement.
534 *
535 * If a layer filter has been set via
536 * ghostty_kitty_graphics_placement_iterator_set(), only placements
537 * matching that layer are returned.
538 *
539 * @param iterator The iterator handle (may be NULL)
540 * @return true if advanced to the next placement, false if at the end
541 *
542 * @ingroup kitty_graphics
543 */
544GHOSTTY_API bool ghostty_kitty_graphics_placement_next(
545 GhosttyKittyGraphicsPlacementIterator iterator);
546
547/**
548 * Get data from the current placement in a placement iterator.
549 *
550 * Call ghostty_kitty_graphics_placement_next() at least once before
551 * calling this function.
552 *
553 * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
554 * @param data The data kind to query
555 * @param[out] out Pointer to receive the queried value
556 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
557 * iterator is NULL or not positioned on a placement
558 *
559 * @ingroup kitty_graphics
560 */
561GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get(
562 GhosttyKittyGraphicsPlacementIterator iterator,
563 GhosttyKittyGraphicsPlacementData data,
564 void* out);
565
566/**
567 * Get multiple data fields from the current placement in a single call.
568 *
569 * This is an optimization over calling ghostty_kitty_graphics_placement_get()
570 * repeatedly, particularly useful in environments with high per-call
571 * overhead such as FFI or Cgo.
572 *
573 * Each element in the keys array specifies a data kind, and the
574 * corresponding element in the values array receives the result.
575 * The type of each values[i] pointer must match the output type
576 * documented for keys[i].
577 *
578 * Processing stops at the first error; on success out_written
579 * is set to count, on error it is set to the index of the
580 * failing key (i.e. the number of values successfully written).
581 *
582 * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
583 * @param count Number of key/value pairs
584 * @param keys Array of data kinds to query
585 * @param values Array of output pointers (types must match each key's
586 * documented output type)
587 * @param[out] out_written On return, receives the number of values
588 * successfully written (may be NULL)
589 * @return GHOSTTY_SUCCESS if all queries succeed
590 *
591 * @ingroup kitty_graphics
592 */
593GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get_multi(
594 GhosttyKittyGraphicsPlacementIterator iterator,
595 size_t count,
596 const GhosttyKittyGraphicsPlacementData* keys,
597 void** values,
598 size_t* out_written);
599
600/**
601 * Compute the grid rectangle occupied by the current placement.
602 *
603 * Uses the placement's pin, the image dimensions, and the terminal's
604 * cell/pixel geometry to calculate the bounding rectangle. Virtual
605 * placements (unicode placeholders) return GHOSTTY_NO_VALUE.
606 *
607 * @param terminal The terminal handle
608 * @param image The image handle for this placement's image
609 * @param iterator The placement iterator positioned on a placement
610 * @param[out] out_selection On success, receives the bounding rectangle
611 * as a selection with rectangle=true
612 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
613 * is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE for
614 * virtual placements or when Kitty graphics are disabled
615 *
616 * @ingroup kitty_graphics
617 */
618GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_rect(
619 GhosttyKittyGraphicsPlacementIterator iterator,
620 GhosttyKittyGraphicsImage image,
621 GhosttyTerminal terminal,
622 GhosttySelection* out_selection);
623
624/**
625 * Compute the rendered pixel size of the current placement.
626 *
627 * Takes into account the placement's source rectangle, specified
628 * columns/rows, and aspect ratio to calculate the final rendered
629 * pixel dimensions.
630 *
631 * @param iterator The placement iterator positioned on a placement
632 * @param image The image handle for this placement's image
633 * @param terminal The terminal handle
634 * @param[out] out_width On success, receives the width in pixels
635 * @param[out] out_height On success, receives the height in pixels
636 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
637 * is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
638 * Kitty graphics are disabled
639 *
640 * @ingroup kitty_graphics
641 */
642GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_pixel_size(
643 GhosttyKittyGraphicsPlacementIterator iterator,
644 GhosttyKittyGraphicsImage image,
645 GhosttyTerminal terminal,
646 uint32_t* out_width,
647 uint32_t* out_height);
648
649/**
650 * Compute the grid cell size of the current placement.
651 *
652 * Returns the number of columns and rows that the placement occupies
653 * in the terminal grid. If the placement specifies explicit columns
654 * and rows, those are returned directly; otherwise they are calculated
655 * from the pixel size and cell dimensions.
656 *
657 * @param iterator The placement iterator positioned on a placement
658 * @param image The image handle for this placement's image
659 * @param terminal The terminal handle
660 * @param[out] out_cols On success, receives the number of columns
661 * @param[out] out_rows On success, receives the number of rows
662 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
663 * is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
664 * Kitty graphics are disabled
665 *
666 * @ingroup kitty_graphics
667 */
668GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_grid_size(
669 GhosttyKittyGraphicsPlacementIterator iterator,
670 GhosttyKittyGraphicsImage image,
671 GhosttyTerminal terminal,
672 uint32_t* out_cols,
673 uint32_t* out_rows);
674
675/**
676 * Get the viewport-relative grid position of the current placement.
677 *
678 * Converts the placement's internal pin to viewport-relative column and
679 * row coordinates. The returned coordinates represent the top-left
680 * corner of the placement in the viewport's grid coordinate space.
681 *
682 * The row value can be negative when the placement's origin has
683 * scrolled above the top of the viewport. For example, a 4-row
684 * image that has scrolled up by 2 rows returns row=-2, meaning
685 * its top 2 rows are above the visible area but its bottom 2 rows
686 * are still on screen. Embedders should use these coordinates
687 * directly when computing the destination rectangle for rendering;
688 * the embedder is responsible for clipping the portion of the image
689 * that falls outside the viewport.
690 *
691 * Returns GHOSTTY_SUCCESS for any placement that is at least
692 * partially visible in the viewport. Returns GHOSTTY_NO_VALUE when
693 * the placement is completely outside the viewport (its bottom edge
694 * is above the viewport or its top edge is at or below the last
695 * viewport row), or when the placement is a virtual (unicode
696 * placeholder) placement.
697 *
698 * @param iterator The placement iterator positioned on a placement
699 * @param image The image handle for this placement's image
700 * @param terminal The terminal handle
701 * @param[out] out_col On success, receives the viewport-relative column
702 * @param[out] out_row On success, receives the viewport-relative row
703 * (may be negative for partially visible placements)
704 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if fully
705 * off-screen or virtual, GHOSTTY_INVALID_VALUE if any handle
706 * is NULL or the iterator is not positioned
707 *
708 * @ingroup kitty_graphics
709 */
710GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_viewport_pos(
711 GhosttyKittyGraphicsPlacementIterator iterator,
712 GhosttyKittyGraphicsImage image,
713 GhosttyTerminal terminal,
714 int32_t* out_col,
715 int32_t* out_row);
716
717/**
718 * Get the resolved source rectangle for the current placement.
719 *
720 * Applies kitty protocol semantics: a width or height of 0 in the
721 * placement means "use the full image dimension", and the resulting
722 * rectangle is clamped to the actual image bounds. The returned
723 * values are in pixels and are ready to use for texture sampling.
724 *
725 * @param iterator The placement iterator positioned on a placement
726 * @param image The image handle for this placement's image
727 * @param[out] out_x Source rect x origin in pixels
728 * @param[out] out_y Source rect y origin in pixels
729 * @param[out] out_width Source rect width in pixels
730 * @param[out] out_height Source rect height in pixels
731 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any
732 * handle is NULL or the iterator is not positioned
733 *
734 * @ingroup kitty_graphics
735 */
736GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_source_rect(
737 GhosttyKittyGraphicsPlacementIterator iterator,
738 GhosttyKittyGraphicsImage image,
739 uint32_t* out_x,
740 uint32_t* out_y,
741 uint32_t* out_width,
742 uint32_t* out_height);
743
744/**
745 * Get all rendering geometry for a placement in a single call.
746 *
747 * Combines pixel size, grid size, viewport position, and source
748 * rectangle into one struct. Initialize with
749 * GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo).
750 *
751 * When viewport_visible is false, the placement is fully off-screen
752 * or is a virtual placement; viewport_col and viewport_row may
753 * contain meaningless values in that case.
754 *
755 * @param iterator The iterator positioned on a placement
756 * @param image The image handle for this placement's image
757 * @param terminal The terminal handle
758 * @param[out] out_info Pointer to receive the rendering geometry
759 * @return GHOSTTY_SUCCESS on success
760 *
761 * @ingroup kitty_graphics
762 */
763GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_render_info(
764 GhosttyKittyGraphicsPlacementIterator iterator,
765 GhosttyKittyGraphicsImage image,
766 GhosttyTerminal terminal,
767 GhosttyKittyGraphicsPlacementRenderInfo* out_info);
768
769/** @} */
770
771#ifdef __cplusplus
772}
773#endif
774
775#endif /* GHOSTTY_VT_KITTY_GRAPHICS_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/modes.h+198−0
@@ -0,0 +1,198 @@
1/**
2 * @file modes.h
3 *
4 * Terminal mode utilities - pack and unpack ANSI/DEC mode identifiers.
5 */
6
7#ifndef GHOSTTY_VT_MODES_H
8#define GHOSTTY_VT_MODES_H
9
10/** @defgroup modes Mode Utilities
11 *
12 * Utilities for working with terminal modes. A mode is a compact
13 * 16-bit representation of a terminal mode identifier that encodes both
14 * the numeric mode value (up to 15 bits) and whether the mode is an ANSI
15 * mode or a DEC private mode (?-prefixed).
16 *
17 * The packed layout (least-significant bit first) is:
18 * - Bits 0–14: mode value (u15)
19 * - Bit 15: ANSI flag (0 = DEC private mode, 1 = ANSI mode)
20 *
21 * ## Example
22 *
23 * @snippet c-vt-modes/src/main.c modes-pack-unpack
24 *
25 * ## DECRPM Report Encoding
26 *
27 * Use ghostty_mode_report_encode() to encode a DECRPM response into a
28 * caller-provided buffer:
29 *
30 * @snippet c-vt-modes/src/main.c modes-decrpm
31 *
32 * @{
33 */
34
35#include <stdbool.h>
36#include <stddef.h>
37#include <stdint.h>
38
39#include <ghostty/vt/types.h>
40
41#ifdef __cplusplus
42extern "C" {
43#endif
44
45/** @name ANSI Modes
46 * Modes for standard ANSI modes.
47 * @{
48 */
49#define GHOSTTY_MODE_KAM (ghostty_mode_new(2, true)) /**< Keyboard action (disable keyboard) */
50#define GHOSTTY_MODE_INSERT (ghostty_mode_new(4, true)) /**< Insert mode */
51#define GHOSTTY_MODE_SRM (ghostty_mode_new(12, true)) /**< Send/receive mode */
52#define GHOSTTY_MODE_LINEFEED (ghostty_mode_new(20, true)) /**< Linefeed/new line mode */
53/** @} */
54
55/** @name DEC Private Modes
56 * Modes for DEC private modes (?-prefixed).
57 * @{
58 */
59#define GHOSTTY_MODE_DECCKM (ghostty_mode_new(1, false)) /**< Cursor keys */
60#define GHOSTTY_MODE_132_COLUMN (ghostty_mode_new(3, false)) /**< 132/80 column mode */
61#define GHOSTTY_MODE_SLOW_SCROLL (ghostty_mode_new(4, false)) /**< Slow scroll */
62#define GHOSTTY_MODE_REVERSE_COLORS (ghostty_mode_new(5, false)) /**< Reverse video */
63#define GHOSTTY_MODE_ORIGIN (ghostty_mode_new(6, false)) /**< Origin mode */
64#define GHOSTTY_MODE_WRAPAROUND (ghostty_mode_new(7, false)) /**< Auto-wrap mode */
65#define GHOSTTY_MODE_AUTOREPEAT (ghostty_mode_new(8, false)) /**< Auto-repeat keys */
66#define GHOSTTY_MODE_X10_MOUSE (ghostty_mode_new(9, false)) /**< X10 mouse reporting */
67#define GHOSTTY_MODE_CURSOR_BLINKING (ghostty_mode_new(12, false)) /**< Cursor blink */
68#define GHOSTTY_MODE_CURSOR_VISIBLE (ghostty_mode_new(25, false)) /**< Cursor visible (DECTCEM) */
69#define GHOSTTY_MODE_ENABLE_MODE_3 (ghostty_mode_new(40, false)) /**< Allow 132 column mode */
70#define GHOSTTY_MODE_REVERSE_WRAP (ghostty_mode_new(45, false)) /**< Reverse wrap */
71#define GHOSTTY_MODE_ALT_SCREEN_LEGACY (ghostty_mode_new(47, false)) /**< Alternate screen (legacy) */
72#define GHOSTTY_MODE_KEYPAD_KEYS (ghostty_mode_new(66, false)) /**< Application keypad */
73#define GHOSTTY_MODE_BACKARROW_KEY_MODE (ghostty_mode_new(67, false)) /**< Backarrow key mode (DECBKM) */
74#define GHOSTTY_MODE_LEFT_RIGHT_MARGIN (ghostty_mode_new(69, false)) /**< Left/right margin mode */
75#define GHOSTTY_MODE_NORMAL_MOUSE (ghostty_mode_new(1000, false)) /**< Normal mouse tracking */
76#define GHOSTTY_MODE_BUTTON_MOUSE (ghostty_mode_new(1002, false)) /**< Button-event mouse tracking */
77#define GHOSTTY_MODE_ANY_MOUSE (ghostty_mode_new(1003, false)) /**< Any-event mouse tracking */
78#define GHOSTTY_MODE_FOCUS_EVENT (ghostty_mode_new(1004, false)) /**< Focus in/out events */
79#define GHOSTTY_MODE_UTF8_MOUSE (ghostty_mode_new(1005, false)) /**< UTF-8 mouse format */
80#define GHOSTTY_MODE_SGR_MOUSE (ghostty_mode_new(1006, false)) /**< SGR mouse format */
81#define GHOSTTY_MODE_ALT_SCROLL (ghostty_mode_new(1007, false)) /**< Alternate scroll mode */
82#define GHOSTTY_MODE_URXVT_MOUSE (ghostty_mode_new(1015, false)) /**< URxvt mouse format */
83#define GHOSTTY_MODE_SGR_PIXELS_MOUSE (ghostty_mode_new(1016, false)) /**< SGR-Pixels mouse format */
84#define GHOSTTY_MODE_NUMLOCK_KEYPAD (ghostty_mode_new(1035, false)) /**< Ignore keypad with NumLock */
85#define GHOSTTY_MODE_ALT_ESC_PREFIX (ghostty_mode_new(1036, false)) /**< Alt key sends ESC prefix */
86#define GHOSTTY_MODE_ALT_SENDS_ESC (ghostty_mode_new(1039, false)) /**< Alt sends escape */
87#define GHOSTTY_MODE_REVERSE_WRAP_EXT (ghostty_mode_new(1045, false)) /**< Extended reverse wrap */
88#define GHOSTTY_MODE_ALT_SCREEN (ghostty_mode_new(1047, false)) /**< Alternate screen */
89#define GHOSTTY_MODE_SAVE_CURSOR (ghostty_mode_new(1048, false)) /**< Save cursor (DECSC) */
90#define GHOSTTY_MODE_ALT_SCREEN_SAVE (ghostty_mode_new(1049, false)) /**< Alt screen + save cursor + clear */
91#define GHOSTTY_MODE_BRACKETED_PASTE (ghostty_mode_new(2004, false)) /**< Bracketed paste mode */
92#define GHOSTTY_MODE_SYNC_OUTPUT (ghostty_mode_new(2026, false)) /**< Synchronized output */
93#define GHOSTTY_MODE_GRAPHEME_CLUSTER (ghostty_mode_new(2027, false)) /**< Grapheme cluster mode */
94#define GHOSTTY_MODE_COLOR_SCHEME_REPORT (ghostty_mode_new(2031, false)) /**< Report color scheme */
95#define GHOSTTY_MODE_IN_BAND_RESIZE (ghostty_mode_new(2048, false)) /**< In-band size reports */
96/** @} */
97
98/**
99 * A packed 16-bit terminal mode.
100 *
101 * Encodes a mode value (bits 0–14) and an ANSI flag (bit 15) into a
102 * single 16-bit integer. Use the inline helper functions to construct
103 * and inspect modes rather than manipulating bits directly.
104 */
105typedef uint16_t GhosttyMode;
106
107/**
108 * Create a mode from a mode value and ANSI flag.
109 *
110 * @param value The numeric mode value (0–32767)
111 * @param ansi true for an ANSI mode, false for a DEC private mode
112 * @return The packed mode
113 *
114 * @ingroup modes
115 */
116static inline GhosttyMode ghostty_mode_new(uint16_t value, bool ansi) {
117 return (GhosttyMode)((value & 0x7FFF) | ((uint16_t)ansi << 15));
118}
119
120/**
121 * Extract the numeric mode value from a mode.
122 *
123 * @param mode The mode
124 * @return The mode value (0–32767)
125 *
126 * @ingroup modes
127 */
128static inline uint16_t ghostty_mode_value(GhosttyMode mode) {
129 return mode & 0x7FFF;
130}
131
132/**
133 * Check whether a mode represents an ANSI mode.
134 *
135 * @param mode The mode
136 * @return true if this is an ANSI mode, false if it is a DEC private mode
137 *
138 * @ingroup modes
139 */
140static inline bool ghostty_mode_ansi(GhosttyMode mode) {
141 return (mode >> 15) != 0;
142}
143
144/**
145 * DECRPM report state values.
146 *
147 * These correspond to the Ps2 parameter in a DECRPM response
148 * sequence (CSI ? Ps1 ; Ps2 $ y).
149 */
150typedef enum GHOSTTY_ENUM_TYPED {
151 /** Mode is not recognized */
152 GHOSTTY_MODE_REPORT_NOT_RECOGNIZED = 0,
153 /** Mode is set (enabled) */
154 GHOSTTY_MODE_REPORT_SET = 1,
155 /** Mode is reset (disabled) */
156 GHOSTTY_MODE_REPORT_RESET = 2,
157 /** Mode is permanently set */
158 GHOSTTY_MODE_REPORT_PERMANENTLY_SET = 3,
159 /** Mode is permanently reset */
160 GHOSTTY_MODE_REPORT_PERMANENTLY_RESET = 4,
161 GHOSTTY_MODE_REPORT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
162} GhosttyModeReportState;
163
164/**
165 * Encode a DECRPM (DEC Private Mode Report) response sequence.
166 *
167 * Writes a mode report escape sequence into the provided buffer.
168 * The generated sequence has the form:
169 * - DEC private mode: CSI ? Ps1 ; Ps2 $ y
170 * - ANSI mode: CSI Ps1 ; Ps2 $ y
171 *
172 * If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
173 * and writes the required buffer size to @p out_written. The caller can
174 * then retry with a sufficiently sized buffer.
175 *
176 * @param mode The mode identifying the mode to report on
177 * @param state The report state for this mode
178 * @param buf Output buffer to write the encoded sequence into (may be NULL)
179 * @param buf_len Size of the output buffer in bytes
180 * @param[out] out_written On success, the number of bytes written. On
181 * GHOSTTY_OUT_OF_SPACE, the required buffer size.
182 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
183 * is too small
184 */
185GHOSTTY_API GhosttyResult ghostty_mode_report_encode(
186 GhosttyMode mode,
187 GhosttyModeReportState state,
188 char* buf,
189 size_t buf_len,
190 size_t* out_written);
191
192#ifdef __cplusplus
193}
194#endif
195
196/** @} */
197
198#endif /* GHOSTTY_VT_MODES_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse.h+70−0
@@ -0,0 +1,70 @@
1/**
2 * @file mouse.h
3 *
4 * Mouse encoding module - encode mouse events into terminal escape sequences.
5 */
6
7#ifndef GHOSTTY_VT_MOUSE_H
8#define GHOSTTY_VT_MOUSE_H
9
10/** @defgroup mouse Mouse Encoding
11 *
12 * Utilities for encoding mouse events into terminal escape sequences,
13 * supporting X10, UTF-8, SGR, URxvt, and SGR-Pixels mouse protocols.
14 *
15 * ## Basic Usage
16 *
17 * 1. Create an encoder instance with ghostty_mouse_encoder_new().
18 * 2. Configure encoder options with ghostty_mouse_encoder_setopt() or
19 * ghostty_mouse_encoder_setopt_from_terminal().
20 * 3. For each mouse event:
21 * - Create a mouse event with ghostty_mouse_event_new().
22 * - Set event properties (action, button, modifiers, position).
23 * - Encode with ghostty_mouse_encoder_encode().
24 * - Free the event with ghostty_mouse_event_free() or reuse it.
25 * 4. Free the encoder with ghostty_mouse_encoder_free() when done.
26 *
27 * For a complete working example, see example/c-vt-encode-mouse in the
28 * repository.
29 *
30 * ## Example
31 *
32 * @snippet c-vt-encode-mouse/src/main.c mouse-encode
33 *
34 * ## Example: Encoding with Terminal State
35 *
36 * When you have a GhosttyTerminal, you can sync its tracking mode and
37 * output format into the encoder automatically:
38 *
39 * @code{.c}
40 * // Create a terminal and feed it some VT data that enables mouse tracking
41 * GhosttyTerminal terminal;
42 * ghostty_terminal_new(NULL, &terminal,
43 * (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0});
44 *
45 * // Application might write data that enables mouse reporting, etc.
46 * ghostty_terminal_vt_write(terminal, vt_data, vt_len);
47 *
48 * // Create an encoder and sync its options from the terminal
49 * GhosttyMouseEncoder encoder;
50 * ghostty_mouse_encoder_new(NULL, &encoder);
51 * ghostty_mouse_encoder_setopt_from_terminal(encoder, terminal);
52 *
53 * // Encode a mouse event using the terminal-derived options
54 * char buf[128];
55 * size_t written = 0;
56 * ghostty_mouse_encoder_encode(encoder, event, buf, sizeof(buf), &written);
57 *
58 * ghostty_mouse_encoder_free(encoder);
59 * ghostty_terminal_free(terminal);
60 * @endcode
61 *
62 * @{
63 */
64
65#include <ghostty/vt/mouse/event.h>
66#include <ghostty/vt/mouse/encoder.h>
67
68/** @} */
69
70#endif /* GHOSTTY_VT_MOUSE_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/encoder.h+214−0
@@ -0,0 +1,214 @@
1/**
2 * @file encoder.h
3 *
4 * Mouse event encoding to terminal escape sequences.
5 */
6
7#ifndef GHOSTTY_VT_MOUSE_ENCODER_H
8#define GHOSTTY_VT_MOUSE_ENCODER_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/allocator.h>
14#include <ghostty/vt/mouse/event.h>
15#include <ghostty/vt/terminal.h>
16#include <ghostty/vt/types.h>
17
18/**
19 * Opaque handle to a mouse encoder instance.
20 *
21 * This handle represents a mouse encoder that converts normalized
22 * mouse events into terminal escape sequences.
23 *
24 * @ingroup mouse
25 */
26typedef struct GhosttyMouseEncoderImpl *GhosttyMouseEncoder;
27
28/**
29 * Mouse tracking mode.
30 *
31 * @ingroup mouse
32 */
33typedef enum GHOSTTY_ENUM_TYPED {
34 /** Mouse reporting disabled. */
35 GHOSTTY_MOUSE_TRACKING_NONE = 0,
36
37 /** X10 mouse mode. */
38 GHOSTTY_MOUSE_TRACKING_X10 = 1,
39
40 /** Normal mouse mode (button press/release only). */
41 GHOSTTY_MOUSE_TRACKING_NORMAL = 2,
42
43 /** Button-event tracking mode. */
44 GHOSTTY_MOUSE_TRACKING_BUTTON = 3,
45
46 /** Any-event tracking mode. */
47 GHOSTTY_MOUSE_TRACKING_ANY = 4,
48 GHOSTTY_MOUSE_TRACKING_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
49} GhosttyMouseTrackingMode;
50
51/**
52 * Mouse output format.
53 *
54 * @ingroup mouse
55 */
56typedef enum GHOSTTY_ENUM_TYPED {
57 GHOSTTY_MOUSE_FORMAT_X10 = 0,
58 GHOSTTY_MOUSE_FORMAT_UTF8 = 1,
59 GHOSTTY_MOUSE_FORMAT_SGR = 2,
60 GHOSTTY_MOUSE_FORMAT_URXVT = 3,
61 GHOSTTY_MOUSE_FORMAT_SGR_PIXELS = 4,
62 GHOSTTY_MOUSE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
63} GhosttyMouseFormat;
64
65/**
66 * Mouse encoder size and geometry context.
67 *
68 * This describes the rendered terminal geometry used to convert
69 * surface-space positions into encoded coordinates.
70 *
71 * @ingroup mouse
72 */
73typedef struct {
74 /** Size of this struct in bytes. Must be set to sizeof(GhosttyMouseEncoderSize). */
75 size_t size;
76
77 /** Full screen width in pixels. */
78 uint32_t screen_width;
79
80 /** Full screen height in pixels. */
81 uint32_t screen_height;
82
83 /** Cell width in pixels. Must be non-zero. */
84 uint32_t cell_width;
85
86 /** Cell height in pixels. Must be non-zero. */
87 uint32_t cell_height;
88
89 /** Top padding in pixels. */
90 uint32_t padding_top;
91
92 /** Bottom padding in pixels. */
93 uint32_t padding_bottom;
94
95 /** Right padding in pixels. */
96 uint32_t padding_right;
97
98 /** Left padding in pixels. */
99 uint32_t padding_left;
100} GhosttyMouseEncoderSize;
101
102/**
103 * Mouse encoder option identifiers.
104 *
105 * These values are used with ghostty_mouse_encoder_setopt() to configure
106 * the behavior of the mouse encoder.
107 *
108 * @ingroup mouse
109 */
110typedef enum GHOSTTY_ENUM_TYPED {
111 /** Mouse tracking mode (value: GhosttyMouseTrackingMode). */
112 GHOSTTY_MOUSE_ENCODER_OPT_EVENT = 0,
113
114 /** Mouse output format (value: GhosttyMouseFormat). */
115 GHOSTTY_MOUSE_ENCODER_OPT_FORMAT = 1,
116
117 /** Renderer size context (value: GhosttyMouseEncoderSize). */
118 GHOSTTY_MOUSE_ENCODER_OPT_SIZE = 2,
119
120 /** Whether any mouse button is currently pressed (value: bool). */
121 GHOSTTY_MOUSE_ENCODER_OPT_ANY_BUTTON_PRESSED = 3,
122
123 /** Whether to enable motion deduplication by last cell (value: bool). */
124 GHOSTTY_MOUSE_ENCODER_OPT_TRACK_LAST_CELL = 4,
125 GHOSTTY_MOUSE_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
126} GhosttyMouseEncoderOption;
127
128/**
129 * Create a new mouse encoder instance.
130 *
131 * @param allocator Pointer to allocator, or NULL to use the default allocator
132 * @param encoder Pointer to store the created encoder handle
133 * @return GHOSTTY_SUCCESS on success, or an error code on failure
134 *
135 * @ingroup mouse
136 */
137GHOSTTY_API GhosttyResult ghostty_mouse_encoder_new(const GhosttyAllocator *allocator,
138 GhosttyMouseEncoder *encoder);
139
140/**
141 * Free a mouse encoder instance.
142 *
143 * @param encoder The encoder handle to free (may be NULL)
144 *
145 * @ingroup mouse
146 */
147GHOSTTY_API void ghostty_mouse_encoder_free(GhosttyMouseEncoder encoder);
148
149/**
150 * Set an option on the mouse encoder.
151 *
152 * A null pointer value does nothing. It does not reset to defaults.
153 *
154 * @param encoder The encoder handle, must not be NULL
155 * @param option The option to set
156 * @param value Pointer to option value (type depends on option)
157 *
158 * @ingroup mouse
159 */
160GHOSTTY_API void ghostty_mouse_encoder_setopt(GhosttyMouseEncoder encoder,
161 GhosttyMouseEncoderOption option,
162 const void *value);
163
164/**
165 * Set encoder options from a terminal's current state.
166 *
167 * This sets tracking mode and output format from terminal state.
168 * It does not modify size or any-button state.
169 *
170 * @param encoder The encoder handle, must not be NULL
171 * @param terminal The terminal handle, must not be NULL
172 *
173 * @ingroup mouse
174 */
175GHOSTTY_API void ghostty_mouse_encoder_setopt_from_terminal(GhosttyMouseEncoder encoder,
176 GhosttyTerminal terminal);
177
178/**
179 * Reset internal encoder state.
180 *
181 * This clears motion deduplication state (last tracked cell).
182 *
183 * @param encoder The encoder handle (may be NULL)
184 *
185 * @ingroup mouse
186 */
187GHOSTTY_API void ghostty_mouse_encoder_reset(GhosttyMouseEncoder encoder);
188
189/**
190 * Encode a mouse event into a terminal escape sequence.
191 *
192 * Not all mouse events produce output. In such cases this returns
193 * GHOSTTY_SUCCESS with out_len set to 0.
194 *
195 * If the output buffer is too small, this returns GHOSTTY_OUT_OF_SPACE
196 * and out_len contains the required size.
197 *
198 * @param encoder The encoder handle, must not be NULL
199 * @param event The mouse event to encode, must not be NULL
200 * @param out_buf Buffer to write encoded bytes to, or NULL to query required size
201 * @param out_buf_size Size of out_buf in bytes
202 * @param out_len Pointer to store bytes written (or required bytes on failure)
203 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer is too small,
204 * or another error code
205 *
206 * @ingroup mouse
207 */
208GHOSTTY_API GhosttyResult ghostty_mouse_encoder_encode(GhosttyMouseEncoder encoder,
209 GhosttyMouseEvent event,
210 char *out_buf,
211 size_t out_buf_size,
212 size_t *out_len);
213
214#endif /* GHOSTTY_VT_MOUSE_ENCODER_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/event.h+195−0
@@ -0,0 +1,195 @@
1/**
2 * @file event.h
3 *
4 * Mouse event representation and manipulation.
5 */
6
7#ifndef GHOSTTY_VT_MOUSE_EVENT_H
8#define GHOSTTY_VT_MOUSE_EVENT_H
9
10#include <stdbool.h>
11#include <ghostty/vt/allocator.h>
12#include <ghostty/vt/key/event.h>
13#include <ghostty/vt/types.h>
14
15/**
16 * Opaque handle to a mouse event.
17 *
18 * This handle represents a normalized mouse input event containing
19 * action, button, modifiers, and surface-space position.
20 *
21 * @ingroup mouse
22 */
23typedef struct GhosttyMouseEventImpl *GhosttyMouseEvent;
24
25/**
26 * Mouse event action type.
27 *
28 * @ingroup mouse
29 */
30typedef enum GHOSTTY_ENUM_TYPED {
31 /** Mouse button was pressed. */
32 GHOSTTY_MOUSE_ACTION_PRESS = 0,
33
34 /** Mouse button was released. */
35 GHOSTTY_MOUSE_ACTION_RELEASE = 1,
36
37 /** Mouse moved. */
38 GHOSTTY_MOUSE_ACTION_MOTION = 2,
39 GHOSTTY_MOUSE_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
40} GhosttyMouseAction;
41
42/**
43 * Mouse button identity.
44 *
45 * @ingroup mouse
46 */
47typedef enum GHOSTTY_ENUM_TYPED {
48 GHOSTTY_MOUSE_BUTTON_UNKNOWN = 0,
49 GHOSTTY_MOUSE_BUTTON_LEFT = 1,
50 GHOSTTY_MOUSE_BUTTON_RIGHT = 2,
51 GHOSTTY_MOUSE_BUTTON_MIDDLE = 3,
52 GHOSTTY_MOUSE_BUTTON_FOUR = 4,
53 GHOSTTY_MOUSE_BUTTON_FIVE = 5,
54 GHOSTTY_MOUSE_BUTTON_SIX = 6,
55 GHOSTTY_MOUSE_BUTTON_SEVEN = 7,
56 GHOSTTY_MOUSE_BUTTON_EIGHT = 8,
57 GHOSTTY_MOUSE_BUTTON_NINE = 9,
58 GHOSTTY_MOUSE_BUTTON_TEN = 10,
59 GHOSTTY_MOUSE_BUTTON_ELEVEN = 11,
60 GHOSTTY_MOUSE_BUTTON_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
61} GhosttyMouseButton;
62
63/**
64 * Mouse position in surface-space pixels.
65 *
66 * @ingroup mouse
67 */
68typedef struct {
69 float x;
70 float y;
71} GhosttyMousePosition;
72
73/**
74 * Create a new mouse event instance.
75 *
76 * @param allocator Pointer to allocator, or NULL to use the default allocator
77 * @param event Pointer to store the created event handle
78 * @return GHOSTTY_SUCCESS on success, or an error code on failure
79 *
80 * @ingroup mouse
81 */
82GHOSTTY_API GhosttyResult ghostty_mouse_event_new(const GhosttyAllocator *allocator,
83 GhosttyMouseEvent *event);
84
85/**
86 * Free a mouse event instance.
87 *
88 * @param event The mouse event handle to free (may be NULL)
89 *
90 * @ingroup mouse
91 */
92GHOSTTY_API void ghostty_mouse_event_free(GhosttyMouseEvent event);
93
94/**
95 * Set the event action.
96 *
97 * @param event The event handle, must not be NULL
98 * @param action The action to set
99 *
100 * @ingroup mouse
101 */
102GHOSTTY_API void ghostty_mouse_event_set_action(GhosttyMouseEvent event,
103 GhosttyMouseAction action);
104
105/**
106 * Get the event action.
107 *
108 * @param event The event handle, must not be NULL
109 * @return The event action
110 *
111 * @ingroup mouse
112 */
113GHOSTTY_API GhosttyMouseAction ghostty_mouse_event_get_action(GhosttyMouseEvent event);
114
115/**
116 * Set the event button.
117 *
118 * This sets a concrete button identity for the event.
119 * To represent "no button" (for motion events), use
120 * ghostty_mouse_event_clear_button().
121 *
122 * @param event The event handle, must not be NULL
123 * @param button The button to set
124 *
125 * @ingroup mouse
126 */
127GHOSTTY_API void ghostty_mouse_event_set_button(GhosttyMouseEvent event,
128 GhosttyMouseButton button);
129
130/**
131 * Clear the event button.
132 *
133 * This sets the event button to "none".
134 *
135 * @param event The event handle, must not be NULL
136 *
137 * @ingroup mouse
138 */
139GHOSTTY_API void ghostty_mouse_event_clear_button(GhosttyMouseEvent event);
140
141/**
142 * Get the event button.
143 *
144 * @param event The event handle, must not be NULL
145 * @param out_button Output pointer for the button value (may be NULL)
146 * @return true if a button is set, false if no button is set
147 *
148 * @ingroup mouse
149 */
150GHOSTTY_API bool ghostty_mouse_event_get_button(GhosttyMouseEvent event,
151 GhosttyMouseButton *out_button);
152
153/**
154 * Set keyboard modifiers held during the event.
155 *
156 * @param event The event handle, must not be NULL
157 * @param mods Modifier bitmask
158 *
159 * @ingroup mouse
160 */
161GHOSTTY_API void ghostty_mouse_event_set_mods(GhosttyMouseEvent event,
162 GhosttyMods mods);
163
164/**
165 * Get keyboard modifiers held during the event.
166 *
167 * @param event The event handle, must not be NULL
168 * @return Modifier bitmask
169 *
170 * @ingroup mouse
171 */
172GHOSTTY_API GhosttyMods ghostty_mouse_event_get_mods(GhosttyMouseEvent event);
173
174/**
175 * Set the event position in surface-space pixels.
176 *
177 * @param event The event handle, must not be NULL
178 * @param position The position to set
179 *
180 * @ingroup mouse
181 */
182GHOSTTY_API void ghostty_mouse_event_set_position(GhosttyMouseEvent event,
183 GhosttyMousePosition position);
184
185/**
186 * Get the event position in surface-space pixels.
187 *
188 * @param event The event handle, must not be NULL
189 * @return The current event position
190 *
191 * @ingroup mouse
192 */
193GHOSTTY_API GhosttyMousePosition ghostty_mouse_event_get_position(GhosttyMouseEvent event);
194
195#endif /* GHOSTTY_VT_MOUSE_EVENT_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/osc.h+215−0
@@ -0,0 +1,215 @@
1/**
2 * @file osc.h
3 *
4 * OSC (Operating System Command) sequence parser and command handling.
5 */
6
7#ifndef GHOSTTY_VT_OSC_H
8#define GHOSTTY_VT_OSC_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/types.h>
14#include <ghostty/vt/allocator.h>
15
16/** @defgroup osc OSC Parser
17 *
18 * OSC (Operating System Command) sequence parser and command handling.
19 *
20 * The parser operates in a streaming fashion, processing input byte-by-byte
21 * to handle OSC sequences that may arrive in fragments across multiple reads.
22 * This interface makes it easy to integrate into most environments and avoids
23 * over-allocating buffers.
24 *
25 * ## Basic Usage
26 *
27 * 1. Create a parser instance with ghostty_osc_new()
28 * 2. Feed bytes to the parser using ghostty_osc_next()
29 * 3. Finalize parsing with ghostty_osc_end() to get the command
30 * 4. Query command type and extract data using ghostty_osc_command_type()
31 * and ghostty_osc_command_data()
32 * 5. Free the parser with ghostty_osc_free() when done
33 *
34 * @{
35 */
36
37/**
38 * OSC command types.
39 *
40 * @ingroup osc
41 */
42typedef enum GHOSTTY_ENUM_TYPED {
43 GHOSTTY_OSC_COMMAND_INVALID = 0,
44 GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE = 1,
45 GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_ICON = 2,
46 GHOSTTY_OSC_COMMAND_SEMANTIC_PROMPT = 3,
47 GHOSTTY_OSC_COMMAND_CLIPBOARD_CONTENTS = 4,
48 GHOSTTY_OSC_COMMAND_REPORT_PWD = 5,
49 GHOSTTY_OSC_COMMAND_MOUSE_SHAPE = 6,
50 GHOSTTY_OSC_COMMAND_COLOR_OPERATION = 7,
51 GHOSTTY_OSC_COMMAND_KITTY_COLOR_PROTOCOL = 8,
52 GHOSTTY_OSC_COMMAND_SHOW_DESKTOP_NOTIFICATION = 9,
53 GHOSTTY_OSC_COMMAND_HYPERLINK_START = 10,
54 GHOSTTY_OSC_COMMAND_HYPERLINK_END = 11,
55 GHOSTTY_OSC_COMMAND_CONEMU_SLEEP = 12,
56 GHOSTTY_OSC_COMMAND_CONEMU_SHOW_MESSAGE_BOX = 13,
57 GHOSTTY_OSC_COMMAND_CONEMU_CHANGE_TAB_TITLE = 14,
58 GHOSTTY_OSC_COMMAND_CONEMU_PROGRESS_REPORT = 15,
59 GHOSTTY_OSC_COMMAND_CONEMU_WAIT_INPUT = 16,
60 GHOSTTY_OSC_COMMAND_CONEMU_GUIMACRO = 17,
61 GHOSTTY_OSC_COMMAND_CONEMU_RUN_PROCESS = 18,
62 GHOSTTY_OSC_COMMAND_CONEMU_OUTPUT_ENVIRONMENT_VARIABLE = 19,
63 GHOSTTY_OSC_COMMAND_CONEMU_XTERM_EMULATION = 20,
64 GHOSTTY_OSC_COMMAND_CONEMU_COMMENT = 21,
65 GHOSTTY_OSC_COMMAND_KITTY_TEXT_SIZING = 22,
66 GHOSTTY_OSC_COMMAND_TYPE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
67} GhosttyOscCommandType;
68
69/**
70 * OSC command data types.
71 *
72 * These values specify what type of data to extract from an OSC command
73 * using `ghostty_osc_command_data`.
74 *
75 * @ingroup osc
76 */
77typedef enum GHOSTTY_ENUM_TYPED {
78 /** Invalid data type. Never results in any data extraction. */
79 GHOSTTY_OSC_DATA_INVALID = 0,
80
81 /**
82 * Window title string data.
83 *
84 * Valid for: GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE
85 *
86 * Output type: const char ** (pointer to null-terminated string)
87 *
88 * Lifetime: Valid until the next call to any ghostty_osc_* function with
89 * the same parser instance. Memory is owned by the parser.
90 */
91 GHOSTTY_OSC_DATA_CHANGE_WINDOW_TITLE_STR = 1,
92 GHOSTTY_OSC_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
93} GhosttyOscCommandData;
94
95/**
96 * Create a new OSC parser instance.
97 *
98 * Creates a new OSC (Operating System Command) parser using the provided
99 * allocator. The parser must be freed using ghostty_vt_osc_free() when
100 * no longer needed.
101 *
102 * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
103 * @param parser Pointer to store the created parser handle
104 * @return GHOSTTY_SUCCESS on success, or an error code on failure
105 *
106 * @ingroup osc
107 */
108GHOSTTY_API GhosttyResult ghostty_osc_new(const GhosttyAllocator *allocator, GhosttyOscParser *parser);
109
110/**
111 * Free an OSC parser instance.
112 *
113 * Releases all resources associated with the OSC parser. After this call,
114 * the parser handle becomes invalid and must not be used.
115 *
116 * @param parser The parser handle to free (may be NULL)
117 *
118 * @ingroup osc
119 */
120GHOSTTY_API void ghostty_osc_free(GhosttyOscParser parser);
121
122/**
123 * Reset an OSC parser instance to its initial state.
124 *
125 * Resets the parser state, clearing any partially parsed OSC sequences
126 * and returning the parser to its initial state. This is useful for
127 * reusing a parser instance or recovering from parse errors.
128 *
129 * @param parser The parser handle to reset, must not be null.
130 *
131 * @ingroup osc
132 */
133GHOSTTY_API void ghostty_osc_reset(GhosttyOscParser parser);
134
135/**
136 * Parse the next byte in an OSC sequence.
137 *
138 * Processes a single byte as part of an OSC sequence. The parser maintains
139 * internal state to track the progress through the sequence. Call this
140 * function for each byte in the sequence data.
141 *
142 * When finished pumping the parser with bytes, call ghostty_osc_end
143 * to get the final result.
144 *
145 * @param parser The parser handle, must not be null.
146 * @param byte The next byte to parse
147 *
148 * @ingroup osc
149 */
150GHOSTTY_API void ghostty_osc_next(GhosttyOscParser parser, uint8_t byte);
151
152/**
153 * Finalize OSC parsing and retrieve the parsed command.
154 *
155 * Call this function after feeding all bytes of an OSC sequence to the parser
156 * using ghostty_osc_next() with the exception of the terminating character
157 * (ESC or ST). This function finalizes the parsing process and returns the
158 * parsed OSC command.
159 *
160 * The return value is never NULL. Invalid commands will return a command
161 * with type GHOSTTY_OSC_COMMAND_INVALID.
162 *
163 * The terminator parameter specifies the byte that terminated the OSC sequence
164 * (typically 0x07 for BEL or 0x5C for ST after ESC). This information is
165 * preserved in the parsed command so that responses can use the same terminator
166 * format for better compatibility with the calling program. For commands that
167 * do not require a response, this parameter is ignored and the resulting
168 * command will not retain the terminator information.
169 *
170 * The returned command handle is valid until the next call to any
171 * `ghostty_osc_*` function with the same parser instance with the exception
172 * of command introspection functions such as `ghostty_osc_command_type`.
173 *
174 * @param parser The parser handle, must not be null.
175 * @param terminator The terminating byte of the OSC sequence (0x07 for BEL, 0x5C for ST)
176 * @return Handle to the parsed OSC command
177 *
178 * @ingroup osc
179 */
180GHOSTTY_API GhosttyOscCommand ghostty_osc_end(GhosttyOscParser parser, uint8_t terminator);
181
182/**
183 * Get the type of an OSC command.
184 *
185 * Returns the type identifier for the given OSC command. This can be used
186 * to determine what kind of command was parsed and what data might be
187 * available from it.
188 *
189 * @param command The OSC command handle to query (may be NULL)
190 * @return The command type, or GHOSTTY_OSC_COMMAND_INVALID if command is NULL
191 *
192 * @ingroup osc
193 */
194GHOSTTY_API GhosttyOscCommandType ghostty_osc_command_type(GhosttyOscCommand command);
195
196/**
197 * Extract data from an OSC command.
198 *
199 * Extracts typed data from the given OSC command based on the specified
200 * data type. The output pointer must be of the appropriate type for the
201 * requested data kind. Valid command types, output types, and memory
202 * safety information are documented in the `GhosttyOscCommandData` enum.
203 *
204 * @param command The OSC command handle to query (may be NULL)
205 * @param data The type of data to extract
206 * @param out Pointer to store the extracted data (type depends on data parameter)
207 * @return true if data extraction was successful, false otherwise
208 *
209 * @ingroup osc
210 */
211GHOSTTY_API bool ghostty_osc_command_data(GhosttyOscCommand command, GhosttyOscCommandData data, void *out);
212
213/** @} */
214
215#endif /* GHOSTTY_VT_OSC_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/paste.h+101−0
@@ -0,0 +1,101 @@
1/**
2 * @file paste.h
3 *
4 * Paste utilities - validate and encode paste data for terminal input.
5 */
6
7#ifndef GHOSTTY_VT_PASTE_H
8#define GHOSTTY_VT_PASTE_H
9
10/** @defgroup paste Paste Utilities
11 *
12 * Utilities for validating and encoding paste data for terminal input.
13 *
14 * ## Basic Usage
15 *
16 * Use ghostty_paste_is_safe() to check if paste data contains potentially
17 * dangerous sequences before sending it to the terminal.
18 *
19 * Use ghostty_paste_encode() to encode paste data for writing to the pty,
20 * including bracketed paste wrapping and unsafe byte stripping.
21 *
22 * ## Examples
23 *
24 * ### Safety Check
25 *
26 * @snippet c-vt-paste/src/main.c paste-safety
27 *
28 * ### Encoding
29 *
30 * @snippet c-vt-paste/src/main.c paste-encode
31 *
32 * @{
33 */
34
35#include <stdbool.h>
36#include <stddef.h>
37#include <ghostty/vt/types.h>
38
39#ifdef __cplusplus
40extern "C" {
41#endif
42
43/**
44 * Check if paste data is safe to paste into the terminal.
45 *
46 * Data is considered unsafe if it contains:
47 * - Newlines (`\n`) which can inject commands
48 * - The bracketed paste end sequence (`\x1b[201~`) which can be used
49 * to exit bracketed paste mode and inject commands
50 *
51 * This check is conservative and considers data unsafe regardless of
52 * current terminal state.
53 *
54 * @param data The paste data to check (must not be NULL)
55 * @param len The length of the data in bytes
56 * @return true if the data is safe to paste, false otherwise
57 */
58GHOSTTY_API bool ghostty_paste_is_safe(const char* data, size_t len);
59
60/**
61 * Encode paste data for writing to the terminal pty.
62 *
63 * This function prepares paste data for terminal input by:
64 * - Stripping unsafe control bytes (NUL, ESC, DEL, etc.) by replacing
65 * them with spaces
66 * - Wrapping the data in bracketed paste sequences if @p bracketed is true
67 * - Replacing newlines with carriage returns if @p bracketed is false
68 *
69 * The input @p data buffer is modified in place during encoding. The
70 * encoded result (potentially with bracketed paste prefix/suffix) is
71 * written to the output buffer.
72 *
73 * If the output buffer is too small, the function returns
74 * GHOSTTY_OUT_OF_SPACE and sets the required size in @p out_written.
75 * The caller can then retry with a sufficiently sized buffer.
76 *
77 * @param data The paste data to encode (modified in place, may be NULL)
78 * @param data_len The length of the input data in bytes
79 * @param bracketed Whether bracketed paste mode is active
80 * @param buf Output buffer to write the encoded result into (may be NULL)
81 * @param buf_len Size of the output buffer in bytes
82 * @param[out] out_written On success, the number of bytes written. On
83 * GHOSTTY_OUT_OF_SPACE, the required buffer size.
84 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
85 * is too small
86 */
87GHOSTTY_API GhosttyResult ghostty_paste_encode(
88 char* data,
89 size_t data_len,
90 bool bracketed,
91 char* buf,
92 size_t buf_len,
93 size_t* out_written);
94
95#ifdef __cplusplus
96}
97#endif
98
99/** @} */
100
101#endif /* GHOSTTY_VT_PASTE_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/point.h+89−0
@@ -0,0 +1,89 @@
1/**
2 * @file point.h
3 *
4 * Terminal point types for referencing locations in the terminal grid.
5 */
6
7#ifndef GHOSTTY_VT_POINT_H
8#define GHOSTTY_VT_POINT_H
9
10#include <stdint.h>
11
12#ifdef __cplusplus
13extern "C" {
14#endif
15
16/** @defgroup point Point
17 *
18 * Types for referencing x/y positions in the terminal grid under
19 * different coordinate systems (active area, viewport, full screen,
20 * scrollback history).
21 *
22 * @{
23 */
24
25/**
26 * A coordinate in the terminal grid.
27 *
28 * @ingroup point
29 */
30typedef struct {
31 /** Column (0-indexed). */
32 uint16_t x;
33
34 /** Row (0-indexed). May exceed page size for screen/history tags. */
35 uint32_t y;
36} GhosttyPointCoordinate;
37
38/**
39 * Point reference tag.
40 *
41 * Determines which coordinate system a point uses.
42 *
43 * @ingroup point
44 */
45typedef enum GHOSTTY_ENUM_TYPED {
46 /** Active area where the cursor can move. */
47 GHOSTTY_POINT_TAG_ACTIVE = 0,
48
49 /** Visible viewport (changes when scrolled). */
50 GHOSTTY_POINT_TAG_VIEWPORT = 1,
51
52 /** Full screen including scrollback. */
53 GHOSTTY_POINT_TAG_SCREEN = 2,
54
55 /** Scrollback history only (before active area). */
56 GHOSTTY_POINT_TAG_HISTORY = 3,
57 GHOSTTY_POINT_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
58 } GhosttyPointTag;
59
60/**
61 * Point value union.
62 *
63 * @ingroup point
64 */
65typedef union {
66 /** Coordinate (used for all tag variants). */
67 GhosttyPointCoordinate coordinate;
68
69 /** Padding for ABI compatibility. Do not use. */
70 uint64_t _padding[2];
71} GhosttyPointValue;
72
73/**
74 * Tagged union for a point in the terminal grid.
75 *
76 * @ingroup point
77 */
78typedef struct {
79 GhosttyPointTag tag;
80 GhosttyPointValue value;
81} GhosttyPoint;
82
83/** @} */
84
85#ifdef __cplusplus
86}
87#endif
88
89#endif /* GHOSTTY_VT_POINT_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/render.h+729−0
@@ -0,0 +1,729 @@
1/**
2 * @file render.h
3 *
4 * Render state for creating high performance renderers.
5 */
6
7#ifndef GHOSTTY_VT_RENDER_H
8#define GHOSTTY_VT_RENDER_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/allocator.h>
14#include <ghostty/vt/color.h>
15#include <ghostty/vt/terminal.h>
16#include <ghostty/vt/types.h>
17
18#ifdef __cplusplus
19extern "C" {
20#endif
21
22/** @defgroup render Render State
23 *
24 * Represents the state required to render a visible screen (a viewport)
25 * of a terminal instance. This is stateful and optimized for repeated
26 * updates from a single terminal instance and only updating dirty regions
27 * of the screen.
28 *
29 * The key design principle of this API is that it only needs read/write
30 * access to the terminal instance during the update call. This allows
31 * the render state to minimally impact terminal IO performance and also
32 * allows the renderer to be safely multi-threaded (as long as a lock is
33 * held during the update call to ensure exclusive access to the terminal
34 * instance).
35 *
36 * The basic usage of this API is:
37 *
38 * 1. Create an empty render state
39 * 2. Update it from a terminal instance whenever you need.
40 * 3. Read from the render state to get the data needed to draw your frame.
41 *
42 * ## Dirty Tracking
43 *
44 * Dirty tracking is a key feature of the render state that allows renderers
45 * to efficiently determine what parts of the screen have changed and only
46 * redraw changed regions.
47 *
48 * The render state API keeps track of dirty state at two independent layers:
49 * a global dirty state that indicates whether the entire frame is clean,
50 * partially dirty, or fully dirty, and a per-row dirty state that allows
51 * tracking which rows in a partially dirty frame have changed.
52 *
53 * The user of the render state API is expected to unset both of these.
54 * The `update` call does not unset dirty state, it only updates it.
55 *
56 * An extremely important detail: setting one dirty state doesn't unset
57 * the other. For example, setting the global dirty state to false does not
58 * reset the row-level dirty flags. So, the caller of the render state API must
59 * be careful to manage both layers of dirty state correctly.
60 *
61 * ## Examples
62 *
63 * ### Creating and updating render state
64 * @snippet c-vt-render/src/main.c render-state-update
65 *
66 * ### Checking dirty state
67 * @snippet c-vt-render/src/main.c render-dirty-check
68 *
69 * ### Reading colors
70 * @snippet c-vt-render/src/main.c render-colors
71 *
72 * ### Reading cursor state
73 * @snippet c-vt-render/src/main.c render-cursor
74 *
75 * ### Iterating rows and cells
76 * @snippet c-vt-render/src/main.c render-row-iterate
77 *
78 * ### Resetting dirty state after rendering
79 * @snippet c-vt-render/src/main.c render-dirty-reset
80 *
81 * @{
82 */
83
84/**
85 * Dirty state of a render state after update.
86 *
87 * @ingroup render
88 */
89typedef enum GHOSTTY_ENUM_TYPED {
90 /** Not dirty at all; rendering can be skipped. */
91 GHOSTTY_RENDER_STATE_DIRTY_FALSE = 0,
92
93 /** Some rows changed; renderer can redraw incrementally. */
94 GHOSTTY_RENDER_STATE_DIRTY_PARTIAL = 1,
95
96 /** Global state changed; renderer should redraw everything. */
97 GHOSTTY_RENDER_STATE_DIRTY_FULL = 2,
98 GHOSTTY_RENDER_STATE_DIRTY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
99} GhosttyRenderStateDirty;
100
101/**
102 * Visual style of the cursor.
103 *
104 * @ingroup render
105 */
106typedef enum GHOSTTY_ENUM_TYPED {
107 /** Bar cursor (DECSCUSR 5, 6). */
108 GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BAR = 0,
109
110 /** Block cursor (DECSCUSR 1, 2). */
111 GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK = 1,
112
113 /** Underline cursor (DECSCUSR 3, 4). */
114 GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_UNDERLINE = 2,
115
116 /** Hollow block cursor. */
117 GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK_HOLLOW = 3,
118 GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
119} GhosttyRenderStateCursorVisualStyle;
120
121/**
122 * Queryable data kinds for ghostty_render_state_get().
123 *
124 * @ingroup render
125 */
126typedef enum GHOSTTY_ENUM_TYPED {
127 /** Invalid / sentinel value. */
128 GHOSTTY_RENDER_STATE_DATA_INVALID = 0,
129
130 /** Viewport width in cells (uint16_t). */
131 GHOSTTY_RENDER_STATE_DATA_COLS = 1,
132
133 /** Viewport height in cells (uint16_t). */
134 GHOSTTY_RENDER_STATE_DATA_ROWS = 2,
135
136 /** Current dirty state (GhosttyRenderStateDirty). */
137 GHOSTTY_RENDER_STATE_DATA_DIRTY = 3,
138
139 /** Populate a pre-allocated GhosttyRenderStateRowIterator with row data
140 * from the render state (GhosttyRenderStateRowIterator). Row data is
141 * only valid as long as the underlying render state is not updated.
142 * It is unsafe to use row data after updating the render state.
143 * */
144 GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR = 4,
145
146 /** Default/current background color (GhosttyColorRgb). */
147 GHOSTTY_RENDER_STATE_DATA_COLOR_BACKGROUND = 5,
148
149 /** Default/current foreground color (GhosttyColorRgb). */
150 GHOSTTY_RENDER_STATE_DATA_COLOR_FOREGROUND = 6,
151
152 /** Cursor color when explicitly set by terminal state (GhosttyColorRgb).
153 * Returns GHOSTTY_INVALID_VALUE if no explicit cursor color is set;
154 * use COLOR_CURSOR_HAS_VALUE to check first. */
155 GHOSTTY_RENDER_STATE_DATA_COLOR_CURSOR = 7,
156
157 /** Whether an explicit cursor color is set (bool). */
158 GHOSTTY_RENDER_STATE_DATA_COLOR_CURSOR_HAS_VALUE = 8,
159
160 /** The active 256-color palette (GhosttyColorRgb[256]). */
161 GHOSTTY_RENDER_STATE_DATA_COLOR_PALETTE = 9,
162
163 /** The visual style of the cursor (GhosttyRenderStateCursorVisualStyle). */
164 GHOSTTY_RENDER_STATE_DATA_CURSOR_VISUAL_STYLE = 10,
165
166 /** Whether the cursor is visible based on terminal modes (bool). */
167 GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE = 11,
168
169 /** Whether the cursor should blink based on terminal modes (bool). */
170 GHOSTTY_RENDER_STATE_DATA_CURSOR_BLINKING = 12,
171
172 /** Whether the cursor is at a password input field (bool). */
173 GHOSTTY_RENDER_STATE_DATA_CURSOR_PASSWORD_INPUT = 13,
174
175 /** Whether the cursor is visible within the viewport (bool).
176 * If false, the cursor viewport position values are undefined. */
177 GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE = 14,
178
179 /** Cursor viewport x position in cells (uint16_t).
180 * Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */
181 GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X = 15,
182
183 /** Cursor viewport y position in cells (uint16_t).
184 * Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */
185 GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y = 16,
186
187 /** Whether the cursor is on the tail of a wide character (bool).
188 * Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */
189 GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_WIDE_TAIL = 17,
190 GHOSTTY_RENDER_STATE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
191} GhosttyRenderStateData;
192
193/**
194 * Settable options for ghostty_render_state_set().
195 *
196 * @ingroup render
197 */
198typedef enum GHOSTTY_ENUM_TYPED {
199 /** Set dirty state (GhosttyRenderStateDirty). */
200 GHOSTTY_RENDER_STATE_OPTION_DIRTY = 0,
201 GHOSTTY_RENDER_STATE_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
202} GhosttyRenderStateOption;
203
204/**
205 * Queryable data kinds for ghostty_render_state_row_get().
206 *
207 * @ingroup render
208 */
209typedef enum GHOSTTY_ENUM_TYPED {
210 /** Invalid / sentinel value. */
211 GHOSTTY_RENDER_STATE_ROW_DATA_INVALID = 0,
212
213 /** Whether the current row is dirty (bool). */
214 GHOSTTY_RENDER_STATE_ROW_DATA_DIRTY = 1,
215
216 /** The raw row value (GhosttyRow). */
217 GHOSTTY_RENDER_STATE_ROW_DATA_RAW = 2,
218
219 /** Populate a pre-allocated GhosttyRenderStateRowCells with cell data for
220 * the current row (GhosttyRenderStateRowCells). Cell data is only
221 * valid as long as the underlying render state is not updated.
222 * It is unsafe to use cell data after updating the render state. */
223 GHOSTTY_RENDER_STATE_ROW_DATA_CELLS = 3,
224
225 /** Row-local selected cell range (GhosttyRenderStateRowSelection). */
226 GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION = 4,
227 GHOSTTY_RENDER_STATE_ROW_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
228} GhosttyRenderStateRowData;
229
230/**
231 * Settable options for ghostty_render_state_row_set().
232 *
233 * @ingroup render
234 */
235typedef enum GHOSTTY_ENUM_TYPED {
236 /** Set dirty state for the current row (bool). */
237 GHOSTTY_RENDER_STATE_ROW_OPTION_DIRTY = 0,
238 GHOSTTY_RENDER_STATE_ROW_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
239} GhosttyRenderStateRowOption;
240
241/**
242 * Row-local selection range.
243 *
244 * This struct uses the sized-struct ABI pattern. Initialize with
245 * GHOSTTY_INIT_SIZED(GhosttyRenderStateRowSelection) before querying
246 * GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION.
247 *
248 * Querying GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION returns GHOSTTY_NO_VALUE
249 * if the current row does not intersect the current selection.
250 *
251 * @ingroup render
252 */
253typedef struct {
254 /** Size of this struct in bytes. Must be set to sizeof(GhosttyRenderStateRowSelection). */
255 size_t size;
256
257 /** Start column of the row-local selection range, inclusive. */
258 uint16_t start_x;
259
260 /** End column of the row-local selection range, inclusive. */
261 uint16_t end_x;
262} GhosttyRenderStateRowSelection;
263
264/**
265 * Render-state color information.
266 *
267 * This struct uses the sized-struct ABI pattern. Initialize with
268 * GHOSTTY_INIT_SIZED(GhosttyRenderStateColors) before calling
269 * ghostty_render_state_colors_get().
270 *
271 * Example:
272 * @code
273 * GhosttyRenderStateColors colors = GHOSTTY_INIT_SIZED(GhosttyRenderStateColors);
274 * GhosttyResult result = ghostty_render_state_colors_get(state, &colors);
275 * @endcode
276 *
277 * @ingroup render
278 */
279typedef struct {
280 /** Size of this struct in bytes. Must be set to sizeof(GhosttyRenderStateColors). */
281 size_t size;
282
283 /** The default/current background color for the render state. */
284 GhosttyColorRgb background;
285
286 /** The default/current foreground color for the render state. */
287 GhosttyColorRgb foreground;
288
289 /** The cursor color when explicitly set by terminal state. */
290 GhosttyColorRgb cursor;
291
292 /**
293 * True when cursor contains a valid explicit cursor color value.
294 * If this is false, the cursor color should be ignored; it will
295 * contain undefined data.
296 * */
297 bool cursor_has_value;
298
299 /** The active 256-color palette for this render state. */
300 GhosttyColorRgb palette[256];
301} GhosttyRenderStateColors;
302
303/**
304 * Create a new render state instance.
305 *
306 * @param allocator Pointer to allocator, or NULL to use the default allocator
307 * @param state Pointer to store the created render state handle
308 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
309 * failure
310 *
311 * @ingroup render
312 */
313GHOSTTY_API GhosttyResult ghostty_render_state_new(const GhosttyAllocator* allocator,
314 GhosttyRenderState* state);
315
316/**
317 * Free a render state instance.
318 *
319 * Releases all resources associated with the render state. After this call,
320 * the render state handle becomes invalid.
321 *
322 * @param state The render state handle to free (may be NULL)
323 *
324 * @ingroup render
325 */
326GHOSTTY_API void ghostty_render_state_free(GhosttyRenderState state);
327
328/**
329 * Update a render state instance from a terminal.
330 *
331 * This consumes terminal/screen dirty state in the same way as the internal
332 * render state update path.
333 *
334 * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
335 * @param terminal The terminal handle to read from (NULL returns GHOSTTY_INVALID_VALUE)
336 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or
337 * `terminal` is NULL, GHOSTTY_OUT_OF_MEMORY if updating the state requires
338 * allocation and that allocation fails
339 *
340 * @ingroup render
341 */
342GHOSTTY_API GhosttyResult ghostty_render_state_update(GhosttyRenderState state,
343 GhosttyTerminal terminal);
344
345/**
346 * Get a value from a render state.
347 *
348 * The `out` pointer must point to a value of the type corresponding to the
349 * requested data kind (see GhosttyRenderStateData).
350 *
351 * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
352 * @param data The data kind to query
353 * @param[out] out Pointer to receive the queried value
354 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` is
355 * NULL or `data` is not a recognized enum value
356 *
357 * @ingroup render
358 */
359GHOSTTY_API GhosttyResult ghostty_render_state_get(GhosttyRenderState state,
360 GhosttyRenderStateData data,
361 void* out);
362
363/**
364 * Get multiple data fields from a render state in a single call.
365 *
366 * Each element in the keys array specifies a data kind, and the
367 * corresponding element in the values array receives the result.
368 *
369 * Processing stops at the first error; on success out_written
370 * is set to count, on error it is set to the index of the
371 * failing key (i.e. the number of values successfully written).
372 *
373 * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
374 * @param count Number of key/value pairs
375 * @param keys Array of data kinds to query
376 * @param values Array of output pointers (types must match each key's
377 * documented output type)
378 * @param[out] out_written On return, receives the number of values
379 * successfully written (may be NULL)
380 * @return GHOSTTY_SUCCESS if all queries succeed
381 *
382 * @ingroup render
383 */
384GHOSTTY_API GhosttyResult ghostty_render_state_get_multi(
385 GhosttyRenderState state,
386 size_t count,
387 const GhosttyRenderStateData* keys,
388 void** values,
389 size_t* out_written);
390
391/**
392 * Set an option on a render state.
393 *
394 * The `value` pointer must point to a value of the type corresponding to the
395 * requested option kind (see GhosttyRenderStateOption).
396 *
397 * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
398 * @param option The option to set
399 * @param[in] value Pointer to the value to set (NULL returns
400 * GHOSTTY_INVALID_VALUE)
401 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or
402 * `value` is NULL
403 *
404 * @ingroup render
405 */
406GHOSTTY_API GhosttyResult ghostty_render_state_set(GhosttyRenderState state,
407 GhosttyRenderStateOption option,
408 const void* value);
409
410/**
411 * Get the current color information from a render state.
412 *
413 * This writes as many fields as fit in the caller-provided sized struct.
414 * `out_colors->size` must be set by the caller (typically via
415 * GHOSTTY_INIT_SIZED(GhosttyRenderStateColors)).
416 *
417 * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
418 * @param[out] out_colors Sized output struct to receive render-state colors
419 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or
420 * `out_colors` is NULL, or if `out_colors->size` is smaller than
421 * `sizeof(size_t)`
422 *
423 * @ingroup render
424 */
425GHOSTTY_API GhosttyResult ghostty_render_state_colors_get(GhosttyRenderState state,
426 GhosttyRenderStateColors* out_colors);
427
428/**
429 * Create a new row iterator instance.
430 *
431 * All fields except the allocator are left undefined until populated
432 * via ghostty_render_state_get() with
433 * GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR.
434 *
435 * @param allocator Pointer to allocator, or NULL to use the default allocator
436 * @param[out] out_iterator On success, receives the created iterator handle
437 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
438 * failure
439 *
440 * @ingroup render
441 */
442GHOSTTY_API GhosttyResult ghostty_render_state_row_iterator_new(
443 const GhosttyAllocator* allocator,
444 GhosttyRenderStateRowIterator* out_iterator);
445
446/**
447 * Free a render-state row iterator.
448 *
449 * @param iterator The iterator handle to free (may be NULL)
450 *
451 * @ingroup render
452 */
453GHOSTTY_API void ghostty_render_state_row_iterator_free(GhosttyRenderStateRowIterator iterator);
454
455/**
456 * Move a render-state row iterator to the next row.
457 *
458 * Returns true if the iterator moved successfully and row data is
459 * available to read at the new position.
460 *
461 * @param iterator The iterator handle to advance (may be NULL)
462 * @return true if advanced to the next row, false if `iterator` is
463 * NULL or if the iterator has reached the end
464 *
465 * @ingroup render
466 */
467GHOSTTY_API bool ghostty_render_state_row_iterator_next(GhosttyRenderStateRowIterator iterator);
468
469/**
470 * Get a value from the current row in a render-state row iterator.
471 *
472 * The `out` pointer must point to a value of the type corresponding to the
473 * requested data kind (see GhosttyRenderStateRowData).
474 * Call ghostty_render_state_row_iterator_next() at least once before
475 * calling this function.
476 *
477 * @param iterator The iterator handle to query (NULL returns GHOSTTY_INVALID_VALUE)
478 * @param data The data kind to query
479 * @param[out] out Pointer to receive the queried value
480 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if
481 * `iterator` is NULL or the iterator is not positioned on a row
482 *
483 * @ingroup render
484 */
485GHOSTTY_API GhosttyResult ghostty_render_state_row_get(
486 GhosttyRenderStateRowIterator iterator,
487 GhosttyRenderStateRowData data,
488 void* out);
489
490/**
491 * Get multiple data fields from the current row in a single call.
492 *
493 * Each element in the keys array specifies a data kind, and the
494 * corresponding element in the values array receives the result.
495 *
496 * Processing stops at the first error; on success out_written
497 * is set to count, on error it is set to the index of the
498 * failing key (i.e. the number of values successfully written).
499 *
500 * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
501 * @param count Number of key/value pairs
502 * @param keys Array of data kinds to query
503 * @param values Array of output pointers (types must match each key's
504 * documented output type)
505 * @param[out] out_written On return, receives the number of values
506 * successfully written (may be NULL)
507 * @return GHOSTTY_SUCCESS if all queries succeed
508 *
509 * @ingroup render
510 */
511GHOSTTY_API GhosttyResult ghostty_render_state_row_get_multi(
512 GhosttyRenderStateRowIterator iterator,
513 size_t count,
514 const GhosttyRenderStateRowData* keys,
515 void** values,
516 size_t* out_written);
517
518/**
519 * Set an option on the current row in a render-state row iterator.
520 *
521 * The `value` pointer must point to a value of the type corresponding to the
522 * requested option kind (see GhosttyRenderStateRowOption).
523 * Call ghostty_render_state_row_iterator_next() at least once before
524 * calling this function.
525 *
526 * @param iterator The iterator handle to update (NULL returns GHOSTTY_INVALID_VALUE)
527 * @param option The option to set
528 * @param[in] value Pointer to the value to set (NULL returns
529 * GHOSTTY_INVALID_VALUE)
530 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if
531 * `iterator` is NULL or the iterator is not positioned on a row
532 *
533 * @ingroup render
534 */
535GHOSTTY_API GhosttyResult ghostty_render_state_row_set(
536 GhosttyRenderStateRowIterator iterator,
537 GhosttyRenderStateRowOption option,
538 const void* value);
539
540/**
541 * Create a new row cells instance.
542 *
543 * All fields except the allocator are left undefined until populated
544 * via ghostty_render_state_row_get() with
545 * GHOSTTY_RENDER_STATE_ROW_DATA_CELLS.
546 *
547 * You can reuse this value repeatedly with ghostty_render_state_row_get() to
548 * avoid allocating a new cells container for every row.
549 *
550 * @param allocator Pointer to allocator, or NULL to use the default allocator
551 * @param[out] out_cells On success, receives the created row cells handle
552 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
553 * failure
554 *
555 * @ingroup render
556 */
557GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_new(
558 const GhosttyAllocator* allocator,
559 GhosttyRenderStateRowCells* out_cells);
560
561/**
562 * Queryable data kinds for ghostty_render_state_row_cells_get().
563 *
564 * @ingroup render
565 */
566typedef enum GHOSTTY_ENUM_TYPED {
567 /** Invalid / sentinel value. */
568 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_INVALID = 0,
569
570 /** The raw cell value (GhosttyCell). */
571 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_RAW = 1,
572
573 /** The style for the current cell (GhosttyStyle). */
574 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE = 2,
575
576 /** The total number of grapheme codepoints including the base codepoint
577 * (uint32_t). Returns 0 if the cell has no text. */
578 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN = 3,
579
580 /** Write grapheme codepoints into a caller-provided buffer (uint32_t*).
581 * The buffer must be at least graphemes_len elements. The base codepoint
582 * is written first, followed by any extra codepoints. */
583 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF = 4,
584
585 /** The resolved background color of the cell (GhosttyColorRgb).
586 * Flattens the three possible sources: content-tag bg_color_rgb,
587 * content-tag bg_color_palette (looked up in the palette), or the
588 * style's bg_color. Returns GHOSTTY_INVALID_VALUE if the cell has
589 * no background color, in which case the caller should use whatever
590 * default background color it wants (e.g. the terminal background). */
591 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR = 5,
592
593 /** The resolved foreground color of the cell (GhosttyColorRgb).
594 * Resolves palette indices through the palette. Bold color handling
595 * is not applied; the caller should handle bold styling separately.
596 * Returns GHOSTTY_INVALID_VALUE if the cell has no explicit foreground
597 * color, in which case the caller should use whatever default foreground
598 * color it wants (e.g. the terminal foreground). */
599 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR = 6,
600
601 /** Whether the cell is contained within the current selection (bool).
602 * This returns true when the cell's column is within the current row's
603 * row-local selection range, and false otherwise. Rendering policy for
604 * selected cells (colors, inversion, etc.) is left to the caller.
605 *
606 * Renderers that can draw cells in spans may be more efficient querying
607 * GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION once per row and applying that
608 * range directly, avoiding one C API call per cell for selection state. */
609 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_SELECTED = 7,
610
611 /** Whether the cell has any explicit styling (bool).
612 * This is equivalent to querying the raw cell's
613 * GHOSTTY_CELL_DATA_HAS_STYLING value, but avoids materializing the raw
614 * GhosttyCell for renderers that only need to know whether fetching the
615 * full style is necessary. */
616 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_HAS_STYLING = 8,
617
618 /**
619 * Encode the current cell's full grapheme cluster as UTF-8 into a
620 * caller-provided buffer (GhosttyBuffer).
621 *
622 * The base codepoint is encoded first, followed by any extra grapheme
623 * codepoints. Returns GHOSTTY_SUCCESS with len=0 when the cell has no text.
624 *
625 * If ptr is NULL or cap is too small for a non-empty cell, returns
626 * GHOSTTY_OUT_OF_SPACE without writing any bytes and sets len to the required
627 * buffer size in bytes.
628 */
629 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_UTF8 = 9,
630 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
631} GhosttyRenderStateRowCellsData;
632
633/**
634 * Move a render-state row cells iterator to the next cell.
635 *
636 * Returns true if the iterator moved successfully and cell data is
637 * available to read at the new position.
638 *
639 * @param cells The row cells handle to advance (may be NULL)
640 * @return true if advanced to the next cell, false if `cells` is
641 * NULL or if the iterator has reached the end
642 *
643 * @ingroup render
644 */
645GHOSTTY_API bool ghostty_render_state_row_cells_next(GhosttyRenderStateRowCells cells);
646
647/**
648 * Move a render-state row cells iterator to a specific column.
649 *
650 * Positions the iterator at the given x (column) index so that
651 * subsequent reads return data for that cell.
652 *
653 * @param cells The row cells handle to reposition (NULL returns
654 * GHOSTTY_INVALID_VALUE)
655 * @param x The zero-based column index to select
656 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `cells`
657 * is NULL or `x` is out of range
658 *
659 * @ingroup render
660 */
661GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_select(
662 GhosttyRenderStateRowCells cells, uint16_t x);
663
664/**
665 * Get a value from the current cell in a render-state row cells iterator.
666 *
667 * The `out` pointer must point to a value of the type corresponding to the
668 * requested data kind (see GhosttyRenderStateRowCellsData).
669 * Call ghostty_render_state_row_cells_next() or
670 * ghostty_render_state_row_cells_select() at least once before
671 * calling this function.
672 *
673 * @param cells The row cells handle to query (NULL returns GHOSTTY_INVALID_VALUE)
674 * @param data The data kind to query
675 * @param[out] out Pointer to receive the queried value
676 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if
677 * `cells` is NULL or the iterator is not positioned on a cell
678 *
679 * @ingroup render
680 */
681GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_get(
682 GhosttyRenderStateRowCells cells,
683 GhosttyRenderStateRowCellsData data,
684 void* out);
685
686/**
687 * Get multiple data fields from the current cell in a single call.
688 *
689 * Each element in the keys array specifies a data kind, and the
690 * corresponding element in the values array receives the result.
691 *
692 * Processing stops at the first error; on success out_written
693 * is set to count, on error it is set to the index of the
694 * failing key (i.e. the number of values successfully written).
695 *
696 * @param cells The row cells handle (NULL returns GHOSTTY_INVALID_VALUE)
697 * @param count Number of key/value pairs
698 * @param keys Array of data kinds to query
699 * @param values Array of output pointers (types must match each key's
700 * documented output type)
701 * @param[out] out_written On return, receives the number of values
702 * successfully written (may be NULL)
703 * @return GHOSTTY_SUCCESS if all queries succeed
704 *
705 * @ingroup render
706 */
707GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_get_multi(
708 GhosttyRenderStateRowCells cells,
709 size_t count,
710 const GhosttyRenderStateRowCellsData* keys,
711 void** values,
712 size_t* out_written);
713
714/**
715 * Free a row cells instance.
716 *
717 * @param cells The row cells handle to free (may be NULL)
718 *
719 * @ingroup render
720 */
721GHOSTTY_API void ghostty_render_state_row_cells_free(GhosttyRenderStateRowCells cells);
722
723/** @} */
724
725#ifdef __cplusplus
726}
727#endif
728
729#endif /* GHOSTTY_VT_RENDER_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/screen.h+400−0
@@ -0,0 +1,400 @@
1/**
2 * @file screen.h
3 *
4 * Terminal screen cell and row types.
5 */
6
7#ifndef GHOSTTY_VT_SCREEN_H
8#define GHOSTTY_VT_SCREEN_H
9
10#include <stdbool.h>
11#include <stdint.h>
12#include <ghostty/vt/color.h>
13#include <ghostty/vt/types.h>
14
15#ifdef __cplusplus
16extern "C" {
17#endif
18
19/** @defgroup screen Screen
20 *
21 * Terminal screen cell and row types.
22 *
23 * These types represent the contents of a terminal screen. A GhosttyCell
24 * is a single grid cell and a GhosttyRow is a single row. Both are opaque
25 * values whose fields are accessed via ghostty_cell_get() and
26 * ghostty_row_get() respectively.
27 *
28 * @{
29 */
30
31/**
32 * Opaque cell value.
33 *
34 * Represents a single terminal cell. The internal layout is opaque and
35 * must be queried via ghostty_cell_get(). Obtain cell values from
36 * terminal query APIs.
37 *
38 * @ingroup screen
39 */
40typedef uint64_t GhosttyCell;
41
42/**
43 * Opaque row value.
44 *
45 * Represents a single terminal row. The internal layout is opaque and
46 * must be queried via ghostty_row_get(). Obtain row values from
47 * terminal query APIs.
48 *
49 * @ingroup screen
50 */
51typedef uint64_t GhosttyRow;
52
53/**
54 * Cell content tag.
55 *
56 * Describes what kind of content a cell holds.
57 *
58 * @ingroup screen
59 */
60typedef enum GHOSTTY_ENUM_TYPED {
61 /** A single codepoint (may be zero for empty). */
62 GHOSTTY_CELL_CONTENT_CODEPOINT = 0,
63
64 /** A codepoint that is part of a multi-codepoint grapheme cluster. */
65 GHOSTTY_CELL_CONTENT_CODEPOINT_GRAPHEME = 1,
66
67 /** No text; background color from palette. */
68 GHOSTTY_CELL_CONTENT_BG_COLOR_PALETTE = 2,
69
70 /** No text; background color as RGB. */
71 GHOSTTY_CELL_CONTENT_BG_COLOR_RGB = 3,
72 GHOSTTY_CELL_CONTENT_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
73} GhosttyCellContentTag;
74
75/**
76 * Cell wide property.
77 *
78 * Describes the width behavior of a cell.
79 *
80 * @ingroup screen
81 */
82typedef enum GHOSTTY_ENUM_TYPED {
83 /** Not a wide character, cell width 1. */
84 GHOSTTY_CELL_WIDE_NARROW = 0,
85
86 /** Wide character, cell width 2. */
87 GHOSTTY_CELL_WIDE_WIDE = 1,
88
89 /** Spacer after wide character. Do not render. */
90 GHOSTTY_CELL_WIDE_SPACER_TAIL = 2,
91
92 /** Spacer at end of soft-wrapped line for a wide character. */
93 GHOSTTY_CELL_WIDE_SPACER_HEAD = 3,
94 GHOSTTY_CELL_WIDE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
95} GhosttyCellWide;
96
97/**
98 * Semantic content type of a cell.
99 *
100 * Set by semantic prompt sequences (OSC 133) to distinguish between
101 * command output, user input, and shell prompt text.
102 *
103 * @ingroup screen
104 */
105typedef enum GHOSTTY_ENUM_TYPED {
106 /** Regular output content, such as command output. */
107 GHOSTTY_CELL_SEMANTIC_OUTPUT = 0,
108
109 /** Content that is part of user input. */
110 GHOSTTY_CELL_SEMANTIC_INPUT = 1,
111
112 /** Content that is part of a shell prompt. */
113 GHOSTTY_CELL_SEMANTIC_PROMPT = 2,
114 GHOSTTY_CELL_SEMANTIC_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
115} GhosttyCellSemanticContent;
116
117/**
118 * Cell data types.
119 *
120 * These values specify what type of data to extract from a cell
121 * using `ghostty_cell_get`.
122 *
123 * @ingroup screen
124 */
125typedef enum GHOSTTY_ENUM_TYPED {
126 /** Invalid data type. Never results in any data extraction. */
127 GHOSTTY_CELL_DATA_INVALID = 0,
128
129 /**
130 * The codepoint of the cell (0 if empty or bg-color-only).
131 *
132 * Output type: uint32_t *
133 */
134 GHOSTTY_CELL_DATA_CODEPOINT = 1,
135
136 /**
137 * The content tag describing what kind of content is in the cell.
138 *
139 * Output type: GhosttyCellContentTag *
140 */
141 GHOSTTY_CELL_DATA_CONTENT_TAG = 2,
142
143 /**
144 * The wide property of the cell.
145 *
146 * Output type: GhosttyCellWide *
147 */
148 GHOSTTY_CELL_DATA_WIDE = 3,
149
150 /**
151 * Whether the cell has text to render.
152 *
153 * Output type: bool *
154 */
155 GHOSTTY_CELL_DATA_HAS_TEXT = 4,
156
157 /**
158 * Whether the cell has non-default styling.
159 *
160 * Output type: bool *
161 */
162 GHOSTTY_CELL_DATA_HAS_STYLING = 5,
163
164 /**
165 * The style ID for the cell (for use with style lookups).
166 *
167 * Output type: uint16_t *
168 */
169 GHOSTTY_CELL_DATA_STYLE_ID = 6,
170
171 /**
172 * Whether the cell has a hyperlink.
173 *
174 * Output type: bool *
175 */
176 GHOSTTY_CELL_DATA_HAS_HYPERLINK = 7,
177
178 /**
179 * Whether the cell is protected.
180 *
181 * Output type: bool *
182 */
183 GHOSTTY_CELL_DATA_PROTECTED = 8,
184
185 /**
186 * The semantic content type of the cell (from OSC 133).
187 *
188 * Output type: GhosttyCellSemanticContent *
189 */
190 GHOSTTY_CELL_DATA_SEMANTIC_CONTENT = 9,
191
192 /**
193 * The palette index for the cell's background color.
194 * Only valid when content_tag is GHOSTTY_CELL_CONTENT_BG_COLOR_PALETTE.
195 *
196 * Output type: GhosttyColorPaletteIndex *
197 */
198 GHOSTTY_CELL_DATA_COLOR_PALETTE = 10,
199
200 /**
201 * The RGB value for the cell's background color.
202 * Only valid when content_tag is GHOSTTY_CELL_CONTENT_BG_COLOR_RGB.
203 *
204 * Output type: GhosttyColorRgb *
205 */
206 GHOSTTY_CELL_DATA_COLOR_RGB = 11,
207 GHOSTTY_CELL_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
208} GhosttyCellData;
209
210/**
211 * Row semantic prompt state.
212 *
213 * Indicates whether any cells in a row are part of a shell prompt,
214 * as reported by OSC 133 sequences.
215 *
216 * @ingroup screen
217 */
218typedef enum GHOSTTY_ENUM_TYPED {
219 /** No prompt cells in this row. */
220 GHOSTTY_ROW_SEMANTIC_NONE = 0,
221
222 /** Prompt cells exist and this is a primary prompt line. */
223 GHOSTTY_ROW_SEMANTIC_PROMPT = 1,
224
225 /** Prompt cells exist and this is a continuation line. */
226 GHOSTTY_ROW_SEMANTIC_PROMPT_CONTINUATION = 2,
227 GHOSTTY_ROW_SEMANTIC_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
228} GhosttyRowSemanticPrompt;
229
230/**
231 * Row data types.
232 *
233 * These values specify what type of data to extract from a row
234 * using `ghostty_row_get`.
235 *
236 * @ingroup screen
237 */
238typedef enum GHOSTTY_ENUM_TYPED {
239 /** Invalid data type. Never results in any data extraction. */
240 GHOSTTY_ROW_DATA_INVALID = 0,
241
242 /**
243 * Whether this row is soft-wrapped.
244 *
245 * Output type: bool *
246 */
247 GHOSTTY_ROW_DATA_WRAP = 1,
248
249 /**
250 * Whether this row is a continuation of a soft-wrapped row.
251 *
252 * Output type: bool *
253 */
254 GHOSTTY_ROW_DATA_WRAP_CONTINUATION = 2,
255
256 /**
257 * Whether any cells in this row have grapheme clusters.
258 *
259 * Output type: bool *
260 */
261 GHOSTTY_ROW_DATA_GRAPHEME = 3,
262
263 /**
264 * Whether any cells in this row have styling (may have false positives).
265 *
266 * Output type: bool *
267 */
268 GHOSTTY_ROW_DATA_STYLED = 4,
269
270 /**
271 * Whether any cells in this row have hyperlinks (may have false positives).
272 *
273 * Output type: bool *
274 */
275 GHOSTTY_ROW_DATA_HYPERLINK = 5,
276
277 /**
278 * The semantic prompt state of this row.
279 *
280 * Output type: GhosttyRowSemanticPrompt *
281 */
282 GHOSTTY_ROW_DATA_SEMANTIC_PROMPT = 6,
283
284 /**
285 * Whether this row contains a Kitty virtual placeholder.
286 *
287 * Output type: bool *
288 */
289 GHOSTTY_ROW_DATA_KITTY_VIRTUAL_PLACEHOLDER = 7,
290
291 /**
292 * Whether this row is dirty and requires a redraw.
293 *
294 * Output type: bool *
295 */
296 GHOSTTY_ROW_DATA_DIRTY = 8,
297 GHOSTTY_ROW_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
298} GhosttyRowData;
299
300/**
301 * Get data from a cell.
302 *
303 * Extracts typed data from the given cell based on the specified
304 * data type. The output pointer must be of the appropriate type for the
305 * requested data kind. Valid data types and output types are documented
306 * in the `GhosttyCellData` enum.
307 *
308 * @param cell The cell value
309 * @param data The type of data to extract
310 * @param out Pointer to store the extracted data (type depends on data parameter)
311 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
312 * data type is invalid
313 *
314 * @ingroup screen
315 */
316GHOSTTY_API GhosttyResult ghostty_cell_get(GhosttyCell cell,
317 GhosttyCellData data,
318 void *out);
319
320/**
321 * Get multiple data fields from a cell in a single call.
322 *
323 * Each element in the keys array specifies a data kind, and the
324 * corresponding element in the values array receives the result.
325 *
326 * Processing stops at the first error; on success out_written
327 * is set to count, on error it is set to the index of the
328 * failing key (i.e. the number of values successfully written).
329 *
330 * @param cell The cell value
331 * @param count Number of key/value pairs
332 * @param keys Array of data kinds to query
333 * @param values Array of output pointers (types must match each key's
334 * documented output type)
335 * @param[out] out_written On return, receives the number of values
336 * successfully written (may be NULL)
337 * @return GHOSTTY_SUCCESS if all queries succeed
338 *
339 * @ingroup screen
340 */
341GHOSTTY_API GhosttyResult ghostty_cell_get_multi(GhosttyCell cell,
342 size_t count,
343 const GhosttyCellData* keys,
344 void** values,
345 size_t* out_written);
346
347/**
348 * Get data from a row.
349 *
350 * Extracts typed data from the given row based on the specified
351 * data type. The output pointer must be of the appropriate type for the
352 * requested data kind. Valid data types and output types are documented
353 * in the `GhosttyRowData` enum.
354 *
355 * @param row The row value
356 * @param data The type of data to extract
357 * @param out Pointer to store the extracted data (type depends on data parameter)
358 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
359 * data type is invalid
360 *
361 * @ingroup screen
362 */
363GHOSTTY_API GhosttyResult ghostty_row_get(GhosttyRow row,
364 GhosttyRowData data,
365 void *out);
366
367/**
368 * Get multiple data fields from a row in a single call.
369 *
370 * Each element in the keys array specifies a data kind, and the
371 * corresponding element in the values array receives the result.
372 *
373 * Processing stops at the first error; on success out_written
374 * is set to count, on error it is set to the index of the
375 * failing key (i.e. the number of values successfully written).
376 *
377 * @param row The row value
378 * @param count Number of key/value pairs
379 * @param keys Array of data kinds to query
380 * @param values Array of output pointers (types must match each key's
381 * documented output type)
382 * @param[out] out_written On return, receives the number of values
383 * successfully written (may be NULL)
384 * @return GHOSTTY_SUCCESS if all queries succeed
385 *
386 * @ingroup screen
387 */
388GHOSTTY_API GhosttyResult ghostty_row_get_multi(GhosttyRow row,
389 size_t count,
390 const GhosttyRowData* keys,
391 void** values,
392 size_t* out_written);
393
394/** @} */
395
396#ifdef __cplusplus
397}
398#endif
399
400#endif /* GHOSTTY_VT_SCREEN_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/selection.h+1061−0
@@ -0,0 +1,1061 @@
1/**
2 * @file selection.h
3 *
4 * Selection range type for specifying a region of terminal content.
5 */
6
7#ifndef GHOSTTY_VT_SELECTION_H
8#define GHOSTTY_VT_SELECTION_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/allocator.h>
14#include <ghostty/vt/grid_ref.h>
15#include <ghostty/vt/point.h>
16#include <ghostty/vt/types.h>
17
18#ifdef __cplusplus
19extern "C" {
20#endif
21
22/** @defgroup selection Selection
23 *
24 * A snapshot selection range defined by two grid references that identifies
25 * a contiguous or rectangular region of terminal content.
26 *
27 * The start and end values are GhosttyGridRef values. They are therefore
28 * untracked grid references and inherit the same lifetime rules: they are
29 * only safe to use until the next mutating operation on the terminal that
30 * produced them, including freeing the terminal. To keep a selection valid
31 * across terminal mutations, callers must maintain tracked grid references
32 * for the endpoints and reconstruct a GhosttySelection from fresh snapshots
33 * when needed.
34 *
35 * Selection gestures provide a reusable state machine for turning UI pointer
36 * interactions into selection snapshots. A caller creates one
37 * GhosttySelectionGesture per active gesture stream, reuses typed
38 * GhosttySelectionGestureEvent objects for synthetic press, drag, release,
39 * autoscroll tick, and deep-press events, and applies each event with
40 * ghostty_selection_gesture_event(). The returned GhosttySelection is a
41 * snapshot; the embedder decides whether to render it, format/copy it, or
42 * install it as the terminal's active selection.
43 *
44 * ## Examples
45 *
46 * @snippet c-vt-selection/src/main.c selection-main
47 * @snippet c-vt-selection-gesture/src/main.c selection-gesture-main
48 *
49 * @{
50 */
51
52/**
53 * Opaque handle to state for interpreting terminal selection gestures.
54 *
55 * The gesture owns only the state required to interpret pointer events. Calls
56 * that use a gesture are not concurrency-safe and must be serialized with
57 * terminal mutations.
58 *
59 * @ingroup selection
60 */
61typedef struct GhosttySelectionGestureImpl* GhosttySelectionGesture;
62
63/**
64 * Opaque handle to reusable input data for selection gesture operations.
65 *
66 * Event options are set with ghostty_selection_gesture_event_set(). Individual
67 * gesture operations document which options are required or optional.
68 *
69 * @ingroup selection
70 */
71typedef struct GhosttySelectionGestureEventImpl* GhosttySelectionGestureEvent;
72
73/**
74 * A snapshot selection range defined by two grid references.
75 *
76 * Both endpoints are inclusive. The endpoints preserve selection direction
77 * and may be reversed; callers must not assume that start is the top-left
78 * endpoint or that end is the bottom-right endpoint.
79 *
80 * When rectangle is false, the endpoints describe a linear selection. When
81 * rectangle is true, the same endpoints are interpreted as opposite corners
82 * of a rectangular/block selection.
83 *
84 * The start and end values are untracked GhosttyGridRef snapshots and are
85 * only valid until the next mutating operation on the terminal that produced
86 * them unless the selection is reconstructed from tracked references.
87 *
88 * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
89 *
90 * @ingroup selection
91 */
92typedef struct {
93 /** Size of this struct in bytes. Must be set to sizeof(GhosttySelection). */
94 size_t size;
95
96 /**
97 * Start of the selection range (inclusive).
98 *
99 * This may be after end in terminal order. It is an untracked
100 * GhosttyGridRef snapshot and follows untracked grid-ref lifetime rules.
101 */
102 GhosttyGridRef start;
103
104 /**
105 * End of the selection range (inclusive).
106 *
107 * This may be before start in terminal order. It is an untracked
108 * GhosttyGridRef snapshot and follows untracked grid-ref lifetime rules.
109 */
110 GhosttyGridRef end;
111
112 /**
113 * Whether the endpoints are interpreted as a rectangular/block selection
114 * rather than a linear selection.
115 */
116 bool rectangle;
117} GhosttySelection;
118
119/**
120 * Options for deriving a word selection from a terminal grid reference.
121 *
122 * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
123 * If boundary_codepoints is NULL and boundary_codepoints_len is 0, Ghostty's
124 * default word-boundary codepoints are used. If boundary_codepoints_len is
125 * non-zero, boundary_codepoints must not be NULL.
126 *
127 * @ingroup selection
128 */
129typedef struct {
130 /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectWordOptions). */
131 size_t size;
132
133 /** Grid reference under which to derive the word selection. */
134 GhosttyGridRef ref;
135
136 /** Optional word-boundary codepoints as uint32_t scalar values. */
137 const uint32_t* boundary_codepoints;
138
139 /** Number of entries in boundary_codepoints. */
140 size_t boundary_codepoints_len;
141} GhosttyTerminalSelectWordOptions;
142
143/**
144 * Options for deriving the nearest word selection between two grid references.
145 *
146 * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
147 * If boundary_codepoints is NULL and boundary_codepoints_len is 0, Ghostty's
148 * default word-boundary codepoints are used. If boundary_codepoints_len is
149 * non-zero, boundary_codepoints must not be NULL.
150 *
151 * @ingroup selection
152 */
153typedef struct {
154 /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectWordBetweenOptions). */
155 size_t size;
156
157 /** Starting grid reference for the inclusive search range. */
158 GhosttyGridRef start;
159
160 /** Ending grid reference for the inclusive search range. */
161 GhosttyGridRef end;
162
163 /** Optional word-boundary codepoints as uint32_t scalar values. */
164 const uint32_t* boundary_codepoints;
165
166 /** Number of entries in boundary_codepoints. */
167 size_t boundary_codepoints_len;
168} GhosttyTerminalSelectWordBetweenOptions;
169
170/**
171 * Options for deriving a line selection from a terminal grid reference.
172 *
173 * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
174 * If whitespace is NULL and whitespace_len is 0, Ghostty's default line-trim
175 * whitespace codepoints are used. If whitespace_len is non-zero, whitespace
176 * must not be NULL.
177 *
178 * @ingroup selection
179 */
180typedef struct {
181 /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectLineOptions). */
182 size_t size;
183
184 /** Grid reference under which to derive the line selection. */
185 GhosttyGridRef ref;
186
187 /** Optional codepoints to trim from the start and end of the line. */
188 const uint32_t* whitespace;
189
190 /** Number of entries in whitespace. */
191 size_t whitespace_len;
192
193 /** Whether semantic prompt state changes should bound the line selection. */
194 bool semantic_prompt_boundary;
195} GhosttyTerminalSelectLineOptions;
196
197/**
198 * Options for one-shot formatting of a terminal selection.
199 *
200 * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
201 *
202 * If selection is NULL, the terminal's current active selection is used.
203 * If selection is non-NULL, that caller-provided snapshot selection is used.
204 *
205 * The selection is formatted from the terminal's active screen using the same
206 * formatting semantics as GhosttyFormatter. For copy/clipboard behavior
207 * matching Ghostty's Screen.selectionString(), use plain output with unwrap
208 * and trim both set to true.
209 *
210 * @ingroup selection
211 */
212typedef struct {
213 /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectionFormatOptions). */
214 size_t size;
215
216 /** Output format to emit. */
217 GhosttyFormatterFormat emit;
218
219 /** Whether to unwrap soft-wrapped lines. */
220 bool unwrap;
221
222 /** Whether to trim trailing whitespace on non-blank lines. */
223 bool trim;
224
225 /**
226 * Optional selection to format.
227 *
228 * If NULL, the terminal's current active selection is used. If the terminal
229 * has no active selection, formatting returns GHOSTTY_NO_VALUE.
230 *
231 * If non-NULL, the pointed-to selection must be a valid snapshot selection
232 * for this terminal and must obey GhosttySelection lifetime rules.
233 */
234 const GhosttySelection *selection;
235} GhosttyTerminalSelectionFormatOptions;
236
237/**
238 * Ordering of a selection's endpoints in terminal coordinates.
239 *
240 * Mirrored orders are only produced by rectangular selections whose start
241 * and end endpoints are on opposite diagonal corners that are not simple
242 * top-left-to-bottom-right or bottom-right-to-top-left orderings.
243 *
244 * @ingroup selection
245 */
246typedef enum GHOSTTY_ENUM_TYPED {
247 /** Start is before end in top-left to bottom-right order. */
248 GHOSTTY_SELECTION_ORDER_FORWARD = 0,
249
250 /** End is before start in top-left to bottom-right order. */
251 GHOSTTY_SELECTION_ORDER_REVERSE = 1,
252
253 /** Rectangular selection from top-right to bottom-left. */
254 GHOSTTY_SELECTION_ORDER_MIRRORED_FORWARD = 2,
255
256 /** Rectangular selection from bottom-left to top-right. */
257 GHOSTTY_SELECTION_ORDER_MIRRORED_REVERSE = 3,
258
259 GHOSTTY_SELECTION_ORDER_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
260} GhosttySelectionOrder;
261
262/**
263 * Operation used to adjust a selection endpoint.
264 *
265 * Adjustment mutates the selection's logical end endpoint, not whichever
266 * endpoint is visually bottom/right. This preserves keyboard and drag
267 * behavior for both forward and reversed selections.
268 *
269 * @ingroup selection
270 */
271typedef enum GHOSTTY_ENUM_TYPED {
272 /** Move left to the previous non-empty cell, wrapping upward. */
273 GHOSTTY_SELECTION_ADJUST_LEFT = 0,
274
275 /** Move right to the next non-empty cell, wrapping downward. */
276 GHOSTTY_SELECTION_ADJUST_RIGHT = 1,
277
278 /**
279 * Move up one row at the current column, or to the beginning of the
280 * line if already at the top.
281 */
282 GHOSTTY_SELECTION_ADJUST_UP = 2,
283
284 /**
285 * Move down to the next non-blank row at the current column, or to the
286 * end of the line if none exists.
287 */
288 GHOSTTY_SELECTION_ADJUST_DOWN = 3,
289
290 /** Move to the top-left cell of the screen. */
291 GHOSTTY_SELECTION_ADJUST_HOME = 4,
292
293 /** Move to the right edge of the last non-blank row on the screen. */
294 GHOSTTY_SELECTION_ADJUST_END = 5,
295
296 /**
297 * Move up by one terminal page height, or to home if that would move
298 * past the top.
299 */
300 GHOSTTY_SELECTION_ADJUST_PAGE_UP = 6,
301
302 /**
303 * Move down by one terminal page height, or to end if that would move
304 * past the bottom.
305 */
306 GHOSTTY_SELECTION_ADJUST_PAGE_DOWN = 7,
307
308 /** Move to the left edge of the current line. */
309 GHOSTTY_SELECTION_ADJUST_BEGINNING_OF_LINE = 8,
310
311 /** Move to the right edge of the current line. */
312 GHOSTTY_SELECTION_ADJUST_END_OF_LINE = 9,
313
314 GHOSTTY_SELECTION_ADJUST_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
315} GhosttySelectionAdjust;
316
317/**
318 * Selection behavior chosen for a gesture's click sequence.
319 *
320 * @ingroup selection
321 */
322typedef enum GHOSTTY_ENUM_TYPED {
323 /** Cell-granular drag selection. */
324 GHOSTTY_SELECTION_GESTURE_BEHAVIOR_CELL = 0,
325
326 /** Word selection on press and word-granular drag selection. */
327 GHOSTTY_SELECTION_GESTURE_BEHAVIOR_WORD = 1,
328
329 /** Line selection on press and line-granular drag selection. */
330 GHOSTTY_SELECTION_GESTURE_BEHAVIOR_LINE = 2,
331
332 /** Semantic command output selection on press and drag. */
333 GHOSTTY_SELECTION_GESTURE_BEHAVIOR_OUTPUT = 3,
334
335 GHOSTTY_SELECTION_GESTURE_BEHAVIOR_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
336} GhosttySelectionGestureBehavior;
337
338/**
339 * Selection behaviors for single-, double-, and triple-click gestures.
340 *
341 * @ingroup selection
342 */
343typedef struct {
344 /** Behavior for single-click selection gestures. */
345 GhosttySelectionGestureBehavior single_click;
346
347 /** Behavior for double-click selection gestures. */
348 GhosttySelectionGestureBehavior double_click;
349
350 /** Behavior for triple-click selection gestures. */
351 GhosttySelectionGestureBehavior triple_click;
352} GhosttySelectionGestureBehaviors;
353
354/**
355 * Display geometry used to interpret selection gesture drag events.
356 *
357 * @ingroup selection
358 */
359typedef struct {
360 /** Number of columns in the rendered terminal grid. Must be non-zero. */
361 uint32_t columns;
362
363 /** Width of one terminal cell in surface pixels. Must be non-zero. */
364 uint32_t cell_width;
365
366 /** Left padding before the terminal grid begins in surface pixels. */
367 uint32_t padding_left;
368
369 /** Height of the rendered terminal surface in surface pixels. Must be non-zero. */
370 uint32_t screen_height;
371} GhosttySelectionGestureGeometry;
372
373/**
374 * Current autoscroll direction for an active selection drag gesture.
375 *
376 * @ingroup selection
377 */
378typedef enum GHOSTTY_ENUM_TYPED {
379 /** No selection autoscroll is requested. */
380 GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_NONE = 0,
381
382 /** Selection dragging should autoscroll the viewport upward. */
383 GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_UP = 1,
384
385 /** Selection dragging should autoscroll the viewport downward. */
386 GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_DOWN = 2,
387
388 GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
389} GhosttySelectionGestureAutoscroll;
390
391/**
392 * Data fields readable from a selection gesture with
393 * ghostty_selection_gesture_get().
394 *
395 * @ingroup selection
396 */
397typedef enum GHOSTTY_ENUM_TYPED {
398 /** Current click count: uint8_t*. 0 means inactive. */
399 GHOSTTY_SELECTION_GESTURE_DATA_CLICK_COUNT = 0,
400
401 /** Whether the current/last left-click gesture has dragged: bool*. */
402 GHOSTTY_SELECTION_GESTURE_DATA_DRAGGED = 1,
403
404 /** Current autoscroll request: GhosttySelectionGestureAutoscroll*. */
405 GHOSTTY_SELECTION_GESTURE_DATA_AUTOSCROLL = 2,
406
407 /** Current gesture behavior: GhosttySelectionGestureBehavior*. */
408 GHOSTTY_SELECTION_GESTURE_DATA_BEHAVIOR = 3,
409
410 /**
411 * Current left-click anchor: GhosttyGridRef*.
412 *
413 * Returns GHOSTTY_NO_VALUE if there is no valid active anchor. On success,
414 * writes an untracked GhosttyGridRef snapshot with normal GhosttyGridRef
415 * lifetime rules.
416 */
417 GHOSTTY_SELECTION_GESTURE_DATA_ANCHOR = 4,
418
419 GHOSTTY_SELECTION_GESTURE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
420} GhosttySelectionGestureData;
421
422/**
423 * Selection gesture event type.
424 *
425 * The event type is fixed when the event is created. Each event type documents
426 * which options are valid and which options are required by gesture operations.
427 *
428 * @ingroup selection
429 */
430typedef enum GHOSTTY_ENUM_TYPED {
431 /** Press event for ghostty_selection_gesture_event(). */
432 GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_PRESS = 0,
433
434 /** Release event for ghostty_selection_gesture_event(). */
435 GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_RELEASE = 1,
436
437 /** Drag event for ghostty_selection_gesture_event(). */
438 GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DRAG = 2,
439
440 /** Autoscroll tick event for ghostty_selection_gesture_event(). */
441 GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_AUTOSCROLL_TICK = 3,
442
443 /** Deep press event for ghostty_selection_gesture_event(). */
444 GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DEEP_PRESS = 4,
445
446 GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
447} GhosttySelectionGestureEventType;
448
449/**
450 * Options stored on a reusable selection gesture event.
451 *
452 * Passing NULL as the value to ghostty_selection_gesture_event_set() clears the
453 * corresponding option.
454 *
455 * @ingroup selection
456 */
457typedef enum GHOSTTY_ENUM_TYPED {
458 /**
459 * Grid reference under the pointer: GhosttyGridRef*.
460 *
461 * Required for PRESS and DRAG events. Optional for RELEASE events; when unset
462 * or cleared, release records that the pointer did not map to a valid cell.
463 */
464 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF = 0,
465
466 /**
467 * Surface-space pointer position: GhosttySurfacePosition*.
468 *
469 * Valid for PRESS, DRAG, and AUTOSCROLL_TICK.
470 */
471 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_POSITION = 1,
472
473 /** Maximum repeat-click distance in pixels: double*. */
474 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REPEAT_DISTANCE = 2,
475
476 /**
477 * Optional monotonic event time in nanoseconds: uint64_t*.
478 *
479 * If unset, press treats the event as untimed and only single-click behavior
480 * is available.
481 */
482 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_TIME_NS = 3,
483
484 /** Maximum interval between repeat clicks in nanoseconds: uint64_t*. */
485 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REPEAT_INTERVAL_NS = 4,
486
487 /**
488 * Word-boundary codepoints: GhosttyCodepoints*.
489 *
490 * The codepoints are copied into event-owned storage when set. If unset,
491 * operations that need word boundaries use Ghostty's defaults.
492 *
493 * Valid for PRESS, DRAG, AUTOSCROLL_TICK, and DEEP_PRESS.
494 */
495 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_WORD_BOUNDARY_CODEPOINTS = 5,
496
497 /**
498 * Selection behavior table: GhosttySelectionGestureBehaviors*.
499 *
500 * If unset, press uses the default behavior table: cell, word, line.
501 */
502 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_BEHAVIORS = 6,
503
504 /** Whether a drag or autoscroll tick should produce a rectangular selection: bool*. */
505 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_RECTANGLE = 7,
506
507 /** Drag display geometry: GhosttySelectionGestureGeometry*. Required for DRAG and AUTOSCROLL_TICK. */
508 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_GEOMETRY = 8,
509
510 /** Viewport coordinate for an autoscroll tick: GhosttyPointCoordinate*. Required for AUTOSCROLL_TICK. */
511 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_VIEWPORT = 9,
512
513 GHOSTTY_SELECTION_GESTURE_EVENT_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
514} GhosttySelectionGestureEventOption;
515
516/**
517 * Create a reusable selection gesture event object.
518 *
519 * @param allocator Allocator, or NULL for the default allocator
520 * @param out_event Receives the created event handle
521 * @param type Event type. This is fixed for the lifetime of the event.
522 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if out_event is
523 * NULL or type is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation fails
524 *
525 * @ingroup selection
526 */
527GHOSTTY_API GhosttyResult ghostty_selection_gesture_event_new(
528 const GhosttyAllocator* allocator,
529 GhosttySelectionGestureEvent* out_event,
530 GhosttySelectionGestureEventType type);
531
532/**
533 * Free a selection gesture event object.
534 *
535 * Passing NULL is allowed and is a no-op.
536 *
537 * @param event Selection gesture event handle to free
538 *
539 * @ingroup selection
540 */
541GHOSTTY_API void ghostty_selection_gesture_event_free(
542 GhosttySelectionGestureEvent event);
543
544/**
545 * Set or clear an option on a selection gesture event.
546 *
547 * The value type depends on option and is documented by
548 * GhosttySelectionGestureEventOption. Passing NULL for value clears the option.
549 *
550 * @param event Selection gesture event handle (NULL returns GHOSTTY_INVALID_VALUE)
551 * @param option Event option to set or clear
552 * @param value Pointer to the input value for option, or NULL to clear
553 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY if copying
554 * event-owned data fails, or GHOSTTY_INVALID_VALUE if event, option, or
555 * value is invalid
556 *
557 * @ingroup selection
558 */
559GHOSTTY_API GhosttyResult ghostty_selection_gesture_event_set(
560 GhosttySelectionGestureEvent event,
561 GhosttySelectionGestureEventOption option,
562 const void* value);
563
564/**
565 * Apply a selection gesture event and return the resulting selection snapshot.
566 *
567 * This dispatches to the gesture operation matching the event's fixed type.
568 * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_PRESS, the event must have
569 * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF set before calling this function.
570 * All other press options use their initialized defaults when unset or cleared.
571 *
572 * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_RELEASE, only
573 * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF is valid. It is optional; if unset or
574 * cleared, release records that the pointer did not map to a valid cell. Release
575 * events update gesture state but do not produce a selection, so this function
576 * returns GHOSTTY_NO_VALUE after applying them.
577 *
578 * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DRAG,
579 * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF and
580 * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_GEOMETRY are required. Position,
581 * rectangle, and word-boundary codepoints are optional and use initialized
582 * defaults when unset or cleared.
583 *
584 * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_AUTOSCROLL_TICK,
585 * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_VIEWPORT and
586 * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_GEOMETRY are required. Position,
587 * rectangle, and word-boundary codepoints are optional and use initialized
588 * defaults when unset or cleared.
589 *
590 * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DEEP_PRESS, only
591 * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_WORD_BOUNDARY_CODEPOINTS is valid. It is
592 * optional and uses initialized defaults when unset or cleared.
593 *
594 * The returned selection is not installed as the terminal's current selection.
595 * It is a snapshot with the same lifetime rules as GhosttySelection.
596 *
597 * @param gesture Selection gesture handle (NULL returns GHOSTTY_INVALID_VALUE)
598 * @param terminal Terminal used to interpret and update gesture state
599 * @param event Selection gesture event handle (NULL returns GHOSTTY_INVALID_VALUE)
600 * @param[out] out_selection On success, receives the resulting selection. May
601 * be NULL to apply the event and discard the selection result.
602 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the event does not
603 * currently produce a selection, GHOSTTY_OUT_OF_MEMORY if tracking
604 * gesture state fails, or GHOSTTY_INVALID_VALUE if gesture, terminal,
605 * event, or required event data is invalid
606 *
607 * @ingroup selection
608 */
609GHOSTTY_API GhosttyResult ghostty_selection_gesture_event(
610 GhosttySelectionGesture gesture,
611 GhosttyTerminal terminal,
612 GhosttySelectionGestureEvent event,
613 GhosttySelection* out_selection);
614
615/**
616 * Create a selection gesture object.
617 *
618 * The gesture stores mutable state for terminal text selection gestures. The
619 * gesture is not bound to a terminal at creation time; terminal-dependent APIs
620 * take the terminal explicitly.
621 *
622 * @param allocator Allocator, or NULL for the default allocator
623 * @param out_gesture Receives the created gesture handle
624 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if out_gesture is
625 * NULL, or GHOSTTY_OUT_OF_MEMORY if allocation fails
626 *
627 * @ingroup selection
628 */
629GHOSTTY_API GhosttyResult ghostty_selection_gesture_new(
630 const GhosttyAllocator* allocator,
631 GhosttySelectionGesture* out_gesture);
632
633/**
634 * Free a selection gesture object.
635 *
636 * This releases any tracked terminal references owned by the gesture using the
637 * provided terminal, then frees the gesture object. Passing NULL for gesture is
638 * allowed and is a no-op.
639 *
640 * If the terminal is still alive, pass the terminal most recently used with the
641 * gesture so any tracked terminal references can be released correctly. If the
642 * terminal has already been freed, pass NULL for terminal; the terminal's page
643 * storage has already released the underlying tracked references, so the
644 * gesture wrapper can be safely discarded without touching the stale terminal
645 * state.
646 *
647 * @param gesture Selection gesture handle to free
648 * @param terminal Terminal used to release tracked gesture state, or NULL if
649 * the terminal has already been freed
650 *
651 * @ingroup selection
652 */
653GHOSTTY_API void ghostty_selection_gesture_free(
654 GhosttySelectionGesture gesture,
655 GhosttyTerminal terminal);
656
657/**
658 * Reset any active selection gesture state.
659 *
660 * This cancels the active click sequence and releases any tracked terminal
661 * references owned by the gesture without freeing the gesture object.
662 * Passing NULL is allowed and is a no-op.
663 *
664 * @param gesture Selection gesture handle to reset
665 * @param terminal Terminal used to release tracked gesture state
666 *
667 * @ingroup selection
668 */
669GHOSTTY_API void ghostty_selection_gesture_reset(
670 GhosttySelectionGesture gesture,
671 GhosttyTerminal terminal);
672
673/**
674 * Read data from a selection gesture.
675 *
676 * The type of value depends on data and is documented by
677 * GhosttySelectionGestureData. For GHOSTTY_SELECTION_GESTURE_DATA_ANCHOR,
678 * the returned GhosttyGridRef is an untracked snapshot with normal grid-ref
679 * lifetime rules.
680 *
681 * @param gesture Selection gesture handle (NULL returns GHOSTTY_INVALID_VALUE)
682 * @param terminal Terminal used to validate terminal-backed gesture state
683 * @param data Data field to read
684 * @param value Output pointer whose type depends on data
685 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the requested data
686 * has no value, or GHOSTTY_INVALID_VALUE if gesture, terminal, data, or
687 * value is invalid
688 *
689 * @ingroup selection
690 */
691GHOSTTY_API GhosttyResult ghostty_selection_gesture_get(
692 GhosttySelectionGesture gesture,
693 GhosttyTerminal terminal,
694 GhosttySelectionGestureData data,
695 void* value);
696
697/**
698 * Read multiple data fields from a selection gesture in a single call.
699 *
700 * This is an optimization over calling ghostty_selection_gesture_get() multiple
701 * times. Each entry in values must point to storage of the type documented by
702 * the corresponding GhosttySelectionGestureData key.
703 *
704 * If any individual read fails, the function returns that error and writes the
705 * index of the failing key to out_written when out_written is non-NULL. On
706 * success, out_written receives count when non-NULL.
707 *
708 * @param gesture Selection gesture handle (NULL returns GHOSTTY_INVALID_VALUE)
709 * @param terminal Terminal used to validate terminal-backed gesture state
710 * @param count Number of data fields to read
711 * @param keys Data fields to read (must not be NULL)
712 * @param values Output pointers corresponding to keys (must not be NULL)
713 * @param out_written Optional number of fields read, or failing index on error
714 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if a requested data
715 * field has no value, or GHOSTTY_INVALID_VALUE if gesture, terminal,
716 * keys, values, or a value pointer is invalid
717 *
718 * @ingroup selection
719 */
720GHOSTTY_API GhosttyResult ghostty_selection_gesture_get_multi(
721 GhosttySelectionGesture gesture,
722 GhosttyTerminal terminal,
723 size_t count,
724 const GhosttySelectionGestureData* keys,
725 void** values,
726 size_t* out_written);
727
728/**
729 * Derive a word selection snapshot from a terminal grid reference.
730 *
731 * The returned selection is not installed as the terminal's current
732 * selection. It is a snapshot with the same lifetime rules as GhosttySelection.
733 *
734 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
735 * @param options Word-selection options
736 * @param[out] out_selection On success, receives the derived selection
737 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the valid ref has
738 * no selectable word content, or GHOSTTY_INVALID_VALUE if the
739 * terminal, options, ref, codepoint pointer, or output pointer are
740 * invalid.
741 *
742 * @ingroup selection
743 */
744GHOSTTY_API GhosttyResult ghostty_terminal_select_word(
745 GhosttyTerminal terminal,
746 const GhosttyTerminalSelectWordOptions* options,
747 GhosttySelection* out_selection);
748
749/**
750 * Derive the nearest word selection snapshot between two terminal grid refs.
751 *
752 * Starting at options->start, this searches toward options->end (inclusive)
753 * and returns the first selectable word found using Ghostty's word-selection
754 * rules.
755 *
756 * This is useful for implementing double-click-and-drag selection in a UI. If
757 * a user double-clicks one word and drags across spaces or punctuation toward
758 * another word, selecting only the word directly under the current pointer can
759 * flicker or collapse when the pointer is between words. Instead, ask for the
760 * nearest word between the original click and the drag point, ask again in the
761 * reverse direction, and combine the two word bounds into the drag selection.
762 *
763 * @snippet c-vt-selection/src/main.c selection-word-between
764 *
765 * The returned selection is not installed as the terminal's current
766 * selection. It is a snapshot with the same lifetime rules as GhosttySelection.
767 *
768 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
769 * @param options Word-between-selection options
770 * @param[out] out_selection On success, receives the derived selection
771 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if there is no
772 * selectable word content between the valid refs, or
773 * GHOSTTY_INVALID_VALUE if the terminal, options, refs, codepoint
774 * pointer, or output pointer are invalid.
775 *
776 * @ingroup selection
777 */
778GHOSTTY_API GhosttyResult ghostty_terminal_select_word_between(
779 GhosttyTerminal terminal,
780 const GhosttyTerminalSelectWordBetweenOptions* options,
781 GhosttySelection* out_selection);
782
783/**
784 * Derive a line selection snapshot from a terminal grid reference.
785 *
786 * The returned selection is not installed as the terminal's current
787 * selection. It is a snapshot with the same lifetime rules as GhosttySelection.
788 *
789 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
790 * @param options Line-selection options
791 * @param[out] out_selection On success, receives the derived selection
792 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the valid ref has
793 * no selectable line content, or GHOSTTY_INVALID_VALUE if the
794 * terminal, options, ref, codepoint pointer, or output pointer are
795 * invalid.
796 *
797 * @ingroup selection
798 */
799GHOSTTY_API GhosttyResult ghostty_terminal_select_line(
800 GhosttyTerminal terminal,
801 const GhosttyTerminalSelectLineOptions* options,
802 GhosttySelection* out_selection);
803
804/**
805 * Derive a selection snapshot covering all selectable terminal content.
806 *
807 * The returned selection is not installed as the terminal's current
808 * selection. It is a snapshot with the same lifetime rules as GhosttySelection.
809 *
810 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
811 * @param[out] out_selection On success, receives the derived selection
812 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if there is no
813 * selectable content, or GHOSTTY_INVALID_VALUE if the terminal or
814 * output pointer is invalid.
815 *
816 * @ingroup selection
817 */
818GHOSTTY_API GhosttyResult ghostty_terminal_select_all(
819 GhosttyTerminal terminal,
820 GhosttySelection* out_selection);
821
822/**
823 * Derive a command-output selection snapshot from a terminal grid reference.
824 *
825 * The returned selection is not installed as the terminal's current
826 * selection. It is a snapshot with the same lifetime rules as GhosttySelection.
827 *
828 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
829 * @param ref Grid reference within command output to select
830 * @param[out] out_selection On success, receives the derived selection
831 * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the valid ref is
832 * not selectable command output, or GHOSTTY_INVALID_VALUE if the
833 * terminal, ref, or output pointer is invalid.
834 *
835 * @ingroup selection
836 */
837GHOSTTY_API GhosttyResult ghostty_terminal_select_output(
838 GhosttyTerminal terminal,
839 GhosttyGridRef ref,
840 GhosttySelection* out_selection);
841
842/**
843 * Format a terminal selection into a caller-provided buffer.
844 *
845 * This is a one-shot convenience API for formatting either the terminal's
846 * active selection or a caller-provided GhosttySelection without explicitly
847 * creating a GhosttyFormatter.
848 *
849 * Pass NULL for buf to query the required output size. In that case,
850 * out_written receives the required size and the function returns
851 * GHOSTTY_OUT_OF_SPACE.
852 *
853 * If buf is too small, the function returns GHOSTTY_OUT_OF_SPACE and writes
854 * the required size to out_written. The caller can then retry with a larger
855 * buffer.
856 *
857 * If options.selection is NULL and the terminal has no active selection, the
858 * function returns GHOSTTY_NO_VALUE.
859 *
860 * @param terminal The terminal to read from (must not be NULL)
861 * @param options Selection formatting options
862 * @param buf Output buffer, or NULL to query required size
863 * @param buf_len Length of buf in bytes
864 * @param out_written Number of bytes written, or required size on
865 * GHOSTTY_OUT_OF_SPACE (must not be NULL)
866 * @return GHOSTTY_SUCCESS on success, or an error code on failure
867 *
868 * @ingroup selection
869 */
870GHOSTTY_API GhosttyResult ghostty_terminal_selection_format_buf(
871 GhosttyTerminal terminal,
872 GhosttyTerminalSelectionFormatOptions options,
873 uint8_t* buf,
874 size_t buf_len,
875 size_t* out_written);
876
877/**
878 * Format a terminal selection into an allocated buffer.
879 *
880 * This is a one-shot convenience API for formatting either the terminal's
881 * active selection or a caller-provided GhosttySelection without explicitly
882 * creating a GhosttyFormatter.
883 *
884 * The returned buffer is allocated using allocator, or the default allocator
885 * if NULL is passed. The caller owns the returned buffer and must free it with
886 * ghostty_free(), passing the same allocator and returned length.
887 *
888 * The returned bytes are not NUL-terminated. This supports plain text, VT, and
889 * HTML uniformly as byte output.
890 *
891 * If options.selection is NULL and the terminal has no active selection, the
892 * function returns GHOSTTY_NO_VALUE and leaves out_ptr as NULL and out_len as 0.
893 *
894 * @param terminal The terminal to read from (must not be NULL)
895 * @param allocator Allocator used for the returned buffer, or NULL for the default allocator
896 * @param options Selection formatting options
897 * @param out_ptr Receives the allocated output buffer (must not be NULL)
898 * @param out_len Receives the output length in bytes (must not be NULL)
899 * @return GHOSTTY_SUCCESS on success, or an error code on failure
900 *
901 * @ingroup selection
902 */
903GHOSTTY_API GhosttyResult ghostty_terminal_selection_format_alloc(
904 GhosttyTerminal terminal,
905 const GhosttyAllocator* allocator,
906 GhosttyTerminalSelectionFormatOptions options,
907 uint8_t** out_ptr,
908 size_t* out_len);
909
910/**
911 * Adjust a selection snapshot using terminal selection semantics.
912 *
913 * This mutates the caller-provided GhosttySelection in place. The logical end
914 * endpoint is always moved, regardless of whether the selection is forward or
915 * reversed visually. The input selection remains a snapshot: after adjustment,
916 * call ghostty_terminal_set() with GHOSTTY_TERMINAL_OPT_SELECTION to install it
917 * as the terminal-owned selection if desired.
918 *
919 * The selection's start and end grid refs must both be valid untracked
920 * snapshots for the given terminal's currently active screen. In practice,
921 * they must come from that terminal and screen, and no mutating terminal call
922 * may have occurred since the refs were produced or reconstructed from
923 * tracked refs. Passing refs from another terminal, another screen, or stale
924 * refs violates this precondition.
925 *
926 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
927 * @param selection Selection snapshot to adjust in place
928 * @param adjustment The adjustment operation to apply
929 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal,
930 * selection, or adjustment are invalid. Selection reference validity
931 * is a precondition and is not checked.
932 *
933 * @ingroup selection
934 */
935GHOSTTY_API GhosttyResult ghostty_terminal_selection_adjust(
936 GhosttyTerminal terminal,
937 GhosttySelection* selection,
938 GhosttySelectionAdjust adjustment);
939
940/**
941 * Get the current endpoint ordering of a selection snapshot.
942 *
943 * The selection's start and end grid refs must both be valid untracked
944 * snapshots for the given terminal's currently active screen. In practice,
945 * they must come from that terminal and screen, and no mutating terminal call
946 * may have occurred since the refs were produced or reconstructed from
947 * tracked refs. Passing refs from another terminal, another screen, or stale
948 * refs violates this precondition.
949 *
950 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
951 * @param selection Selection snapshot to inspect
952 * @param[out] out_order On success, receives the selection order
953 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal,
954 * selection, or output pointer are invalid. Selection reference
955 * validity is a precondition and is not checked.
956 *
957 * @ingroup selection
958 */
959GHOSTTY_API GhosttyResult ghostty_terminal_selection_order(
960 GhosttyTerminal terminal,
961 const GhosttySelection* selection,
962 GhosttySelectionOrder* out_order);
963
964/**
965 * Return a selection snapshot with endpoints ordered as requested.
966 *
967 * Use GHOSTTY_SELECTION_ORDER_FORWARD to get top-left to bottom-right bounds,
968 * and GHOSTTY_SELECTION_ORDER_REVERSE to get bottom-right to top-left bounds.
969 * Mirrored desired orders are accepted but normalized the same as forward.
970 * The output selection is a fresh untracked snapshot and is not installed as
971 * the terminal's current selection.
972 *
973 * The selection's start and end grid refs must both be valid untracked
974 * snapshots for the given terminal's currently active screen. In practice,
975 * they must come from that terminal and screen, and no mutating terminal call
976 * may have occurred since the refs were produced or reconstructed from
977 * tracked refs. Passing refs from another terminal, another screen, or stale
978 * refs violates this precondition.
979 *
980 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
981 * @param selection Selection snapshot to order
982 * @param desired Desired endpoint order
983 * @param[out] out_selection On success, receives the ordered selection
984 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal,
985 * selection, desired order, or output pointer are invalid. Selection
986 * reference validity is a precondition and is not checked.
987 *
988 * @ingroup selection
989 */
990GHOSTTY_API GhosttyResult ghostty_terminal_selection_ordered(
991 GhosttyTerminal terminal,
992 const GhosttySelection* selection,
993 GhosttySelectionOrder desired,
994 GhosttySelection* out_selection);
995
996/**
997 * Test whether a terminal point is inside a selection snapshot.
998 *
999 * This uses the same selection semantics as the terminal, including
1000 * rectangular/block selections and linear selections spanning multiple rows.
1001 *
1002 * The selection's start and end grid refs must both be valid untracked
1003 * snapshots for the given terminal's currently active screen. In practice,
1004 * they must come from that terminal and screen, and no mutating terminal call
1005 * may have occurred since the refs were produced or reconstructed from
1006 * tracked refs. Passing refs from another terminal, another screen, or stale
1007 * refs violates this precondition.
1008 *
1009 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
1010 * @param selection Selection snapshot to inspect
1011 * @param point Point to test for containment
1012 * @param[out] out_contains On success, receives whether point is inside selection
1013 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal,
1014 * selection, point, or output pointer are invalid. Selection reference
1015 * validity is a precondition and is not checked.
1016 *
1017 * @ingroup selection
1018 */
1019GHOSTTY_API GhosttyResult ghostty_terminal_selection_contains(
1020 GhosttyTerminal terminal,
1021 const GhosttySelection* selection,
1022 GhosttyPoint point,
1023 bool* out_contains);
1024
1025/**
1026 * Test whether two selection snapshots are equal.
1027 *
1028 * Equality uses the terminal's internal selection semantics: both endpoint
1029 * pins must match and both selections must have the same rectangular/block
1030 * state. This avoids requiring callers to compare raw GhosttyGridRef internals.
1031 *
1032 * Both selections' start and end grid refs must be valid untracked snapshots
1033 * for the given terminal's currently active screen. In practice, they must
1034 * come from that terminal and screen, and no mutating terminal call may have
1035 * occurred since the refs were produced or reconstructed from tracked refs.
1036 * Passing refs from another terminal, another screen, or stale refs violates
1037 * this precondition.
1038 *
1039 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
1040 * @param a First selection snapshot to compare
1041 * @param b Second selection snapshot to compare
1042 * @param[out] out_equal On success, receives whether the selections are equal
1043 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal,
1044 * selections, or output pointer are invalid. Selection reference
1045 * validity is a precondition and is not checked.
1046 *
1047 * @ingroup selection
1048 */
1049GHOSTTY_API GhosttyResult ghostty_terminal_selection_equal(
1050 GhosttyTerminal terminal,
1051 const GhosttySelection* a,
1052 const GhosttySelection* b,
1053 bool* out_equal);
1054
1055/** @} */
1056
1057#ifdef __cplusplus
1058}
1059#endif
1060
1061#endif /* GHOSTTY_VT_SELECTION_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sgr.h+350−0
@@ -0,0 +1,350 @@
1/**
2 * @file sgr.h
3 *
4 * SGR (Select Graphic Rendition) attribute parsing and handling.
5 */
6
7#ifndef GHOSTTY_VT_SGR_H
8#define GHOSTTY_VT_SGR_H
9
10/** @defgroup sgr SGR Parser
11 *
12 * SGR (Select Graphic Rendition) attribute parser.
13 *
14 * SGR sequences are the syntax used to set styling attributes such as
15 * bold, italic, underline, and colors for text in terminal emulators.
16 * For example, you may be familiar with sequences like `ESC[1;31m`. The
17 * `1;31` is the SGR attribute list.
18 *
19 * The parser processes SGR parameters from CSI sequences (e.g., `ESC[1;31m`)
20 * and returns individual text attributes like bold, italic, colors, etc.
21 * It supports both semicolon (`;`) and colon (`:`) separators, possibly mixed,
22 * and handles various color formats including 8-color, 16-color, 256-color,
23 * X11 named colors, and RGB in multiple formats.
24 *
25 * ## Basic Usage
26 *
27 * 1. Create a parser instance with ghostty_sgr_new()
28 * 2. Set SGR parameters with ghostty_sgr_set_params()
29 * 3. Iterate through attributes using ghostty_sgr_next()
30 * 4. Free the parser with ghostty_sgr_free() when done
31 *
32 * ## Example
33 *
34 * @snippet c-vt-sgr/src/main.c sgr-basic
35 *
36 * @{
37 */
38
39#include <ghostty/vt/allocator.h>
40#include <ghostty/vt/color.h>
41#include <ghostty/vt/types.h>
42#include <stdbool.h>
43#include <stddef.h>
44#include <stdint.h>
45
46#ifdef __cplusplus
47extern "C" {
48#endif
49
50/**
51 * SGR attribute tags.
52 *
53 * These values identify the type of an SGR attribute in a tagged union.
54 * Use the tag to determine which field in the attribute value union to access.
55 *
56 * @ingroup sgr
57 */
58typedef enum GHOSTTY_ENUM_TYPED {
59 GHOSTTY_SGR_ATTR_UNSET = 0,
60 GHOSTTY_SGR_ATTR_UNKNOWN = 1,
61 GHOSTTY_SGR_ATTR_BOLD = 2,
62 GHOSTTY_SGR_ATTR_RESET_BOLD = 3,
63 GHOSTTY_SGR_ATTR_ITALIC = 4,
64 GHOSTTY_SGR_ATTR_RESET_ITALIC = 5,
65 GHOSTTY_SGR_ATTR_FAINT = 6,
66 GHOSTTY_SGR_ATTR_UNDERLINE = 7,
67 GHOSTTY_SGR_ATTR_UNDERLINE_COLOR = 8,
68 GHOSTTY_SGR_ATTR_UNDERLINE_COLOR_256 = 9,
69 GHOSTTY_SGR_ATTR_RESET_UNDERLINE_COLOR = 10,
70 GHOSTTY_SGR_ATTR_OVERLINE = 11,
71 GHOSTTY_SGR_ATTR_RESET_OVERLINE = 12,
72 GHOSTTY_SGR_ATTR_BLINK = 13,
73 GHOSTTY_SGR_ATTR_RESET_BLINK = 14,
74 GHOSTTY_SGR_ATTR_INVERSE = 15,
75 GHOSTTY_SGR_ATTR_RESET_INVERSE = 16,
76 GHOSTTY_SGR_ATTR_INVISIBLE = 17,
77 GHOSTTY_SGR_ATTR_RESET_INVISIBLE = 18,
78 GHOSTTY_SGR_ATTR_STRIKETHROUGH = 19,
79 GHOSTTY_SGR_ATTR_RESET_STRIKETHROUGH = 20,
80 GHOSTTY_SGR_ATTR_DIRECT_COLOR_FG = 21,
81 GHOSTTY_SGR_ATTR_DIRECT_COLOR_BG = 22,
82 GHOSTTY_SGR_ATTR_BG_8 = 23,
83 GHOSTTY_SGR_ATTR_FG_8 = 24,
84 GHOSTTY_SGR_ATTR_RESET_FG = 25,
85 GHOSTTY_SGR_ATTR_RESET_BG = 26,
86 GHOSTTY_SGR_ATTR_BRIGHT_BG_8 = 27,
87 GHOSTTY_SGR_ATTR_BRIGHT_FG_8 = 28,
88 GHOSTTY_SGR_ATTR_BG_256 = 29,
89 GHOSTTY_SGR_ATTR_FG_256 = 30,
90 GHOSTTY_SGR_ATTR_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
91} GhosttySgrAttributeTag;
92
93/**
94 * Underline style types.
95 *
96 * @ingroup sgr
97 */
98typedef enum GHOSTTY_ENUM_TYPED {
99 GHOSTTY_SGR_UNDERLINE_NONE = 0,
100 GHOSTTY_SGR_UNDERLINE_SINGLE = 1,
101 GHOSTTY_SGR_UNDERLINE_DOUBLE = 2,
102 GHOSTTY_SGR_UNDERLINE_CURLY = 3,
103 GHOSTTY_SGR_UNDERLINE_DOTTED = 4,
104 GHOSTTY_SGR_UNDERLINE_DASHED = 5,
105 GHOSTTY_SGR_UNDERLINE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
106} GhosttySgrUnderline;
107
108/**
109 * Unknown SGR attribute data.
110 *
111 * Contains the full parameter list and the partial list where parsing
112 * encountered an unknown or invalid sequence.
113 *
114 * @ingroup sgr
115 */
116typedef struct {
117 const uint16_t* full_ptr;
118 size_t full_len;
119 const uint16_t* partial_ptr;
120 size_t partial_len;
121} GhosttySgrUnknown;
122
123/**
124 * SGR attribute value union.
125 *
126 * This union contains all possible attribute values. Use the tag field
127 * to determine which union member is active. Attributes without associated
128 * data (like bold, italic) don't use the union value.
129 *
130 * @ingroup sgr
131 */
132typedef union {
133 GhosttySgrUnknown unknown;
134 GhosttySgrUnderline underline;
135 GhosttyColorRgb underline_color;
136 GhosttyColorPaletteIndex underline_color_256;
137 GhosttyColorRgb direct_color_fg;
138 GhosttyColorRgb direct_color_bg;
139 GhosttyColorPaletteIndex bg_8;
140 GhosttyColorPaletteIndex fg_8;
141 GhosttyColorPaletteIndex bright_bg_8;
142 GhosttyColorPaletteIndex bright_fg_8;
143 GhosttyColorPaletteIndex bg_256;
144 GhosttyColorPaletteIndex fg_256;
145 uint64_t _padding[8];
146} GhosttySgrAttributeValue;
147
148/**
149 * SGR attribute (tagged union).
150 *
151 * A complete SGR attribute with both its type tag and associated value.
152 * Always check the tag field to determine which value union member is valid.
153 *
154 * Attributes without associated data (e.g., GHOSTTY_SGR_ATTR_BOLD) can be
155 * identified by tag alone; the value union is not used for these and
156 * the memory in the value field is undefined.
157 *
158 * @ingroup sgr
159 */
160typedef struct {
161 GhosttySgrAttributeTag tag;
162 GhosttySgrAttributeValue value;
163} GhosttySgrAttribute;
164
165/**
166 * Create a new SGR parser instance.
167 *
168 * Creates a new SGR (Select Graphic Rendition) parser using the provided
169 * allocator. The parser must be freed using ghostty_sgr_free() when
170 * no longer needed.
171 *
172 * @param allocator Pointer to the allocator to use for memory management, or
173 * NULL to use the default allocator
174 * @param parser Pointer to store the created parser handle
175 * @return GHOSTTY_SUCCESS on success, or an error code on failure
176 *
177 * @ingroup sgr
178 */
179GHOSTTY_API GhosttyResult ghostty_sgr_new(const GhosttyAllocator* allocator,
180 GhosttySgrParser* parser);
181
182/**
183 * Free an SGR parser instance.
184 *
185 * Releases all resources associated with the SGR parser. After this call,
186 * the parser handle becomes invalid and must not be used. This includes
187 * any attributes previously returned by ghostty_sgr_next().
188 *
189 * @param parser The parser handle to free (may be NULL)
190 *
191 * @ingroup sgr
192 */
193GHOSTTY_API void ghostty_sgr_free(GhosttySgrParser parser);
194
195/**
196 * Reset an SGR parser instance to the beginning of the parameter list.
197 *
198 * Resets the parser's iteration state without clearing the parameters.
199 * After calling this, ghostty_sgr_next() will start from the beginning
200 * of the parameter list again.
201 *
202 * @param parser The parser handle to reset, must not be NULL
203 *
204 * @ingroup sgr
205 */
206GHOSTTY_API void ghostty_sgr_reset(GhosttySgrParser parser);
207
208/**
209 * Set SGR parameters for parsing.
210 *
211 * Sets the SGR parameter list to parse. Parameters are the numeric values
212 * from a CSI SGR sequence (e.g., for `ESC[1;31m`, params would be {1, 31}).
213 *
214 * The separators array optionally specifies the separator type for each
215 * parameter position. Each byte should be either ';' for semicolon or ':'
216 * for colon. This is needed for certain color formats that use colon
217 * separators (e.g., `ESC[4:3m` for curly underline). Any invalid separator
218 * values are treated as semicolons. The separators array must have the same
219 * length as the params array, if it is not NULL.
220 *
221 * If separators is NULL, all parameters are assumed to be semicolon-separated.
222 *
223 * This function makes an internal copy of the parameter and separator data,
224 * so the caller can safely free or modify the input arrays after this call.
225 *
226 * After calling this function, the parser is automatically reset and ready
227 * to iterate from the beginning.
228 *
229 * @param parser The parser handle, must not be NULL
230 * @param params Array of SGR parameter values
231 * @param separators Optional array of separator characters (';' or ':'), or
232 * NULL
233 * @param len Number of parameters (and separators if provided)
234 * @return GHOSTTY_SUCCESS on success, or an error code on failure
235 *
236 * @ingroup sgr
237 */
238GHOSTTY_API GhosttyResult ghostty_sgr_set_params(GhosttySgrParser parser,
239 const uint16_t* params,
240 const char* separators,
241 size_t len);
242
243/**
244 * Get the next SGR attribute.
245 *
246 * Parses and returns the next attribute from the parameter list.
247 * Call this function repeatedly until it returns false to process
248 * all attributes in the sequence.
249 *
250 * @param parser The parser handle, must not be NULL
251 * @param attr Pointer to store the next attribute
252 * @return true if an attribute was returned, false if no more attributes
253 *
254 * @ingroup sgr
255 */
256GHOSTTY_API bool ghostty_sgr_next(GhosttySgrParser parser, GhosttySgrAttribute* attr);
257
258/**
259 * Get the full parameter list from an unknown SGR attribute.
260 *
261 * This function retrieves the full parameter list that was provided to the
262 * parser when an unknown attribute was encountered. Primarily useful in
263 * WebAssembly environments where accessing struct fields directly is difficult.
264 *
265 * @param unknown The unknown attribute data
266 * @param ptr Pointer to store the pointer to the parameter array (may be NULL)
267 * @return The length of the full parameter array
268 *
269 * @ingroup sgr
270 */
271GHOSTTY_API size_t ghostty_sgr_unknown_full(GhosttySgrUnknown unknown,
272 const uint16_t** ptr);
273
274/**
275 * Get the partial parameter list from an unknown SGR attribute.
276 *
277 * This function retrieves the partial parameter list where parsing stopped
278 * when an unknown attribute was encountered. Primarily useful in WebAssembly
279 * environments where accessing struct fields directly is difficult.
280 *
281 * @param unknown The unknown attribute data
282 * @param ptr Pointer to store the pointer to the parameter array (may be NULL)
283 * @return The length of the partial parameter array
284 *
285 * @ingroup sgr
286 */
287GHOSTTY_API size_t ghostty_sgr_unknown_partial(GhosttySgrUnknown unknown,
288 const uint16_t** ptr);
289
290/**
291 * Get the tag from an SGR attribute.
292 *
293 * This function extracts the tag that identifies which type of attribute
294 * this is. Primarily useful in WebAssembly environments where accessing
295 * struct fields directly is difficult.
296 *
297 * @param attr The SGR attribute
298 * @return The attribute tag
299 *
300 * @ingroup sgr
301 */
302GHOSTTY_API GhosttySgrAttributeTag ghostty_sgr_attribute_tag(GhosttySgrAttribute attr);
303
304/**
305 * Get the value from an SGR attribute.
306 *
307 * This function returns a pointer to the value union from an SGR attribute. Use
308 * the tag to determine which field of the union is valid. Primarily useful in
309 * WebAssembly environments where accessing struct fields directly is difficult.
310 *
311 * @param attr Pointer to the SGR attribute
312 * @return Pointer to the attribute value union
313 *
314 * @ingroup sgr
315 */
316GHOSTTY_API GhosttySgrAttributeValue* ghostty_sgr_attribute_value(
317 GhosttySgrAttribute* attr);
318
319#ifdef __wasm__
320/**
321 * Allocate memory for an SGR attribute (WebAssembly only).
322 *
323 * This is a convenience function for WebAssembly environments to allocate
324 * memory for an SGR attribute structure that can be passed to ghostty_sgr_next.
325 *
326 * @return Pointer to the allocated attribute structure
327 *
328 * @ingroup wasm
329 */
330GHOSTTY_API GhosttySgrAttribute* ghostty_wasm_alloc_sgr_attribute(void);
331
332/**
333 * Free memory for an SGR attribute (WebAssembly only).
334 *
335 * Frees memory allocated by ghostty_wasm_alloc_sgr_attribute.
336 *
337 * @param attr Pointer to the attribute structure to free
338 *
339 * @ingroup wasm
340 */
341GHOSTTY_API void ghostty_wasm_free_sgr_attribute(GhosttySgrAttribute* attr);
342#endif
343
344#ifdef __cplusplus
345}
346#endif
347
348/** @} */
349
350#endif /* GHOSTTY_VT_SGR_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/size_report.h+101−0
@@ -0,0 +1,101 @@
1/**
2 * @file size_report.h
3 *
4 * Size report encoding - encode terminal size reports into escape sequences.
5 */
6
7#ifndef GHOSTTY_VT_SIZE_REPORT_H
8#define GHOSTTY_VT_SIZE_REPORT_H
9
10/** @defgroup size_report Size Report Encoding
11 *
12 * Utilities for encoding terminal size reports into escape sequences,
13 * supporting in-band size reports (mode 2048) and XTWINOPS responses
14 * (CSI 14 t, CSI 16 t, CSI 18 t).
15 *
16 * ## Basic Usage
17 *
18 * Use ghostty_size_report_encode() to encode a size report into a
19 * caller-provided buffer. If the buffer is too small, the function
20 * returns GHOSTTY_OUT_OF_SPACE and sets the required size in the
21 * output parameter.
22 *
23 * ## Example
24 *
25 * @snippet c-vt-size-report/src/main.c size-report-encode
26 *
27 * @{
28 */
29
30#include <stddef.h>
31#include <stdint.h>
32#include <ghostty/vt/types.h>
33
34#ifdef __cplusplus
35extern "C" {
36#endif
37
38/**
39 * Size report style.
40 *
41 * Determines the output format for the terminal size report.
42 */
43typedef enum GHOSTTY_ENUM_TYPED {
44 /** In-band size report (mode 2048): ESC [ 48 ; rows ; cols ; height ; width t */
45 GHOSTTY_SIZE_REPORT_MODE_2048 = 0,
46 /** XTWINOPS text area size in pixels: ESC [ 4 ; height ; width t */
47 GHOSTTY_SIZE_REPORT_CSI_14_T = 1,
48 /** XTWINOPS cell size in pixels: ESC [ 6 ; height ; width t */
49 GHOSTTY_SIZE_REPORT_CSI_16_T = 2,
50 /** XTWINOPS text area size in characters: ESC [ 8 ; rows ; cols t */
51 GHOSTTY_SIZE_REPORT_CSI_18_T = 3,
52 GHOSTTY_SIZE_REPORT_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
53} GhosttySizeReportStyle;
54
55/**
56 * Terminal size information for encoding size reports.
57 */
58typedef struct {
59 /** Terminal row count in cells. */
60 uint16_t rows;
61 /** Terminal column count in cells. */
62 uint16_t columns;
63 /** Width of a single terminal cell in pixels. */
64 uint32_t cell_width;
65 /** Height of a single terminal cell in pixels. */
66 uint32_t cell_height;
67} GhosttySizeReportSize;
68
69/**
70 * Encode a terminal size report into an escape sequence.
71 *
72 * Encodes a size report in the format specified by @p style into the
73 * provided buffer.
74 *
75 * If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
76 * and writes the required buffer size to @p out_written. The caller can
77 * then retry with a sufficiently sized buffer.
78 *
79 * @param style The size report format to encode
80 * @param size Terminal size information
81 * @param buf Output buffer to write the encoded sequence into (may be NULL)
82 * @param buf_len Size of the output buffer in bytes
83 * @param[out] out_written On success, the number of bytes written. On
84 * GHOSTTY_OUT_OF_SPACE, the required buffer size.
85 * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
86 * is too small
87 */
88GHOSTTY_API GhosttyResult ghostty_size_report_encode(
89 GhosttySizeReportStyle style,
90 GhosttySizeReportSize size,
91 char* buf,
92 size_t buf_len,
93 size_t* out_written);
94
95#ifdef __cplusplus
96}
97#endif
98
99/** @} */
100
101#endif /* GHOSTTY_VT_SIZE_REPORT_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/style.h+139−0
@@ -0,0 +1,139 @@
1/**
2 * @file style.h
3 *
4 * Terminal cell style types.
5 */
6
7#ifndef GHOSTTY_VT_STYLE_H
8#define GHOSTTY_VT_STYLE_H
9
10#include <ghostty/vt/color.h>
11#include <ghostty/vt/types.h>
12#include <stdbool.h>
13#include <stddef.h>
14#include <stdint.h>
15
16#ifdef __cplusplus
17extern "C" {
18#endif
19
20/** @defgroup style Style
21 *
22 * Terminal cell style attributes.
23 *
24 * A style describes the visual attributes of a terminal cell, including
25 * foreground, background, and underline colors, as well as flags for
26 * bold, italic, underline, and other text decorations.
27 *
28 * @{
29 */
30
31/**
32 * Style identifier type.
33 *
34 * Used to look up the full style from a grid reference.
35 * Obtain this from a cell via GHOSTTY_CELL_DATA_STYLE_ID.
36 *
37 * @ingroup style
38 */
39typedef uint16_t GhosttyStyleId;
40
41/**
42 * Style color tags.
43 *
44 * These values identify the type of color in a style color.
45 * Use the tag to determine which field in the color value union to access.
46 *
47 * @ingroup style
48 */
49typedef enum GHOSTTY_ENUM_TYPED {
50 GHOSTTY_STYLE_COLOR_NONE = 0,
51 GHOSTTY_STYLE_COLOR_PALETTE = 1,
52 GHOSTTY_STYLE_COLOR_RGB = 2,
53 GHOSTTY_STYLE_COLOR_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
54 } GhosttyStyleColorTag;
55
56/**
57 * Style color value union.
58 *
59 * Use the tag to determine which field is active.
60 *
61 * @ingroup style
62 */
63typedef union {
64 GhosttyColorPaletteIndex palette;
65 GhosttyColorRgb rgb;
66 uint64_t _padding;
67} GhosttyStyleColorValue;
68
69/**
70 * Style color (tagged union).
71 *
72 * A color used in a style attribute. Can be unset (none), a palette
73 * index, or a direct RGB value.
74 *
75 * @ingroup style
76 */
77typedef struct {
78 GhosttyStyleColorTag tag;
79 GhosttyStyleColorValue value;
80} GhosttyStyleColor;
81
82/**
83 * Terminal cell style.
84 *
85 * Describes the complete visual style for a terminal cell, including
86 * foreground, background, and underline colors, as well as text
87 * decoration flags. The underline field uses the same values as
88 * GhosttySgrUnderline.
89 *
90 * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
91 *
92 * @ingroup style
93 */
94typedef struct {
95 size_t size;
96 GhosttyStyleColor fg_color;
97 GhosttyStyleColor bg_color;
98 GhosttyStyleColor underline_color;
99 bool bold;
100 bool italic;
101 bool faint;
102 bool blink;
103 bool inverse;
104 bool invisible;
105 bool strikethrough;
106 bool overline;
107 int underline; /**< One of GHOSTTY_SGR_UNDERLINE_* values */
108} GhosttyStyle;
109
110/**
111 * Get the default style.
112 *
113 * Initializes the style to the default values (no colors, no flags).
114 *
115 * @param style Pointer to the style to initialize
116 *
117 * @ingroup style
118 */
119GHOSTTY_API void ghostty_style_default(GhosttyStyle* style);
120
121/**
122 * Check if a style is the default style.
123 *
124 * Returns true if all colors are unset and all flags are off.
125 *
126 * @param style Pointer to the style to check
127 * @return true if the style is the default style
128 *
129 * @ingroup style
130 */
131GHOSTTY_API bool ghostty_style_is_default(const GhosttyStyle* style);
132
133#ifdef __cplusplus
134}
135#endif
136
137/** @} */
138
139#endif /* GHOSTTY_VT_STYLE_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sys.h+210−0
@@ -0,0 +1,210 @@
1/**
2 * @file sys.h
3 *
4 * System interface - runtime-swappable implementations for external dependencies.
5 */
6
7#ifndef GHOSTTY_VT_SYS_H
8#define GHOSTTY_VT_SYS_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/types.h>
14#include <ghostty/vt/allocator.h>
15
16/** @defgroup sys System Interface
17 *
18 * Runtime-swappable function pointers for operations that depend on
19 * external implementations (e.g. image decoding).
20 *
21 * These are process-global settings that must be configured at startup
22 * before any terminal functionality that depends on them is used.
23 * Setting these enables various optional features of the terminal. For
24 * example, setting a PNG decoder enables PNG image support in the Kitty
25 * Graphics Protocol.
26 *
27 * Use ghostty_sys_set() with a `GhosttySysOption` to install or clear
28 * an implementation. Passing NULL as the value clears the implementation
29 * and disables the corresponding feature.
30 *
31 * ## Example
32 *
33 * ### Defining a PNG decode callback
34 * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png
35 *
36 * ### Installing the callback and sending a PNG image
37 * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main
38 *
39 * @{
40 */
41
42#ifdef __cplusplus
43extern "C" {
44#endif
45
46/**
47 * Result of decoding an image.
48 *
49 * The `data` buffer must be allocated through the allocator provided to
50 * the decode callback. The library takes ownership and will free it
51 * with the same allocator.
52 */
53typedef struct {
54 /** Image width in pixels. */
55 uint32_t width;
56
57 /** Image height in pixels. */
58 uint32_t height;
59
60 /** Pointer to the decoded RGBA pixel data. */
61 uint8_t* data;
62
63 /** Length of the pixel data in bytes. */
64 size_t data_len;
65} GhosttySysImage;
66
67/**
68 * Log severity levels for the log callback.
69 */
70typedef enum GHOSTTY_ENUM_TYPED {
71 GHOSTTY_SYS_LOG_LEVEL_ERROR = 0,
72 GHOSTTY_SYS_LOG_LEVEL_WARNING = 1,
73 GHOSTTY_SYS_LOG_LEVEL_INFO = 2,
74 GHOSTTY_SYS_LOG_LEVEL_DEBUG = 3,
75 GHOSTTY_SYS_LOG_LEVEL_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
76} GhosttySysLogLevel;
77
78/**
79 * Callback type for logging.
80 *
81 * When installed, internal library log messages are delivered through
82 * this callback instead of being discarded. The embedder is responsible
83 * for formatting and routing log output.
84 *
85 * @p scope is the log scope name as UTF-8 bytes (e.g. "osc", "kitty").
86 * When the log is unscoped (default scope), @p scope_len is 0.
87 *
88 * All pointer arguments are only valid for the duration of the callback.
89 * The callback must be safe to call from any thread.
90 *
91 * @param userdata The userdata pointer set via GHOSTTY_SYS_OPT_USERDATA
92 * @param level The severity level of the log message
93 * @param scope Pointer to the scope name bytes
94 * @param scope_len Length of the scope name in bytes
95 * @param message Pointer to the log message bytes
96 * @param message_len Length of the log message in bytes
97 */
98typedef void (*GhosttySysLogFn)(
99 void* userdata,
100 GhosttySysLogLevel level,
101 const uint8_t* scope,
102 size_t scope_len,
103 const uint8_t* message,
104 size_t message_len);
105
106/**
107 * Callback type for PNG decoding.
108 *
109 * Decodes raw PNG data into RGBA pixels. The output pixel data must be
110 * allocated through the provided allocator. The library takes ownership
111 * of the buffer and will free it with the same allocator.
112 *
113 * @param userdata The userdata pointer set via GHOSTTY_SYS_OPT_USERDATA
114 * @param allocator The allocator to use for the output pixel buffer
115 * @param data Pointer to the raw PNG data
116 * @param data_len Length of the raw PNG data in bytes
117 * @param[out] out On success, filled with the decoded image
118 * @return true on success, false on failure
119 */
120typedef bool (*GhosttySysDecodePngFn)(
121 void* userdata,
122 const GhosttyAllocator* allocator,
123 const uint8_t* data,
124 size_t data_len,
125 GhosttySysImage* out);
126
127/**
128 * System option identifiers for ghostty_sys_set().
129 */
130typedef enum GHOSTTY_ENUM_TYPED {
131 /**
132 * Set the userdata pointer passed to all sys callbacks.
133 *
134 * Input type: void* (or NULL)
135 */
136 GHOSTTY_SYS_OPT_USERDATA = 0,
137
138 /**
139 * Set the PNG decode function.
140 *
141 * When set, the terminal can accept PNG images via the Kitty
142 * Graphics Protocol. When cleared (NULL value), PNG decoding is
143 * unsupported and PNG image data will be rejected.
144 *
145 * Input type: GhosttySysDecodePngFn (function pointer, or NULL)
146 */
147 GHOSTTY_SYS_OPT_DECODE_PNG = 1,
148
149 /**
150 * Set the log callback.
151 *
152 * When set, internal library log messages are delivered to this
153 * callback. When cleared (NULL value), log messages are silently
154 * discarded.
155 *
156 * Use ghostty_sys_log_stderr as a convenience callback that
157 * writes formatted messages to stderr.
158 *
159 * Which log levels are emitted depends on the build mode of the
160 * library and is not configurable at runtime. Debug builds emit
161 * all levels (debug and above). Release builds emit info and
162 * above; debug-level messages are compiled out entirely and will
163 * never reach the callback.
164 *
165 * Input type: GhosttySysLogFn (function pointer, or NULL)
166 */
167 GHOSTTY_SYS_OPT_LOG = 2,
168 GHOSTTY_SYS_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
169} GhosttySysOption;
170
171/**
172 * Set a system-level option.
173 *
174 * Configures a process-global implementation function. These should be
175 * set once at startup before using any terminal functionality that
176 * depends on them.
177 *
178 * @param option The option to set
179 * @param value Pointer to the value (type depends on the option),
180 * or NULL to clear it
181 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
182 * option is not recognized
183 */
184GHOSTTY_API GhosttyResult ghostty_sys_set(GhosttySysOption option,
185 const void* value);
186
187/**
188 * Built-in log callback that writes to stderr.
189 *
190 * Formats each message as "[level](scope): message\n".
191 * Can be passed directly to ghostty_sys_set():
192 *
193 * @code
194 * ghostty_sys_set(GHOSTTY_SYS_OPT_LOG, &ghostty_sys_log_stderr);
195 * @endcode
196 */
197GHOSTTY_API void ghostty_sys_log_stderr(void* userdata,
198 GhosttySysLogLevel level,
199 const uint8_t* scope,
200 size_t scope_len,
201 const uint8_t* message,
202 size_t message_len);
203
204#ifdef __cplusplus
205}
206#endif
207
208/** @} */
209
210#endif /* GHOSTTY_VT_SYS_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/terminal.h+1322−0
@@ -0,0 +1,1322 @@
1/**
2 * @file terminal.h
3 *
4 * Complete terminal emulator state and rendering.
5 */
6
7#ifndef GHOSTTY_VT_TERMINAL_H
8#define GHOSTTY_VT_TERMINAL_H
9
10#include <stdbool.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <ghostty/vt/types.h>
14#include <ghostty/vt/allocator.h>
15#include <ghostty/vt/device.h>
16#include <ghostty/vt/modes.h>
17#include <ghostty/vt/size_report.h>
18#include <ghostty/vt/grid_ref.h>
19#include <ghostty/vt/kitty_graphics.h>
20#include <ghostty/vt/screen.h>
21#include <ghostty/vt/point.h>
22#include <ghostty/vt/selection.h>
23#include <ghostty/vt/style.h>
24
25#ifdef __cplusplus
26extern "C" {
27#endif
28
29/** @defgroup terminal Terminal
30 *
31 * Complete terminal emulator state and rendering.
32 *
33 * A terminal instance manages the full emulator state including the screen,
34 * scrollback, cursor, styles, modes, and VT stream processing.
35 *
36 * Once a terminal session is up and running, you can configure a key encoder
37 * to write keyboard input via ghostty_key_encoder_setopt_from_terminal().
38 *
39 * ### Example: VT stream processing
40 * @snippet c-vt-stream/src/main.c vt-stream-init
41 * @snippet c-vt-stream/src/main.c vt-stream-write
42 *
43 * ## Effects
44 *
45 * By default, the terminal sequence processing with ghostty_terminal_vt_write()
46 * only process sequences that directly affect terminal state and
47 * ignores sequences that have side effect behavior or require responses.
48 * These sequences include things like bell characters, title changes, device
49 * attributes queries, and more. To handle these sequences, the embedder
50 * must configure "effects."
51 *
52 * Effects are callbacks that the terminal invokes in response to VT
53 * sequences processed during ghostty_terminal_vt_write(). They let the
54 * embedding application react to terminal-initiated events such as bell
55 * characters, title changes, device status report responses, and more.
56 *
57 * Each effect is registered with ghostty_terminal_set() using the
58 * corresponding `GhosttyTerminalOption` identifier. A `NULL` value
59 * pointer clears the callback and disables the effect.
60 *
61 * A userdata pointer can be attached via `GHOSTTY_TERMINAL_OPT_USERDATA`
62 * and is passed to every callback, allowing callers to route events
63 * back to their own application state without global variables.
64 * You cannot specify different userdata for different callbacks.
65 *
66 * All callbacks are invoked synchronously during
67 * ghostty_terminal_vt_write(). Callbacks **must not** call
68 * ghostty_terminal_vt_write() on the same terminal (no reentrancy).
69 * And callbacks must be very careful to not block for too long or perform
70 * expensive operations, since they are blocking further IO processing.
71 *
72 * The available effects are:
73 *
74 * | Option | Callback Type | Trigger |
75 * |-----------------------------------------|-----------------------------------|-------------------------------------------|
76 * | `GHOSTTY_TERMINAL_OPT_WRITE_PTY` | `GhosttyTerminalWritePtyFn` | Query responses written back to the pty |
77 * | `GHOSTTY_TERMINAL_OPT_BELL` | `GhosttyTerminalBellFn` | BEL character (0x07) |
78 * | `GHOSTTY_TERMINAL_OPT_TITLE_CHANGED` | `GhosttyTerminalTitleChangedFn` | Title change via OSC 0 / OSC 2 |
79 * | `GHOSTTY_TERMINAL_OPT_PWD_CHANGED` | `GhosttyTerminalPwdChangedFn` | Pwd change via OSC 7 / OSC 9 / OSC 1337 |
80 * | `GHOSTTY_TERMINAL_OPT_ENQUIRY` | `GhosttyTerminalEnquiryFn` | ENQ character (0x05) |
81 * | `GHOSTTY_TERMINAL_OPT_XTVERSION` | `GhosttyTerminalXtversionFn` | XTVERSION query (CSI > q) |
82 * | `GHOSTTY_TERMINAL_OPT_SIZE` | `GhosttyTerminalSizeFn` | XTWINOPS size query (CSI 14/16/18 t) |
83 * | `GHOSTTY_TERMINAL_OPT_COLOR_SCHEME` | `GhosttyTerminalColorSchemeFn` | Color scheme query (CSI ? 996 n) |
84 * | `GHOSTTY_TERMINAL_OPT_DEVICE_ATTRIBUTES`| `GhosttyTerminalDeviceAttributesFn`| Device attributes query (CSI c / > c / = c)|
85 *
86 * ### Defining a write_pty callback
87 * @snippet c-vt-effects/src/main.c effects-write-pty
88 *
89 * ### Defining a bell callback
90 * @snippet c-vt-effects/src/main.c effects-bell
91 *
92 * ### Defining a title_changed callback
93 * @snippet c-vt-effects/src/main.c effects-title-changed
94 *
95 * ### Registering effects and processing VT data
96 * @snippet c-vt-effects/src/main.c effects-register
97 *
98 * ## Color Theme
99 *
100 * The terminal maintains a set of colors used for rendering: a foreground
101 * color, a background color, a cursor color, and a 256-color palette. Each
102 * of these has two layers: a **default** value set by the embedder, and an
103 * **override** value that programs running in the terminal can set via OSC
104 * escape sequences (e.g. OSC 10/11/12 for foreground/background/cursor,
105 * OSC 4 for individual palette entries).
106 *
107 * ### Default Colors
108 *
109 * Use ghostty_terminal_set() with the color options to configure the
110 * default colors. These represent the theme or configuration chosen by
111 * the embedder. Passing `NULL` clears the default, leaving the color
112 * unset.
113 *
114 * | Option | Input Type | Description |
115 * |-----------------------------------------|-------------------------|--------------------------------------|
116 * | `GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND` | `GhosttyColorRgb*` | Default foreground color |
117 * | `GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND` | `GhosttyColorRgb*` | Default background color |
118 * | `GHOSTTY_TERMINAL_OPT_COLOR_CURSOR` | `GhosttyColorRgb*` | Default cursor color |
119 * | `GHOSTTY_TERMINAL_OPT_COLOR_PALETTE` | `GhosttyColorRgb[256]*` | Default 256-color palette |
120 *
121 * For the palette, passing `NULL` resets to the built-in default palette.
122 * The palette set operation preserves any per-index OSC overrides that
123 * programs have applied; only unmodified indices are updated.
124 *
125 * ### Reading colors
126 *
127 * Use ghostty_terminal_get() to read colors. There are two variants for
128 * each color: the **effective** value (which returns the OSC override if
129 * one is active, otherwise the default) and the **default** value (which
130 * ignores any OSC overrides).
131 *
132 * | Data | Output Type | Description |
133 * |---------------------------------------------------|-------------------------|------------------------------------------------|
134 * | `GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND` | `GhosttyColorRgb*` | Effective foreground (override or default) |
135 * | `GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND` | `GhosttyColorRgb*` | Effective background (override or default) |
136 * | `GHOSTTY_TERMINAL_DATA_COLOR_CURSOR` | `GhosttyColorRgb*` | Effective cursor (override or default) |
137 * | `GHOSTTY_TERMINAL_DATA_COLOR_PALETTE` | `GhosttyColorRgb[256]*` | Current palette (with any OSC overrides) |
138 * | `GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND_DEFAULT` | `GhosttyColorRgb*` | Default foreground only (ignores OSC override) |
139 * | `GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND_DEFAULT` | `GhosttyColorRgb*` | Default background only (ignores OSC override) |
140 * | `GHOSTTY_TERMINAL_DATA_COLOR_CURSOR_DEFAULT` | `GhosttyColorRgb*` | Default cursor only (ignores OSC override) |
141 * | `GHOSTTY_TERMINAL_DATA_COLOR_PALETTE_DEFAULT` | `GhosttyColorRgb[256]*` | Default palette only (ignores OSC overrides) |
142 *
143 * For foreground, background, and cursor colors, the getters return
144 * `GHOSTTY_NO_VALUE` if no color is configured (neither a default nor an
145 * OSC override). The palette getters always succeed since the palette
146 * always has a value (the built-in default if nothing else is set).
147 *
148 * ### Setting a color theme
149 * @snippet c-vt-colors/src/main.c colors-set-defaults
150 *
151 * ### Reading effective and default colors
152 * @snippet c-vt-colors/src/main.c colors-read
153 *
154 * ### Full example with OSC overrides
155 * @snippet c-vt-colors/src/main.c colors-main
156 *
157 * @{
158 */
159
160/**
161 * Terminal initialization options.
162 *
163 * @ingroup terminal
164 */
165typedef struct {
166 /** Terminal width in cells. Must be greater than zero. */
167 uint16_t cols;
168
169 /** Terminal height in cells. Must be greater than zero. */
170 uint16_t rows;
171
172 /** Maximum number of lines to keep in scrollback history. */
173 size_t max_scrollback;
174
175 // TODO: Consider ABI compatibility implications of this struct.
176 // We may want to artificially pad it significantly to support
177 // future options.
178} GhosttyTerminalOptions;
179
180/**
181 * Scroll viewport behavior tag.
182 *
183 * @ingroup terminal
184 */
185typedef enum GHOSTTY_ENUM_TYPED {
186 /** Scroll to the top of the scrollback. */
187 GHOSTTY_SCROLL_VIEWPORT_TOP,
188
189 /** Scroll to the bottom (active area). */
190 GHOSTTY_SCROLL_VIEWPORT_BOTTOM,
191
192 /** Scroll by a delta amount (up is negative). */
193 GHOSTTY_SCROLL_VIEWPORT_DELTA,
194 GHOSTTY_SCROLL_VIEWPORT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
195} GhosttyTerminalScrollViewportTag;
196
197/**
198 * Scroll viewport value.
199 *
200 * @ingroup terminal
201 */
202typedef union {
203 /** Scroll delta (only used with GHOSTTY_SCROLL_VIEWPORT_DELTA). Up is negative. */
204 intptr_t delta;
205
206 /** Padding for ABI compatibility. Do not use. */
207 uint64_t _padding[2];
208} GhosttyTerminalScrollViewportValue;
209
210/**
211 * Tagged union for scroll viewport behavior.
212 *
213 * @ingroup terminal
214 */
215typedef struct {
216 GhosttyTerminalScrollViewportTag tag;
217 GhosttyTerminalScrollViewportValue value;
218} GhosttyTerminalScrollViewport;
219
220/**
221 * Terminal screen identifier.
222 *
223 * Identifies which screen buffer is active in the terminal.
224 *
225 * @ingroup terminal
226 */
227typedef enum GHOSTTY_ENUM_TYPED {
228 /** The primary (normal) screen. */
229 GHOSTTY_TERMINAL_SCREEN_PRIMARY = 0,
230
231 /** The alternate screen. */
232 GHOSTTY_TERMINAL_SCREEN_ALTERNATE = 1,
233 GHOSTTY_TERMINAL_SCREEN_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
234} GhosttyTerminalScreen;
235
236/**
237 * Visual style of the terminal cursor.
238 *
239 * @ingroup terminal
240 */
241typedef enum GHOSTTY_ENUM_TYPED {
242 /** Bar cursor (DECSCUSR 5, 6). */
243 GHOSTTY_TERMINAL_CURSOR_STYLE_BAR = 0,
244
245 /** Block cursor (DECSCUSR 1, 2). */
246 GHOSTTY_TERMINAL_CURSOR_STYLE_BLOCK = 1,
247
248 /** Underline cursor (DECSCUSR 3, 4). */
249 GHOSTTY_TERMINAL_CURSOR_STYLE_UNDERLINE = 2,
250
251 /** Hollow block cursor. */
252 GHOSTTY_TERMINAL_CURSOR_STYLE_BLOCK_HOLLOW = 3,
253 GHOSTTY_TERMINAL_CURSOR_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
254} GhosttyTerminalCursorStyle;
255
256/**
257 * Scrollbar state for the terminal viewport.
258 *
259 * Represents the scrollable area dimensions needed to render a scrollbar.
260 *
261 * @ingroup terminal
262 */
263typedef struct {
264 /** Total size of the scrollable area in rows. */
265 uint64_t total;
266
267 /** Offset into the total area that the viewport is at. */
268 uint64_t offset;
269
270 /** Length of the visible area in rows. */
271 uint64_t len;
272} GhosttyTerminalScrollbar;
273
274/**
275 * Callback function type for bell.
276 *
277 * Called when the terminal receives a BEL character (0x07).
278 *
279 * @param terminal The terminal handle
280 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
281 *
282 * @ingroup terminal
283 */
284typedef void (*GhosttyTerminalBellFn)(GhosttyTerminal terminal,
285 void* userdata);
286
287/**
288 * Callback function type for color scheme queries (CSI ? 996 n).
289 *
290 * Called when the terminal receives a color scheme device status report
291 * query. Return true and fill *out_scheme with the current color scheme,
292 * or return false to silently ignore the query.
293 *
294 * @param terminal The terminal handle
295 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
296 * @param[out] out_scheme Pointer to store the current color scheme
297 * @return true if the color scheme was filled, false to ignore the query
298 *
299 * @ingroup terminal
300 */
301typedef bool (*GhosttyTerminalColorSchemeFn)(GhosttyTerminal terminal,
302 void* userdata,
303 GhosttyColorScheme* out_scheme);
304
305/**
306 * Callback function type for device attributes queries (DA1/DA2/DA3).
307 *
308 * Called when the terminal receives a device attributes query (CSI c,
309 * CSI > c, or CSI = c). Return true and fill *out_attrs with the
310 * response data, or return false to silently ignore the query.
311 *
312 * The terminal uses whichever sub-struct (primary, secondary, tertiary)
313 * matches the request type, but all three should be filled for simplicity.
314 *
315 * @param terminal The terminal handle
316 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
317 * @param[out] out_attrs Pointer to store the device attributes response
318 * @return true if attributes were filled, false to ignore the query
319 *
320 * @ingroup terminal
321 */
322typedef bool (*GhosttyTerminalDeviceAttributesFn)(GhosttyTerminal terminal,
323 void* userdata,
324 GhosttyDeviceAttributes* out_attrs);
325
326/**
327 * Callback function type for enquiry (ENQ, 0x05).
328 *
329 * Called when the terminal receives an ENQ character. Return the
330 * response bytes as a GhosttyString. The memory must remain valid
331 * until the callback returns. Return a zero-length string to send
332 * no response.
333 *
334 * @param terminal The terminal handle
335 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
336 * @return The response bytes to write back to the pty
337 *
338 * @ingroup terminal
339 */
340typedef GhosttyString (*GhosttyTerminalEnquiryFn)(GhosttyTerminal terminal,
341 void* userdata);
342
343/**
344 * Callback function type for size queries (XTWINOPS).
345 *
346 * Called in response to XTWINOPS size queries (CSI 14/16/18 t).
347 * Return true and fill *out_size with the current terminal geometry,
348 * or return false to silently ignore the query.
349 *
350 * @param terminal The terminal handle
351 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
352 * @param[out] out_size Pointer to store the terminal size information
353 * @return true if size was filled, false to ignore the query
354 *
355 * @ingroup terminal
356 */
357typedef bool (*GhosttyTerminalSizeFn)(GhosttyTerminal terminal,
358 void* userdata,
359 GhosttySizeReportSize* out_size);
360
361/**
362 * Callback function type for title_changed.
363 *
364 * Called when the terminal title changes via escape sequences
365 * (e.g. OSC 0 or OSC 2). The new title can be queried from the
366 * terminal after the callback returns.
367 *
368 * @param terminal The terminal handle
369 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
370 *
371 * @ingroup terminal
372 */
373typedef void (*GhosttyTerminalTitleChangedFn)(GhosttyTerminal terminal,
374 void* userdata);
375
376/**
377 * Callback function type for pwd_changed.
378 *
379 * Called when the terminal pwd (current working directory) changes via
380 * escape sequences: OSC 7 (file:// URI), OSC 9 (ConEmu CurrentDir), or
381 * OSC 1337 CurrentDir (iTerm2). Use ghostty_terminal_get() with
382 * GHOSTTY_TERMINAL_DATA_PWD inside the callback to read the new value.
383 *
384 * The terminal stores whatever bytes the shell emitted, without parsing.
385 * That means for OSC 7 the value is the raw URI (typically file://...);
386 * for OSC 9/OSC 1337 it is typically a bare path. The embedder is
387 * responsible for decoding any URI scheme or host if it cares about them.
388 *
389 * The callback also fires when the shell clears the pwd (e.g. an empty
390 * OSC 7). In that case GHOSTTY_TERMINAL_DATA_PWD returns a zero-length
391 * string.
392 *
393 * @param terminal The terminal handle
394 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
395 *
396 * @ingroup terminal
397 */
398typedef void (*GhosttyTerminalPwdChangedFn)(GhosttyTerminal terminal,
399 void* userdata);
400
401/**
402 * Callback function type for write_pty.
403 *
404 * Called when the terminal needs to write data back to the pty, for
405 * example in response to a device status report or mode query. The
406 * data is only valid for the duration of the call; callers must copy
407 * it if it needs to persist.
408 *
409 * @param terminal The terminal handle
410 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
411 * @param data Pointer to the response bytes
412 * @param len Length of the response in bytes
413 *
414 * @ingroup terminal
415 */
416typedef void (*GhosttyTerminalWritePtyFn)(GhosttyTerminal terminal,
417 void* userdata,
418 const uint8_t* data,
419 size_t len);
420
421/**
422 * Callback function type for XTVERSION.
423 *
424 * Called when the terminal receives an XTVERSION query (CSI > q).
425 * Return the version string (e.g. "myterm 1.0") as a GhosttyString.
426 * The memory must remain valid until the callback returns. Return a
427 * zero-length string to report the default "libghostty" version.
428 *
429 * @param terminal The terminal handle
430 * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA
431 * @return The version string to report
432 *
433 * @ingroup terminal
434 */
435typedef GhosttyString (*GhosttyTerminalXtversionFn)(GhosttyTerminal terminal,
436 void* userdata);
437
438/**
439 * Terminal option identifiers.
440 *
441 * These values are used with ghostty_terminal_set() to configure
442 * terminal callbacks and associated state.
443 *
444 * @ingroup terminal
445 */
446typedef enum GHOSTTY_ENUM_TYPED {
447 /**
448 * Opaque userdata pointer passed to all callbacks.
449 *
450 * Input type: void*
451 */
452 GHOSTTY_TERMINAL_OPT_USERDATA = 0,
453
454 /**
455 * Callback invoked when the terminal needs to write data back
456 * to the pty (e.g. in response to a DECRQM query or device
457 * status report). Set to NULL to ignore such sequences.
458 *
459 * Input type: GhosttyTerminalWritePtyFn
460 */
461 GHOSTTY_TERMINAL_OPT_WRITE_PTY = 1,
462
463 /**
464 * Callback invoked when the terminal receives a BEL character
465 * (0x07). Set to NULL to ignore bell events.
466 *
467 * Input type: GhosttyTerminalBellFn
468 */
469 GHOSTTY_TERMINAL_OPT_BELL = 2,
470
471 /**
472 * Callback invoked when the terminal receives an ENQ character
473 * (0x05). Set to NULL to send no response.
474 *
475 * Input type: GhosttyTerminalEnquiryFn
476 */
477 GHOSTTY_TERMINAL_OPT_ENQUIRY = 3,
478
479 /**
480 * Callback invoked when the terminal receives an XTVERSION query
481 * (CSI > q). Set to NULL to report the default "libghostty" string.
482 *
483 * Input type: GhosttyTerminalXtversionFn
484 */
485 GHOSTTY_TERMINAL_OPT_XTVERSION = 4,
486
487 /**
488 * Callback invoked when the terminal title changes via escape
489 * sequences (e.g. OSC 0 or OSC 2). Set to NULL to ignore title
490 * change events.
491 *
492 * Input type: GhosttyTerminalTitleChangedFn
493 */
494 GHOSTTY_TERMINAL_OPT_TITLE_CHANGED = 5,
495
496 /**
497 * Callback invoked in response to XTWINOPS size queries
498 * (CSI 14/16/18 t). Set to NULL to silently ignore size queries.
499 *
500 * Input type: GhosttyTerminalSizeFn
501 */
502 GHOSTTY_TERMINAL_OPT_SIZE = 6,
503
504 /**
505 * Callback invoked in response to a color scheme device status
506 * report query (CSI ? 996 n). Return true and fill the out pointer
507 * to report the current scheme, or return false to silently ignore.
508 * Set to NULL to ignore color scheme queries.
509 *
510 * Input type: GhosttyTerminalColorSchemeFn
511 */
512 GHOSTTY_TERMINAL_OPT_COLOR_SCHEME = 7,
513
514 /**
515 * Callback invoked in response to a device attributes query
516 * (CSI c, CSI > c, or CSI = c). Return true and fill the out
517 * pointer with response data, or return false to silently ignore.
518 * Set to NULL to ignore device attributes queries.
519 *
520 * Input type: GhosttyTerminalDeviceAttributesFn
521 */
522 GHOSTTY_TERMINAL_OPT_DEVICE_ATTRIBUTES = 8,
523
524 /**
525 * Set the terminal title manually.
526 *
527 * The string data is copied into the terminal. A NULL value pointer
528 * clears the title (equivalent to setting an empty string).
529 *
530 * Input type: GhosttyString*
531 */
532 GHOSTTY_TERMINAL_OPT_TITLE = 9,
533
534 /**
535 * Set the terminal working directory manually.
536 *
537 * The string data is copied into the terminal. A NULL value pointer
538 * clears the pwd (equivalent to setting an empty string).
539 *
540 * Input type: GhosttyString*
541 */
542 GHOSTTY_TERMINAL_OPT_PWD = 10,
543
544 /**
545 * Set the default foreground color.
546 *
547 * A NULL value pointer clears the default (unset).
548 *
549 * Input type: GhosttyColorRgb*
550 */
551 GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND = 11,
552
553 /**
554 * Set the default background color.
555 *
556 * A NULL value pointer clears the default (unset).
557 *
558 * Input type: GhosttyColorRgb*
559 */
560 GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND = 12,
561
562 /**
563 * Set the default cursor color.
564 *
565 * A NULL value pointer clears the default (unset).
566 *
567 * Input type: GhosttyColorRgb*
568 */
569 GHOSTTY_TERMINAL_OPT_COLOR_CURSOR = 13,
570
571 /**
572 * Set the default 256-color palette.
573 *
574 * The value must point to an array of exactly 256 GhosttyColorRgb values.
575 * A NULL value pointer resets to the built-in default palette.
576 *
577 * Input type: GhosttyColorRgb[256]*
578 */
579 GHOSTTY_TERMINAL_OPT_COLOR_PALETTE = 14,
580
581 /**
582 * Set the Kitty image storage limit in bytes.
583 *
584 * Applied to all initialized screens (primary and alternate).
585 * A value of zero disables the Kitty graphics protocol entirely,
586 * deleting all stored images and placements. A NULL value pointer
587 * is equivalent to zero (disables). Has no effect when Kitty graphics
588 * are disabled at build time.
589 *
590 * Input type: uint64_t*
591 */
592 GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT = 15,
593
594 /**
595 * Enable or disable Kitty image loading via the file medium.
596 *
597 * A NULL value pointer is a no-op. Has no effect when Kitty graphics
598 * are disabled at build time.
599 *
600 * Input type: bool*
601 */
602 GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_MEDIUM_FILE = 16,
603
604 /**
605 * Enable or disable Kitty image loading via the temporary file medium.
606 *
607 * A NULL value pointer is a no-op. Has no effect when Kitty graphics
608 * are disabled at build time.
609 *
610 * Input type: bool*
611 */
612 GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_MEDIUM_TEMP_FILE = 17,
613
614 /**
615 * Enable or disable Kitty image loading via the shared memory medium.
616 *
617 * A NULL value pointer is a no-op. Has no effect when Kitty graphics
618 * are disabled at build time.
619 *
620 * Input type: bool*
621 */
622 GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_MEDIUM_SHARED_MEM = 18,
623
624 /**
625 * Set the maximum bytes the APC handler will buffer for all protocols.
626 * This prevents malicious input from causing unbounded memory allocation.
627 * A NULL value pointer removes all overrides, reverting to the built-in
628 * defaults.
629 *
630 * Input type: size_t*
631 */
632 GHOSTTY_TERMINAL_OPT_APC_MAX_BYTES = 19,
633
634 /**
635 * Set the maximum bytes the APC handler will buffer for Kitty graphics
636 * protocol data. A NULL value pointer removes the override, reverting
637 * to the built-in default.
638 *
639 * Input type: size_t*
640 */
641 GHOSTTY_TERMINAL_OPT_APC_MAX_BYTES_KITTY = 20,
642
643 /**
644 * Set the active screen selection.
645 *
646 * The value must point to a GhosttySelection whose grid references are
647 * valid for this terminal's active screen at the time of the call. The
648 * terminal copies the selection immediately and converts it to
649 * terminal-owned tracked state, so the GhosttySelection struct and its
650 * untracked grid references do not need to outlive this call.
651 *
652 * Passing NULL clears the active screen selection.
653 *
654 * Input type: GhosttySelection*
655 */
656 GHOSTTY_TERMINAL_OPT_SELECTION = 21,
657
658 /**
659 * Set the default cursor style used by DECSCUSR reset (CSI 0 q).
660 *
661 * A NULL value pointer resets to the built-in default block cursor.
662 *
663 * Input type: GhosttyTerminalCursorStyle*
664 */
665 GHOSTTY_TERMINAL_OPT_DEFAULT_CURSOR_STYLE = 22,
666
667 /**
668 * Set whether the default cursor should blink when reset by DECSCUSR
669 * (CSI 0 q).
670 *
671 * A NULL value pointer resets to the built-in default of not blinking.
672 *
673 * Input type: bool*
674 */
675 GHOSTTY_TERMINAL_OPT_DEFAULT_CURSOR_BLINK = 23,
676
677 /**
678 * Enable or disable Glyph Protocol APC handling.
679 *
680 * When disabled, Glyph Protocol APC sequences are ignored and no
681 * support/query/register/clear responses are emitted. Disabling also clears
682 * the terminal session's glyph glossary. A NULL value pointer is a no-op.
683 *
684 * Input type: bool*
685 */
686 GHOSTTY_TERMINAL_OPT_GLYPH_PROTOCOL = 24,
687
688 /**
689 * Callback invoked when the terminal pwd changes via escape
690 * sequences (OSC 7, OSC 9, or OSC 1337 CurrentDir). Set to NULL
691 * to ignore pwd change events.
692 *
693 * Input type: GhosttyTerminalPwdChangedFn
694 */
695 GHOSTTY_TERMINAL_OPT_PWD_CHANGED = 25,
696 GHOSTTY_TERMINAL_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
697} GhosttyTerminalOption;
698
699/**
700 * Terminal data types.
701 *
702 * These values specify what type of data to extract from a terminal
703 * using `ghostty_terminal_get`.
704 *
705 * @ingroup terminal
706 */
707typedef enum GHOSTTY_ENUM_TYPED {
708 /** Invalid data type. Never results in any data extraction. */
709 GHOSTTY_TERMINAL_DATA_INVALID = 0,
710
711 /**
712 * Terminal width in cells.
713 *
714 * Output type: uint16_t *
715 */
716 GHOSTTY_TERMINAL_DATA_COLS = 1,
717
718 /**
719 * Terminal height in cells.
720 *
721 * Output type: uint16_t *
722 */
723 GHOSTTY_TERMINAL_DATA_ROWS = 2,
724
725 /**
726 * Cursor column position (0-indexed).
727 *
728 * Output type: uint16_t *
729 */
730 GHOSTTY_TERMINAL_DATA_CURSOR_X = 3,
731
732 /**
733 * Cursor row position within the active area (0-indexed).
734 *
735 * Output type: uint16_t *
736 */
737 GHOSTTY_TERMINAL_DATA_CURSOR_Y = 4,
738
739 /**
740 * Whether the cursor has a pending wrap (next print will soft-wrap).
741 *
742 * Output type: bool *
743 */
744 GHOSTTY_TERMINAL_DATA_CURSOR_PENDING_WRAP = 5,
745
746 /**
747 * The currently active screen.
748 *
749 * Output type: GhosttyTerminalScreen *
750 */
751 GHOSTTY_TERMINAL_DATA_ACTIVE_SCREEN = 6,
752
753 /**
754 * Whether the cursor is visible (DEC mode 25).
755 *
756 * Output type: bool *
757 */
758 GHOSTTY_TERMINAL_DATA_CURSOR_VISIBLE = 7,
759
760 /**
761 * Current Kitty keyboard protocol flags.
762 *
763 * Output type: GhosttyKittyKeyFlags * (uint8_t *)
764 */
765 GHOSTTY_TERMINAL_DATA_KITTY_KEYBOARD_FLAGS = 8,
766
767 /**
768 * Scrollbar state for the terminal viewport.
769 *
770 * This may be expensive to calculate depending on where the viewport
771 * is (arbitrary pins are expensive). The caller should take care to only
772 * call this as needed and not too frequently.
773 *
774 * Output type: GhosttyTerminalScrollbar *
775 */
776 GHOSTTY_TERMINAL_DATA_SCROLLBAR = 9,
777
778 /**
779 * The current SGR style of the cursor.
780 *
781 * This is the style that will be applied to newly printed characters.
782 *
783 * Output type: GhosttyStyle *
784 */
785 GHOSTTY_TERMINAL_DATA_CURSOR_STYLE = 10,
786
787 /**
788 * Whether any mouse tracking mode is active.
789 *
790 * Returns true if any of the mouse tracking modes (X10, normal, button,
791 * or any-event) are enabled.
792 *
793 * Output type: bool *
794 */
795 GHOSTTY_TERMINAL_DATA_MOUSE_TRACKING = 11,
796
797 /**
798 * The terminal title as set by escape sequences (e.g. OSC 0/2).
799 *
800 * Returns a borrowed string. The pointer is valid until the next call
801 * to ghostty_terminal_vt_write() or ghostty_terminal_reset(). An empty
802 * string (len=0) is returned when no title has been set.
803 *
804 * Output type: GhosttyString *
805 */
806 GHOSTTY_TERMINAL_DATA_TITLE = 12,
807
808 /**
809 * The terminal's current working directory as set by escape sequences
810 * (e.g. OSC 7).
811 *
812 * Returns a borrowed string. The pointer is valid until the next call
813 * to ghostty_terminal_vt_write() or ghostty_terminal_reset(). An empty
814 * string (len=0) is returned when no pwd has been set.
815 *
816 * Output type: GhosttyString *
817 */
818 GHOSTTY_TERMINAL_DATA_PWD = 13,
819
820 /**
821 * The total number of rows in the active screen including scrollback.
822 *
823 * Output type: size_t *
824 */
825 GHOSTTY_TERMINAL_DATA_TOTAL_ROWS = 14,
826
827 /**
828 * The number of scrollback rows (total rows minus viewport rows).
829 *
830 * Output type: size_t *
831 */
832 GHOSTTY_TERMINAL_DATA_SCROLLBACK_ROWS = 15,
833
834 /**
835 * The total width of the terminal in pixels.
836 *
837 * This is cols * cell_width_px as set by ghostty_terminal_resize().
838 *
839 * Output type: uint32_t *
840 */
841 GHOSTTY_TERMINAL_DATA_WIDTH_PX = 16,
842
843 /**
844 * The total height of the terminal in pixels.
845 *
846 * This is rows * cell_height_px as set by ghostty_terminal_resize().
847 *
848 * Output type: uint32_t *
849 */
850 GHOSTTY_TERMINAL_DATA_HEIGHT_PX = 17,
851
852 /**
853 * The effective foreground color (override or default).
854 *
855 * Returns GHOSTTY_NO_VALUE if no foreground color is set.
856 *
857 * Output type: GhosttyColorRgb *
858 */
859 GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND = 18,
860
861 /**
862 * The effective background color (override or default).
863 *
864 * Returns GHOSTTY_NO_VALUE if no background color is set.
865 *
866 * Output type: GhosttyColorRgb *
867 */
868 GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND = 19,
869
870 /**
871 * The effective cursor color (override or default).
872 *
873 * Returns GHOSTTY_NO_VALUE if no cursor color is set.
874 *
875 * Output type: GhosttyColorRgb *
876 */
877 GHOSTTY_TERMINAL_DATA_COLOR_CURSOR = 20,
878
879 /**
880 * The current 256-color palette.
881 *
882 * Output type: GhosttyColorRgb[256] *
883 */
884 GHOSTTY_TERMINAL_DATA_COLOR_PALETTE = 21,
885
886 /**
887 * The default foreground color (ignoring any OSC override).
888 *
889 * Returns GHOSTTY_NO_VALUE if no default foreground color is set.
890 *
891 * Output type: GhosttyColorRgb *
892 */
893 GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND_DEFAULT = 22,
894
895 /**
896 * The default background color (ignoring any OSC override).
897 *
898 * Returns GHOSTTY_NO_VALUE if no default background color is set.
899 *
900 * Output type: GhosttyColorRgb *
901 */
902 GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND_DEFAULT = 23,
903
904 /**
905 * The default cursor color (ignoring any OSC override).
906 *
907 * Returns GHOSTTY_NO_VALUE if no default cursor color is set.
908 *
909 * Output type: GhosttyColorRgb *
910 */
911 GHOSTTY_TERMINAL_DATA_COLOR_CURSOR_DEFAULT = 24,
912
913 /**
914 * The default 256-color palette (ignoring any OSC overrides).
915 *
916 * Output type: GhosttyColorRgb[256] *
917 */
918 GHOSTTY_TERMINAL_DATA_COLOR_PALETTE_DEFAULT = 25,
919
920 /**
921 * The Kitty image storage limit in bytes for the active screen.
922 *
923 * A value of zero means the Kitty graphics protocol is disabled.
924 * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
925 *
926 * Output type: uint64_t *
927 */
928 GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_STORAGE_LIMIT = 26,
929
930 /**
931 * Whether the file medium is enabled for Kitty image loading on the
932 * active screen.
933 *
934 * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
935 *
936 * Output type: bool *
937 */
938 GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_MEDIUM_FILE = 27,
939
940 /**
941 * Whether the temporary file medium is enabled for Kitty image loading
942 * on the active screen.
943 *
944 * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
945 *
946 * Output type: bool *
947 */
948 GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_MEDIUM_TEMP_FILE = 28,
949
950 /**
951 * Whether the shared memory medium is enabled for Kitty image loading
952 * on the active screen.
953 *
954 * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
955 *
956 * Output type: bool *
957 */
958 GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_MEDIUM_SHARED_MEM = 29,
959
960 /**
961 * The Kitty graphics image storage for the active screen.
962 *
963 * Returns a borrowed pointer to the image storage. The pointer is valid
964 * until the next mutating terminal call (e.g. ghostty_terminal_vt_write()
965 * or ghostty_terminal_reset()).
966 *
967 * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
968 *
969 * Output type: GhosttyKittyGraphics *
970 */
971 GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS = 30,
972
973 /**
974 * The active screen's current selection.
975 *
976 * On success, writes an untracked snapshot of the terminal-owned selection
977 * to the caller-provided GhosttySelection. The GhosttySelection struct is
978 * caller-owned and may be kept, but the grid references inside it are
979 * untracked borrowed references into the active screen. They are only valid
980 * until the next mutating terminal call, such as ghostty_terminal_set(),
981 * ghostty_terminal_vt_write(), ghostty_terminal_resize(), or
982 * ghostty_terminal_reset().
983 *
984 * Returns GHOSTTY_NO_VALUE when there is no active selection.
985 *
986 * Output type: GhosttySelection *
987 */
988 GHOSTTY_TERMINAL_DATA_SELECTION = 31,
989
990 /**
991 * Whether the viewport is currently pinned to the active area.
992 *
993 * This is true when the viewport is following the active terminal area,
994 * and false when the user has scrolled into history.
995 *
996 * Output type: bool *
997 */
998 GHOSTTY_TERMINAL_DATA_VIEWPORT_ACTIVE = 32,
999 GHOSTTY_TERMINAL_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
1000} GhosttyTerminalData;
1001
1002/**
1003 * Create a new terminal instance.
1004 *
1005 * @param allocator Pointer to allocator, or NULL to use the default allocator
1006 * @param terminal Pointer to store the created terminal handle
1007 * @param options Terminal initialization options
1008 * @return GHOSTTY_SUCCESS on success, or an error code on failure
1009 *
1010 * @ingroup terminal
1011 */
1012GHOSTTY_API GhosttyResult ghostty_terminal_new(const GhosttyAllocator* allocator,
1013 GhosttyTerminal* terminal,
1014 GhosttyTerminalOptions options);
1015
1016/**
1017 * Free a terminal instance.
1018 *
1019 * Releases all resources associated with the terminal. After this call,
1020 * the terminal handle becomes invalid and must not be used.
1021 *
1022 * @param terminal The terminal handle to free (may be NULL)
1023 *
1024 * @ingroup terminal
1025 */
1026GHOSTTY_API void ghostty_terminal_free(GhosttyTerminal terminal);
1027
1028/**
1029 * Perform a full reset of the terminal (RIS).
1030 *
1031 * Resets all terminal state back to its initial configuration, including
1032 * modes, scrollback, scrolling region, and screen contents. The terminal
1033 * dimensions are preserved.
1034 *
1035 * @param terminal The terminal handle (may be NULL, in which case this is a no-op)
1036 *
1037 * @ingroup terminal
1038 */
1039GHOSTTY_API void ghostty_terminal_reset(GhosttyTerminal terminal);
1040
1041/**
1042 * Resize the terminal to the given dimensions.
1043 *
1044 * Changes the number of columns and rows in the terminal. The primary
1045 * screen will reflow content if wraparound mode is enabled; the alternate
1046 * screen does not reflow. If the dimensions are unchanged, this is a no-op.
1047 *
1048 * This also updates the terminal's pixel dimensions (used for image
1049 * protocols and size reports), disables synchronized output mode (allowed
1050 * by the spec so that resize results are shown immediately), and sends an
1051 * in-band size report if mode 2048 is enabled.
1052 *
1053 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
1054 * @param cols New width in cells (must be greater than zero)
1055 * @param rows New height in cells (must be greater than zero)
1056 * @param cell_width_px Width of a single cell in pixels
1057 * @param cell_height_px Height of a single cell in pixels
1058 * @return GHOSTTY_SUCCESS on success, or an error code on failure
1059 *
1060 * @ingroup terminal
1061 */
1062GHOSTTY_API GhosttyResult ghostty_terminal_resize(GhosttyTerminal terminal,
1063 uint16_t cols,
1064 uint16_t rows,
1065 uint32_t cell_width_px,
1066 uint32_t cell_height_px);
1067
1068/**
1069 * Set an option on the terminal.
1070 *
1071 * Configures terminal callbacks and associated state such as the
1072 * write_pty callback and userdata pointer. The value is passed
1073 * directly for pointer types (callbacks, userdata) or as a pointer
1074 * to the value for non-pointer types (e.g. GhosttyString*).
1075 * NULL clears the option to its default.
1076 *
1077 * Callbacks are invoked synchronously during ghostty_terminal_vt_write().
1078 * Callbacks must not call ghostty_terminal_vt_write() on the same
1079 * terminal (no reentrancy).
1080 *
1081 * @param terminal The terminal handle (may be NULL, in which case this is a no-op)
1082 * @param option The option to set
1083 * @param value Pointer to the value to set (type depends on the option),
1084 * or NULL to clear the option
1085 *
1086 * @ingroup terminal
1087 */
1088GHOSTTY_API GhosttyResult ghostty_terminal_set(GhosttyTerminal terminal,
1089 GhosttyTerminalOption option,
1090 const void* value);
1091
1092/**
1093 * Write VT-encoded data to the terminal for processing.
1094 *
1095 * Feeds raw bytes through the terminal's VT stream parser, updating
1096 * terminal state accordingly. By default, sequences that require output
1097 * (queries, device status reports) are silently ignored. Use
1098 * ghostty_terminal_set() with GHOSTTY_TERMINAL_OPT_WRITE_PTY to install
1099 * a callback that receives response data.
1100 *
1101 * This never fails. Any erroneous input or errors in processing the
1102 * input are logged internally but do not cause this function to fail
1103 * because this input is assumed to be untrusted and from an external
1104 * source; so the primary goal is to keep the terminal state consistent and
1105 * not allow malformed input to corrupt or crash.
1106 *
1107 * @param terminal The terminal handle
1108 * @param data Pointer to the data to write
1109 * @param len Length of the data in bytes
1110 *
1111 * @ingroup terminal
1112 */
1113GHOSTTY_API void ghostty_terminal_vt_write(GhosttyTerminal terminal,
1114 const uint8_t* data,
1115 size_t len);
1116
1117/**
1118 * Scroll the terminal viewport.
1119 *
1120 * Scrolls the terminal's viewport according to the given behavior.
1121 * When using GHOSTTY_SCROLL_VIEWPORT_DELTA, set the delta field in
1122 * the value union to specify the number of rows to scroll (negative
1123 * for up, positive for down). For other behaviors, the value is ignored.
1124 *
1125 * @param terminal The terminal handle (may be NULL, in which case this is a no-op)
1126 * @param behavior The scroll behavior as a tagged union
1127 *
1128 * @ingroup terminal
1129 */
1130GHOSTTY_API void ghostty_terminal_scroll_viewport(GhosttyTerminal terminal,
1131 GhosttyTerminalScrollViewport behavior);
1132
1133/**
1134 * Get the current value of a terminal mode.
1135 *
1136 * Returns the value of the mode identified by the given mode.
1137 *
1138 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
1139 * @param mode The mode identifying the mode to query
1140 * @param[out] out_value On success, set to true if the mode is set, false
1141 * if it is reset
1142 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal
1143 * is NULL or the mode does not correspond to a known mode
1144 *
1145 * @ingroup terminal
1146 */
1147GHOSTTY_API GhosttyResult ghostty_terminal_mode_get(GhosttyTerminal terminal,
1148 GhosttyMode mode,
1149 bool* out_value);
1150
1151/**
1152 * Set the value of a terminal mode.
1153 *
1154 * Sets the mode identified by the given mode to the specified value.
1155 *
1156 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
1157 * @param mode The mode identifying the mode to set
1158 * @param value true to set the mode, false to reset it
1159 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal
1160 * is NULL or the mode does not correspond to a known mode
1161 *
1162 * @ingroup terminal
1163 */
1164GHOSTTY_API GhosttyResult ghostty_terminal_mode_set(GhosttyTerminal terminal,
1165 GhosttyMode mode,
1166 bool value);
1167
1168/**
1169 * Get data from a terminal instance.
1170 *
1171 * Extracts typed data from the given terminal based on the specified
1172 * data type. The output pointer must be of the appropriate type for the
1173 * requested data kind. Valid data types and output types are documented
1174 * in the `GhosttyTerminalData` enum.
1175 *
1176 * @param terminal The terminal handle (may be NULL)
1177 * @param data The type of data to extract
1178 * @param out Pointer to store the extracted data (type depends on data parameter)
1179 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal
1180 * is NULL or the data type is invalid
1181 *
1182 * @ingroup terminal
1183 */
1184GHOSTTY_API GhosttyResult ghostty_terminal_get(GhosttyTerminal terminal,
1185 GhosttyTerminalData data,
1186 void *out);
1187
1188/**
1189 * Get multiple data fields from a terminal in a single call.
1190 *
1191 * This is an optimization over calling ghostty_terminal_get()
1192 * repeatedly, particularly useful in environments with high per-call
1193 * overhead such as FFI or Cgo.
1194 *
1195 * Each element in the keys array specifies a data kind, and the
1196 * corresponding element in the values array receives the result.
1197 * The type of each values[i] pointer must match the output type
1198 * documented for keys[i].
1199 *
1200 * Processing stops at the first error; on success out_written
1201 * is set to count, on error it is set to the index of the
1202 * failing key (i.e. the number of values successfully written).
1203 *
1204 * @param terminal The terminal handle (may be NULL)
1205 * @param count Number of key/value pairs
1206 * @param keys Array of data kinds to query
1207 * @param values Array of output pointers (types must match each key's
1208 * documented output type)
1209 * @param[out] out_written On return, receives the number of values
1210 * successfully written (may be NULL)
1211 * @return GHOSTTY_SUCCESS if all queries succeed
1212 *
1213 * @ingroup terminal
1214 */
1215GHOSTTY_API GhosttyResult ghostty_terminal_get_multi(GhosttyTerminal terminal,
1216 size_t count,
1217 const GhosttyTerminalData* keys,
1218 void** values,
1219 size_t* out_written);
1220
1221/**
1222 * Resolve a point in the terminal grid to a grid reference.
1223 *
1224 * Resolves the given point (which can be in active, viewport, screen,
1225 * or history coordinates) to a grid reference for that location. Use
1226 * ghostty_grid_ref_cell() and ghostty_grid_ref_row() to extract the cell
1227 * and row.
1228 *
1229 * Lookups using the `active` and `viewport` tags are fast. The `screen`
1230 * and `history` tags may require traversing the full scrollback page list
1231 * to resolve the y coordinate, so they can be expensive for large
1232 * scrollback buffers.
1233 *
1234 * This function isn't meant to be used as the core of render loop. It
1235 * isn't built to sustain the framerates needed for rendering large screens.
1236 * Use the render state API for that. This API is instead meant for less
1237 * strictly performance-sensitive use cases.
1238 *
1239 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
1240 * @param point The point specifying which cell to look up
1241 * @param[out] out_ref On success, set to the grid reference at the given point (may be NULL)
1242 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal
1243 * is NULL or the point is out of bounds
1244 *
1245 * @ingroup terminal
1246 */
1247GHOSTTY_API GhosttyResult ghostty_terminal_grid_ref(GhosttyTerminal terminal,
1248 GhosttyPoint point,
1249 GhosttyGridRef *out_ref);
1250
1251/**
1252 * Create an owned tracked grid reference for a terminal point.
1253 *
1254 * This is the tracked variant of ghostty_terminal_grid_ref(). The returned
1255 * handle follows the referenced cell as the terminal's page list is modified:
1256 * scrolling, pruning, resize/reflow, and other page-list operations update the
1257 * tracked reference automatically.
1258 *
1259 * The reference is attached to the terminal screen/page-list that is active at
1260 * creation time.
1261 *
1262 * If the point is outside the requested coordinate space, this returns
1263 * GHOSTTY_INVALID_VALUE and writes NULL to out_ref.
1264 *
1265 * The returned handle must be freed with ghostty_tracked_grid_ref_free(). If
1266 * the terminal is freed first, the handle remains valid only for
1267 * tracked-grid-ref APIs: it reports no value and can still be freed.
1268 *
1269 * @param terminal Terminal instance.
1270 * @param point Point to track.
1271 * @param[out] out_ref On success, receives the tracked reference handle.
1272 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if terminal,
1273 * point, or out_ref is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation
1274 * fails.
1275 *
1276 * @ingroup terminal
1277 */
1278GHOSTTY_API GhosttyResult ghostty_terminal_grid_ref_track(
1279 GhosttyTerminal terminal,
1280 GhosttyPoint point,
1281 GhosttyTrackedGridRef *out_ref);
1282
1283/**
1284 * Convert a grid reference back to a point in the given coordinate system.
1285 *
1286 * This is the inverse of ghostty_terminal_grid_ref(): given a grid reference,
1287 * it returns the x/y coordinates in the requested coordinate system (active,
1288 * viewport, screen, or history).
1289 *
1290 * The grid reference must have been obtained from the same terminal instance.
1291 * Like all grid references, it is only valid until the next mutating terminal
1292 * call.
1293 *
1294 * Not every grid reference is representable in every coordinate system. For
1295 * example, a cell in scrollback history cannot be expressed in active
1296 * coordinates, and a cell that has scrolled off the visible area cannot be
1297 * expressed in viewport coordinates. In these cases, the function returns
1298 * GHOSTTY_NO_VALUE.
1299 *
1300 * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE)
1301 * @param ref Pointer to the grid reference to convert
1302 * @param tag The target coordinate system
1303 * @param[out] out On success, set to the coordinate in the requested system (may be NULL)
1304 * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal
1305 * or ref is NULL/invalid, GHOSTTY_NO_VALUE if the ref falls outside
1306 * the requested coordinate system
1307 *
1308 * @ingroup terminal
1309 */
1310GHOSTTY_API GhosttyResult ghostty_terminal_point_from_grid_ref(
1311 GhosttyTerminal terminal,
1312 const GhosttyGridRef *ref,
1313 GhosttyPointTag tag,
1314 GhosttyPointCoordinate *out);
1315
1316/** @} */
1317
1318#ifdef __cplusplus
1319}
1320#endif
1321
1322#endif /* GHOSTTY_VT_TERMINAL_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/types.h+335−0
@@ -0,0 +1,335 @@
1/**
2 * @file types.h
3 *
4 * Common types, macros, and utilities for libghostty-vt.
5 */
6
7#ifndef GHOSTTY_VT_TYPES_H
8#define GHOSTTY_VT_TYPES_H
9
10#include <limits.h>
11#include <stddef.h>
12#include <stdint.h>
13
14// Symbol visibility for shared library builds. On Windows, functions
15// are exported from the DLL when building and imported when consuming.
16// On other platforms with GCC/Clang, functions are marked with default
17// visibility so they remain accessible when the library is built with
18// -fvisibility=hidden. For static library builds, define GHOSTTY_STATIC
19// before including this header to make this a no-op.
20#ifndef GHOSTTY_API
21#if defined(GHOSTTY_STATIC)
22 #define GHOSTTY_API
23#elif defined(_WIN32) || defined(_WIN64)
24 #ifdef GHOSTTY_BUILD_SHARED
25 #define GHOSTTY_API __declspec(dllexport)
26 #else
27 #define GHOSTTY_API __declspec(dllimport)
28 #endif
29#elif defined(__GNUC__) && __GNUC__ >= 4
30 #define GHOSTTY_API __attribute__((visibility("default")))
31#else
32 #define GHOSTTY_API
33#endif
34#endif
35
36/**
37 * Enum int-sizing helpers.
38 *
39 * The Zig side backs all C enums with c_int, so the C declarations
40 * must use int as their underlying type to maintain ABI compatibility.
41 *
42 * C23 (detected via __STDC_VERSION__ >= 202311L) supports explicit
43 * enum underlying types with `enum : int { ... }`. For pre-C23
44 * compilers, which are free to choose any type that can represent
45 * all values (C11 §6.7.2.2), we add an INT_MAX sentinel as the last
46 * entry to force the compiler to use int.
47 *
48 * INT_MAX is used rather than a fixed constant like 0xFFFFFFFF
49 * because enum constants must have type int (which is signed).
50 * Values above INT_MAX overflow signed int and are a constraint
51 * violation in standard C; compilers that accept them interpret them
52 * as negative values via two's complement, which can collide with
53 * legitimate negative enum values.
54 *
55 * Usage:
56 * @code
57 * typedef enum GHOSTTY_ENUM_TYPED {
58 * FOO_A = 0,
59 * FOO_B = 1,
60 * FOO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
61 * } Foo;
62 * @endcode
63 */
64#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
65#define GHOSTTY_ENUM_TYPED : int
66#else
67#define GHOSTTY_ENUM_TYPED
68#endif
69#define GHOSTTY_ENUM_MAX_VALUE INT_MAX
70
71/**
72 * Result codes for libghostty-vt operations.
73 */
74typedef enum GHOSTTY_ENUM_TYPED {
75 /** Operation completed successfully */
76 GHOSTTY_SUCCESS = 0,
77 /** Operation failed due to failed allocation */
78 GHOSTTY_OUT_OF_MEMORY = -1,
79 /** Operation failed due to invalid value */
80 GHOSTTY_INVALID_VALUE = -2,
81 /** Operation failed because the provided buffer was too small */
82 GHOSTTY_OUT_OF_SPACE = -3,
83 /** The requested value has no value */
84 GHOSTTY_NO_VALUE = -4,
85 GHOSTTY_RESULT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
86} GhosttyResult;
87
88/* ---- Opaque handles ---- */
89
90/**
91 * Opaque handle to a terminal instance.
92 *
93 * @ingroup terminal
94 */
95typedef struct GhosttyTerminalImpl* GhosttyTerminal;
96
97/**
98 * Opaque handle to a tracked grid reference.
99 *
100 * A tracked grid reference is owned by the caller and must be freed with
101 * ghostty_tracked_grid_ref_free(). If the terminal that created it is freed
102 * first, the handle remains valid only for tracked-grid-ref APIs: it reports no
103 * value and can still be freed.
104 *
105 * @ingroup grid_ref
106 */
107typedef struct GhosttyTrackedGridRefImpl* GhosttyTrackedGridRef;
108
109/**
110 * Opaque handle to a Kitty graphics image storage.
111 *
112 * Obtained via ghostty_terminal_get() with
113 * GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS. The pointer is borrowed from
114 * the terminal and remains valid until the next mutating terminal call
115 * (e.g. ghostty_terminal_vt_write() or ghostty_terminal_reset()).
116 *
117 * @ingroup kitty_graphics
118 */
119typedef struct GhosttyKittyGraphicsImpl* GhosttyKittyGraphics;
120
121/**
122 * Opaque handle to a Kitty graphics image.
123 *
124 * Obtained via ghostty_kitty_graphics_image() with an image ID. The
125 * pointer is borrowed from the storage and remains valid until the next
126 * mutating terminal call.
127 *
128 * @ingroup kitty_graphics
129 */
130typedef const struct GhosttyKittyGraphicsImageImpl* GhosttyKittyGraphicsImage;
131
132/**
133 * Opaque handle to a Kitty graphics placement iterator.
134 *
135 * @ingroup kitty_graphics
136 */
137typedef struct GhosttyKittyGraphicsPlacementIteratorImpl* GhosttyKittyGraphicsPlacementIterator;
138
139/**
140 * Opaque handle to a render state instance.
141 *
142 * @ingroup render
143 */
144typedef struct GhosttyRenderStateImpl* GhosttyRenderState;
145
146/**
147 * Opaque handle to a render-state row iterator.
148 *
149 * @ingroup render
150 */
151typedef struct GhosttyRenderStateRowIteratorImpl* GhosttyRenderStateRowIterator;
152
153/**
154 * Opaque handle to render-state row cells.
155 *
156 * @ingroup render
157 */
158typedef struct GhosttyRenderStateRowCellsImpl* GhosttyRenderStateRowCells;
159
160/**
161 * Opaque handle to an SGR parser instance.
162 *
163 * This handle represents an SGR (Select Graphic Rendition) parser that can
164 * be used to parse SGR sequences and extract individual text attributes.
165 *
166 * @ingroup sgr
167 */
168typedef struct GhosttySgrParserImpl* GhosttySgrParser;
169
170/**
171 * Opaque handle to a formatter instance.
172 *
173 * @ingroup formatter
174 */
175typedef struct GhosttyFormatterImpl* GhosttyFormatter;
176
177/**
178 * Opaque handle to an OSC parser instance.
179 *
180 * This handle represents an OSC (Operating System Command) parser that can
181 * be used to parse the contents of OSC sequences.
182 *
183 * @ingroup osc
184 */
185typedef struct GhosttyOscParserImpl* GhosttyOscParser;
186
187/**
188 * Opaque handle to a single OSC command.
189 *
190 * This handle represents a parsed OSC (Operating System Command) command.
191 * The command can be queried for its type and associated data.
192 *
193 * @ingroup osc
194 */
195typedef struct GhosttyOscCommandImpl* GhosttyOscCommand;
196
197/* ---- Common value types ---- */
198
199/**
200 * Terminal content output format.
201 *
202 * @ingroup formatter
203 */
204typedef enum GHOSTTY_ENUM_TYPED {
205 /** Plain text (no escape sequences). */
206 GHOSTTY_FORMATTER_FORMAT_PLAIN,
207
208 /** VT sequences preserving colors, styles, URLs, etc. */
209 GHOSTTY_FORMATTER_FORMAT_VT,
210
211 /** HTML with inline styles. */
212 GHOSTTY_FORMATTER_FORMAT_HTML,
213 GHOSTTY_FORMATTER_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
214} GhosttyFormatterFormat;
215
216/**
217 * A borrowed byte string (pointer + length).
218 *
219 * The memory is not owned by this struct. The pointer is only valid
220 * for the lifetime documented by the API that produces or consumes it.
221 */
222typedef struct {
223 /** Pointer to the string bytes. */
224 const uint8_t* ptr;
225
226 /** Length of the string in bytes. */
227 size_t len;
228} GhosttyString;
229
230/**
231 * A caller-provided byte buffer.
232 *
233 * APIs that write to this type use `len` for the number of bytes written on
234 * GHOSTTY_SUCCESS and the required byte capacity on GHOSTTY_OUT_OF_SPACE.
235 */
236typedef struct {
237 /** Destination buffer for bytes. May be NULL when cap is 0 to query required size. */
238 uint8_t* ptr;
239
240 /** Capacity of ptr in bytes. */
241 size_t cap;
242
243 /** Bytes written on success, or required byte capacity on GHOSTTY_OUT_OF_SPACE. */
244 size_t len;
245} GhosttyBuffer;
246
247/**
248 * A surface-space position in pixels.
249 *
250 * This is not a terminal grid coordinate. It represents an x/y position in the
251 * rendered surface coordinate space, with (0, 0) at the top-left of the
252 * surface.
253 */
254typedef struct {
255 /** X position in surface pixels. */
256 double x;
257
258 /** Y position in surface pixels. */
259 double y;
260} GhosttySurfacePosition;
261
262/**
263 * A borrowed list of Unicode scalar values.
264 *
265 * Values are encoded as uint32_t scalar values. The memory is not owned by this
266 * struct. The pointer is only valid for the lifetime documented by the API that
267 * consumes or produces it.
268 *
269 * APIs may document special handling for NULL + len 0, such as “use defaults”.
270 */
271typedef struct {
272 /** Pointer to Unicode scalar values. */
273 const uint32_t* ptr;
274
275 /** Number of entries in ptr. */
276 size_t len;
277} GhosttyCodepoints;
278
279/**
280 * Initialize a sized struct to zero and set its size field.
281 *
282 * Sized structs use a `size` field as the first member for ABI
283 * compatibility. This macro zero-initializes the struct and sets the
284 * size field to `sizeof(type)`, which allows the library to detect
285 * which version of the struct the caller was compiled against.
286 *
287 * @param type The struct type to initialize
288 * @return A zero-initialized struct with the size field set
289 *
290 * Example:
291 * @code
292 * GhosttyFormatterTerminalOptions opts = GHOSTTY_INIT_SIZED(GhosttyFormatterTerminalOptions);
293 * opts.emit = GHOSTTY_FORMATTER_FORMAT_PLAIN;
294 * opts.trim = true;
295 * @endcode
296 */
297#define GHOSTTY_INIT_SIZED(type) \
298 ((type){ .size = sizeof(type) })
299
300/**
301 * Return a pointer to a null-terminated JSON string describing the
302 * layout of every C API struct for the current target.
303 *
304 * This is primarily useful for language bindings that can't easily
305 * set C struct fields and need to do so via byte offsets. For example,
306 * WebAssembly modules can't share struct definitions with the host.
307 *
308 * Example (abbreviated):
309 * @code{.json}
310 * {
311 * "GhosttyMouseEncoderSize": {
312 * "size": 40,
313 * "align": 8,
314 * "fields": {
315 * "size": { "offset": 0, "size": 8, "type": "u64" },
316 * "screen_width": { "offset": 8, "size": 4, "type": "u32" },
317 * "screen_height": { "offset": 12, "size": 4, "type": "u32" },
318 * "cell_width": { "offset": 16, "size": 4, "type": "u32" },
319 * "cell_height": { "offset": 20, "size": 4, "type": "u32" },
320 * "padding_top": { "offset": 24, "size": 4, "type": "u32" },
321 * "padding_bottom": { "offset": 28, "size": 4, "type": "u32" },
322 * "padding_right": { "offset": 32, "size": 4, "type": "u32" },
323 * "padding_left": { "offset": 36, "size": 4, "type": "u32" }
324 * }
325 * }
326 * }
327 * @endcode
328 *
329 * The returned pointer is valid for the lifetime of the process.
330 *
331 * @return Pointer to the null-terminated JSON string.
332 */
333GHOSTTY_API const char *ghostty_type_json(void);
334
335#endif /* GHOSTTY_VT_TYPES_H */
apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/wasm.h+160−0
@@ -0,0 +1,160 @@
1/**
2 * @file wasm.h
3 *
4 * WebAssembly utility functions for libghostty-vt.
5 */
6
7#ifndef GHOSTTY_VT_WASM_H
8#define GHOSTTY_VT_WASM_H
9
10#ifdef __wasm__
11
12#include <stddef.h>
13#include <stdint.h>
14#include <ghostty/vt/types.h>
15
16/** @defgroup wasm WebAssembly Utilities
17 *
18 * Convenience functions for allocating various types in WebAssembly builds.
19 * **These are only available the libghostty-vt wasm module.**
20 *
21 * Ghostty relies on pointers to various types for ABI compatibility, and
22 * creating those pointers in Wasm can be tedious. These functions provide
23 * a purely additive set of utilities that simplify memory management in
24 * Wasm environments without changing the core C library API.
25 *
26 * @note These functions always use the default allocator. If you need
27 * custom allocation strategies, you should allocate types manually using
28 * your custom allocator. This is a very rare use case in the WebAssembly
29 * world so these are optimized for simplicity.
30 *
31 * ## Example Usage
32 *
33 * Here's a simple example of using the Wasm utilities with the key encoder:
34 *
35 * @code
36 * const { exports } = wasmInstance;
37 * const view = new DataView(wasmMemory.buffer);
38 *
39 * // Create key encoder
40 * const encoderPtr = exports.ghostty_wasm_alloc_opaque();
41 * exports.ghostty_key_encoder_new(null, encoderPtr);
42 * const encoder = view.getUint32(encoder, true);
43 *
44 * // Configure encoder with Kitty protocol flags
45 * const flagsPtr = exports.ghostty_wasm_alloc_u8();
46 * view.setUint8(flagsPtr, 0x1F);
47 * exports.ghostty_key_encoder_setopt(encoder, 5, flagsPtr);
48 *
49 * // Allocate output buffer and size pointer
50 * const bufferSize = 32;
51 * const bufPtr = exports.ghostty_wasm_alloc_u8_array(bufferSize);
52 * const writtenPtr = exports.ghostty_wasm_alloc_usize();
53 *
54 * // Encode the key event
55 * exports.ghostty_key_encoder_encode(
56 * encoder, eventPtr, bufPtr, bufferSize, writtenPtr
57 * );
58 *
59 * // Read encoded output
60 * const bytesWritten = view.getUint32(writtenPtr, true);
61 * const encoded = new Uint8Array(wasmMemory.buffer, bufPtr, bytesWritten);
62 * @endcode
63 *
64 * @remark The code above is pretty ugly! This is the lowest level interface
65 * to the libghostty-vt Wasm module. In practice, this should be wrapped
66 * in a higher-level API that abstracts away all this.
67 *
68 * @{
69 */
70
71/**
72 * Allocate an opaque pointer. This can be used for any opaque pointer
73 * types such as GhosttyKeyEncoder, GhosttyKeyEvent, etc.
74 *
75 * @return Pointer to allocated opaque pointer, or NULL if allocation failed
76 * @ingroup wasm
77 */
78GHOSTTY_API void** ghostty_wasm_alloc_opaque(void);
79
80/**
81 * Free an opaque pointer allocated by ghostty_wasm_alloc_opaque().
82 *
83 * @param ptr Pointer to free, or NULL (NULL is safely ignored)
84 * @ingroup wasm
85 */
86GHOSTTY_API void ghostty_wasm_free_opaque(void **ptr);
87
88/**
89 * Allocate an array of uint8_t values.
90 *
91 * @param len Number of uint8_t elements to allocate
92 * @return Pointer to allocated array, or NULL if allocation failed
93 * @ingroup wasm
94 */
95GHOSTTY_API uint8_t* ghostty_wasm_alloc_u8_array(size_t len);
96
97/**
98 * Free an array allocated by ghostty_wasm_alloc_u8_array().
99 *
100 * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored)
101 * @param len Length of the array (must match the length passed to alloc)
102 * @ingroup wasm
103 */
104GHOSTTY_API void ghostty_wasm_free_u8_array(uint8_t *ptr, size_t len);
105
106/**
107 * Allocate an array of uint16_t values.
108 *
109 * @param len Number of uint16_t elements to allocate
110 * @return Pointer to allocated array, or NULL if allocation failed
111 * @ingroup wasm
112 */
113GHOSTTY_API uint16_t* ghostty_wasm_alloc_u16_array(size_t len);
114
115/**
116 * Free an array allocated by ghostty_wasm_alloc_u16_array().
117 *
118 * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored)
119 * @param len Length of the array (must match the length passed to alloc)
120 * @ingroup wasm
121 */
122GHOSTTY_API void ghostty_wasm_free_u16_array(uint16_t *ptr, size_t len);
123
124/**
125 * Allocate a single uint8_t value.
126 *
127 * @return Pointer to allocated uint8_t, or NULL if allocation failed
128 * @ingroup wasm
129 */
130GHOSTTY_API uint8_t* ghostty_wasm_alloc_u8(void);
131
132/**
133 * Free a uint8_t allocated by ghostty_wasm_alloc_u8().
134 *
135 * @param ptr Pointer to free, or NULL (NULL is safely ignored)
136 * @ingroup wasm
137 */
138GHOSTTY_API void ghostty_wasm_free_u8(uint8_t *ptr);
139
140/**
141 * Allocate a single size_t value.
142 *
143 * @return Pointer to allocated size_t, or NULL if allocation failed
144 * @ingroup wasm
145 */
146GHOSTTY_API size_t* ghostty_wasm_alloc_usize(void);
147
148/**
149 * Free a size_t allocated by ghostty_wasm_alloc_usize().
150 *
151 * @param ptr Pointer to free, or NULL (NULL is safely ignored)
152 * @ingroup wasm
153 */
154GHOSTTY_API void ghostty_wasm_free_usize(size_t *ptr);
155
156/** @} */
157
158#endif /* __wasm__ */
159
160#endif /* GHOSTTY_VT_WASM_H */
apps/mobile/modules/t3-terminal/android/.gitignore+1−0
@@ -0,0 +1 @@
1.cxx/
apps/mobile/modules/t3-terminal/android/build.gradle+14−0
@@ -6,11 +6,25 @@ version = '0.0.0' · 5 unmodified lines
6 6
7android {7android {
8 namespace 'expo.modules.t3terminal'8 namespace 'expo.modules.t3terminal'
9 ndkVersion rootProject.ext.ndkVersion
9 compileSdk rootProject.ext.compileSdkVersion10 compileSdk rootProject.ext.compileSdkVersion
10 11
11 defaultConfig {12 defaultConfig {
12 minSdkVersion rootProject.ext.minSdkVersion13 minSdkVersion rootProject.ext.minSdkVersion
13 targetSdkVersion rootProject.ext.targetSdkVersion14 targetSdkVersion rootProject.ext.targetSdkVersion
15
16 externalNativeBuild {
17 cmake {
18 cppFlags '-std=c++17 -Wall -Wextra -Werror'
19 }
20 }
21 }
22
23 externalNativeBuild {
24 cmake {
25 path 'src/main/cpp/CMakeLists.txt'
26 version '3.22.1'
27 }
14 }28 }
15}29}
16 30
apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Bold.ttf+0−0

Binary file not shown.

apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Regular.ttf+0−0

Binary file not shown.

apps/mobile/modules/t3-terminal/android/src/main/cpp/CMakeLists.txt+23−0
@@ -0,0 +1,23 @@
1cmake_minimum_required(VERSION 3.22.1)
2
3project(t3terminal LANGUAGES CXX)
4
5add_library(ghostty-vt SHARED IMPORTED)
6set_target_properties(
7 ghostty-vt
8 PROPERTIES IMPORTED_LOCATION
9 "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libghostty-vt.so"
10)
11
12add_library(t3terminal SHARED t3_terminal_jni.cpp)
13
14target_include_directories(
15 t3terminal
16 PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include"
17)
18
19target_link_options(
20 t3terminal PRIVATE "-Wl,-z,common-page-size=16384" "-Wl,-z,max-page-size=16384"
21)
22
23target_link_libraries(t3terminal PRIVATE ghostty-vt log)
apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp+516−0
@@ -0,0 +1,516 @@
1#include <jni.h>
2
3#include <algorithm>
4#include <cstdint>
5#include <mutex>
6#include <utility>
7#include <vector>
8
9#include <ghostty/vt.h>
10
11namespace {
12
13constexpr uint32_t kSnapshotMagic = 0x54563354; // "T3VT" in little endian.
14constexpr uint16_t kSnapshotVersion = 1;
15constexpr size_t kMaxScrollbackRows = 10000;
16
17enum CellFlag : uint16_t {
18 kBold = 1 << 0,
19 kItalic = 1 << 1,
20 kFaint = 1 << 2,
21 kInverse = 1 << 3,
22 kInvisible = 1 << 4,
23 kStrikethrough = 1 << 5,
24 kOverline = 1 << 6,
25 kUnderline = 1 << 7,
26 kSelected = 1 << 8,
27};
28
29struct Session {
30 GhosttyTerminal terminal = nullptr;
31 GhosttyRenderState render_state = nullptr;
32 GhosttyRenderStateRowIterator row_iterator = nullptr;
33 GhosttyRenderStateRowCells row_cells = nullptr;
34 std::vector<uint8_t> responses;
35 std::mutex mutex;
36};
37
38class ByteWriter {
39 public:
40 explicit ByteWriter(size_t capacity) { bytes_.reserve(capacity); }
41
42 void U8(uint8_t value) { bytes_.push_back(value); }
43
44 void U16(uint16_t value) {
45 U8(static_cast<uint8_t>(value));
46 U8(static_cast<uint8_t>(value >> 8));
47 }
48
49 void U32(uint32_t value) {
50 U16(static_cast<uint16_t>(value));
51 U16(static_cast<uint16_t>(value >> 16));
52 }
53
54 void Bytes(const std::vector<uint8_t>& value) {
55 bytes_.insert(bytes_.end(), value.begin(), value.end());
56 }
57
58 std::vector<uint8_t> Take() { return std::move(bytes_); }
59
60 private:
61 std::vector<uint8_t> bytes_;
62};
63
64Session* FromHandle(jlong handle) {
65 return reinterpret_cast<Session*>(static_cast<intptr_t>(handle));
66}
67
68jbyteArray ToJavaBytes(JNIEnv* env, const std::vector<uint8_t>& bytes) {
69 auto result = env->NewByteArray(static_cast<jsize>(bytes.size()));
70 if (result != nullptr && !bytes.empty()) {
71 env->SetByteArrayRegion(result, 0, static_cast<jsize>(bytes.size()),
72 reinterpret_cast<const jbyte*>(bytes.data()));
73 }
74 return result;
75}
76
77GhosttyColorRgb RgbFromArgb(jint color) {
78 const auto value = static_cast<uint32_t>(color);
79 return {
80 .r = static_cast<uint8_t>(value >> 16),
81 .g = static_cast<uint8_t>(value >> 8),
82 .b = static_cast<uint8_t>(value),
83 };
84}
85
86uint32_t ArgbFromRgb(GhosttyColorRgb color) {
87 return 0xFF000000U | (static_cast<uint32_t>(color.r) << 16U) |
88 (static_cast<uint32_t>(color.g) << 8U) | color.b;
89}
90
91GhosttyColorRgb Blend(GhosttyColorRgb foreground, GhosttyColorRgb background,
92 uint8_t foreground_weight) {
93 const auto blend = [foreground_weight](uint8_t front, uint8_t back) {
94 const uint16_t back_weight = 255 - foreground_weight;
95 return static_cast<uint8_t>((front * foreground_weight + back * back_weight) / 255);
96 };
97 return {
98 .r = blend(foreground.r, background.r),
99 .g = blend(foreground.g, background.g),
100 .b = blend(foreground.b, background.b),
101 };
102}
103
104void AppendUtf8(std::vector<uint8_t>* output, uint32_t codepoint) {
105 if (codepoint <= 0x7F) {
106 output->push_back(static_cast<uint8_t>(codepoint));
107 } else if (codepoint <= 0x7FF) {
108 output->push_back(static_cast<uint8_t>(0xC0 | (codepoint >> 6)));
109 output->push_back(static_cast<uint8_t>(0x80 | (codepoint & 0x3F)));
110 } else if (codepoint <= 0xFFFF && !(codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
111 output->push_back(static_cast<uint8_t>(0xE0 | (codepoint >> 12)));
112 output->push_back(static_cast<uint8_t>(0x80 | ((codepoint >> 6) & 0x3F)));
113 output->push_back(static_cast<uint8_t>(0x80 | (codepoint & 0x3F)));
114 } else if (codepoint <= 0x10FFFF) {
115 output->push_back(static_cast<uint8_t>(0xF0 | (codepoint >> 18)));
116 output->push_back(static_cast<uint8_t>(0x80 | ((codepoint >> 12) & 0x3F)));
117 output->push_back(static_cast<uint8_t>(0x80 | ((codepoint >> 6) & 0x3F)));
118 output->push_back(static_cast<uint8_t>(0x80 | (codepoint & 0x3F)));
119 }
120}
121
122void OnWritePty(GhosttyTerminal, void* userdata, const uint8_t* data, size_t len) {
123 auto* session = static_cast<Session*>(userdata);
124 if (session == nullptr || data == nullptr || len == 0) return;
125 session->responses.insert(session->responses.end(), data, data + len);
126}
127
128void ApplyTheme(Session* session, jint foreground, jint background, jint cursor,
129 JNIEnv* env, jintArray palette_array) {
130 auto foreground_rgb = RgbFromArgb(foreground);
131 auto background_rgb = RgbFromArgb(background);
132 auto cursor_rgb = RgbFromArgb(cursor);
133 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND,
134 &foreground_rgb);
135 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND,
136 &background_rgb);
137 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_CURSOR, &cursor_rgb);
138
139 if (palette_array == nullptr) return;
140 const auto palette_length = env->GetArrayLength(palette_array);
141 if (palette_length <= 0) return;
142
143 GhosttyColorRgb palette[256];
144 if (ghostty_terminal_get(session->terminal,
145 GHOSTTY_TERMINAL_DATA_COLOR_PALETTE_DEFAULT,
146 palette) != GHOSTTY_SUCCESS) {
147 return;
148 }
149
150 const auto copied_length = std::min<jsize>(palette_length, 256);
151 std::vector<jint> colors(static_cast<size_t>(copied_length));
152 env->GetIntArrayRegion(palette_array, 0, copied_length, colors.data());
153 for (jsize index = 0; index < copied_length; ++index) {
154 palette[index] = RgbFromArgb(colors[index]);
155 }
156 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_PALETTE, palette);
157}
158
159void FreeSession(Session* session) {
160 if (session == nullptr) return;
161 ghostty_render_state_row_cells_free(session->row_cells);
162 ghostty_render_state_row_iterator_free(session->row_iterator);
163 ghostty_render_state_free(session->render_state);
164 ghostty_terminal_free(session->terminal);
165 delete session;
166}
167
168std::vector<uint8_t> DrainResponses(Session* session) {
169 std::vector<uint8_t> responses;
170 responses.swap(session->responses);
171 return responses;
172}
173
174bool ViewportGridRef(Session* session, jint x, jint y, GhosttyGridRef* out) {
175 *out = GhosttyGridRef{};
176 out->size = sizeof(*out);
177 GhosttyPoint point{};
178 point.tag = GHOSTTY_POINT_TAG_VIEWPORT;
179 point.value.coordinate.x = static_cast<uint16_t>(std::max<jint>(x, 0));
180 point.value.coordinate.y = static_cast<uint32_t>(std::max<jint>(y, 0));
181 return ghostty_terminal_grid_ref(session->terminal, point, out) == GHOSTTY_SUCCESS;
182}
183
184uint16_t StyleFlags(const GhosttyStyle& style, bool selected) {
185 uint16_t flags = 0;
186 if (style.bold) flags |= kBold;
187 if (style.italic) flags |= kItalic;
188 if (style.faint) flags |= kFaint;
189 if (style.inverse) flags |= kInverse;
190 if (style.invisible) flags |= kInvisible;
191 if (style.strikethrough) flags |= kStrikethrough;
192 if (style.overline) flags |= kOverline;
193 if (style.underline != 0) flags |= kUnderline;
194 if (selected) flags |= kSelected;
195 return flags;
196}
197
198} // namespace
199
200extern "C" JNIEXPORT jlong JNICALL
201Java_expo_modules_t3terminal_GhosttyBridge_nativeCreate(
202 JNIEnv* env, jclass, jint cols, jint rows, jint cell_width, jint cell_height,
203 jint foreground, jint background, jint cursor, jintArray palette) {
204 auto* session = new Session();
205 GhosttyTerminalOptions options = {
206 .cols = static_cast<uint16_t>(std::clamp(cols, 1, 65535)),
207 .rows = static_cast<uint16_t>(std::clamp(rows, 1, 65535)),
208 .max_scrollback = kMaxScrollbackRows,
209 };
210 if (ghostty_terminal_new(nullptr, &session->terminal, options) != GHOSTTY_SUCCESS ||
211 ghostty_render_state_new(nullptr, &session->render_state) != GHOSTTY_SUCCESS ||
212 ghostty_render_state_row_iterator_new(nullptr, &session->row_iterator) != GHOSTTY_SUCCESS ||
213 ghostty_render_state_row_cells_new(nullptr, &session->row_cells) != GHOSTTY_SUCCESS) {
214 FreeSession(session);
215 return 0;
216 }
217
218 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_USERDATA, session);
219 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_WRITE_PTY,
220 reinterpret_cast<const void*>(OnWritePty));
221 ApplyTheme(session, foreground, background, cursor, env, palette);
222 ghostty_terminal_resize(session->terminal, options.cols, options.rows,
223 static_cast<uint32_t>(std::max(cell_width, 1)),
224 static_cast<uint32_t>(std::max(cell_height, 1)));
225 return static_cast<jlong>(reinterpret_cast<intptr_t>(session));
226}
227
228extern "C" JNIEXPORT void JNICALL
229Java_expo_modules_t3terminal_GhosttyBridge_nativeDestroy(JNIEnv*, jclass, jlong handle) {
230 FreeSession(FromHandle(handle));
231}
232
233extern "C" JNIEXPORT jbyteArray JNICALL
234Java_expo_modules_t3terminal_GhosttyBridge_nativeFeed(JNIEnv* env, jclass, jlong handle,
235 jbyteArray data) {
236 auto* session = FromHandle(handle);
237 if (session == nullptr || data == nullptr) return env->NewByteArray(0);
238 std::lock_guard<std::mutex> lock(session->mutex);
239 const auto length = env->GetArrayLength(data);
240 std::vector<uint8_t> bytes(static_cast<size_t>(length));
241 if (length > 0) {
242 env->GetByteArrayRegion(data, 0, length, reinterpret_cast<jbyte*>(bytes.data()));
243 ghostty_terminal_vt_write(session->terminal, bytes.data(), bytes.size());
244 }
245 return ToJavaBytes(env, DrainResponses(session));
246}
247
248extern "C" JNIEXPORT jbyteArray JNICALL
249Java_expo_modules_t3terminal_GhosttyBridge_nativeResize(
250 JNIEnv* env, jclass, jlong handle, jint cols, jint rows, jint cell_width, jint cell_height) {
251 auto* session = FromHandle(handle);
252 if (session == nullptr) return env->NewByteArray(0);
253 std::lock_guard<std::mutex> lock(session->mutex);
254 ghostty_terminal_resize(session->terminal,
255 static_cast<uint16_t>(std::clamp(cols, 1, 65535)),
256 static_cast<uint16_t>(std::clamp(rows, 1, 65535)),
257 static_cast<uint32_t>(std::max(cell_width, 1)),
258 static_cast<uint32_t>(std::max(cell_height, 1)));
259 return ToJavaBytes(env, DrainResponses(session));
260}
261
262extern "C" JNIEXPORT void JNICALL
263Java_expo_modules_t3terminal_GhosttyBridge_nativeScroll(JNIEnv*, jclass, jlong handle,
264 jint rows) {
265 auto* session = FromHandle(handle);
266 if (session == nullptr || rows == 0) return;
267 std::lock_guard<std::mutex> lock(session->mutex);
268 GhosttyTerminalScrollViewport scroll = {
269 .tag = GHOSTTY_SCROLL_VIEWPORT_DELTA,
270 .value = {.delta = rows},
271 };
272 ghostty_terminal_scroll_viewport(session->terminal, scroll);
273}
274
275extern "C" JNIEXPORT void JNICALL
276Java_expo_modules_t3terminal_GhosttyBridge_nativeSetTheme(
277 JNIEnv* env, jclass, jlong handle, jint foreground, jint background, jint cursor,
278 jintArray palette) {
279 auto* session = FromHandle(handle);
280 if (session == nullptr) return;
281 std::lock_guard<std::mutex> lock(session->mutex);
282 ApplyTheme(session, foreground, background, cursor, env, palette);
283}
284
285extern "C" JNIEXPORT jboolean JNICALL
286Java_expo_modules_t3terminal_GhosttyBridge_nativeSelectWordAt(JNIEnv*, jclass,
287 jlong handle, jint x,
288 jint y) {
289 auto* session = FromHandle(handle);
290 if (session == nullptr) return JNI_FALSE;
291 std::lock_guard<std::mutex> lock(session->mutex);
292 GhosttyTerminalSelectWordOptions options{};
293 options.size = sizeof(options);
294 if (!ViewportGridRef(session, x, y, &options.ref)) return JNI_FALSE;
295 GhosttySelection selection{};
296 selection.size = sizeof(selection);
297 if (ghostty_terminal_select_word(session->terminal, &options, &selection) !=
298 GHOSTTY_SUCCESS) {
299 return JNI_FALSE;
300 }
301 return ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION,
302 &selection) == GHOSTTY_SUCCESS
303 ? JNI_TRUE
304 : JNI_FALSE;
305}
306
307extern "C" JNIEXPORT void JNICALL
308Java_expo_modules_t3terminal_GhosttyBridge_nativeExtendSelection(
309 JNIEnv*, jclass, jlong handle, jint anchor_x, jint anchor_y, jint x, jint y) {
310 auto* session = FromHandle(handle);
311 if (session == nullptr) return;
312 std::lock_guard<std::mutex> lock(session->mutex);
313 GhosttySelection selection{};
314 selection.size = sizeof(selection);
315 if (!ViewportGridRef(session, anchor_x, anchor_y, &selection.start)) return;
316 if (!ViewportGridRef(session, x, y, &selection.end)) return;
317 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, &selection);
318}
319
320extern "C" JNIEXPORT jboolean JNICALL
321Java_expo_modules_t3terminal_GhosttyBridge_nativeSelectAll(JNIEnv*, jclass,
322 jlong handle) {
323 auto* session = FromHandle(handle);
324 if (session == nullptr) return JNI_FALSE;
325 std::lock_guard<std::mutex> lock(session->mutex);
326 GhosttySelection selection{};
327 selection.size = sizeof(selection);
328 if (ghostty_terminal_select_all(session->terminal, &selection) != GHOSTTY_SUCCESS) {
329 return JNI_FALSE;
330 }
331 return ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION,
332 &selection) == GHOSTTY_SUCCESS
333 ? JNI_TRUE
334 : JNI_FALSE;
335}
336
337extern "C" JNIEXPORT void JNICALL
338Java_expo_modules_t3terminal_GhosttyBridge_nativeClearSelection(JNIEnv*, jclass,
339 jlong handle) {
340 auto* session = FromHandle(handle);
341 if (session == nullptr) return;
342 std::lock_guard<std::mutex> lock(session->mutex);
343 ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, nullptr);
344}
345
346// Returns the active selection as UTF-8 bytes (soft-wrapped lines unwrapped,
347// trailing whitespace trimmed), or null when there is no selection.
348extern "C" JNIEXPORT jbyteArray JNICALL
349Java_expo_modules_t3terminal_GhosttyBridge_nativeGetSelectionText(JNIEnv* env, jclass,
350 jlong handle) {
351 auto* session = FromHandle(handle);
352 if (session == nullptr) return nullptr;
353 std::lock_guard<std::mutex> lock(session->mutex);
354 GhosttyTerminalSelectionFormatOptions options{};
355 options.size = sizeof(options);
356 options.emit = GHOSTTY_FORMATTER_FORMAT_PLAIN;
357 options.unwrap = true;
358 options.trim = true;
359 uint8_t* bytes = nullptr;
360 size_t len = 0;
361 if (ghostty_terminal_selection_format_alloc(session->terminal, nullptr, options,
362 &bytes, &len) != GHOSTTY_SUCCESS ||
363 bytes == nullptr) {
364 return nullptr;
365 }
366 auto result = env->NewByteArray(static_cast<jsize>(len));
367 if (result != nullptr && len > 0) {
368 env->SetByteArrayRegion(result, 0, static_cast<jsize>(len),
369 reinterpret_cast<const jbyte*>(bytes));
370 }
371 ghostty_free(nullptr, bytes, len);
372 return result;
373}
374
375extern "C" JNIEXPORT jbyteArray JNICALL
376Java_expo_modules_t3terminal_GhosttyBridge_nativeSnapshot(JNIEnv* env, jclass,
377 jlong handle) {
378 auto* session = FromHandle(handle);
379 if (session == nullptr) return env->NewByteArray(0);
380 std::lock_guard<std::mutex> lock(session->mutex);
381
382 if (ghostty_render_state_update(session->render_state, session->terminal) != GHOSTTY_SUCCESS) {
383 return env->NewByteArray(0);
384 }
385
386 uint16_t cols = 0;
387 uint16_t rows = 0;
388 bool cursor_visible = false;
389 bool cursor_in_viewport = false;
390 bool cursor_blinking = false;
391 uint16_t cursor_x = 0xFFFF;
392 uint16_t cursor_y = 0xFFFF;
393 GhosttyRenderStateCursorVisualStyle cursor_style =
394 GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK;
395 ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_COLS, &cols);
396 ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_ROWS, &rows);
397 ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE,
398 &cursor_visible);
399 ghostty_render_state_get(session->render_state,
400 GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE,
401 &cursor_in_viewport);
402 ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_CURSOR_BLINKING,
403 &cursor_blinking);
404 ghostty_render_state_get(session->render_state,
405 GHOSTTY_RENDER_STATE_DATA_CURSOR_VISUAL_STYLE, &cursor_style);
406 if (cursor_in_viewport) {
407 ghostty_render_state_get(session->render_state,
408 GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X, &cursor_x);
409 ghostty_render_state_get(session->render_state,
410 GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y, &cursor_y);
411 }
412
413 GhosttyRenderStateColors colors{};
414 colors.size = sizeof(colors);
415 if (ghostty_render_state_colors_get(session->render_state, &colors) != GHOSTTY_SUCCESS) {
416 return env->NewByteArray(0);
417 }
418 const auto cursor_color = colors.cursor_has_value ? colors.cursor : colors.foreground;
419
420 ByteWriter writer(32 + static_cast<size_t>(cols) * rows * 14);
421 writer.U32(kSnapshotMagic);
422 writer.U16(kSnapshotVersion);
423 writer.U16(cols);
424 writer.U16(rows);
425 writer.U16(cursor_x);
426 writer.U16(cursor_y);
427 writer.U8(cursor_visible && cursor_in_viewport ? 1 : 0);
428 writer.U8(static_cast<uint8_t>(cursor_style));
429 writer.U8(cursor_blinking ? 1 : 0);
430 writer.U8(0);
431 writer.U32(ArgbFromRgb(colors.foreground));
432 writer.U32(ArgbFromRgb(colors.background));
433 writer.U32(ArgbFromRgb(cursor_color));
434
435 if (ghostty_render_state_get(session->render_state,
436 GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR,
437 &session->row_iterator) != GHOSTTY_SUCCESS) {
438 return env->NewByteArray(0);
439 }
440
441 uint16_t written_rows = 0;
442 while (written_rows < rows &&
443 ghostty_render_state_row_iterator_next(session->row_iterator)) {
444 if (ghostty_render_state_row_get(session->row_iterator,
445 GHOSTTY_RENDER_STATE_ROW_DATA_CELLS,
446 &session->row_cells) != GHOSTTY_SUCCESS) {
447 break;
448 }
449
450 uint16_t written_cols = 0;
451 while (written_cols < cols && ghostty_render_state_row_cells_next(session->row_cells)) {
452 GhosttyStyle style{};
453 style.size = sizeof(style);
454 bool selected = false;
455 GhosttyColorRgb foreground = colors.foreground;
456 GhosttyColorRgb background = colors.background;
457 ghostty_render_state_row_cells_get(session->row_cells,
458 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE,
459 &style);
460 ghostty_render_state_row_cells_get(session->row_cells,
461 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_SELECTED,
462 &selected);
463 ghostty_render_state_row_cells_get(session->row_cells,
464 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR,
465 &foreground);
466 ghostty_render_state_row_cells_get(session->row_cells,
467 GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR,
468 &background);
469 if (style.inverse) std::swap(foreground, background);
470 if (style.faint) foreground = Blend(foreground, background, 155);
471
472 uint32_t grapheme_count = 0;
473 ghostty_render_state_row_cells_get(
474 session->row_cells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN,
475 &grapheme_count);
476 std::vector<uint8_t> utf8;
477 if (grapheme_count > 0) {
478 std::vector<uint32_t> codepoints(grapheme_count);
479 if (ghostty_render_state_row_cells_get(
480 session->row_cells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF,
481 codepoints.data()) == GHOSTTY_SUCCESS) {
482 utf8.reserve(grapheme_count * 4);
483 for (const auto codepoint : codepoints) AppendUtf8(&utf8, codepoint);
484 }
485 }
486
487 const auto text_length = static_cast<uint16_t>(std::min<size_t>(utf8.size(), 65535));
488 writer.U32(ArgbFromRgb(foreground));
489 writer.U32(ArgbFromRgb(background));
490 writer.U16(StyleFlags(style, selected));
491 writer.U16(text_length);
492 if (text_length != utf8.size()) utf8.resize(text_length);
493 writer.Bytes(utf8);
494 ++written_cols;
495 }
496
497 while (written_cols++ < cols) {
498 writer.U32(ArgbFromRgb(colors.foreground));
499 writer.U32(ArgbFromRgb(colors.background));
500 writer.U16(0);
501 writer.U16(0);
502 }
503 ++written_rows;
504 }
505
506 while (written_rows++ < rows) {
507 for (uint16_t column = 0; column < cols; ++column) {
508 writer.U32(ArgbFromRgb(colors.foreground));
509 writer.U32(ArgbFromRgb(colors.background));
510 writer.U16(0);
511 writer.U16(0);
512 }
513 }
514
515 return ToJavaBytes(env, writer.Take());
516}
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/GhosttyBridge.kt+64−0
@@ -0,0 +1,64 @@
1package expo.modules.t3terminal
2
3internal object GhosttyBridge {
4 init {
5 System.loadLibrary("ghostty-vt")
6 System.loadLibrary("t3terminal")
7 }
8
9 @JvmStatic
10 @Suppress("LongParameterList")
11 external fun nativeCreate(
12 cols: Int,
13 rows: Int,
14 cellWidth: Int,
15 cellHeight: Int,
16 foreground: Int,
17 background: Int,
18 cursor: Int,
19 palette: IntArray
20 ): Long
21
22 @JvmStatic external fun nativeDestroy(handle: Long)
23
24 @JvmStatic external fun nativeFeed(handle: Long, data: ByteArray): ByteArray
25
26 @JvmStatic
27 external fun nativeResize(
28 handle: Long,
29 cols: Int,
30 rows: Int,
31 cellWidth: Int,
32 cellHeight: Int
33 ): ByteArray
34
35 @JvmStatic external fun nativeScroll(handle: Long, rows: Int)
36
37 @JvmStatic
38 external fun nativeSetTheme(
39 handle: Long,
40 foreground: Int,
41 background: Int,
42 cursor: Int,
43 palette: IntArray
44 )
45
46 @JvmStatic external fun nativeSnapshot(handle: Long): ByteArray
47
48 @JvmStatic external fun nativeSelectWordAt(handle: Long, col: Int, row: Int): Boolean
49
50 @JvmStatic
51 external fun nativeExtendSelection(
52 handle: Long,
53 anchorCol: Int,
54 anchorRow: Int,
55 col: Int,
56 row: Int
57 )
58
59 @JvmStatic external fun nativeSelectAll(handle: Long): Boolean
60
61 @JvmStatic external fun nativeClearSelection(handle: Long)
62
63 @JvmStatic external fun nativeGetSelectionText(handle: Long): ByteArray?
64}
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt+18−0
@@ -7,6 +7,12 @@ class T3TerminalModule : Module() { · 6 unmodified lines
7 override fun definition() = ModuleDefinition {7 override fun definition() = ModuleDefinition {
8 Name("T3TerminalSurface")8 Name("T3TerminalSurface")
9 9
10 // Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
11 // logs so a stale native binary is distinguishable from a broken key pipeline.
12 Constants(
13 "hardwareKeyRevision" to 2,
14 )
15
10 View(T3TerminalView::class) {16 View(T3TerminalView::class) {
11 Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->17 Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
12 view.terminalKey = terminalKey18 view.terminalKey = terminalKey
@@ -20,6 +26,14 @@ class T3TerminalModule : Module() { · 7 unmodified lines
20 view.fontSize = fontSize.toFloat()26 view.fontSize = fontSize.toFloat()
21 }27 }
22 28
29 Prop("focusRequest") { view: T3TerminalView, focusRequest: Double ->
30 view.focusRequest = focusRequest
31 }
32
33 Prop("autoFocus") { view: T3TerminalView, autoFocus: Boolean ->
34 view.autoFocus = autoFocus
35 }
36
23 Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->37 Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
24 view.appearanceScheme = appearanceScheme38 view.appearanceScheme = appearanceScheme
25 }39 }
@@ -41,6 +55,10 @@ class T3TerminalModule : Module() { · 15 unmodified lines
41 }55 }
42 56
43 Events("onInput", "onResize")57 Events("onInput", "onResize")
58
59 OnViewDestroys { view: T3TerminalView ->
60 view.cleanup()
61 }
44 }62 }
45 }63 }
46}64}
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt+327−101
@@ -3,64 +3,89 @@ package expo.modules.t3terminal · 2 unmodified lines
3import android.content.Context3import android.content.Context
4import android.graphics.Color4import android.graphics.Color
5import android.graphics.Typeface5import android.graphics.Typeface
6import android.view.View6import android.text.Editable
7import android.text.InputType
8import android.text.TextWatcher
9import android.view.KeyEvent
7import android.view.ViewGroup10import android.view.ViewGroup
8import android.view.inputmethod.InputMethodManager
9import android.view.inputmethod.EditorInfo11import android.view.inputmethod.EditorInfo
12import android.view.inputmethod.InputMethodManager
10import android.widget.EditText13import android.widget.EditText
11import android.widget.LinearLayout14import android.widget.FrameLayout
12import android.widget.ScrollView
13import android.widget.TextView
14import androidx.core.widget.doAfterTextChanged
15import expo.modules.kotlin.AppContext15import expo.modules.kotlin.AppContext
16import expo.modules.kotlin.views.ExpoView
17import expo.modules.kotlin.viewevent.EventDispatcher16import expo.modules.kotlin.viewevent.EventDispatcher
17import expo.modules.kotlin.views.ExpoView
18import kotlin.math.max18import kotlin.math.max
19import kotlin.math.min
20 19
21class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {20class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
22 private val container = LinearLayout(context)21 private val container = FrameLayout(context)
23 private val scrollView = ScrollView(context)22 private val terminalCanvas = TerminalCanvasView(context)
24 private val textView = TextView(context)
25 private val inputView = EditText(context)23 private val inputView = EditText(context)
26 private val onInput by EventDispatcher()24 private val onInput by EventDispatcher()
27 private val onResize by EventDispatcher()25 private val onResize by EventDispatcher()
28 private var lastWidth = 026 private var terminalHandle = 0L
29 private var lastHeight = 027 private var fedBuffer = ""
28 private var cols = 0
29 private var rows = 0
30 private var clearingInput = false30 private var clearingInput = false
31 private var isCleanedUp = false
31 private var backgroundColorValue = Color.parseColor("#24292E")32 private var backgroundColorValue = Color.parseColor("#24292E")
32 private var foregroundColorValue = Color.parseColor("#D1D5DA")33 private var foregroundColorValue = Color.parseColor("#D1D5DA")
33 private var mutedForegroundColorValue = Color.parseColor("#959DA5")34 private var mutedForegroundColorValue = Color.parseColor("#959DA5")
35 private var cursorColorValue = Color.parseColor("#009FFF")
36 private var paletteColors = IntArray(0)
34 37
35 var terminalKey: String = ""38 var terminalKey: String = ""
36 set(value) {39 set(value) {
40 if (field == value) return
37 field = value41 field = value
38 contentDescription = "t3-terminal-$value"42 contentDescription = "t3-terminal-$value"
43 recreateTerminal()
39 }44 }
40 45
41 var initialBuffer: String = ""46 var initialBuffer: String = ""
42 set(value) {47 set(value) {
48 if (field == value) return
43 field = value49 field = value
44 textView.text = value.ifEmpty { "$ " }50 feedPendingBuffer()
45 scrollView.post {
46 scrollView.fullScroll(View.FOCUS_DOWN)
47 }
48 }51 }
49 52
50 var fontSize: Float = 10f53 var fontSize: Float = 10f
51 set(value) {54 set(value) {
52 field = value55 field = value
53 textView.textSize = value56 terminalCanvas.fontSizeSp = value
54 inputView.textSize = max(value, 13f)57 inputView.textSize = max(value, 13f)
55 emitResize()58 emitResize()
56 }59 }
57 60
58 var appearanceScheme: String = "dark"61 var appearanceScheme: String = "dark"
62
63 var themeConfig: String = ""
59 set(value) {64 set(value) {
60 field = value65 field = value
66 parseThemeConfig(value)
67 applyTheme()
61 }68 }
62 69
63 var themeConfig: String = ""70 var focusRequest: Double = 0.0
71 set(value) {
72 val previous = field
73 field = value
74 if (value != previous && value > 0) {
75 requestKeyboardFocus()
76 }
77 }
78
79 var autoFocus: Boolean = true
80 set(value) {
81 field = value
82 if (value) {
83 requestKeyboardFocus()
84 } else {
85 inputView.clearFocus()
86 hideKeyboard()
87 }
88 }
64 89
65 var backgroundColorHex: String = "#24292E"90 var backgroundColorHex: String = "#24292E"
66 set(value) {91 set(value) {
@@ -80,121 +105,327 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex · 13 unmodified lines
80 set(value) {105 set(value) {
81 field = value106 field = value
82 mutedForegroundColorValue = parseColor(value, mutedForegroundColorValue)107 mutedForegroundColorValue = parseColor(value, mutedForegroundColorValue)
83 applyTheme()
84 }108 }
85 109
86 init {110 init {
111 terminalCanvas.fontSizeSp = fontSize
112 terminalCanvas.onRequestKeyboard = { requestKeyboardFocus() }
113 terminalCanvas.onScrollRows = { delta ->
114 if (terminalHandle != 0L) {
115 GhosttyBridge.nativeScroll(terminalHandle, delta)
116 renderSnapshot()
117 }
118 }
119 terminalCanvas.onCellMetricsChanged = { emitResize() }
120 terminalCanvas.selectionDelegate = object : TerminalSelectionDelegate {
121 override fun selectWordAt(col: Int, row: Int): Boolean {
122 if (terminalHandle == 0L) return false
123 val selected = GhosttyBridge.nativeSelectWordAt(terminalHandle, col, row)
124 if (selected) renderSnapshot()
125 return selected
126 }
127
128 override fun extendSelection(anchorCol: Int, anchorRow: Int, col: Int, row: Int) {
129 if (terminalHandle == 0L) return
130 GhosttyBridge.nativeExtendSelection(terminalHandle, anchorCol, anchorRow, col, row)
131 renderSnapshot()
132 }
133
134 override fun selectAll(): Boolean {
135 if (terminalHandle == 0L) return false
136 val selected = GhosttyBridge.nativeSelectAll(terminalHandle)
137 if (selected) renderSnapshot()
138 return selected
139 }
140
141 override fun clearSelection() {
142 if (terminalHandle == 0L) return
143 GhosttyBridge.nativeClearSelection(terminalHandle)
144 renderSnapshot()
145 }
146
147 override fun selectionText(): String? =
148 if (terminalHandle == 0L) {
149 null
150 } else {
151 GhosttyBridge.nativeGetSelectionText(terminalHandle)?.let { String(it, Charsets.UTF_8) }
152 }
153 }
154
155 configureInputView()
156 container.addView(
157 terminalCanvas,
158 FrameLayout.LayoutParams(
159 ViewGroup.LayoutParams.MATCH_PARENT,
160 ViewGroup.LayoutParams.MATCH_PARENT,
161 ),
162 )
163 container.addView(inputView, FrameLayout.LayoutParams(1, 1))
164 addView(
165 container,
166 LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
167 )
87 applyTheme()168 applyTheme()
88 container.orientation = LinearLayout.VERTICAL169 }
89 textView.typeface = Typeface.MONOSPACE170
90 textView.textSize = fontSize171 override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
91 textView.setPadding(8, 8, 8, 8)172 super.onSizeChanged(width, height, oldWidth, oldHeight)
92 textView.text = "$ "173 if (width != oldWidth || height != oldHeight) emitResize()
174 }
175
176 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
177 super.onMeasure(widthMeasureSpec, heightMeasureSpec)
178 val childWidthSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY)
179 val childHeightSpec = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY)
180 container.measure(childWidthSpec, childHeightSpec)
181 }
182
183 override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
184 container.layout(0, 0, right - left, bottom - top)
185 if (changed) emitResize()
186 }
187
188 fun cleanup() {
189 if (isCleanedUp) return
190 isCleanedUp = true
191 inputView.setOnEditorActionListener(null)
192 terminalCanvas.onScrollRows = null
193 terminalCanvas.onRequestKeyboard = null
194 terminalCanvas.onCellMetricsChanged = null
195 terminalCanvas.selectionDelegate = null
196 destroyTerminal()
197 }
93 198
199 private fun configureInputView() {
94 inputView.setSingleLine(true)200 inputView.setSingleLine(true)
95 inputView.setTextColor(Color.TRANSPARENT)201 inputView.setTextColor(Color.TRANSPARENT)
96 inputView.setHintTextColor(Color.TRANSPARENT)202 inputView.setHintTextColor(Color.TRANSPARENT)
97 inputView.setBackgroundColor(Color.TRANSPARENT)203 inputView.setBackgroundColor(Color.TRANSPARENT)
98 inputView.typeface = Typeface.MONOSPACE204 inputView.typeface = Typeface.MONOSPACE
99 inputView.textSize = max(fontSize, 13f)205 inputView.textSize = max(fontSize, 13f)
100 inputView.hint = ""206 inputView.alpha = 0.01f
101 inputView.alpha = 0.02f207 inputView.isFocusableInTouchMode = true
102 inputView.imeOptions = EditorInfo.IME_ACTION_SEND208 inputView.imeOptions = EditorInfo.IME_ACTION_SEND or
209 EditorInfo.IME_FLAG_NO_EXTRACT_UI or
210 EditorInfo.IME_FLAG_NO_FULLSCREEN or
211 EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
212 inputView.inputType = InputType.TYPE_CLASS_TEXT or
213 InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD or
214 InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
103 inputView.setPadding(0, 0, 0, 0)215 inputView.setPadding(0, 0, 0, 0)
104 inputView.setOnFocusChangeListener { _, hasFocus ->216 inputView.setOnEditorActionListener { _, actionId, event ->
105 if (hasFocus) {217 val isKeyUp = event?.action == KeyEvent.ACTION_UP
106 showKeyboard()218 val isImeSend = actionId == EditorInfo.IME_ACTION_SEND && !isKeyUp
219 val isHardwareEnter = event?.keyCode == KeyEvent.KEYCODE_ENTER &&
220 event.action == KeyEvent.ACTION_DOWN
221 val isEnter = isImeSend || isHardwareEnter
222 if (isEnter) {
223 // Enter must send CR: raw-mode TUIs treat LF as Ctrl+J (insert newline).
224 onInput(mapOf("data" to "\r"))
225 true
226 } else {
227 false
107 }228 }
108 }229 }
109 inputView.setOnEditorActionListener { view, actionId, _ ->
110 if (actionId != EditorInfo.IME_ACTION_SEND) return@setOnEditorActionListener false
111 onInput(mapOf("data" to "\n"))
112 true
113 }
114 inputView.setOnKeyListener { _, keyCode, event ->230 inputView.setOnKeyListener { _, keyCode, event ->
115 if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false231 if (event.action != KeyEvent.ACTION_DOWN) return@setOnKeyListener false
116 when (keyCode) {232 when {
117 android.view.KeyEvent.KEYCODE_DEL -> {233 keyCode == KeyEvent.KEYCODE_DEL -> {
118 onInput(mapOf("data" to "\u007F"))234 onInput(mapOf("data" to "\u007F"))
119 true235 true
120 }236 }
237 // Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...).
238 event.isCtrlPressed && keyCode in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z -> {
239 onInput(
240 mapOf("data" to (keyCode - KeyEvent.KEYCODE_A + 1).toChar().toString()),
241 )
242 true
243 }
121 else -> false244 else -> false
122 }245 }
123 }246 }
124 inputView.doAfterTextChanged { editable ->247 inputView.addTextChangedListener(
125 if (clearingInput) return@doAfterTextChanged248 object : TextWatcher {
126 val text = editable?.toString().orEmpty()249 override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
127 if (text.isEmpty()) return@doAfterTextChanged250
128 onInput(mapOf("data" to text))251 override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
129 clearingInput = true252 if (clearingInput || s == null || count <= 0) return
130 inputView.text?.clear()253 val end = (start + count).coerceAtMost(s.length)
131 clearingInput = false254 if (start >= end) return
132 }255 val insertedText = s.subSequence(start, end).toString()
133 256 if (insertedText.isNotEmpty()) {
134 textView.setOnClickListener { requestKeyboardFocus() }257 onInput(mapOf("data" to insertedText))
135 scrollView.setOnClickListener { requestKeyboardFocus() }258 }
136 container.setOnClickListener { requestKeyboardFocus() }259 }
137 isClickable = true260
138 setOnClickListener { requestKeyboardFocus() }261 override fun afterTextChanged(editable: Editable?) {
139 262 if (clearingInput || editable.isNullOrEmpty()) return
140 scrollView.addView(263 clearingInput = true
141 textView,264 editable.clear()
142 LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT),265 clearingInput = false
143 )266 }
144 container.addView(267 },
145 scrollView,
146 LinearLayout.LayoutParams(
147 ViewGroup.LayoutParams.MATCH_PARENT,
148 0,
149 1f,
150 ),
151 )
152 container.addView(
153 inputView,
154 LinearLayout.LayoutParams(1, 1),
155 )268 )
156 addView(269 }
157 container,270
158 LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),271 @Suppress("ComplexCondition")
272 private fun emitResize() {
273 if (
274 width <= 0 ||
275 height <= 0 ||
276 terminalCanvas.width <= 0 ||
277 terminalCanvas.height <= 0 ||
278 isCleanedUp
279 ) {
280 return
281 }
282 val nextCols = (terminalCanvas.usableWidth() / terminalCanvas.cellWidthPx)
283 .toInt()
284 .coerceIn(2, 400)
285 val nextRows = (terminalCanvas.usableHeight() / terminalCanvas.cellHeightPx)
286 .toInt()
287 .coerceIn(2, 200)
288 if (nextCols == cols && nextRows == rows && terminalHandle != 0L) return
289 cols = nextCols
290 rows = nextRows
291 val response = if (terminalHandle == 0L) {
292 createTerminal()
293 ByteArray(0)
294 } else {
295 GhosttyBridge.nativeResize(
296 terminalHandle,
297 cols,
298 rows,
299 terminalCanvas.cellWidthPx.toInt(),
300 terminalCanvas.cellHeightPx.toInt(),
301 )
302 }
303 emitResponse(response)
304 onResize(mapOf("cols" to cols, "rows" to rows))
305 feedPendingBuffer()
306 renderSnapshot()
307 }
308
309 @Suppress("ComplexCondition")
310 private fun createTerminal() {
311 if (terminalHandle != 0L || cols <= 0 || rows <= 0 || isCleanedUp) return
312 terminalHandle = GhosttyBridge.nativeCreate(
313 cols,
314 rows,
315 terminalCanvas.cellWidthPx.toInt(),
316 terminalCanvas.cellHeightPx.toInt(),
317 foregroundColorValue,
318 backgroundColorValue,
319 cursorColorValue,
320 paletteColors,
159 )321 )
322 fedBuffer = ""
323 }
160 324
161 post {325 private fun recreateTerminal() {
162 requestKeyboardFocus()326 if (terminalHandle == 0L) return
327 destroyTerminal()
328 createTerminal()
329 feedPendingBuffer()
330 renderSnapshot()
331 }
332
333 private fun destroyTerminal() {
334 if (terminalHandle == 0L) return
335 GhosttyBridge.nativeDestroy(terminalHandle)
336 terminalHandle = 0L
337 fedBuffer = ""
338 terminalCanvas.resetSelectionState()
339 }
340
341 private fun feedPendingBuffer() {
342 if (terminalHandle == 0L || initialBuffer == fedBuffer) return
343 if (!initialBuffer.startsWith(fedBuffer)) {
344 recreateTerminal()
345 if (terminalHandle == 0L) return
163 }346 }
347 val suffix = initialBuffer.substring(fedBuffer.length)
348 if (suffix.isNotEmpty()) {
349 emitResponse(GhosttyBridge.nativeFeed(terminalHandle, suffix.toByteArray(Charsets.UTF_8)))
350 // New output invalidates an active selection (matches the web drawer);
351 // otherwise the copy toolbar drifts out of sync with the grid.
352 if (terminalCanvas.hasActiveSelection()) {
353 GhosttyBridge.nativeClearSelection(terminalHandle)
354 terminalCanvas.resetSelectionState()
355 }
356 }
357 fedBuffer = initialBuffer
358 renderSnapshot()
164 }359 }
165 360
166 override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {361 private fun renderSnapshot() {
167 super.onSizeChanged(width, height, oldWidth, oldHeight)362 if (terminalHandle == 0L) return
168 if (width == lastWidth && height == lastHeight) return363 TerminalFrame.decode(
169 lastWidth = width364 GhosttyBridge.nativeSnapshot(terminalHandle)
170 lastHeight = height365 )?.let(terminalCanvas::setFrame)
171 emitResize()
172 }366 }
173 367
174 private fun emitResize() {368 private fun emitResponse(response: ByteArray) {
175 if (width <= 0 || height <= 0) return369 if (response.isNotEmpty()) {
176 val density = resources.displayMetrics.scaledDensity370 onInput(mapOf("data" to String(response, Charsets.UTF_8)))
177 val fontPx = max(fontSize * density, 1f)371 }
178 val cols = max(20, min(400, (width / (fontPx * 0.62f)).toInt()))
179 val terminalHeight = max(height - inputView.height, 0)
180 val rows = max(5, min(200, (terminalHeight / (fontPx * 1.35f)).toInt()))
181 onResize(mapOf("cols" to cols, "rows" to rows))
182 }372 }
183 373
184 private fun requestKeyboardFocus() {374 private fun requestKeyboardFocus() {
185 inputView.requestFocus()375 inputView.requestFocus()
186 showKeyboard()376 val inputMethodManager = context.getSystemService(
377 Context.INPUT_METHOD_SERVICE
378 ) as? InputMethodManager
379 inputMethodManager?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT)
380 }
381
382 private fun hideKeyboard() {
383 val inputMethodManager = context.getSystemService(
384 Context.INPUT_METHOD_SERVICE
385 ) as? InputMethodManager
386 inputMethodManager?.hideSoftInputFromWindow(windowToken, 0)
187 }387 }
188 388
189 private fun applyTheme() {389 private fun applyTheme() {
190 setBackgroundColor(backgroundColorValue)390 setBackgroundColor(backgroundColorValue)
191 container.setBackgroundColor(backgroundColorValue)391 container.setBackgroundColor(backgroundColorValue)
192 scrollView.setBackgroundColor(backgroundColorValue)392 terminalCanvas.setBackgroundColor(backgroundColorValue)
193 textView.setTextColor(foregroundColorValue)393 if (terminalHandle != 0L) {
194 textView.setBackgroundColor(backgroundColorValue)394 GhosttyBridge.nativeSetTheme(
195 inputView.setTextColor(Color.TRANSPARENT)395 terminalHandle,
196 inputView.setHintTextColor(mutedForegroundColorValue)396 foregroundColorValue,
197 inputView.setBackgroundColor(Color.TRANSPARENT)397 backgroundColorValue,
398 cursorColorValue,
399 paletteColors,
400 )
401 renderSnapshot()
402 }
403 }
404
405 @Suppress("LoopWithTooManyJumpStatements")
406 private fun parseThemeConfig(config: String) {
407 val palette = sortedMapOf<Int, Int>()
408 for (line in config.lineSequence()) {
409 val parts = line.split('=', limit = 2)
410 if (parts.size != 2) continue
411 val key = parts[0].trim()
412 val value = parts[1].trim()
413 when (key) {
414 "cursor-color" -> cursorColorValue = parseColor(value, cursorColorValue)
415 "palette" -> {
416 val paletteParts = value.split('=', limit = 2)
417 val index = paletteParts.firstOrNull()?.trim()?.toIntOrNull() ?: continue
418 val color = paletteParts.getOrNull(1)?.trim() ?: continue
419 if (index in 0..255) palette[index] = parseColor(color, foregroundColorValue)
420 }
421 }
422 }
423 if (palette.isNotEmpty()) {
424 val lastIndex = palette.lastKey()
425 paletteColors = IntArray(lastIndex + 1) { index ->
426 palette[index] ?: foregroundColorValue

15 more lines aren’t shown here.

apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt+628−0

This diff is large: its 629 lines aren’t shown here.

apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalFrame.kt+82−0

This diff is large: its 83 lines aren’t shown here.

apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so+0−0

Binary file not shown.

apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so+0−0

Binary file not shown.

apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so+0−0

Binary file not shown.

apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so+0−0

Binary file not shown.

apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift+14−0

This diff is large: its 28 lines aren’t shown here.

apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift+159−3

This diff is large: its 211 lines aren’t shown here.

apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh+152−0

This diff is large: its 153 lines aren’t shown here.

apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0001-link-android-libvt-with-libc.patch+25−0

This diff is large: its 26 lines aren’t shown here.

apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0002-align-android-libvt-to-16kb-pages.patch+11−0

This diff is large: its 12 lines aren’t shown here.

apps/mobile/package.json+42−21

This diff is large: its 124 lines aren’t shown here.

apps/mobile/plugins/lib/addWidgetAssetCatalog.cjs+81−0

This diff is large: its 82 lines aren’t shown here.

apps/mobile/plugins/withAndroidGradleHeap.cjs+22−0

This diff is large: its 23 lines aren’t shown here.

apps/mobile/plugins/withAndroidModernAlertDialog.cjs+188−0

This diff is large: its 189 lines aren’t shown here.

apps/mobile/plugins/withAndroidModernPopupMenu.cjs+250−0

This diff is large: its 251 lines aren’t shown here.

apps/mobile/plugins/withAndroidPredictiveBackCompat.cjs+104−0

This diff is large: its 105 lines aren’t shown here.

apps/mobile/plugins/withIosCocoaPodsUuidCache.cjs+52−0

This diff is large: its 53 lines aren’t shown here.

apps/mobile/plugins/withIosSceneLifecycle.cjs+99−0

This diff is large: its 100 lines aren’t shown here.

apps/mobile/plugins/withShareExtensionDisplayName.cjs+93−0

This diff is large: its 94 lines aren’t shown here.

apps/mobile/plugins/withWidgetLogoAsset.cjs+68−0

This diff is large: its 69 lines aren’t shown here.

apps/mobile/plugins/withoutIosPersonalTeamCapabilities.cjs+10−0

This diff is large: its 11 lines aren’t shown here.

apps/mobile/scripts/wire-widget-asset-catalog.cjs+30−0

This diff is large: its 31 lines aren’t shown here.

apps/mobile/src/App.tsx+88−0

This diff is large: its 89 lines aren’t shown here.

apps/mobile/src/Stack.tsx+567−0

This diff is large: its 568 lines aren’t shown here.

apps/mobile/src/app/+not-found.tsx+0−43

This diff is large: its 44 lines aren’t shown here.

apps/mobile/src/app/_layout.tsx+0−149

This diff is large: its 150 lines aren’t shown here.

apps/mobile/src/app/connections/_layout.tsx+0−29

This diff is large: its 30 lines aren’t shown here.

apps/mobile/src/app/index.tsx+0−120

This diff is large: its 121 lines aren’t shown here.

apps/mobile/src/app/new/_layout.tsx+0−50

This diff is large: its 51 lines aren’t shown here.

apps/mobile/src/app/new/add-project/destination.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/new/add-project/index.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/new/add-project/local.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/new/add-project/repository.tsx+0−23

This diff is large: its 24 lines aren’t shown here.

apps/mobile/src/app/new/draft.tsx+0−29

This diff is large: its 30 lines aren’t shown here.

apps/mobile/src/app/new/index.tsx+0−218

This diff is large: its 219 lines aren’t shown here.

apps/mobile/src/app/settings/_layout.tsx+0−62

This diff is large: its 63 lines aren’t shown here.

apps/mobile/src/app/settings/archive.tsx+0−3

This diff is large: its 4 lines aren’t shown here.

apps/mobile/src/app/settings/auth.tsx+0−33

This diff is large: its 34 lines aren’t shown here.

apps/mobile/src/app/settings/environment-new.tsx+0−1

This diff is large: its 2 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx+0−107

This diff is large: its 108 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx+0−58

This diff is large: its 59 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx+0−18

This diff is large: its 19 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx+0−10

This diff is large: its 11 lines aren’t shown here.

apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx+0−5

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/components/AndroidAnchoredMenu.tsx+337−0

This diff is large: its 338 lines aren’t shown here.

apps/mobile/src/components/AndroidScreenHeader.tsx+117−0

This diff is large: its 118 lines aren’t shown here.

apps/mobile/src/components/AppSymbol.tsx+202−0

This diff is large: its 203 lines aren’t shown here.

apps/mobile/src/components/AppText.tsx+5−14

This diff is large: its 49 lines aren’t shown here.

apps/mobile/src/components/BrandMark.tsx+15−10

This diff is large: its 44 lines aren’t shown here.

apps/mobile/src/components/ComposerAttachmentStrip.tsx+5−11

This diff is large: its 42 lines aren’t shown here.

apps/mobile/src/components/ComposerToolbarTrigger.tsx+11−7

This diff is large: its 73 lines aren’t shown here.

apps/mobile/src/components/ConfirmDialogHost.tsx+111−0

This diff is large: its 112 lines aren’t shown here.

apps/mobile/src/components/ControlPill.tsx+58−6

This diff is large: its 86 lines aren’t shown here.

apps/mobile/src/components/CopyTextButton.tsx+6−2

This diff is large: its 19 lines aren’t shown here.

apps/mobile/src/components/EmptyState.tsx+23−1

This diff is large: its 35 lines aren’t shown here.

apps/mobile/src/components/ErrorBanner.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/components/GlassSafeAreaView.tsx+5−15

This diff is large: its 28 lines aren’t shown here.

apps/mobile/src/components/GlassSurface.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/components/OverlayPortal.tsx+69−0

This diff is large: its 70 lines aren’t shown here.

apps/mobile/src/components/PierreEntryIcon.tsx+1−1

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/components/ProjectFavicon.tsx+11−5

This diff is large: its 61 lines aren’t shown here.

apps/mobile/src/components/T3Wordmark.tsx+23−0

This diff is large: its 24 lines aren’t shown here.

apps/mobile/src/connection/catalog-store.ts+25−26

This diff is large: its 108 lines aren’t shown here.

apps/mobile/src/connection/environment-cache-store.test.ts+97−0

This diff is large: its 98 lines aren’t shown here.

apps/mobile/src/connection/environment-cache-store.ts+234−0

This diff is large: its 235 lines aren’t shown here.

apps/mobile/src/connection/platform.ts+94−79

This diff is large: its 214 lines aren’t shown here.

apps/mobile/src/connection/runtime.ts+6−1

This diff is large: its 24 lines aren’t shown here.

apps/mobile/src/connection/storage.test.ts+25−12

This diff is large: its 78 lines aren’t shown here.

apps/mobile/src/connection/storage.ts+2−300

This diff is large: its 342 lines aren’t shown here.

apps/mobile/src/features/agent-awareness/capabilities.ts+5−0

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts+87−18

This diff is large: its 177 lines aren’t shown here.

apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts+65−39

This diff is large: its 113 lines aren’t shown here.

apps/mobile/src/features/agent-awareness/notificationNavigation.ts+4−4

This diff is large: its 31 lines aren’t shown here.

apps/mobile/src/features/agent-awareness/registrationPayload.ts+16−3

This diff is large: its 46 lines aren’t shown here.

apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts+321−3

This diff is large: its 397 lines aren’t shown here.

apps/mobile/src/features/agent-awareness/remoteRegistration.ts+442−53

This diff is large: its 761 lines aren’t shown here.

apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx+487−271

This diff is large: its 883 lines aren’t shown here.

apps/mobile/src/features/cloud/CloudAuthProvider.tsx+23−1

This diff is large: its 55 lines aren’t shown here.

apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx+26−113

This diff is large: its 204 lines aren’t shown here.

apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx+137−0

This diff is large: its 138 lines aren’t shown here.

apps/mobile/src/features/cloud/connectOnboarding.ts+24−0

This diff is large: its 25 lines aren’t shown here.

apps/mobile/src/features/cloud/connectOnboardingNavigation.ts+49−0

This diff is large: its 50 lines aren’t shown here.

apps/mobile/src/features/cloud/connectOnboardingOptOut.ts+21−0

This diff is large: its 22 lines aren’t shown here.

apps/mobile/src/features/cloud/dpop.ts+41−9

This diff is large: its 87 lines aren’t shown here.

apps/mobile/src/features/cloud/linkEnvironment.test.ts+78−8

This diff is large: its 141 lines aren’t shown here.

apps/mobile/src/features/cloud/linkEnvironment.ts+49−22

This diff is large: its 122 lines aren’t shown here.

apps/mobile/src/features/connection/CloudEnvironmentRows.tsxrenamed from apps/mobile/src/app/settings/environments.tsx+77−149

This diff is large: its 318 lines aren’t shown here.

apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx+10−23

This diff is large: its 110 lines aren’t shown here.

apps/mobile/src/features/connection/ConnectionSheetButton.tsx+21−36

This diff is large: its 93 lines aren’t shown here.

apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsxrenamed from apps/mobile/src/app/connections/new.tsx+65−45

This diff is large: its 200 lines aren’t shown here.

apps/mobile/src/features/connection/ConnectionsRouteScreen.tsxrenamed from apps/mobile/src/app/connections/index.tsx+31−23

This diff is large: its 98 lines aren’t shown here.

apps/mobile/src/features/connection/EnvironmentConnectionNotice.tsx+3−3

This diff is large: its 22 lines aren’t shown here.

apps/mobile/src/features/connection/environmentSections.test.ts+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts+189−0

This diff is large: its 190 lines aren’t shown here.

apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts+72−8

This diff is large: its 135 lines aren’t shown here.

apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts+39−2

This diff is large: its 55 lines aren’t shown here.

apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts+139−6

This diff is large: its 198 lines aren’t shown here.

apps/mobile/src/features/files/FileMarkdownPreview.tsx+69−15

This diff is large: its 175 lines aren’t shown here.

apps/mobile/src/features/files/FileTreeBrowser.tsx+145−55

This diff is large: its 288 lines aren’t shown here.

apps/mobile/src/features/files/SourceFileSurface.tsx+98−65

This diff is large: its 279 lines aren’t shown here.

apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx+360−319

This diff is large: its 866 lines aren’t shown here.

apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/features/files/nativeSourceFileAdapter.ts+26−14

This diff is large: its 53 lines aren’t shown here.

apps/mobile/src/features/files/preload-workspace-file.ts+74−0

This diff is large: its 75 lines aren’t shown here.

apps/mobile/src/features/files/source-file-document.test.ts+16−0

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/features/files/source-file-document.ts+54−0

This diff is large: its 55 lines aren’t shown here.

apps/mobile/src/features/files/sourceHighlightingState.test.ts+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/features/files/thread-file-navigator-pane.tsx+175−0

This diff is large: its 176 lines aren’t shown here.

apps/mobile/src/features/home/AndroidHomeFab.tsx+51−0

This diff is large: its 52 lines aren’t shown here.

apps/mobile/src/features/home/HomeHeader.tsx+383−206

This diff is large: its 622 lines aren’t shown here.

apps/mobile/src/features/home/HomeRouteScreen.tsx+155−0

This diff is large: its 156 lines aren’t shown here.

apps/mobile/src/features/home/HomeScreen.tsx+332−452

This diff is large: its 886 lines aren’t shown here.

apps/mobile/src/features/home/WorkspaceConnectionStatus.test.ts+87−0

This diff is large: its 88 lines aren’t shown here.

apps/mobile/src/features/home/WorkspaceConnectionStatus.tsx+56−0

This diff is large: its 57 lines aren’t shown here.

apps/mobile/src/features/home/home-list-filter-menu.ts+120−0

This diff is large: its 121 lines aren’t shown here.

apps/mobile/src/features/home/home-list-options.test.ts+31−0

This diff is large: its 32 lines aren’t shown here.

apps/mobile/src/features/home/home-list-options.ts+144−0

This diff is large: its 145 lines aren’t shown here.

apps/mobile/src/features/home/homeListItems.test.ts+254−0

This diff is large: its 255 lines aren’t shown here.

apps/mobile/src/features/home/homeListItems.ts+207−0

This diff is large: its 208 lines aren’t shown here.

apps/mobile/src/features/home/homeThreadList.test.ts+143−0

This diff is large: its 162 lines aren’t shown here.

apps/mobile/src/features/home/homeThreadList.ts+130−5

This diff is large: its 210 lines aren’t shown here.

apps/mobile/src/features/home/thread-swipe-actions.tsx+253−12

This diff is large: its 298 lines aren’t shown here.

apps/mobile/src/features/home/usePendingTaskListActions.ts+57−0

This diff is large: its 58 lines aren’t shown here.

apps/mobile/src/features/home/useThreadListActions.ts+18−9

This diff is large: its 55 lines aren’t shown here.

apps/mobile/src/features/home/workspace-connection-status.ts+26−0

This diff is large: its 27 lines aren’t shown here.

apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx+73−0

This diff is large: its 74 lines aren’t shown here.

apps/mobile/src/features/keyboard/hardwareKeyboardCommands.test.ts+28−0

This diff is large: its 29 lines aren’t shown here.

apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts+78−0

This diff is large: its 79 lines aren’t shown here.

apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx+526−0

This diff is large: its 527 lines aren’t shown here.

apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx+30−0

This diff is large: its 31 lines aren’t shown here.

apps/mobile/src/features/layout/native-glass-header-items.ts+33−0

This diff is large: its 34 lines aren’t shown here.

apps/mobile/src/features/layout/native-mail-search-toolbar.ts+25−0

This diff is large: its 26 lines aren’t shown here.

apps/mobile/src/features/layout/workspace-inspector-pane.tsx+146−0

This diff is large: its 147 lines aren’t shown here.

apps/mobile/src/features/layout/workspace-pane-animation.ts+16−0

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/features/layout/workspace-pane-divider.tsx+107−0

This diff is large: its 108 lines aren’t shown here.

apps/mobile/src/features/layout/workspace-sidebar-toolbar.tsx+32−0

This diff is large: its 33 lines aren’t shown here.

apps/mobile/src/features/projects/AddProjectDestinationRoute.tsx+15−0

This diff is large: its 16 lines aren’t shown here.

apps/mobile/src/features/projects/AddProjectLocalRoute.tsx+12−0

This diff is large: its 13 lines aren’t shown here.

apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx+31−0

This diff is large: its 32 lines aren’t shown here.

apps/mobile/src/features/projects/AddProjectScreen.tsx+70−71

This diff is large: its 338 lines aren’t shown here.

apps/mobile/src/features/projects/AddProjectSourceRoute.tsx+5−0

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx+83−52

This diff is large: its 240 lines aren’t shown here.

apps/mobile/src/features/review/ReviewSheet.tsx+592−187

This diff is large: its 926 lines aren’t shown here.

apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts+56−0

This diff is large: its 57 lines aren’t shown here.

apps/mobile/src/features/review/nativeReviewDiffAdapter.ts+98−36

This diff is large: its 177 lines aren’t shown here.

apps/mobile/src/features/review/review-section-menu.test.ts+40−0

This diff is large: its 41 lines aren’t shown here.

apps/mobile/src/features/review/review-section-menu.ts+21−0

This diff is large: its 22 lines aren’t shown here.

apps/mobile/src/features/review/reviewDiffBridgeKeys.test.tsrenamed from apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts+1−1

This diff is large: its 8 lines aren’t shown here.

apps/mobile/src/features/review/reviewDiffBridgeKeys.ts+35−0

This diff is large: its 36 lines aren’t shown here.

apps/mobile/src/features/review/reviewDiffRendering.tsx+18−11

This diff is large: its 76 lines aren’t shown here.

apps/mobile/src/features/review/reviewPaneSelection.test.ts+35−0

This diff is large: its 36 lines aren’t shown here.

apps/mobile/src/features/review/reviewPaneSelection.ts+16−0

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/features/review/useNativeReviewDiffBridge.ts+6−36

This diff is large: its 65 lines aren’t shown here.

apps/mobile/src/features/review/useReviewCommentSelectionController.ts+6−7

This diff is large: its 39 lines aren’t shown here.

apps/mobile/src/features/review/useReviewDiffData.ts+11−9

This diff is large: its 48 lines aren’t shown here.

apps/mobile/src/features/review/useReviewDiffPrewarming.ts+101−0

This diff is large: its 102 lines aren’t shown here.

apps/mobile/src/features/settings/SettingsAppearanceRouteScreen.tsx+28−0

This diff is large: its 29 lines aren’t shown here.

apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx+39−0

This diff is large: its 40 lines aren’t shown here.

apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx+215−0

This diff is large: its 216 lines aren’t shown here.

apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx+179−0

This diff is large: its 180 lines aren’t shown here.

apps/mobile/src/features/settings/SettingsLegalRouteScreen.tsx+6−0

This diff is large: its 7 lines aren’t shown here.

apps/mobile/src/features/settings/SettingsRouteScreen.tsxrenamed from apps/mobile/src/app/settings/index.tsx+221−165

This diff is large: its 585 lines aren’t shown here.

apps/mobile/src/features/settings/SettingsWaitlistRouteScreen.tsxrenamed from apps/mobile/src/app/settings/waitlist.tsx+19−14

This diff is large: its 64 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx+126−0

This diff is large: its 127 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/components/AppearancePreviews.tsx+177−0

This diff is large: its 178 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/components/FontSizeSliderRow.tsx+214−0

This diff is large: its 215 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/sections/CodeAppearanceSection.tsx+64−0

This diff is large: its 65 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/sections/TerminalAppearanceSection.tsx+54−0

This diff is large: its 55 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx+34−0

This diff is large: its 35 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/useAppearanceCodeSurface.ts+34−0

This diff is large: its 35 lines aren’t shown here.

apps/mobile/src/features/settings/appearance/useScaledTextRole.ts+36−0

This diff is large: its 37 lines aren’t shown here.

apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx+186−0

This diff is large: its 187 lines aren’t shown here.

apps/mobile/src/features/settings/components/SettingsRow.tsx+95−0

This diff is large: its 96 lines aren’t shown here.

apps/mobile/src/features/settings/components/SettingsSection.tsx+26−0

This diff is large: its 27 lines aren’t shown here.

apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx+40−0

This diff is large: its 41 lines aren’t shown here.

apps/mobile/src/features/settings/components/settings-sheet-targets.ts+7−0

This diff is large: its 8 lines aren’t shown here.

apps/mobile/src/features/settings/lib/legal-document-url.test.ts+24−0

This diff is large: its 25 lines aren’t shown here.

apps/mobile/src/features/settings/lib/legal-document-url.ts+58−0

This diff is large: its 59 lines aren’t shown here.

apps/mobile/src/features/sharing/IncomingShareProvider.tsx+310−0

This diff is large: its 311 lines aren’t shown here.

apps/mobile/src/features/sharing/incoming-share-inbox.test.ts+236−0

This diff is large: its 237 lines aren’t shown here.

apps/mobile/src/features/sharing/incoming-share-inbox.ts+193−0

This diff is large: its 194 lines aren’t shown here.

apps/mobile/src/features/sharing/incoming-share-model.test.ts+196−0

This diff is large: its 197 lines aren’t shown here.

apps/mobile/src/features/sharing/incoming-share-model.ts+217−0

This diff is large: its 218 lines aren’t shown here.

apps/mobile/src/features/sharing/incoming-share-presentation.test.ts+92−0

This diff is large: its 93 lines aren’t shown here.

apps/mobile/src/features/sharing/incoming-share-presentation.ts+71−0

This diff is large: its 72 lines aren’t shown here.

apps/mobile/src/features/sharing/incoming-share-storage.ts+80−0

This diff is large: its 81 lines aren’t shown here.

apps/mobile/src/features/shortcuts/appShortcuts.test.ts+155−0

This diff is large: its 156 lines aren’t shown here.

apps/mobile/src/features/shortcuts/appShortcuts.ts+137−0

This diff is large: its 138 lines aren’t shown here.

apps/mobile/src/features/shortcuts/useAppShortcuts.ts+136−0

This diff is large: its 137 lines aren’t shown here.

apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx+224−0

This diff is large: its 225 lines aren’t shown here.

apps/mobile/src/features/showcase/nativeShowcaseScene.ts+68−0

This diff is large: its 69 lines aren’t shown here.

apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts+70−0

This diff is large: its 71 lines aren’t shown here.

apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts+70−0

This diff is large: its 71 lines aren’t shown here.

apps/mobile/src/features/showcase/showcasePendingTasks.test.ts+72−0

This diff is large: its 73 lines aren’t shown here.

apps/mobile/src/features/showcase/showcasePendingTasks.ts+66−0

This diff is large: its 67 lines aren’t shown here.

apps/mobile/src/features/showcase/showcaseRetry.test.ts+44−0

This diff is large: its 45 lines aren’t shown here.

apps/mobile/src/features/showcase/showcaseRetry.ts+46−0

This diff is large: its 47 lines aren’t shown here.

apps/mobile/src/features/terminal/NativeTerminalSurface.tsx+26−61

This diff is large: its 199 lines aren’t shown here.

apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx+91−1

This diff is large: its 111 lines aren’t shown here.

apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx+371−169

This diff is large: its 733 lines aren’t shown here.

apps/mobile/src/features/terminal/nativeTerminalModule.ts+22−1

This diff is large: its 43 lines aren’t shown here.

apps/mobile/src/features/terminal/terminalMenu.test.ts+70−0

This diff is large: its 87 lines aren’t shown here.

apps/mobile/src/features/terminal/terminalMenu.ts+29−0

This diff is large: its 36 lines aren’t shown here.

apps/mobile/src/features/terminal/terminalPreferences.ts+1−1

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/features/threads/ComposerCommandPopover.tsx+7−24

This diff is large: its 73 lines aren’t shown here.

apps/mobile/src/features/threads/GitActionProgressOverlay.tsx+3−2

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx+49−0

This diff is large: its 50 lines aren’t shown here.

apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+719−117

This diff is large: its 1040 lines aren’t shown here.

apps/mobile/src/features/threads/NewTaskRouteScreen.tsx+326−0

This diff is large: its 327 lines aren’t shown here.

apps/mobile/src/features/threads/PendingApprovalCard.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/features/threads/PendingUserInputCard.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadActivityInspector.tsx+24−7

This diff is large: its 61 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadComposer.tsx+203−137

This diff is large: its 526 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadDetailScreen.tsx+180−130

This diff is large: its 425 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadFeed.tsx+480−216

This diff is large: its 1155 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadGitControls.tsx+382−122

This diff is large: its 565 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx+0−282

This diff is large: its 283 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx+753−0

This diff is large: its 754 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx+10−8

This diff is large: its 44 lines aren’t shown here.

apps/mobile/src/features/threads/ThreadRouteScreen.tsx+552−139

This diff is large: its 841 lines aren’t shown here.

apps/mobile/src/features/threads/git/GitBranchesSheet.tsx+127−149

This diff is large: its 308 lines aren’t shown here.

apps/mobile/src/features/threads/git/GitCommitSheet.tsx+161−174

This diff is large: its 387 lines aren’t shown here.

apps/mobile/src/features/threads/git/GitConfirmSheet.tsx+40−25

This diff is large: its 127 lines aren’t shown here.

apps/mobile/src/features/threads/git/GitOverviewSheet.tsx+289−118

This diff is large: its 475 lines aren’t shown here.

apps/mobile/src/features/threads/git/git-overview-navigation.test.ts+13−0

This diff is large: its 14 lines aren’t shown here.

apps/mobile/src/features/threads/git/git-overview-navigation.ts+5−0

This diff is large: its 6 lines aren’t shown here.

apps/mobile/src/features/threads/git/gitSheetComponents.tsx+23−41

This diff is large: its 113 lines aren’t shown here.

apps/mobile/src/features/threads/markdownCodeHighlightState.ts+87−0

This diff is large: its 88 lines aren’t shown here.

apps/mobile/src/features/threads/new-task-flow-provider.tsx+404−48

This diff is large: its 620 lines aren’t shown here.

apps/mobile/src/features/threads/sidebar-filter-button.tsx+42−0

This diff is large: its 43 lines aren’t shown here.

apps/mobile/src/features/threads/sidebar-header-actions.android.tsx+16−0

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/features/threads/sidebar-header-actions.tsx+58−0

This diff is large: its 59 lines aren’t shown here.

apps/mobile/src/features/threads/sidebar-native-header-items.ts+63−0

This diff is large: its 64 lines aren’t shown here.

apps/mobile/src/features/threads/sidebar-navigation-shell.tsx+73−0

This diff is large: its 74 lines aren’t shown here.

apps/mobile/src/features/threads/thread-inspector-content-stack.tsx+101−0

This diff is large: its 102 lines aren’t shown here.

apps/mobile/src/features/threads/thread-list-items.tsx+666−0

This diff is large: its 667 lines aren’t shown here.

apps/mobile/src/features/threads/thread-work-log.tsx+41−33

This diff is large: its 163 lines aren’t shown here.

apps/mobile/src/features/threads/threadContentPresentation.ts+7−1

This diff is large: its 15 lines aren’t shown here.

apps/mobile/src/features/threads/threadPresentation.ts+104−19

This diff is large: its 149 lines aren’t shown here.

apps/mobile/src/features/threads/use-project-actions.ts+22−52

This diff is large: its 118 lines aren’t shown here.

apps/mobile/src/lib/adaptive-navigation.test.ts+68−0

This diff is large: its 69 lines aren’t shown here.

apps/mobile/src/lib/adaptive-navigation.ts+35−0

This diff is large: its 36 lines aren’t shown here.

apps/mobile/src/lib/appBlurTarget.ts+8−0

This diff is large: its 9 lines aren’t shown here.

apps/mobile/src/lib/appearancePreferences.test.ts+142−0

This diff is large: its 143 lines aren’t shown here.

apps/mobile/src/lib/appearancePreferences.ts+245−0

This diff is large: its 246 lines aren’t shown here.

apps/mobile/src/lib/base64.ts+4−0

This diff is large: its 5 lines aren’t shown here.

apps/mobile/src/lib/composerImages.test.ts+31−1

This diff is large: its 39 lines aren’t shown here.

apps/mobile/src/lib/composerImages.ts+14−5

This diff is large: its 35 lines aren’t shown here.

apps/mobile/src/lib/layout.test.ts+343−0

This diff is large: its 344 lines aren’t shown here.

apps/mobile/src/lib/layout.ts+226−4

This diff is large: its 252 lines aren’t shown here.

apps/mobile/src/lib/native-glass-capability.test.ts+18−0

This diff is large: its 19 lines aren’t shown here.

apps/mobile/src/lib/native-glass-capability.ts+6−0

This diff is large: its 7 lines aren’t shown here.

apps/mobile/src/lib/projectThreadStartTurn.ts+90−0

This diff is large: its 91 lines aren’t shown here.

apps/mobile/src/lib/routes.test.ts+0−45

This diff is large: its 46 lines aren’t shown here.

apps/mobile/src/lib/routes.ts+0−134

This diff is large: its 135 lines aren’t shown here.

apps/mobile/src/lib/runtime.ts+3−0

This diff is large: its 24 lines aren’t shown here.

apps/mobile/src/lib/serialized-async-queue.test.ts+45−0

This diff is large: its 46 lines aren’t shown here.

apps/mobile/src/lib/serialized-async-queue.ts+16−0

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/lib/storage.test.ts+148−8

This diff is large: its 188 lines aren’t shown here.

apps/mobile/src/lib/storage.ts+0−201

This diff is large: its 202 lines aren’t shown here.

apps/mobile/src/lib/time.ts+4−3

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/lib/typography.test.ts+4−7

This diff is large: its 26 lines aren’t shown here.

apps/mobile/src/lib/typography.ts+10−11

This diff is large: its 30 lines aren’t shown here.

apps/mobile/src/lib/useFontFamily.ts+15−0

This diff is large: its 16 lines aren’t shown here.

apps/mobile/src/lib/uuid.ts+6−0

This diff is large: its 10 lines aren’t shown here.

apps/mobile/src/native/StackHeader.tsx+457−0

This diff is large: its 458 lines aren’t shown here.

apps/mobile/src/native/T3ComposerEditor.android.tsx+6−0

This diff is large: its 7 lines aren’t shown here.

apps/mobile/src/native/T3ComposerEditor.ios.tsx+10−6

This diff is large: its 74 lines aren’t shown here.

apps/mobile/src/native/T3ComposerEditor.native.tsx+286−0

This diff is large: its 287 lines aren’t shown here.

apps/mobile/src/native/T3ComposerEditor.tsx+7−3

This diff is large: its 37 lines aren’t shown here.

apps/mobile/src/native/T3ComposerEditor.types.ts+4−0

This diff is large: its 16 lines aren’t shown here.

apps/mobile/src/native/T3HeaderButton.android.tsx+26−0

This diff is large: its 27 lines aren’t shown here.

apps/mobile/src/native/T3KeyboardCommands.ios.tsx+31−0

This diff is large: its 32 lines aren’t shown here.

apps/mobile/src/native/T3KeyboardCommands.tsx+13−0

This diff is large: its 14 lines aren’t shown here.

apps/mobile/src/native/native-glass.ts+9−0

This diff is large: its 10 lines aren’t shown here.

apps/mobile/src/native/scrollEdgeEffects.test.ts+29−0

This diff is large: its 30 lines aren’t shown here.

apps/mobile/src/native/scrollEdgeEffects.ts+37−0

This diff is large: its 38 lines aren’t shown here.

apps/mobile/src/persistence/imperative.ts+53−0

This diff is large: its 54 lines aren’t shown here.

apps/mobile/src/persistence/layer.ts+16−0

This diff is large: its 17 lines aren’t shown here.

apps/mobile/src/persistence/mobile-database.test.ts+71−0

This diff is large: its 72 lines aren’t shown here.

apps/mobile/src/persistence/mobile-database.ts+409−0

This diff is large: its 410 lines aren’t shown here.

apps/mobile/src/persistence/mobile-preferences.ts+305−0

This diff is large: its 306 lines aren’t shown here.

apps/mobile/src/persistence/mobile-secure-storage.ts+52−0

This diff is large: its 53 lines aren’t shown here.

apps/mobile/src/persistence/mobile-storage.ts+266−0

This diff is large: its 267 lines aren’t shown here.

apps/mobile/src/state/client-cache-state.ts+87−0

This diff is large: its 88 lines aren’t shown here.

apps/mobile/src/state/preferences.test.ts+272−0

This diff is large: its 273 lines aren’t shown here.

apps/mobile/src/state/preferences.ts+124−0

This diff is large: its 125 lines aren’t shown here.

apps/mobile/src/state/thread-outbox-manager.ts+35−1

This diff is large: its 57 lines aren’t shown here.

apps/mobile/src/state/thread-outbox-model.ts+56−2

This diff is large: its 117 lines aren’t shown here.

apps/mobile/src/state/thread-outbox.test.ts+146−0

This diff is large: its 191 lines aren’t shown here.

apps/mobile/src/state/thread-outbox.ts+5−0

This diff is large: its 12 lines aren’t shown here.

apps/mobile/src/state/thread-pr-presentation.ts+36−0

This diff is large: its 37 lines aren’t shown here.

apps/mobile/src/state/use-composer-drafts.test.ts+89−1

This diff is large: its 119 lines aren’t shown here.

apps/mobile/src/state/use-composer-drafts.ts+152−2

This diff is large: its 233 lines aren’t shown here.

apps/mobile/src/state/use-pending-new-tasks.ts+35−0

This diff is large: its 36 lines aren’t shown here.

apps/mobile/src/state/use-thread-outbox-drain.ts+173−62

This diff is large: its 344 lines aren’t shown here.

apps/mobile/src/state/use-thread-outbox.ts+31−1

This diff is large: its 47 lines aren’t shown here.

apps/mobile/src/state/use-thread-pr.test.ts+36−0

This diff is large: its 37 lines aren’t shown here.

apps/mobile/src/state/use-thread-pr.ts+41−0

This diff is large: its 42 lines aren’t shown here.

apps/mobile/src/state/use-thread-selection.ts+138−20

This diff is large: its 187 lines aren’t shown here.

apps/mobile/src/widgets/AgentActivity.test.ts+242−8

This diff is large: its 284 lines aren’t shown here.

apps/mobile/src/widgets/AgentActivity.tsx+290−230

This diff is large: its 579 lines aren’t shown here.

apps/server/package.json+1−1

This diff is large: its 8 lines aren’t shown here.

apps/server/scripts/t3-sqlite-state.test.ts+119−0

This diff is large: its 120 lines aren’t shown here.

apps/server/scripts/t3-sqlite-state.ts+285−0

This diff is large: its 286 lines aren’t shown here.

apps/server/src/assets/AssetAccess.test.ts+3−1

This diff is large: its 24 lines aren’t shown here.

apps/server/src/assets/AssetAccess.ts+4−8

This diff is large: its 47 lines aren’t shown here.

apps/server/src/auth/http.ts+10−0

This diff is large: its 24 lines aren’t shown here.

apps/server/src/cli/config.test.ts+23−6

This diff is large: its 92 lines aren’t shown here.

apps/server/src/cli/config.ts+11−7

This diff is large: its 39 lines aren’t shown here.

apps/server/src/cli/connect.test.ts+54−1

This diff is large: its 80 lines aren’t shown here.

apps/server/src/cli/connect.ts+354−54

This diff is large: its 546 lines aren’t shown here.

apps/server/src/cli/project.ts+5−0

This diff is large: its 19 lines aren’t shown here.

apps/server/src/cloud/CliState.test.ts+23−0

This diff is large: its 28 lines aren’t shown here.

apps/server/src/cloud/CliState.ts+26−2

This diff is large: its 46 lines aren’t shown here.

apps/server/src/cloud/CliTokenManager.test.ts+264−0

This diff is large: its 265 lines aren’t shown here.

apps/server/src/cloud/CliTokenManager.ts+283−68

This diff is large: its 481 lines aren’t shown here.

apps/server/src/cloud/bootService.test.ts+529−0

This diff is large: its 530 lines aren’t shown here.

apps/server/src/cloud/bootService.ts+452−0

This diff is large: its 453 lines aren’t shown here.

apps/server/src/cloud/cliAuthHtml.test.ts+31−0

This diff is large: its 32 lines aren’t shown here.

apps/server/src/cloud/cliAuthHtml.ts+155−0

This diff is large: its 156 lines aren’t shown here.

apps/server/src/cloud/http.test.ts+37−1

This diff is large: its 56 lines aren’t shown here.

apps/server/src/cloud/http.ts+40−18

This diff is large: its 129 lines aren’t shown here.

apps/server/src/cloud/publicConfig.test.ts+35−0

This diff is large: its 49 lines aren’t shown here.

apps/server/src/cloud/publicConfig.ts+40−1

This diff is large: its 59 lines aren’t shown here.

apps/server/src/config.ts+9−1

This diff is large: its 26 lines aren’t shown here.

apps/server/src/environment/ServerEnvironment.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/server/src/environment/ServerEnvironment.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/server/src/http.ts+1−16

This diff is large: its 31 lines aren’t shown here.

apps/server/src/imageMime.test.ts+57−0

This diff is large: its 64 lines aren’t shown here.

apps/server/src/imageMime.ts+63−8

This diff is large: its 90 lines aren’t shown here.

apps/server/src/keybindings.test.ts+22−0

This diff is large: its 29 lines aren’t shown here.

apps/server/src/keybindings.ts+3−1

This diff is large: its 11 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts+6−0

This diff is large: its 48 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts+2−1

This diff is large: its 17 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts+24−20

This diff is large: its 72 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts+2−0

This diff is large: its 16 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts+3−0

This diff is large: its 24 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts+6−2

This diff is large: its 50 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts+3−0

This diff is large: its 24 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts+7−1

This diff is large: its 57 lines aren’t shown here.

apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts+7−0

This diff is large: its 14 lines aren’t shown here.

apps/server/src/orchestration-v2/ShellStream.test.ts+33−0

This diff is large: its 34 lines aren’t shown here.

apps/server/src/orchestration-v2/ShellStream.ts+18−0

This diff is large: its 29 lines aren’t shown here.

apps/server/src/orchestration-v2/http.ts+117−0

This diff is large: its 118 lines aren’t shown here.

apps/server/src/orchestration/Layers/OrchestrationEngine.ts+7−2

This diff is large: its 23 lines aren’t shown here.

apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+31−0

This diff is large: its 52 lines aren’t shown here.

apps/server/src/orchestration/Services/OrchestrationEngine.ts+12−0

This diff is large: its 30 lines aren’t shown here.

apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts+11−0

This diff is large: its 25 lines aren’t shown here.

apps/server/src/orchestration/commandInvariants.ts+25−0

This diff is large: its 39 lines aren’t shown here.

apps/server/src/orchestration/decider.ts+23−2

This diff is large: its 64 lines aren’t shown here.

apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts+14−0

This diff is large: its 21 lines aren’t shown here.

apps/server/src/persistence/Layers/OrchestrationEventStore.ts+3−2

This diff is large: its 26 lines aren’t shown here.

apps/server/src/persistence/Migrations.ts+4−8

This diff is large: its 20 lines aren’t shown here.

apps/server/src/persistence/ProviderSessionRuntime.ts+20−6

This diff is large: its 47 lines aren’t shown here.

apps/server/src/persistence/RepositoryErrorCorrelation.test.ts+18−10

This diff is large: its 43 lines aren’t shown here.

apps/server/src/persistence/Services/OrchestrationEventStore.ts+6−0

This diff is large: its 13 lines aren’t shown here.

apps/server/src/provider/CodexDeveloperInstructions.ts+25−0

This diff is large: its 33 lines aren’t shown here.

apps/server/src/provider/Drivers/ClaudeDriver.ts+3−2

This diff is large: its 22 lines aren’t shown here.

apps/server/src/provider/Drivers/ClaudeExecutable.test.ts+124−0

This diff is large: its 125 lines aren’t shown here.

apps/server/src/provider/Drivers/ClaudeExecutable.ts+90−0

This diff is large: its 91 lines aren’t shown here.

apps/server/src/provider/Drivers/ClaudeHome.test.ts+11−2

This diff is large: its 26 lines aren’t shown here.

apps/server/src/provider/Drivers/ClaudeHome.ts+9−2

This diff is large: its 26 lines aren’t shown here.

apps/server/src/provider/Drivers/CodexHomeLayout.test.ts+36−0

This diff is large: its 56 lines aren’t shown here.

apps/server/src/provider/Drivers/CodexHomeLayout.ts+29−10

This diff is large: its 64 lines aren’t shown here.

apps/server/src/provider/Drivers/GrokDriver.ts+2−0

This diff is large: its 16 lines aren’t shown here.

apps/server/src/provider/Layers/ClaudeProvider.ts+68−12

This diff is large: its 193 lines aren’t shown here.

apps/server/src/provider/Layers/CodexProvider.ts+14−4

This diff is large: its 60 lines aren’t shown here.

apps/server/src/provider/Layers/CodexSessionRuntime.test.ts+101−3

This diff is large: its 151 lines aren’t shown here.

apps/server/src/provider/Layers/CodexSessionRuntime.ts+14−14

This diff is large: its 61 lines aren’t shown here.

apps/server/src/provider/Layers/CursorProvider.ts+1−4

This diff is large: its 33 lines aren’t shown here.

apps/server/src/provider/Layers/GrokProvider.ts+7−9

This diff is large: its 49 lines aren’t shown here.

apps/server/src/provider/Layers/OpenCodeProvider.test.ts+20−2

This diff is large: its 39 lines aren’t shown here.

apps/server/src/provider/Layers/OpenCodeProvider.ts+27−40

This diff is large: its 123 lines aren’t shown here.

apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/server/src/provider/Layers/ProviderRegistry.test.ts+48−6

This diff is large: its 115 lines aren’t shown here.

apps/server/src/provider/Layers/codexLaunchArgs.test.ts+59−0

This diff is large: its 60 lines aren’t shown here.

apps/server/src/provider/Layers/codexLaunchArgs.ts+48−0

This diff is large: its 49 lines aren’t shown here.

apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts+37−0

This diff is large: its 44 lines aren’t shown here.

apps/server/src/provider/acp/AcpSessionRuntime.ts+23−6

This diff is large: its 114 lines aren’t shown here.

apps/server/src/provider/acp/GrokAcpSupport.ts+2−1

This diff is large: its 15 lines aren’t shown here.

apps/server/src/provider/opencodeRuntime.cliParsers.test.ts+229−0

This diff is large: its 230 lines aren’t shown here.

apps/server/src/provider/opencodeRuntime.ts+177−1

This diff is large: its 219 lines aren’t shown here.

apps/server/src/provider/providerSnapshot.test.ts+20−2

This diff is large: its 41 lines aren’t shown here.

apps/server/src/provider/providerSnapshot.ts+2−3

This diff is large: its 26 lines aren’t shown here.

apps/server/src/relay/AgentAwarenessRelay.ts+88−0

This diff is large: its 123 lines aren’t shown here.

apps/server/src/server.ts+6−1

This diff is large: its 28 lines aren’t shown here.

apps/server/src/serverSettings.test.ts+2−0

This diff is large: its 16 lines aren’t shown here.

apps/server/src/terminal/Manager.test.ts+57−0

This diff is large: its 64 lines aren’t shown here.

apps/server/src/terminal/Manager.ts+48−1

This diff is large: its 63 lines aren’t shown here.

apps/server/src/textGeneration/ClaudeTextGeneration.test.ts+14−14

This diff is large: its 81 lines aren’t shown here.

apps/server/src/textGeneration/CodexTextGeneration.test.ts+70−2

This diff is large: its 116 lines aren’t shown here.

apps/server/src/textGeneration/CodexTextGeneration.ts+3−0

This diff is large: its 24 lines aren’t shown here.

apps/server/src/textGeneration/GrokTextGeneration.ts+3−1

This diff is large: its 22 lines aren’t shown here.

apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts+8−0

This diff is large: its 15 lines aren’t shown here.

apps/server/src/vcs/GitVcsDriverCore.test.ts+91−0

This diff is large: its 120 lines aren’t shown here.

apps/server/src/vcs/GitVcsDriverCore.ts+18−3

This diff is large: its 56 lines aren’t shown here.

apps/server/src/ws.ts+206−83

This diff is large: its 381 lines aren’t shown here.

apps/server/vite.config.ts+3−0

This diff is large: its 24 lines aren’t shown here.

apps/web/package.json+1−1

This diff is large: its 8 lines aren’t shown here.

apps/web/public/apple-touch-icon.png+0−0

Binary file not shown.

apps/web/public/favicon-16x16.png+0−0

Binary file not shown.

apps/web/public/favicon-32x32.png+0−0

Binary file not shown.

apps/web/public/favicon.ico+0−0

Binary file not shown.

apps/web/src/assets/assetUrls.ts+22−2

This diff is large: its 41 lines aren’t shown here.

apps/web/src/branding.logic.ts+4−0

This diff is large: its 11 lines aren’t shown here.

apps/web/src/branding.test.ts+11−0

This diff is large: its 18 lines aren’t shown here.

apps/web/src/browser/browserTargetResolver.test.ts+104−2

This diff is large: its 134 lines aren’t shown here.

apps/web/src/browser/browserTargetResolver.ts+95−46

This diff is large: its 180 lines aren’t shown here.

apps/web/src/cloud/connectCliAuth.test.ts+69−0

This diff is large: its 70 lines aren’t shown here.

apps/web/src/cloud/connectCliAuth.ts+91−0

This diff is large: its 92 lines aren’t shown here.

apps/web/src/cloud/connectOnboarding.ts+18−0

This diff is large: its 19 lines aren’t shown here.

apps/web/src/cloud/linkEnvironment.test.ts+55−0

This diff is large: its 90 lines aren’t shown here.

apps/web/src/cloud/linkEnvironment.ts+19−5

This diff is large: its 71 lines aren’t shown here.

apps/web/src/cloud/linkEnvironmentAtoms.ts+6−2

This diff is large: its 22 lines aren’t shown here.

apps/web/src/cloud/publicConfig.ts+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/cloud/useCloudLinkController.ts+163−0

This diff is large: its 164 lines aren’t shown here.

apps/web/src/components/AppSidebarLayout.tsx+96−18

This diff is large: its 180 lines aren’t shown here.

apps/web/src/components/ChatMarkdown.tsx+22−5

This diff is large: its 56 lines aren’t shown here.

apps/web/src/components/ChatView.logic.test.ts+38−1

This diff is large: its 50 lines aren’t shown here.

apps/web/src/components/ChatView.logic.ts+9−1

This diff is large: its 51 lines aren’t shown here.

apps/web/src/components/ChatView.tsx+257−53

This diff is large: its 591 lines aren’t shown here.

apps/web/src/components/ComposerPromptEditor.test.ts+73−0

This diff is large: its 74 lines aren’t shown here.

apps/web/src/components/ComposerPromptEditor.tsx+149−4

This diff is large: its 230 lines aren’t shown here.

apps/web/src/components/ConnectionStatusDot.tsx+56−0

This diff is large: its 57 lines aren’t shown here.

apps/web/src/components/DiffPanel.tsx+14−4

This diff is large: its 45 lines aren’t shown here.

apps/web/src/components/GitActionsControl.logic.test.ts+13−0

This diff is large: its 27 lines aren’t shown here.

apps/web/src/components/GitActionsControl.logic.ts+10−0

This diff is large: its 17 lines aren’t shown here.

apps/web/src/components/GitActionsControl.tsx+2−3

This diff is large: its 23 lines aren’t shown here.

apps/web/src/components/ProjectFavicon.tsx+2−1

This diff is large: its 15 lines aren’t shown here.

apps/web/src/components/RightPanelTabs.tsx+15−0

This diff is large: its 29 lines aren’t shown here.

apps/web/src/components/Sidebar.logic.test.ts+140−0

This diff is large: its 164 lines aren’t shown here.

apps/web/src/components/Sidebar.logic.ts+120−20

This diff is large: its 173 lines aren’t shown here.

apps/web/src/components/Sidebar.tsx+96−33

This diff is large: its 231 lines aren’t shown here.

apps/web/src/components/SidebarStageBackdrop.tsx+320−0

This diff is large: its 321 lines aren’t shown here.

apps/web/src/components/ThreadStatusIndicators.tsx+5−3

This diff is large: its 29 lines aren’t shown here.

apps/web/src/components/ThreadTerminalDrawer.tsx+43−14

This diff is large: its 101 lines aren’t shown here.

apps/web/src/components/auth/AuthSurfaceShell.tsx+44−0

This diff is large: its 45 lines aren’t shown here.

apps/web/src/components/chat/ChangedFilesTree.test.tsx+26−1

This diff is large: its 34 lines aren’t shown here.

apps/web/src/components/chat/ChangedFilesTree.tsx+64−32

This diff is large: its 123 lines aren’t shown here.

apps/web/src/components/chat/ChatComposer.tsx+128−38

This diff is large: its 298 lines aren’t shown here.

apps/web/src/components/chat/ComposerBannerStack.test.tsx+37−0

This diff is large: its 38 lines aren’t shown here.

apps/web/src/components/chat/ComposerBannerStack.tsx+28−19

This diff is large: its 67 lines aren’t shown here.

apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx+29−0

This diff is large: its 30 lines aren’t shown here.

apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx+18−0

This diff is large: its 32 lines aren’t shown here.

apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/components/chat/DraftHeroHeadline.tsx+114−0

This diff is large: its 115 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.logic.ts+39−0

This diff is large: its 46 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.test.tsx+77−1

This diff is large: its 102 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.tsx+113−48

This diff is large: its 294 lines aren’t shown here.

apps/web/src/components/chat/OpenInPicker.tsx+39−4

This diff is large: its 178 lines aren’t shown here.

apps/web/src/components/chat/ThreadErrorBanner.tsx+9−9

This diff is large: its 27 lines aren’t shown here.

apps/web/src/components/chat/TraitsPicker.tsx+96−56

This diff is large: its 181 lines aren’t shown here.

apps/web/src/components/chat/composerMentionDrag.test.ts+123−0

This diff is large: its 124 lines aren’t shown here.

apps/web/src/components/chat/composerMentionDrag.ts+98−0

This diff is large: its 99 lines aren’t shown here.

apps/web/src/components/chat/draftHeroTransition.test.ts+123−0

This diff is large: its 124 lines aren’t shown here.

apps/web/src/components/chat/draftHeroTransition.ts+82−0

This diff is large: its 83 lines aren’t shown here.

apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx+260−0

This diff is large: its 261 lines aren’t shown here.

apps/web/src/components/cloud/ConnectCliAuthSurface.tsx+188−0

This diff is large: its 189 lines aren’t shown here.

apps/web/src/components/cloud/ConnectOnboardingDialog.tsx+433−0

This diff is large: its 434 lines aren’t shown here.

apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.test.ts+55−0

This diff is large: its 56 lines aren’t shown here.

apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.ts+58−0

This diff is large: its 59 lines aren’t shown here.

apps/web/src/components/composerInlineTokenPaste.ts+104−0

This diff is large: its 105 lines aren’t shown here.

apps/web/src/components/desktopUpdate.logic.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/web/src/components/files/FileBrowserPanel.tsx+140−0

This diff is large: its 183 lines aren’t shown here.

apps/web/src/components/files/FilePreviewPanel.tsx+50−2

This diff is large: its 87 lines aren’t shown here.

apps/web/src/components/files/fileTreeDragMention.test.ts+112−0

This diff is large: its 113 lines aren’t shown here.

apps/web/src/components/files/fileTreeDragMention.ts+95−0

This diff is large: its 96 lines aren’t shown here.

apps/web/src/components/files/projectFilesQueryState.ts+8−2

This diff is large: its 32 lines aren’t shown here.

apps/web/src/components/preview/AgentBrowserCursor.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/components/preview/PreviewAutomationHosts.tsx+9−7

This diff is large: its 37 lines aren’t shown here.

apps/web/src/components/preview/PreviewChromeRow.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/components/preview/PreviewLocalServerCard.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/components/preview/PreviewPanelShell.test.ts+13−0

This diff is large: its 14 lines aren’t shown here.

apps/web/src/components/preview/PreviewPanelShell.tsx+3−0

This diff is large: its 13 lines aren’t shown here.

apps/web/src/components/preview/PreviewUnreachable.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/components/preview/PreviewView.test.tsx+194−0

This diff is large: its 195 lines aren’t shown here.

apps/web/src/components/preview/PreviewView.tsx+33−15

This diff is large: its 76 lines aren’t shown here.

apps/web/src/components/preview/errorCodeMessages.ts+3−3

This diff is large: its 15 lines aren’t shown here.

apps/web/src/components/settings/ConnectionsSettings.tsx+102−412

This diff is large: its 667 lines aren’t shown here.

apps/web/src/components/settings/DiagnosticsSettings.tsx+8−5

This diff is large: its 38 lines aren’t shown here.

apps/web/src/components/settings/KeybindingsSettings.tsx+2−0

This diff is large: its 16 lines aren’t shown here.

apps/web/src/components/settings/ProviderModelsSection.tsx+3−3

This diff is large: its 27 lines aren’t shown here.

apps/web/src/components/settings/ProviderSettingsForm.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/web/src/components/settings/ScheduledTasksSettings.tsx+1−0

This diff is large: its 8 lines aren’t shown here.

apps/web/src/components/settings/SettingsPanels.tsx+13−3

This diff is large: its 55 lines aren’t shown here.

apps/web/src/components/settings/itemRows.ts+5−0

This diff is large: its 6 lines aren’t shown here.

apps/web/src/components/sidebar/SidebarUpdatePill.tsx+55−1

This diff is large: its 72 lines aren’t shown here.

apps/web/src/components/threadSidebarWidth.test.ts+34−0

This diff is large: its 35 lines aren’t shown here.

apps/web/src/components/threadSidebarWidth.ts+22−0

This diff is large: its 23 lines aren’t shown here.

apps/web/src/components/ui/menu.tsx+28−18

This diff is large: its 61 lines aren’t shown here.

apps/web/src/components/ui/sidebar.tsx+14−6

This diff is large: its 63 lines aren’t shown here.

apps/web/src/composer-logic.test.ts+15−0

This diff is large: its 25 lines aren’t shown here.

apps/web/src/composer-logic.ts+7−0

This diff is large: its 14 lines aren’t shown here.

apps/web/src/connection/platform.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/web/src/connection/runtime.ts+6−1

This diff is large: its 24 lines aren’t shown here.

apps/web/src/connection/storage.ts+122−7

This diff is large: its 222 lines aren’t shown here.

apps/web/src/contextMenuFallback.test.ts+17−0

This diff is large: its 24 lines aren’t shown here.

apps/web/src/contextMenuFallback.ts+3−1

This diff is large: its 11 lines aren’t shown here.

apps/web/src/diffPanelStore.ts+6−1

This diff is large: its 21 lines aren’t shown here.

apps/web/src/environmentGrouping.test.ts+121−0

This diff is large: its 133 lines aren’t shown here.

apps/web/src/environments/primary/auth.ts+2−0

This diff is large: its 9 lines aren’t shown here.

apps/web/src/hooks/useHandleNewThread.ts+3−0

This diff is large: its 24 lines aren’t shown here.

apps/web/src/hooks/usePreviewPanelInlineSize.ts+5−4

This diff is large: its 21 lines aren’t shown here.

apps/web/src/hooks/useThreadActions.ts+3−3

This diff is large: its 30 lines aren’t shown here.

apps/web/src/hostedPairing.ts+2−2

This diff is large: its 9 lines aren’t shown here.

apps/web/src/index.css+220−13

This diff is large: its 325 lines aren’t shown here.

apps/web/src/lib/windowControlsOverlay.ts+26−0

This diff is large: its 35 lines aren’t shown here.

apps/web/src/main.tsx+5−1

This diff is large: its 20 lines aren’t shown here.

apps/web/src/markdown-list-indentation.test.tsx+82−0

This diff is large: its 83 lines aren’t shown here.

apps/web/src/markdown-list-indentation.ts+143−0

This diff is large: its 144 lines aren’t shown here.

apps/web/src/modelSelection.test.ts+33−0

This diff is large: its 40 lines aren’t shown here.

apps/web/src/modelSelection.ts+4−6

This diff is large: its 43 lines aren’t shown here.

apps/web/src/projectScripts.test.ts+41−0

This diff is large: its 55 lines aren’t shown here.

apps/web/src/projectScripts.ts+25−0

This diff is large: its 32 lines aren’t shown here.

apps/web/src/rightPanelStore.test.ts+15−0

This diff is large: its 22 lines aren’t shown here.

apps/web/src/routeTree.gen.ts+42−0

This diff is large: its 156 lines aren’t shown here.

apps/web/src/routes/__root.tsx+3−1

This diff is large: its 25 lines aren’t shown here.

apps/web/src/routes/_chat.draft.$draftId.tsx+17−16

This diff is large: its 62 lines aren’t shown here.

apps/web/src/routes/_chat.index.tsx+114−3

This diff is large: its 133 lines aren’t shown here.

apps/web/src/routes/connect.tsx+13−0

This diff is large: its 14 lines aren’t shown here.

apps/web/src/routes/connect_.callback.tsx+13−0

This diff is large: its 14 lines aren’t shown here.

apps/web/src/sidebarProjectGrouping.ts+71−10

This diff is large: its 106 lines aren’t shown here.

apps/web/src/state/desktopUpdate.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/web/src/state/entities.ts+5−0

This diff is large: its 19 lines aren’t shown here.

apps/web/src/state/shell.ts+31−0

This diff is large: its 45 lines aren’t shown here.

apps/web/src/timestampFormat.test.ts+60−0

This diff is large: its 75 lines aren’t shown here.

apps/web/src/timestampFormat.ts+42−10

This diff is large: its 117 lines aren’t shown here.

apps/web/src/vite-env.d.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/web/vite.config.ts+13−0

This diff is large: its 41 lines aren’t shown here.

assets/README.md+50−0

This diff is large: its 51 lines aren’t shown here.

assets/dev/app-icon.icon/Assets/annotations.svg+37−0

This diff is large: its 38 lines aren’t shown here.

assets/dev/app-icon.icon/Assets/background.svg+51−0

This diff is large: its 52 lines aren’t shown here.

assets/dev/app-icon.icon/Assets/text.svg+3−0

This diff is large: its 4 lines aren’t shown here.

assets/dev/app-icon.icon/icon.jsonrenamed from apps/mobile/assets/icon-composer-dev.icon/icon.json+17−12

This diff is large: its 53 lines aren’t shown here.

assets/dev/blueprint-icon-composer.icon/Assets/T3.svg+0−3

This diff is large: its 4 lines aren’t shown here.

assets/dev/blueprint-icon-composer.icon/Assets/Texturelabs_Paper_381XL.jpg+0−0

Binary file not shown.

assets/dev/blueprint-icon-composer.icon/Assets/gpt-image-1.5-kn76n9hynne5q3qxy3g91chp2d84t871.png+0−0

Binary file not shown.

assets/dev/blueprint-icon-composer.icon/icon.json+0−47

This diff is large: its 48 lines aren’t shown here.

assets/dev/blueprint-ios-1024.png+0−0

Binary file not shown.

assets/dev/blueprint-macos-1024.png+0−0

Binary file not shown.

assets/dev/blueprint-universal-1024.png+0−0

Binary file not shown.

assets/dev/blueprint-web-apple-touch-180.png+0−0

Binary file not shown.

assets/dev/blueprint-web-favicon-16x16.png+0−0

Binary file not shown.

assets/dev/blueprint-web-favicon-32x32.png+0−0

Binary file not shown.

assets/dev/blueprint-web-favicon.ico+0−0

Binary file not shown.

assets/dev/blueprint-windows.ico+0−0

Binary file not shown.

assets/nightly/app-icon.icon/Assets/background.svg+43−0

This diff is large: its 44 lines aren’t shown here.

assets/nightly/app-icon.icon/Assets/cloud-lower-left.svg+21−0

This diff is large: its 22 lines aren’t shown here.

assets/nightly/app-icon.icon/Assets/cloud-upper-right.svg+21−0

This diff is large: its 22 lines aren’t shown here.

assets/nightly/app-icon.icon/Assets/text.svg+3−0

This diff is large: its 4 lines aren’t shown here.

assets/nightly/app-icon.icon/icon.json+94−0

This diff is large: its 95 lines aren’t shown here.

assets/nightly/blueprint-ios-1024.png+0−0

Binary file not shown.

assets/nightly/blueprint-macos-1024.png+0−0

Binary file not shown.

assets/nightly/blueprint-universal-1024.png+0−0

Binary file not shown.

assets/nightly/blueprint-web-apple-touch-180.png+0−0

Binary file not shown.

assets/nightly/blueprint-web-favicon-16x16.png+0−0

Binary file not shown.

assets/nightly/blueprint-web-favicon-32x32.png+0−0

Binary file not shown.

assets/nightly/blueprint-web-favicon.ico+0−0

Binary file not shown.

assets/nightly/blueprint-windows.ico+0−0

Binary file not shown.

assets/nightly/nightly-ios-1024.png+0−0

Binary file not shown.

assets/nightly/nightly-macos-1024.png+0−0

Binary file not shown.

assets/nightly/nightly-universal-1024.png+0−0

Binary file not shown.

assets/nightly/nightly-web-apple-touch-180.png+0−0

Binary file not shown.

assets/nightly/nightly-web-favicon-16x16.png+0−0

Binary file not shown.

assets/nightly/nightly-web-favicon-32x32.png+0−0

Binary file not shown.

assets/nightly/nightly-web-favicon.ico+0−0

Binary file not shown.

assets/nightly/nightly-windows.ico+0−0

Binary file not shown.

assets/prod/app-icon.icon/Assets/text.svgrenamed from apps/mobile/assets/icon-composer-dev.icon/Assets/T3.svg+0−0

File renamed without changes.

assets/prod/app-icon.icon/icon.jsonrenamed from apps/mobile/assets/icon-composer-prod.icon/icon.json+2−2

This diff is large: its 11 lines aren’t shown here.

assets/prod/black-ios-1024.png+0−0

Binary file not shown.

assets/prod/black-macos-1024.png+0−0

Binary file not shown.

assets/prod/black-universal-1024.png+0−0

Binary file not shown.

assets/prod/t3-black-web-apple-touch-180.png+0−0

Binary file not shown.

assets/prod/t3-black-web-favicon-16x16.png+0−0

Binary file not shown.

assets/prod/t3-black-web-favicon-32x32.png+0−0

Binary file not shown.

assets/prod/t3-black-web-favicon.ico+0−0

Binary file not shown.

assets/prod/t3-black-windows.ico+0−0

Binary file not shown.

docs/architecture/overview.md+18−26

This diff is large: its 65 lines aren’t shown here.

docs/operations/ci.md+1−1

This diff is large: its 8 lines aren’t shown here.

docs/operations/effect-fn-checklist.md+89−89

This diff is large: its 232 lines aren’t shown here.

docs/operations/mobile-app-store-screenshots.md+159−0

This diff is large: its 160 lines aren’t shown here.

docs/operations/observability.md+17−9

This diff is large: its 82 lines aren’t shown here.

docs/reference/scripts.md+21−19

This diff is large: its 60 lines aren’t shown here.

experiments/messages-glass-lab/MessagesGlassLab.xcodeproj/project.pbxproj+285−0

This diff is large: its 286 lines aren’t shown here.

experiments/messages-glass-lab/MessagesGlassLab/ContentView.swift+386−0

This diff is large: its 387 lines aren’t shown here.

experiments/messages-glass-lab/MessagesGlassLab/MessagesGlassLabApp.swift+10−0

This diff is large: its 11 lines aren’t shown here.

favicon.svg+4−0

This diff is large: its 5 lines aren’t shown here.

infra/relay/migrations/postgres/20260706061126_migration/migration.sql+3−0

This diff is large: its 4 lines aren’t shown here.

infra/relay/migrations/postgres/20260706061126_migration/snapshot.json+1479−0

This diff is large: its 1480 lines aren’t shown here.

infra/relay/package.json+2−0

This diff is large: its 9 lines aren’t shown here.

infra/relay/src/agentActivity/AgentActivityPublisher.test.ts+190−6

This diff is large: its 239 lines aren’t shown here.

infra/relay/src/agentActivity/AgentActivityPublisher.ts+82−13

This diff is large: its 165 lines aren’t shown here.

infra/relay/src/agentActivity/AgentActivityRows.test.ts+9−0

This diff is large: its 16 lines aren’t shown here.

infra/relay/src/agentActivity/AgentActivityRows.ts+92−1

This diff is large: its 135 lines aren’t shown here.

infra/relay/src/agentActivity/ApnsClient.test.ts+108−1

This diff is large: its 157 lines aren’t shown here.

infra/relay/src/agentActivity/ApnsClient.ts+39−115

This diff is large: its 238 lines aren’t shown here.

infra/relay/src/agentActivity/ApnsDeliveries.test.ts+644−36

This diff is large: its 823 lines aren’t shown here.

infra/relay/src/agentActivity/ApnsDeliveries.ts+460−42

This diff is large: its 740 lines aren’t shown here.

infra/relay/src/agentActivity/ApnsDeliveryQueue.ts+7−0

This diff is large: its 27 lines aren’t shown here.

infra/relay/src/agentActivity/ApnsProviderTokens.test.ts+75−0

This diff is large: its 76 lines aren’t shown here.

infra/relay/src/agentActivity/ApnsProviderTokens.ts+63−0

This diff is large: its 64 lines aren’t shown here.

infra/relay/src/agentActivity/Devices.test.ts+4−0

This diff is large: its 18 lines aren’t shown here.

infra/relay/src/agentActivity/Devices.ts+88−82

This diff is large: its 198 lines aren’t shown here.

infra/relay/src/agentActivity/LiveActivities.test.ts+51−0

This diff is large: its 58 lines aren’t shown here.

infra/relay/src/agentActivity/LiveActivities.ts+24−4

This diff is large: its 49 lines aren’t shown here.

infra/relay/src/agentActivity/MobileRegistrations.test.ts+49−41

This diff is large: its 169 lines aren’t shown here.

infra/relay/src/agentActivity/MobileRegistrations.ts+22−1

This diff is large: its 60 lines aren’t shown here.

infra/relay/src/agentActivity/agentActivityPayloads.ts+39−1

This diff is large: its 53 lines aren’t shown here.

infra/relay/src/agentActivity/apnsDeliveryJobs.ts+33−1

This diff is large: its 79 lines aren’t shown here.

infra/relay/src/agentActivity/apnsJwt.ts+160−0

This diff is large: its 161 lines aren’t shown here.

infra/relay/src/environments/EnvironmentLinker.test.ts+75−1

This diff is large: its 97 lines aren’t shown here.

infra/relay/src/environments/EnvironmentLinker.ts+26−1

This diff is large: its 41 lines aren’t shown here.

infra/relay/src/http/Api.test.ts+31−0

This diff is large: its 57 lines aren’t shown here.

infra/relay/src/http/Api.ts+54−1

This diff is large: its 83 lines aren’t shown here.

infra/relay/src/persistence/schema.ts+2−0

This diff is large: its 9 lines aren’t shown here.

infra/relay/src/worker.ts+15−2

This diff is large: its 45 lines aren’t shown here.

package.json+5−2

This diff is large: its 28 lines aren’t shown here.

packages/client-runtime/src/connection/errors.ts+9−0

This diff is large: its 16 lines aren’t shown here.

packages/client-runtime/src/connection/registry.test.ts+4−0

This diff is large: its 11 lines aren’t shown here.

packages/client-runtime/src/connection/resolver.test.ts+2−0

This diff is large: its 16 lines aren’t shown here.

packages/client-runtime/src/connection/supervisor.test.ts+1−1

This diff is large: its 9 lines aren’t shown here.

packages/client-runtime/src/platform/orchestrationCache.test.ts+3−2

This diff is large: its 15 lines aren’t shown here.

packages/client-runtime/src/platform/orchestrationCache.ts+3−3

This diff is large: its 26 lines aren’t shown here.

packages/client-runtime/src/platform/persistence.ts+36−3

This diff is large: its 68 lines aren’t shown here.

packages/client-runtime/src/relay/discovery.test.ts+52−0

This diff is large: its 80 lines aren’t shown here.

packages/client-runtime/src/relay/discovery.ts+26−5

This diff is large: its 46 lines aren’t shown here.

packages/client-runtime/src/relay/managedRelay.ts+49−5

This diff is large: its 122 lines aren’t shown here.

packages/client-runtime/src/relay/managedRelayState.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

packages/client-runtime/src/relay/managedRelayState.ts+4−4

This diff is large: its 36 lines aren’t shown here.

packages/client-runtime/src/rpc/client.ts+88−52

This diff is large: its 182 lines aren’t shown here.

packages/client-runtime/src/rpc/http.ts+2−0

This diff is large: its 16 lines aren’t shown here.

packages/client-runtime/src/rpc/session.test.ts+78−2

This diff is large: its 131 lines aren’t shown here.

packages/client-runtime/src/rpc/session.ts+10−4

This diff is large: its 32 lines aren’t shown here.

packages/client-runtime/src/state/environmentHttpAuth.ts+73−0

This diff is large: its 74 lines aren’t shown here.

packages/client-runtime/src/state/projects.ts+5−31

This diff is large: its 77 lines aren’t shown here.

packages/client-runtime/src/state/server.test.ts+175−2

This diff is large: its 196 lines aren’t shown here.

packages/client-runtime/src/state/server.ts+161−8

This diff is large: its 246 lines aren’t shown here.

packages/client-runtime/src/state/shell-sync.test.ts+207−3

This diff is large: its 272 lines aren’t shown here.

packages/client-runtime/src/state/shell.ts+84−15

This diff is large: its 176 lines aren’t shown here.

packages/client-runtime/src/state/shellReducer.ts+4−1

This diff is large: its 12 lines aren’t shown here.

packages/client-runtime/src/state/shellSnapshotHttp.ts+92−0

This diff is large: its 93 lines aren’t shown here.

packages/client-runtime/src/state/threadDetail.ts+1−1

This diff is large: its 9 lines aren’t shown here.

packages/client-runtime/src/state/threadSnapshotHttp.ts+120−0

This diff is large: its 121 lines aren’t shown here.

packages/client-runtime/src/state/threadSort.test.ts+71−0

This diff is large: its 72 lines aren’t shown here.

packages/client-runtime/src/state/threadSort.ts+4−1

This diff is large: its 12 lines aren’t shown here.

packages/client-runtime/src/state/threadState.ts+16−0

This diff is large: its 17 lines aren’t shown here.

packages/client-runtime/src/state/threads-atoms.test.ts+2−2

This diff is large: its 15 lines aren’t shown here.

packages/client-runtime/src/state/threads-sync.test.ts+544−58

This diff is large: its 646 lines aren’t shown here.

packages/client-runtime/src/state/threads.ts+154−48

This diff is large: its 318 lines aren’t shown here.

packages/client-runtime/src/state/vcs.test.ts+232−0

This diff is large: its 233 lines aren’t shown here.

packages/client-runtime/src/state/vcs.ts+155−13

This diff is large: its 182 lines aren’t shown here.

packages/client-runtime/src/state/vcsAction.test.ts+40−0

This diff is large: its 47 lines aren’t shown here.

packages/client-runtime/src/state/vcsAction.ts+1−3

This diff is large: its 14 lines aren’t shown here.

packages/contracts/package.json+1−1

This diff is large: its 8 lines aren’t shown here.

packages/contracts/src/environment.ts+1−0

This diff is large: its 8 lines aren’t shown here.

packages/contracts/src/environmentHttp.ts+61−1

This diff is large: its 116 lines aren’t shown here.

packages/contracts/src/ipc.ts+14−0

This diff is large: its 42 lines aren’t shown here.

packages/contracts/src/model.ts+5−2

This diff is large: its 21 lines aren’t shown here.

packages/contracts/src/orchestration.ts+7−0

This diff is large: its 28 lines aren’t shown here.

packages/contracts/src/orchestrationV2.ts+44−2

This diff is large: its 71 lines aren’t shown here.

packages/contracts/src/relay.ts+28−0

This diff is large: its 55 lines aren’t shown here.

packages/contracts/src/rpc.ts+8−0

This diff is large: its 29 lines aren’t shown here.

packages/contracts/src/server.ts+4−0

This diff is large: its 11 lines aren’t shown here.

packages/contracts/src/settings.test.ts+4−0

This diff is large: its 30 lines aren’t shown here.

packages/contracts/src/settings.ts+12−4

This diff is large: its 44 lines aren’t shown here.

packages/effect-codex-app-server/scripts/generate.ts+3−1

This diff is large: its 22 lines aren’t shown here.

packages/effect-codex-app-server/src/_generated/meta.gen.ts+43−1

This diff is large: its 248 lines aren’t shown here.

packages/effect-codex-app-server/src/_generated/namespaces.gen.ts+16−1

This diff is large: its 69 lines aren’t shown here.

packages/effect-codex-app-server/src/_generated/schema.gen.ts+5825−1316

This diff is large: its 12757 lines aren’t shown here.

packages/effect-codex-app-server/src/protocol.test.ts+86−0

This diff is large: its 100 lines aren’t shown here.

packages/shared/package.json+8−0

This diff is large: its 22 lines aren’t shown here.

packages/shared/src/agentAwareness.ts+0−8

This diff is large: its 15 lines aren’t shown here.

packages/shared/src/cliArgs.test.ts+29−1

This diff is large: its 43 lines aren’t shown here.

packages/shared/src/cliArgs.ts+59−3

This diff is large: its 79 lines aren’t shown here.

packages/shared/src/connectAuth.test.ts+78−0

This diff is large: its 79 lines aren’t shown here.

packages/shared/src/connectAuth.ts+124−0

This diff is large: its 125 lines aren’t shown here.

packages/shared/src/dpop.ts+9−22

This diff is large: its 67 lines aren’t shown here.

packages/shared/src/hostProcess.ts+14−0

This diff is large: its 19 lines aren’t shown here.

packages/shared/src/model.test.ts+12−88

This diff is large: its 129 lines aren’t shown here.

packages/shared/src/model.ts+10−5

This diff is large: its 29 lines aren’t shown here.

packages/shared/src/path.ts+29−0

This diff is large: its 33 lines aren’t shown here.

packages/shared/src/projectFavicon.test.ts+28−0

This diff is large: its 29 lines aren’t shown here.

packages/shared/src/projectFavicon.ts+12−0

This diff is large: its 13 lines aren’t shown here.

packages/shared/src/remote.test.ts+64−0

This diff is large: its 71 lines aren’t shown here.

packages/shared/src/remote.ts+5−5

This diff is large: its 24 lines aren’t shown here.

patches/@expo%2Fmetro-config@56.0.14.patchrenamed from patches/@expo%2Fmetro-config@56.0.13.patch+0−0

File renamed without changes.

patches/@legendapp__list@3.2.0.patch+922−0

This diff is large: its 923 lines aren’t shown here.

patches/@react-native-menu__menu@2.0.0.patch+46−0

This diff is large: its 47 lines aren’t shown here.

patches/@react-navigation%2Fnative-stack@7.17.6.patch+102−0

This diff is large: its 103 lines aren’t shown here.

patches/expo-modules-jsi@56.0.10.patch+21−0

This diff is large: its 22 lines aren’t shown here.

patches/react-native-gesture-handler@2.31.2.patch+124−0

This diff is large: its 125 lines aren’t shown here.

patches/react-native-keyboard-controller@1.21.13.patch+483−0

This diff is large: its 484 lines aren’t shown here.

patches/react-native-screens@4.25.2.patch+1581−0

This diff is large: its 1582 lines aren’t shown here.

pnpm-lock.yaml+2203−1036

This diff is large: its 5934 lines aren’t shown here.

pnpm-workspace.yaml+57−43

This diff is large: its 157 lines aren’t shown here.

scripts/build-desktop-artifact.test.ts+89−14

This diff is large: its 187 lines aren’t shown here.

scripts/build-desktop-artifact.ts+87−39

This diff is large: its 233 lines aren’t shown here.

scripts/dev-runner.test.ts+51−12

This diff is large: its 138 lines aren’t shown here.

scripts/dev-runner.ts+21−15

This diff is large: its 105 lines aren’t shown here.

scripts/export-brand-icons.ts+810−0

This diff is large: its 811 lines aren’t shown here.

scripts/lib/brand-assets.test.ts+37−0

This diff is large: its 56 lines aren’t shown here.

scripts/lib/brand-assets.ts+20−7

This diff is large: its 44 lines aren’t shown here.

scripts/lib/icon-export.test.ts+47−0

This diff is large: its 48 lines aren’t shown here.

scripts/lib/icon-export.ts+72−0

This diff is large: its 73 lines aren’t shown here.

scripts/lib/public-config.ts+6−1

This diff is large: its 21 lines aren’t shown here.

scripts/mobile-showcase-environment.ts+569−0

This diff is large: its 570 lines aren’t shown here.

scripts/mobile-showcase.config.ts+206−0

This diff is large: its 207 lines aren’t shown here.

scripts/mobile-showcase.test.ts+296−0

This diff is large: its 297 lines aren’t shown here.

scripts/mobile-showcase.ts+1344−0

This diff is large: its 1345 lines aren’t shown here.

scripts/package.json+2−0

This diff is large: its 13 lines aren’t shown here.

vite.config.ts+4−0

This diff is large: its 11 lines aren’t shown here.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t