Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge a47c24e6f8 refactor(server): schema-decode Windows process diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 16:09:04 +00:00
Cursor AgentandJulius Marminge 3168972c0a test(server): assert normalized filesystem errors
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 16:07:48 +00:00
Cursor AgentandJulius Marminge d8e264ee18 refactor(server): use Effect filesystem for workspace reads
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 16:07:28 +00:00
53e3c98a55 feat(web): themed sidebar header art for nightly and dev builds (#4130)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 12:35:58 +02:00
Julius Marmingeandcodex 4f11740510 Add isolated app testing workflow (#4121)
Co-authored-by: codex <[email protected]>
2026-07-19 11:57:58 +02:00
Taras 1735e27d9e Add terminal selection copy action (#2904) 2026-07-19 00:05:09 +02:00
Julius Marminge ebe8afb1df Refresh splash screen and favicon branding (#4120) 2026-07-18 15:44:06 +02:00
Utkarsh PatilandJulius Marminge bf76535fe4 fix(desktop): Validate WSL node version against engine range after probe success (#3621)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 11:54:13 +00:00
5c66110e26 [fix/feat:ui] Make selected menu checks blue (#3234)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-18 13:50:33 +02:00
Maxwell Young da3c2030f7 [codex] canonicalize client timestamps (#4112) 2026-07-18 13:40:34 +02:00
Noah ZepnerandJulius Marminge 0506508e9b Allow failed remote environments to be removed (#4084)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:31:10 +02:00
Guilherme VieiraandJulius Marminge b859a575d1 fix(web): handle macOS Home and End in composer (#2508)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:23:57 +02:00
ssandJulius Marminge e63403fe92 [fix/feat:ui] Preserve open-in editor brand colors (#3225)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:22:37 +02:00
ssandJulius Marminge c0e161af06 [fix/feat:ui] Show default option badge (#3232)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:21:50 +02:00
d0b9f8d40d [codex] Route OpenCode missing-session errors through Effect (#3608)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:52 +02:00
Jake LeventhalandJulius Marminge d8b12ae801 Fix sending messages during active turns (#3919)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:14 +02:00
Jake LeventhalandJulius Marminge 31caa5652b Fix reopening existing Diff tab (#3973)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:18:18 +02:00
Aditya Mer e350c0a07b Add Grok to marketing site provider list (#3484) 2026-07-18 11:18:17 +00:00
Jake LeventhalandJulius Marminge 38e0bb07bb Default diffs to working changes (#3974)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:17:30 +02:00
Chris Michael Guzman 765e1b5fc0 perf(client): defer active thread cache writes (#4006) 2026-07-18 13:16:38 +02:00
AlexandJulius Marminge 03e20c875c fix(mobile): restore iOS home screen branding (#4025)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:14:59 +02:00
Julius Marmingeandcodex 2318e00270 fix(web): avoid duplicate mention text on paste
Co-authored-by: codex <[email protected]>
2026-07-18 13:05:45 +02:00
Yordis PrietoandJulius Marminge 4cfec8c128 feat: file explorer mention actions and zoom-aware context menus (#4054)
Signed-off-by: Yordis Prieto <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:05:26 +02:00
1bd2fa25e2 feat: draft hero landing on the index route (#4055)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-07-18 12:45:45 +02:00
5ca32661b7 fix(web): increase contrast of question option descriptions (#3867)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:53:50 +02:00
Julius Marminge 8b33799523 Preserve T3 Code identity in macOS development launcher (#4102) 2026-07-17 23:39:29 +02:00
Julius Marminge 24f9c2a08e Share MCP OAuth locks across Codex shadow homes (#4104) 2026-07-17 23:26:53 +02:00
31ca9e5531 fix(server): skip undecodable provider runtime rows when listing sessions (#3951)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 21:26:22 +00:00
73bf127d71 [codex] Fix provider update checks restore defaults (#3531)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:25:21 +02:00
43e2aeab38 [codex] fix: tolerate invalid latest user message timestamps (#3521)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:52 +02:00
b655a9f183 [codex] fix: guard invalid web timestamps (#3515)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:10 +02:00
Matt Van HornandJulius Marminge 4e3f2f04d5 fix(server): thread cwd through Claude capability probe (#2048) (#2124)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:22:19 +02:00
1047dac0c5 fix(terminal): strip AppImage runtime env from spawned terminals (#3108)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:21:19 +02:00
JamesandJulius Marminge 143b9c9280 fix(ux): spamming cmd + , no longer stack opening settings (#2757)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:20:28 +02:00
cf58cadd02 feat(server): include runtime model and effort in Codex developer instructions (#3948)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:15:53 +02:00
6a17629670 [codex] fix mobile composer Enter behavior (#3930)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:14:45 +02:00
7b8d12618b fix(web): inset Windows desktop scrollbars from resize edge (#4097)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:52:42 +00:00
Maxwell YoungandJulius Marminge bcd640bf4d [codex] prevent ACP assistant ID collisions after restarts (#3932)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:51:16 +02:00
b49a2e677c Remove unused code parameter from describePreviewError (#3970)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:50:33 +00:00
ed81c156da fix(server): image upload crashed dispatchCommand with a stack overflow (#3952)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:52 +02:00
Kriday DaveandJulius Marminge 7dc75127c2 Fix duplicate keybinding rule when replacing with an existing rule (#3969)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:35 +02:00
Fazal Kadivar e057e2e985 fix: prevent initial right-click from selecting a context menu item (#3877) 2026-07-17 21:42:13 +02:00
Olivier Melcher a7f6d97b94 Allow preview panel to grow on wide displays (#4044) 2026-07-17 18:40:24 +00:00
Kriday DaveandJulius Marminge f9a4f59930 Fix documented task-runner commands (bun run -> vp) (#3965)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 20:35:24 +02:00
BunnyGamezsc 7f1cb61031 fix(cursor): default binary path to cursor-agent (avoid path conflict w/ grok) (#4094) 2026-07-17 18:01:02 +00:00
Kriday Dave c49d424e3a Normalize protocol-relative remote host input as https (#3971) 2026-07-17 18:59:42 +02:00
Manuel De Ceglie 4804a9824f fix(marketing): correct Cursor icon color (#4090) 2026-07-17 18:56:59 +02:00
Manuel De Ceglie 0748134cec Update marketing GitHub star count (#4088) 2026-07-17 18:56:35 +02:00
Julius Marmingeandcodex 6e9987cf17 Refresh app icons across release variants (#4080)
Co-authored-by: codex <[email protected]>
2026-07-17 18:51:14 +02:00
Eric Tsai 8b5469863a fix(server): stabilize non-repository Git diagnostics (#4077) 2026-07-17 11:15:31 +00:00
Eric Tsai 58302b2010 fix(git): treat selected commit paths literally (#3998) 2026-07-17 11:14:29 +00:00
Hugo Vizcaino SantanaandClaude Opus 4.8 1f2797325b feat: show nightly update changelog tooltip (#3832)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-17 13:10:51 +02:00
Ishan c14a5ca492 Fix dropped events during initial thread snapshot (#4079) 2026-07-17 11:58:09 +02:00
Dimitar StoykovandClaude Opus 4.8 eb733c10f2 fix(server): use CLAUDE_CONFIG_DIR instead of HOME for Claude instanc… (#4017)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-17 11:46:55 +02:00
Julius Marmingeandcodex 8a02c71861 [codex] Expand real-route app store screenshot harness (#4014)
Co-authored-by: codex <[email protected]>
2026-07-17 11:33:40 +02:00
Julius Marmingeandcodex fdca15471d Add native mobile share target support (#4021)
Co-authored-by: codex <[email protected]>
2026-07-16 14:29:17 +00:00
Julius Marminge 5d68fca8f2 Fix iOS terminal Enter input encoding (#4043) 2026-07-16 16:17:03 +02:00
Julius Marminge 2a33a18716 fix(mobile): Send composer images in upload wire format (#4035) 2026-07-16 13:04:41 +02:00
Julius Marmingeandcodex bde0a4c0dd Resolve localhost preview URLs for remote environments (#4011)
Co-authored-by: codex <[email protected]>
2026-07-16 11:07:38 +02:00
Julius Marmingeandcodex 54f167e2e0 Normalize over-indented markdown list items (#4020)
Co-authored-by: codex <[email protected]>
2026-07-16 08:47:36 +00:00
Julius Marmingeandcodex d114e2772d Prevent duplicate project workspace roots (#3829)
Co-authored-by: codex <[email protected]>
2026-07-16 10:39:13 +02:00
Ishan 0418301de7 Fix macOS fullscreen titlebar spacing (#4019) 2026-07-16 09:34:33 +02:00
Julius Marminge 5e8b2c800e Isolate native diff highlight grammar state (#4029) 2026-07-16 09:24:41 +02:00
Julius Marmingeandcodex b98233702c [codex] Fix onboarding connection status (#4001)
Co-authored-by: codex <[email protected]>
2026-07-16 09:22:07 +02:00
Julius Marmingeandcodex ecb35f7583 Fix Legal modal header crash (#4000)
Co-authored-by: codex <[email protected]>
2026-07-15 10:48:55 +00:00
Julius Marmingeandcodex d359789ed4 docs: Add T3 Code Legal Docs (#3972)
Co-authored-by: codex <[email protected]>
2026-07-15 11:44:03 +02:00
Kriday Dave 462442667e fix(docs): replace stale codething-mvp absolute paths with repo-relative links (#3992) 2026-07-15 10:55:01 +02:00
Kriday Dave c69120f484 fix(docs): repair broken source links in architecture overview (#3991) 2026-07-15 10:54:40 +02:00
Kriday Dave 7b928d5488 fix(docs): correct CI task-runner commands in ci.md (#3990) 2026-07-15 10:53:48 +02:00
Theo Browne 2fdc704bbb perf(web): duty-cycle status animations and remove fixed noise overlay (#3978) 2026-07-15 09:08:33 +02:00
Julius Marminge 3513fa04fb Prepare Android beta branding and review diff UI (#3967) 2026-07-14 19:21:12 +02:00
Julius Marminge 735240f316 Skip stale working-task notifications (#3961) 2026-07-14 18:00:16 +02:00
Julius Marminge 8de254a685 Use client-side fallbacks for missing project favicons (#3959) 2026-07-14 17:59:00 +02:00
c1ec1915fc [codex] Add Android mobile support (#3579)
Co-authored-by: Horus Lugo <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Shivam Sharma <[email protected]>
Co-authored-by: Ben Davis <[email protected]>
Co-authored-by: Alex <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-12 12:03:35 +02:00
Vedank Purohit 619b0ece94 fix(marketing): show platform-appropriate commit shortcut on the website (#3644) 2026-07-12 09:58:55 +00:00
Jake Leventhal ef943a26ab Fix truncated chat error alert layout (#3899) 2026-07-12 09:50:15 +00:00
Julius Marmingeandcodex f61fa9499d Expose mobile PR indicator labels to accessibility (#3828)
Co-authored-by: codex <[email protected]>
2026-07-09 14:00:51 +00:00
Julius Marmingeandcodex 8619ef22e9 Show compact PR number badges in mobile thread rows (#3827)
Co-authored-by: codex <[email protected]>
2026-07-09 15:29:55 +02:00
Julius Marmingeandcodex 843cf176ea fix(mobile): embed fonts and render project favicons reliably (#3823)
Co-authored-by: codex <[email protected]>
2026-07-09 13:49:16 +02:00
Julius Marmingeandcodex ca1e08b5a0 [codex] Label max and ultra reasoning (#3824)
Co-authored-by: codex <[email protected]>
2026-07-09 10:20:32 +00:00
2250e3ee7a feat(client): persist offline environment data and mobile preferences (#3795)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-09 11:23:51 +02:00
Julius Marmingeandcodex 3201e00ad4 [codex] Preserve worktree metadata during branch sync (#3822)
Co-authored-by: codex <[email protected]>
2026-07-09 09:01:23 +02:00
Julius Marmingeandcodex e9127658a6 [codex] Upgrade Clerk stack (#3821)
Co-authored-by: codex <[email protected]>
2026-07-09 07:54:28 +02:00
Patricio Gómez Meneses 18a41388eb Fix desktop native optional dependency packaging (#3816) 2026-07-09 03:55:33 +00:00
Rowan 0c66565854 fix(release): bump electron-builder so pnpm 11 deduped deps land in the asar (#3790) 2026-07-08 04:38:45 -07:00
Julius Marminge e775bc6228 Upgrade Clerk toolchain to latest versions (#3785) 2026-07-08 04:30:07 -07:00
Julius MarmingeandCursor Agent 03ac1f0cd9 fix(release): stage pnpm 11 allowBuilds for desktop installs (#3781)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 15:55:18 -07:00
Julius MarmingeandCursor Agent 7778a1cea7 Use rounded depth logo for production splash screen (#3780)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 22:49:50 +00:00
Julius MarmingeandClaude Fable 5 dad0889766 Revert "Revert "Add T3 Connect onboarding for mobile and web"" (#3777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 14:17:18 -07:00
b9cc8d6ef1 Set up Cursor Cloud dev environment (web + Android toolchain) (#3755)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-07-07 13:18:58 -07:00
Julius MarmingeandClaude Fable 5 0e0040832c Expose Clerk Google sign-in env vars to Expo (#3772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 12:45:40 -07:00
Julius Marminge cd8b9fc8b3 Revert "Add T3 Connect onboarding for mobile and web" (#3776) 2026-07-07 12:40:12 -07:00
Julius Marminge fa6073e2e1 Add T3 Connect onboarding for mobile and web (#3765) 2026-07-07 12:39:56 -07:00
Julius Marminge 4eb1b57933 Lead with the outcome when no agents are active in the Live Activity (#3768) 2026-07-07 09:12:52 -07:00
572 changed files with 42969 additions and 5375 deletions

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
---
name: test-t3-app
description: 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.
---
# Test T3 App
## Start an isolated web environment
1. Run commands from the repository root.
2. Choose a base directory that belongs only to the current worktree or test:
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
Treat 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.
The 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.
## Authenticate the browser on the first navigation
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
2. 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.
3. Open that complete URL exactly once as the controlled browser's first navigation. Preserve the fragment and token verbatim.
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
5. Continue in the same browser context so its stored bearer session remains available.
Treat 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.
## Recover a consumed or expired pairing token
Create another token against the same database and web URL as the running dev server:
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
```
Use 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.
Always 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.
## Inspect or seed SQLite state
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
## Finish the test
Stop 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.
## Troubleshoot predictably
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
@@ -0,0 +1,4 @@
interface:
display_name: "T3 App Testing"
short_description: "Launch and seed isolated T3 test environments"
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
@@ -0,0 +1,58 @@
# SQLite fixtures
Load this reference only when inspecting or seeding local T3 state directly.
## Select the correct database
When `--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.
Start 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.
## Use the helper
List tables:
```bash
node apps/server/scripts/t3-sqlite-state.ts query \
--base-dir <base-dir> \
--sql "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
```
Inspect current columns before writing a fixture:
```bash
node apps/server/scripts/t3-sqlite-state.ts query \
--base-dir <base-dir> \
--sql "PRAGMA table_info(projection_threads)"
```
Apply a SQL fixture from a file:
```bash
node apps/server/scripts/t3-sqlite-state.ts exec \
--base-dir <base-dir> \
--file /tmp/t3-seed.sql
```
Use 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.
## Seed projection data carefully
The web UI primarily reads these projection tables:
- `projection_projects`
- `projection_threads`
- `projection_thread_messages`
- `projection_thread_activities`
- `projection_thread_sessions`
- `projection_turns`
- `projection_pending_approvals`
- `projection_thread_proposed_plans`
Inspect `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.
For 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.
Direct 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.
Use 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`.
+72
View File
@@ -0,0 +1,72 @@
---
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
alwaysApply: true
---
# Cursor Cloud specific instructions
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
## Toolchain
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
`vp check --fix` before committing.
## Running the web app
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
Without one installed the UI loads but no agent can run. Claude Code
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
server to pick up a newly installed provider CLI immediately.
## Android native builds (apps/mobile)
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
Gradle auto-downloads any additional pinned SDK packages on demand.
- Generate the native project first: from `apps/mobile`,
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
Android Studio bundles is what is installed.
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
scope for environment setup.
## Known flaky tests (unrelated to setup)
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
+4 -1
View File
@@ -57,7 +57,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
+4 -1
View File
@@ -80,7 +80,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
@@ -0,0 +1,134 @@
name: Mobile Showcase Screenshots
on:
workflow_dispatch:
inputs:
platform:
description: Device platforms to capture
required: true
default: all
type: choice
options:
- all
- ios
- android
appearance:
description: System appearances to capture
required: true
default: both
type: choice
options:
- both
- dark
- light
permissions:
contents: read
env:
NODE_OPTIONS: --max-old-space-size=8192
jobs:
ios:
name: iPhone 6.9, iPhone 6.5, and iPad 13
if: inputs.platform == 'all' || inputs.platform == 'ios'
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 60
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Capture iOS showcase
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
- name: Validate App Store Connect assets
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload iOS screenshots
if: always()
uses: actions/upload-artifact@v7
with:
name: app-store-connect-screenshots
path: artifacts/app-store/screenshots/apple/
if-no-files-found: warn
retention-days: 14
android:
name: Android phone, 7-inch tablet, and 10-inch tablet
if: inputs.platform == 'all' || inputs.platform == 'android'
runs-on: blacksmith-16vcpu-ubuntu-2404
timeout-minutes: 60
env:
T3_SHOWCASE_ANDROID_ABI: x86_64
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup Java
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: 17
- name: Setup Gradle cache
uses: gradle/actions/setup-gradle@v5
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
| sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Capture Android showcase
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 36
target: google_apis
arch: x86_64
profile: pixel_7_pro
avd-name: Pixel_10_Pro
cores: 8
ram-size: 4096M
disable-animations: false
script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
- name: Validate Google Play assets
run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload Android screenshots
if: always()
uses: actions/upload-artifact@v7
with:
name: google-play-screenshots
path: artifacts/app-store/screenshots/google-play/
if-no-files-found: warn
retention-days: 14
+3
View File
@@ -27,6 +27,9 @@ squashfs-root/
.gstack/
dist-electron/
.electron-runtime/
.showcase/
apps/mobile/.showcase/
artifacts/app-store/screenshots/
node_modules/
.alchemy/
*.log
@@ -43,6 +43,15 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Dependency acquisition and runtime boundaries
- 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.
- 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.
- `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.
- 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.
- 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.
- 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.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
+9 -24
View File
@@ -2,27 +2,14 @@
## Task Completion Requirements
- `vp check` and `vp run typecheck` must pass before considering tasks completed.
- If changing native mobile code, `vp run lint:mobile` must also pass.
- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.
## Project Snapshot
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
## Core Priorities
1. Performance first.
2. Reliability first.
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Maintainability
Long 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.
- 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.
- 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.
- Backend changes must include and run focused tests for the changed behavior.
- Run targeted formatting, lint, and type checks for the affected scope when available.
- 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.
- After frontend feature development or any user-visible frontend behavior change, the primary agent must use the `test-t3-app` skill once after integrating the work. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
- Subagents must not independently launch dev servers or repeat integrated browser verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## Package Roles
@@ -35,7 +22,6 @@ Long term maintainability is a core priority. If you add new functionality, firs
## Reference Repos
- Open-source Codex repo: https://github.com/openai/codex
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
@@ -47,8 +33,7 @@ agents.
- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
- Do not edit files under `.repos/` unless explicitly asked.
- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
- Manage vendored subtrees with `bun run sync:repos`; use `bun run sync:repos --repo <id>` to sync one
configured repository.
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
`.repos/` matches the installed dependency version.
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
+3
View File
@@ -0,0 +1,3 @@
{
"expo": {}
}
+1 -1
View File
@@ -31,7 +31,7 @@
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
+34 -9
View File
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12;
const LAUNCHER_VERSION = 14;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join(
repoRoot,
@@ -220,11 +220,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
{
@@ -277,11 +278,25 @@ function readJson(path) {
}
}
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
const launcherExecutableName = `${displayName} Launcher`;
return {
launcherExecutableName,
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
};
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
const launcherBinaryPath = isDevelopment
? developmentPaths.launcherBinaryPath
: runtimeElectronBinaryPath;
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
@@ -298,7 +313,8 @@ function buildMacLauncher(electronBinaryPath) {
const currentMetadata = readJson(metadataPath);
if (
NodeFS.existsSync(targetBinaryPath) &&
NodeFS.existsSync(launcherBinaryPath) &&
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
@@ -306,10 +322,10 @@ function buildMacLauncher(electronBinaryPath) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
return launcherBinaryPath;
}
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
@@ -321,15 +337,24 @@ function buildMacLauncher(electronBinaryPath) {
recursive: true,
verbatimSymlinks: true,
});
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchMainBundleInfoPlist(
targetAppBundlePath,
iconPath,
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
// Keep Electron's native executable inside the branded bundle. Launching the
// node_modules copy makes macOS associate the process (and Dock label) with
// Electron.app even though this bundle's Info.plist has the T3 Code name.
// Its conventional executable name also keeps Electron's default-app runtime
// in development mode instead of making app.isPackaged report true.
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
}
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
return launcherBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
@@ -1,6 +1,10 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
import {
makeDevelopmentLauncherScript,
resolveElectronBinaryPath,
resolveMacLauncherPaths,
} from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
@@ -45,4 +49,33 @@ describe("electron development launcher", () => {
);
assert.deepEqual(calls, ["ensure", "require:electron"]);
});
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
const paths = resolveMacLauncherPaths(
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
"T3 Code (Dev)",
);
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
assert.equal(
paths.launcherBinaryPath,
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
);
assert.equal(
paths.runtimeElectronBinaryPath,
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
);
const script = makeDevelopmentLauncherScript({
electronBinaryPath: paths.runtimeElectronBinaryPath,
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {},
});
assert.include(
script,
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
);
assert.notInclude(script, "node_modules/electron");
});
});
@@ -53,13 +53,16 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.isDevelopment, true);
assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
assert.equal(environment.baseDir, "/tmp/t3");
assert.equal(environment.stateDir, "/tmp/t3/dev");
assert.equal(environment.desktopSettingsPath, "/tmp/t3/dev/desktop-settings.json");
assert.equal(environment.clientSettingsPath, "/tmp/t3/dev/client-settings.json");
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
assert.equal(
environment.savedEnvironmentRegistryPath,
"/tmp/t3/userdata/saved-environments.json",
);
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
@@ -78,7 +81,7 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("derives production state paths under userdata", () =>
it.effect("stores production state under userdata in an explicit home", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
{},
@@ -95,6 +98,19 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("keeps implicit development state separate from production state", () =>
Effect.gen(function* () {
const development = yield* makeEnvironment(
{},
{ VITE_DEV_SERVER_URL: "http://localhost:5173" },
);
const production = yield* makeEnvironment();
assert.equal(development.stateDir, "/Users/alice/.t3/dev");
assert.equal(production.stateDir, "/Users/alice/.t3/userdata");
}),
);
it.effect("uses a configured app user model id override", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
+6 -2
View File
@@ -147,7 +147,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
: input.platform === "darwin"
? path.join(homeDirectory, "Library", "Application Support")
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
const baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));
const configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
@@ -155,7 +156,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
const stateDir = path.join(
baseDir,
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const resourcesPath = input.resourcesPath;
+12 -2
View File
@@ -31,6 +31,12 @@ const TestLayer = ElectronMenu.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
const makeWindow = (zoomFactor = 1): Electron.BrowserWindow =>
({
id: 7,
webContents: { getZoomFactor: () => zoomFactor },
}) as unknown as Electron.BrowserWindow;
describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
@@ -70,7 +76,7 @@ describe("ElectronMenu", () => {
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
window: makeWindow(),
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
});
@@ -81,20 +87,24 @@ describe("ElectronMenu", () => {
it.effect("resolves with none when the menu closes without a click", () =>
Effect.gen(function* () {
let popupOptions: Electron.PopupOptions | undefined;
buildFromTemplateMock.mockImplementation(() => ({
popup: (options: Electron.PopupOptions) => {
popupOptions = options;
options.callback?.();
},
}));
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
window: makeWindow(2),
items: [{ id: "copy", label: "Copy" }],
position: Option.some({ x: 10.8, y: 20.2 }),
});
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(popupOptions?.x, 21);
assert.equal(popupOptions?.y, 40);
assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
label: "Copy",
enabled: true,
+13 -3
View File
@@ -94,13 +94,20 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
return normalizedItems;
}
// Renderer positions arrive in CSS pixels; popup() expects window points, so
// page zoom must be factored in or menus drift proportionally to their
// distance from the window origin.
const normalizePosition = (
position: Option.Option<ElectronMenuPosition>,
zoomFactor: number,
): Option.Option<ElectronMenuPosition> =>
Option.filter(
position,
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
({ x, y }) =>
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
).pipe(
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
);
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
@@ -214,7 +221,10 @@ export const make = Effect.gen(function* () {
try {
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupPosition = normalizePosition(
input.position,
input.window.webContents.getZoomFactor(),
);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
@@ -10,6 +10,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
autoInstallOnAppQuit: true,
channel: "latest",
disableDifferentialDownload: false,
fullChangelog: false,
checkForUpdates: vi.fn(() => Promise.resolve(null)),
downloadUpdate: vi.fn(() => Promise.resolve([])),
on: vi.fn(),
@@ -33,6 +34,7 @@ describe("ElectronUpdater", () => {
autoUpdaterMock.autoInstallOnAppQuit = true;
autoUpdaterMock.channel = "latest";
autoUpdaterMock.disableDifferentialDownload = false;
autoUpdaterMock.fullChangelog = false;
autoUpdaterMock.checkForUpdates.mockClear();
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
autoUpdaterMock.downloadUpdate.mockClear();
@@ -98,6 +100,18 @@ describe("ElectronUpdater", () => {
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("sets full changelog mode", () =>
Effect.gen(function* () {
const updater = yield* ElectronUpdater.ElectronUpdater;
yield* updater.setFullChangelog(true);
assert.equal(autoUpdaterMock.fullChangelog, true);
yield* updater.setFullChangelog(false);
assert.equal(autoUpdaterMock.fullChangelog, false);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
Effect.gen(function* () {
const cause = new Error("quit and install failed");
@@ -66,6 +66,7 @@ export class ElectronUpdater extends Context.Service<
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
@@ -112,6 +113,11 @@ export const make = ElectronUpdater.of({
autoUpdater.allowDowngrade = value;
return Effect.void;
}),
setFullChangelog: (value) =>
Effect.suspend(() => {
autoUpdater.fullChangelog = value;
return Effect.void;
}),
setDisableDifferentialDownload: (value) =>
Effect.suspend(() => {
autoUpdater.disableDifferentialDownload = value;
@@ -35,6 +35,7 @@ import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
pickFolder,
setTheme,
@@ -48,6 +49,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
+2
View File
@@ -4,6 +4,8 @@ export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
+21 -1
View File
@@ -1,10 +1,14 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import { getLocalEnvironmentBootstraps } from "./window.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "wsl.exe",
@@ -126,3 +130,19 @@ describe("getLocalEnvironmentBootstraps", () => {
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
});
});
describe("getWindowFullscreenState", () => {
it.effect("reads the current native window state", () => {
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
return Effect.gen(function* () {
assert.isTrue(yield* getWindowFullscreenState.handler());
}).pipe(
Effect.provide(
Layer.mock(ElectronWindow.ElectronWindow)({
currentMainOrFirst: Effect.succeed(Option.some(window)),
}),
),
);
});
});
+10
View File
@@ -55,6 +55,16 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const window = yield* electronWindow.currentMainOrFirst;
return Option.isSome(window) && window.value.isFullScreen();
}),
});
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
+13
View File
@@ -116,6 +116,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
};
},
getWindowFullscreenState: () =>
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
onWindowFullscreenStateChange: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
if (typeof fullscreen !== "boolean") return;
listener(fullscreen);
};
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
};
},
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) =>
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
@@ -38,6 +38,7 @@ const flushCallbacks = Effect.yieldNow;
function makeHarness(options: UpdatesHarnessOptions = {}) {
let checkCount = 0;
let allowDowngrade = false;
let fullChangelog = false;
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
const sentStates: DesktopUpdateState[] = [];
@@ -73,6 +74,10 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
Effect.sync(() => {
allowDowngrade = value;
}),
setFullChangelog: (value) =>
Effect.sync(() => {
fullChangelog = value;
}),
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
@@ -186,6 +191,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
layer,
checkCount: () => checkCount,
feedUrls: () => feedUrls,
fullChangelog: () => fullChangelog,
listenerCount: () =>
Array.from(listeners.values()).reduce(
(total, eventListeners) => total + eventListeners.size,
@@ -287,6 +293,49 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
const harness = makeHarness();
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
yield* updates.setChannel("nightly");
assert.equal(harness.fullChangelog(), true);
harness.emit("update-available", {
version: "1.2.4-nightly.20260709.766",
releaseNotes: [
{
version: "1.2.4-nightly.20260709.766",
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>`,
},
{
version: "1.2.4-nightly.20260709.765",
note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
},
],
});
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "available");
assert.deepEqual(state.releaseNotes, [
{
version: "1.2.4-nightly.20260709.766",
items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
},
{
version: "1.2.4-nightly.20260709.765",
items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
},
]);
assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
+13 -2
View File
@@ -27,6 +27,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
import {
createInitialDesktopUpdateState,
@@ -49,6 +50,10 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
const UpdateInfo = Schema.Struct({
version: Schema.String,
// Left unvalidated on purpose: a malformed release-notes payload must never
// fail the decode and block the update state transition. The shape is
// validated defensively in normalizeDesktopUpdateReleaseNotes.
releaseNotes: Schema.optional(Schema.Unknown),
});
const DownloadProgressInfo = Schema.Struct({
@@ -330,10 +335,12 @@ export const make = Effect.gen(function* () {
yield* electronUpdater.setChannel(channel);
yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
yield* electronUpdater.setFullChangelog(allowsPrerelease);
yield* logUpdaterInfo("using update channel", {
channel,
allowPrerelease: allowsPrerelease,
allowDowngrade: allowsPrerelease,
fullChangelog: allowsPrerelease,
});
});
@@ -567,11 +574,15 @@ export const make = Effect.gen(function* () {
}
const checkedAt = yield* currentIsoTimestamp;
const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
yield* setState(
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
);
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
yield* logUpdaterInfo("update available", { version: info.version });
yield* logUpdaterInfo("update available", {
version: info.version,
releaseNoteGroups: releaseNotes.length,
});
}),
),
Effect.catchCause((cause) => {
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vite-plus/test";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
describe("normalizeDesktopUpdateReleaseNotes", () => {
it("splits a plain string note into items under the fallback version", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
"## What's changed\n- First fix\n- Second fix",
"1.2.3",
);
expect(notes).toEqual([{ version: "1.2.3", items: ["First fix", "Second fix"] }]);
});
it("keeps per-version groups and drops empty ones", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
[
{ version: "1.2.3", note: "- Newer change" },
{ version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" },
{ version: "1.2.1", note: "- Older change" },
],
"1.2.3",
);
expect(notes).toEqual([
{ version: "1.2.3", items: ["Newer change"] },
{ version: "1.2.1", items: ["Older change"] },
]);
});
it("decodes valid HTML entities", () => {
const notes = normalizeDesktopUpdateReleaseNotes("- Fix &amp; polish &#128512;", "1.0.0");
expect(notes).toEqual([{ version: "1.0.0", items: ["Fix & polish 😀"] }]);
});
it("ignores malformed entries instead of throwing", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
[
{ version: "1.2.3", note: "- Valid change" },
{ version: 42, note: "- Bad version type" },
{ version: "1.2.1", note: { html: "<p>object note</p>" } },
"not an object",
null,
],
"1.2.3",
);
expect(notes).toEqual([{ version: "1.2.3", items: ["Valid change"] }]);
});
it("returns non-empty groups even when preceded by many boilerplate-only groups", () => {
const boilerplate = Array.from({ length: 7 }, (_, index) => ({
version: `1.3.${9 - index}`,
note: "Full changelog: https://example.com/compare/x...y",
}));
const notes = normalizeDesktopUpdateReleaseNotes(
[...boilerplate, { version: "1.3.2", note: "- Older but real change" }],
"1.3.9",
);
expect(notes).toEqual([{ version: "1.3.2", items: ["Older but real change"] }]);
});
it("does not throw on out-of-range numeric entities and keeps the literal", () => {
expect(() =>
normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0"),
).not.toThrow();
const notes = normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0");
expect(notes).toEqual([{ version: "1.0.0", items: ["Broken entity &#9999999999;"] }]);
});
});
+125
View File
@@ -0,0 +1,125 @@
import type { DesktopUpdateReleaseNote } from "@t3tools/contracts";
interface ElectronReleaseNoteInfo {
readonly version: string;
readonly note: string | null | undefined;
}
function isElectronReleaseNoteInfo(value: unknown): value is ElectronReleaseNoteInfo {
if (typeof value !== "object" || value === null) return false;
const candidate = value as { readonly version?: unknown; readonly note?: unknown };
return (
typeof candidate.version === "string" &&
(typeof candidate.note === "string" || candidate.note === null || candidate.note === undefined)
);
}
const MAX_RELEASE_NOTE_GROUPS = 6;
const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
const HTML_ENTITY_REPLACEMENTS: Readonly<Record<string, string>> = {
amp: "&",
apos: "'",
gt: ">",
lt: "<",
nbsp: " ",
quot: '"',
};
function decodeCodePoint(codePoint: number, entity: string): string {
// String.fromCodePoint throws RangeError outside the valid Unicode range, and
// Number.isFinite alone lets oversized values (e.g. &#9999999999;) through.
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
return `&${entity};`;
}
return String.fromCodePoint(codePoint);
}
function decodeHtmlEntity(entity: string): string {
const named = HTML_ENTITY_REPLACEMENTS[entity];
if (named) return named;
if (entity.startsWith("#x")) {
return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
}
if (entity.startsWith("#")) {
return decodeCodePoint(Number.parseInt(entity.slice(1), 10), entity);
}
return `&${entity};`;
}
function decodeHtmlEntities(input: string): string {
return input.replace(/&([a-zA-Z]+|#\d+|#x[0-9a-fA-F]+);/g, (_, entity: string) =>
decodeHtmlEntity(entity),
);
}
function stripMarkup(input: string): string {
return decodeHtmlEntities(
input
.replace(/<br\s*\/?>/gi, "\n")
.replace(/<li\b[^>]*>/gi, "\n- ")
.replace(/<\/(?:p|div|li|h[1-6]|ul|ol|blockquote)>/gi, "\n")
.replace(/<[^>]*>/g, "")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/\*\*([^*]+)\*\*/g, "$1"),
);
}
function truncateReleaseNoteItem(item: string): string {
if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item;
return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`;
}
function isIgnoredReleaseNoteLine(line: string): boolean {
const normalized = line
.toLowerCase()
.replace(/[*_`#]/g, "")
.trim();
return (
normalized === "" ||
normalized === "what's changed" ||
normalized === "whats changed" ||
normalized === "full changelog" ||
normalized === "new contributors" ||
normalized.startsWith("compare: ") ||
normalized.includes("/compare/")
);
}
function extractReleaseNoteItems(note: string | null | undefined): ReadonlyArray<string> {
if (!note) return [];
const items: string[] = [];
for (const rawLine of stripMarkup(note).split("\n")) {
const item = rawLine
.trim()
.replace(/^[-*]\s+/, "")
.replace(/^\d+[.)]\s+/, "")
.replace(/\s+/g, " ");
if (isIgnoredReleaseNoteLine(item)) continue;
items.push(truncateReleaseNoteItem(item));
if (items.length >= MAX_RELEASE_NOTE_ITEMS_PER_GROUP) break;
}
return items;
}
export function normalizeDesktopUpdateReleaseNotes(
releaseNotes: unknown,
fallbackVersion: string,
): ReadonlyArray<DesktopUpdateReleaseNote> {
const rawNotes =
typeof releaseNotes === "string"
? [{ version: fallbackVersion, note: releaseNotes }]
: Array.isArray(releaseNotes)
? releaseNotes.filter(isElectronReleaseNoteInfo)
: [];
return rawNotes
.map((entry) => ({
version: entry.version,
items: extractReleaseNoteItems(entry.note),
}))
.filter((entry) => entry.items.length > 0)
.slice(0, MAX_RELEASE_NOTE_GROUPS);
}
@@ -118,6 +118,12 @@ describe("updateMachine", () => {
});
it("tracks available, download start, and progress cleanly", () => {
const releaseNotes = [
{
version: "1.1.0",
items: ["feat: add update release notes"],
},
];
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
@@ -126,15 +132,33 @@ describe("updateMachine", () => {
},
"1.1.0",
"2026-03-04T00:00:00.000Z",
releaseNotes,
);
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(available.releaseNotes).toBe(releaseNotes);
expect(downloading.releaseNotes).toBe(releaseNotes);
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
expect(progress.errorContext).toBeNull();
});
it("clears release notes when checking again", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"),
enabled: true,
status: "available",
availableVersion: "1.1.0-nightly.1",
releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"] }],
},
"2026-03-04T00:00:00.000Z",
);
expect(state.releaseNotes).toEqual([]);
});
});
@@ -1,6 +1,7 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateReleaseNote,
DesktopUpdateState,
} from "@t3tools/contracts";
@@ -29,6 +30,7 @@ export function createInitialDesktopUpdateState(
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt: null,
message: null,
@@ -45,6 +47,7 @@ export function reduceDesktopUpdateStateOnCheckStart(
...state,
status: "checking",
checkedAt,
releaseNotes: [],
message: null,
downloadPercent: null,
errorContext: null,
@@ -72,12 +75,14 @@ export function reduceDesktopUpdateStateOnUpdateAvailable(
state: DesktopUpdateState,
version: string,
checkedAt: string,
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
): DesktopUpdateState {
return {
...state,
status: "available",
availableVersion: version,
downloadedVersion: null,
releaseNotes,
downloadPercent: null,
checkedAt,
message: null,
@@ -95,6 +100,7 @@ export function reduceDesktopUpdateStateOnNoUpdate(
status: "up-to-date",
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt,
message: null,
+38 -2
View File
@@ -28,7 +28,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -46,6 +46,7 @@ const environmentInput = {
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
function makeFakeBrowserWindow() {
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
@@ -66,10 +67,13 @@ function makeFakeBrowserWindow() {
close: vi.fn(),
focus: vi.fn(),
isDestroyed: vi.fn(() => false),
isFullScreen: vi.fn(() => false),
isMinimized: vi.fn(() => false),
isVisible: vi.fn(() => true),
loadURL: vi.fn(() => Promise.resolve()),
on: vi.fn(),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
windowListeners.set(eventName, listener);
}),
once: vi.fn(),
restore: vi.fn(),
setBackgroundColor: vi.fn(),
@@ -88,6 +92,7 @@ function makeFakeBrowserWindow() {
send: webContents.send,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
windowListeners,
};
}
@@ -338,6 +343,37 @@ describe("DesktopWindow", () => {
}),
);
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
if (!enterFullscreen || !leaveFullscreen) {
return yield* Effect.die("fullscreen listeners were not registered");
}
enterFullscreen();
leaveFullscreen();
assert.deepEqual(fakeWindow.send.mock.calls, [
[WINDOW_FULLSCREEN_STATE_CHANNEL, true],
[WINDOW_FULLSCREEN_STATE_CHANNEL, false],
]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+10 -1
View File
@@ -15,7 +15,7 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
const TITLEBAR_HEIGHT = 40;
@@ -365,6 +365,15 @@ export const make = Effect.gen(function* () {
window.setTitle(environment.displayName);
});
if (environment.platform === "darwin") {
window.on("enter-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
});
window.on("leave-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
});
}
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
@@ -16,6 +16,7 @@ import {
formatNodePtyProbeFailureReason,
formatWslShellTransportFailureReason,
parseNodePath,
parseNodeVersion,
parseResolvedPath,
parseToolchainReport,
probeWslDistros,
@@ -173,6 +174,29 @@ describe("parseNodePath", () => {
});
});
describe("parseNodeVersion", () => {
it("extracts the node version from a nodeVersion: line", () => {
expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
});
it("returns null when the version value is empty", () => {
expect(parseNodeVersion("nodeVersion:")).toBeNull();
});
it("returns null when there is no nodeVersion line at all", () => {
expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
});
it("ignores surrounding noise and trims whitespace", () => {
const stdout = [
"some preamble noise",
" nodeVersion:22.16.0 ",
"nodePath:/usr/bin/node",
].join("\n");
expect(parseNodeVersion(stdout)).toBe("22.16.0");
});
});
describe("parseResolvedPath", () => {
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
+42 -4
View File
@@ -32,7 +32,11 @@ export interface EnsureWslNodePtyOptions {
}
export type EnsureWslNodePtyResult =
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
| {
readonly ok: true;
readonly nodePath: string;
readonly resolvedPath: string;
}
| {
readonly ok: false;
readonly reason: string;
@@ -222,6 +226,7 @@ export const formatNodePtyProbeFailureReason = (exitCode: number): string | null
const NODE_PTY_PROBE_SCRIPT = (
linuxServerDir: string,
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
printf 'resolvedPath:%s\\n' "$PATH"
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
// The server bundle externalizes its deps to node_modules, and the WSL Node
@@ -318,6 +323,16 @@ export const parseNodePath = (stdout: string): string | null => {
return path ?? null;
};
export const parseNodeVersion = (stdout: string): string | null => {
const version = stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.startsWith("nodeVersion:"))
.map((line) => line.slice("nodeVersion:".length).trim())
.find((value) => value.length > 0);
return version ?? null;
};
// Captures the login-shell PATH after the shared resolver has loaded version
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
// paths containing spaces or apostrophes can be forwarded as one env argv.
@@ -404,7 +419,11 @@ const ensureNodePtyImpl = (
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
if (transportFailureReason !== null) {
return { ok: false, reason: transportFailureReason, fatal: false } as const;
return {
ok: false,
reason: transportFailureReason,
fatal: false,
} as const;
}
// No node at all, even after the shared resolver repaired PATH. Surface
@@ -457,12 +476,31 @@ const ensureNodePtyImpl = (
} as const;
}
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
if (probe.exitCode === 0) {
const rawVersion = parseNodeVersion(probe.stdout);
if (
rawVersion !== null &&
options.nodeEngineRange &&
!satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
) {
const range = options.nodeEngineRange.trim();
return {
ok: false,
reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
fatal: true,
} as const;
}
return { ok: true, nodePath, resolvedPath } as const;
}
if (options.allowBuild !== true) {
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
if (packagedProbeFailure !== null) {
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
return {
ok: false,
reason: packagedProbeFailure,
fatal: true,
} as const;
}
}
@@ -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>
<?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>

Before

Width:  |  Height:  |  Size: 649 B

After

Width:  |  Height:  |  Size: 665 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
<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" />
<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" />
</svg>

After

Width:  |  Height:  |  Size: 948 B

@@ -0,0 +1,414 @@
---
import Layout from "../layouts/Layout.astro";
interface Props {
readonly title: string;
readonly description: string;
readonly heading: string;
readonly lede: string;
readonly effectiveDate: string;
readonly lastUpdated: string;
readonly sections: ReadonlyArray<readonly [id: string, label: string]>;
}
const { title, description, heading, lede, effectiveDate, lastUpdated, sections } = Astro.props;
---
<Layout title={title} description={description} pageClass="legal-document-page">
<div class="legal-page">
<a class="legal-index-link" href="/legal"><span aria-hidden="true">&#8592;</span> All legal documents</a>
<header class="legal-hero">
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
<h1>{heading}</h1>
<p class="legal-lede">{lede}</p>
<dl class="legal-dates" aria-label="Document dates">
<div>
<dt>Effective Date</dt>
<dd>{effectiveDate}</dd>
</div>
<div>
<dt>Last Updated</dt>
<dd>{lastUpdated}</dd>
</div>
</dl>
</header>
<div class="legal-rule" aria-hidden="true"></div>
<div class="legal-layout">
<aside class="legal-nav" aria-label="On this page">
<p class="legal-nav-label">On this page</p>
<ol>
{sections.map(([id, label], index) => (
<li>
<a href={`#${id}`} data-legal-nav-link={id}>
<span>{String(index + 1).padStart(2, "0")}</span>
{label}
</a>
</li>
))}
</ol>
</aside>
<article class="legal-copy">
<slot />
</article>
</div>
</div>
</Layout>
<script>
const navLinks = Array.from(
document.querySelectorAll<HTMLAnchorElement>("[data-legal-nav-link]"),
);
const sections = navLinks
.map((link) => {
const id = link.dataset.legalNavLink;
const section = id ? document.getElementById(id) : null;
return section ? { link, section } : null;
})
.filter((entry): entry is { link: HTMLAnchorElement; section: HTMLElement } => entry !== null);
let activeId = "";
let frame = 0;
const updateActiveSection = () => {
frame = 0;
const marker = Math.min(180, window.innerHeight * 0.28);
let active = sections[0];
for (const entry of sections) {
if (entry.section.getBoundingClientRect().top > marker) break;
active = entry;
}
if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) {
active = sections[sections.length - 1];
}
if (!active || active.section.id === activeId) return;
activeId = active.section.id;
for (const { link, section } of sections) {
if (section.id === activeId) {
link.setAttribute("aria-current", "location");
} else {
link.removeAttribute("aria-current");
}
}
};
const scheduleUpdate = () => {
if (frame) return;
frame = window.requestAnimationFrame(updateActiveSection);
};
updateActiveSection();
window.addEventListener("scroll", scheduleUpdate, { passive: true });
window.addEventListener("resize", scheduleUpdate);
</script>
<style is:global>
.legal-page {
width: min(1120px, calc(100% - 64px));
margin: 0 auto;
padding: clamp(72px, 10vw, 132px) 0 112px;
}
.legal-index-link {
display: none;
}
.legal-hero {
max-width: 820px;
animation: fade-in 0.8s ease-out both;
}
.legal-hero h1 {
margin-top: 18px;
font-size: clamp(3.4rem, 8vw, 7.4rem);
font-weight: 500;
letter-spacing: -0.02em;
line-height: 0.9;
}
.legal-lede {
max-width: 720px;
margin-top: 34px;
color: var(--fg-muted);
font-size: clamp(1.05rem, 1.8vw, 1.3rem);
line-height: 1.65;
letter-spacing: -0.012em;
}
.legal-dates {
display: flex;
flex-wrap: wrap;
gap: 36px;
margin-top: 38px;
}
.legal-dates div {
display: grid;
gap: 4px;
}
.legal-dates dt,
.legal-nav-label,
.section-number {
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 0.68rem;
font-weight: 500;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.legal-dates dd {
color: var(--fg);
font-family: var(--font-mono);
font-size: 0.8rem;
}
.legal-rule {
height: 1px;
margin: 72px 0;
background: linear-gradient(90deg, var(--border-strong), var(--border) 65%, transparent);
}
.legal-layout {
display: grid;
grid-template-columns: 210px minmax(0, 720px);
gap: clamp(64px, 10vw, 140px);
align-items: start;
}
.legal-nav {
position: sticky;
top: 88px;
max-height: calc(100vh - 112px);
overflow-y: auto;
scrollbar-width: thin;
}
.legal-nav ol {
display: grid;
gap: 2px;
margin-top: 16px;
padding-bottom: 12px;
list-style: none;
}
.legal-nav a {
display: grid;
grid-template-columns: 24px 1fr;
gap: 9px;
margin-left: -10px;
padding: 7px 8px 7px 10px;
border-radius: 6px;
color: var(--fg-dim);
font-size: 0.78rem;
line-height: 1.35;
transition:
color 0.16s ease,
background-color 0.16s ease,
box-shadow 0.16s ease;
}
.legal-nav a span {
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: 0.64rem;
line-height: 1.7;
}
.legal-nav a:hover {
color: var(--fg);
}
.legal-nav a[aria-current="location"] {
color: var(--fg);
background: color-mix(in srgb, var(--accent) 8%, transparent);
box-shadow: inset 2px 0 var(--accent);
}
.legal-nav a[aria-current="location"] span {
color: var(--accent);
}
.legal-copy {
min-width: 0;
}
.legal-copy section {
scroll-margin-top: 104px;
}
.legal-copy section + section {
margin-top: 82px;
padding-top: 82px;
border-top: 1px solid var(--border);
}
.section-number {
color: var(--accent);
}
.legal-copy h2 {
margin: 8px 0 28px;
color: var(--fg);
font-size: clamp(1.75rem, 3vw, 2.45rem);
font-weight: 500;
letter-spacing: -0.04em;
line-height: 1.1;
}
.legal-copy h3 {
margin: 32px 0 10px;
color: var(--fg);
font-size: 1rem;
font-weight: 600;
letter-spacing: -0.015em;
}
.legal-copy h4 {
margin: 24px 0 8px;
color: var(--fg);
font-size: 0.94rem;
font-weight: 600;
}
.legal-copy p,
.legal-copy li,
.legal-copy address {
color: var(--fg-muted);
font-size: 0.98rem;
font-style: normal;
line-height: 1.78;
}
.legal-copy p + p {
margin-top: 18px;
}
.legal-copy strong {
color: var(--fg);
font-weight: 600;
}
.legal-copy ul,
.legal-copy ol {
display: grid;
gap: 12px;
margin: 18px 0 20px;
padding-left: 1.2rem;
}
.legal-copy li {
padding-left: 7px;
}
.legal-copy li::marker {
color: var(--accent);
}
.legal-copy .provider-list {
gap: 28px;
}
.provider-list a,
.legal-copy a {
overflow-wrap: anywhere;
}
.legal-copy a {
color: var(--fg);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--accent) 55%, transparent);
text-underline-offset: 4px;
transition: text-decoration-color 0.16s ease;
}
.legal-copy a:hover {
text-decoration-color: var(--accent);
}
.legal-notice {
color: var(--fg) !important;
font-weight: 600;
}
.legal-copy address {
margin-top: 20px;
}
.contact-link {
display: inline-block;
margin-top: 18px;
font-family: var(--font-mono);
font-size: 0.9rem;
}
@media (max-width: 820px) {
.legal-index-link {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 38px;
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 0.72rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.legal-page {
width: min(100% - 40px, 720px);
padding-top: 56px;
padding-bottom: 80px;
}
.legal-hero h1 {
font-size: clamp(3.1rem, 16vw, 5rem);
}
.legal-rule {
margin: 52px 0;
}
.legal-layout {
display: block;
}
.legal-nav {
display: none;
}
.legal-copy section + section {
margin-top: 62px;
padding-top: 62px;
}
}
@media (max-width: 420px) {
.legal-page {
width: calc(100% - 32px);
padding-top: 42px;
}
.legal-lede {
margin-top: 26px;
font-size: 1rem;
}
.legal-dates {
gap: 24px;
}
.legal-copy p,
.legal-copy li,
.legal-copy address {
font-size: 0.94rem;
}
}
</style>
+31 -2
View File
@@ -4,11 +4,13 @@ import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
description?: string;
pageClass?: string;
}
const {
title = "T3 Code",
description = "T3 Code — The open-source control plane for coding agents.",
pageClass,
} = Astro.props;
---
@@ -30,7 +32,7 @@ const {
<title>{title}</title>
</head>
<body>
<div class="page">
<div class:list={["page", pageClass]}>
<nav class="nav">
<div class="nav-inner">
<a href="/" class="nav-brand" aria-label="T3 Code home">
@@ -67,6 +69,9 @@ const {
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
<a href="/terms-of-service">Terms</a>
<a href="/privacy-policy">Privacy</a>
<a href="/security-policy">Security</a>
</div>
</div>
</footer>
@@ -279,7 +284,7 @@ const {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
overflow-x: clip;
}
.nav {
@@ -402,6 +407,8 @@ const {
.footer-links {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 20px;
}
@@ -421,6 +428,28 @@ const {
padding-left: 20px;
padding-right: 20px;
}
.legal-document-page .nav {
display: none;
}
.footer {
padding-bottom: max(32px, env(safe-area-inset-bottom));
}
.footer-inner {
align-items: flex-start;
flex-direction: column;
gap: 28px;
}
.footer-links {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
width: 100%;
gap: 14px 20px;
justify-content: initial;
}
}
@media (max-width: 420px) {
+1 -1
View File
@@ -1,6 +1,6 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
githubStars: "14k+",
users: "100,000",
} as const;
+44 -10
View File
@@ -33,6 +33,9 @@ const mobileEndorsementRows = [
<span class="hero-float-mark hf-cursor" title="Cursor">
<img src="/harnesses/cursor_light.svg" alt="" />
</span>
<span class="hero-float-mark hf-grok" title="Grok">
<img src="/harnesses/grok-dark.svg" alt="" />
</span>
</div>
<div class="container hero-inner">
@@ -41,7 +44,7 @@ const mobileEndorsementRows = [
</h1>
<p class="hero-sub">
Orchestrate Claude Code, Codex, OpenCode and Cursor from one surface.
Orchestrate Claude Code, Codex, OpenCode, Cursor, and Grok from one surface.
Bring your own subscription. Fork the whole thing.
</p>
@@ -173,7 +176,7 @@ const mobileEndorsementRows = [
<h2>Bring your own sub</h2>
<p>
T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,
or Cursor with the credentials you already have — we orchestrate
Cursor, or Grok with the credentials you already have — we orchestrate
them, you keep your plan.
</p>
</div>
@@ -207,6 +210,13 @@ const mobileEndorsementRows = [
<div class="harness-tag">cursor-agent</div>
</div>
</div>
<div class="harness">
<div class="harness-mark"><img src="/harnesses/grok-dark.svg" alt="" /></div>
<div class="harness-meta">
<div class="harness-name">Grok CLI</div>
<div class="harness-tag">grok login</div>
</div>
</div>
</div>
<div class="harness-footer">
@@ -254,7 +264,7 @@ const mobileEndorsementRows = [
<button class="pr-button">
<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>
Commit &amp; push
<span class="pr-button-kbd">⌘⏎</span>
<span id="pr-button-kbd" class="pr-button-kbd">⌘⏎</span>
</button>
</div>
</div>
@@ -403,12 +413,14 @@ const mobileEndorsementRows = [
const label = document.getElementById("download-label");
const ctaBtn = document.getElementById("cta-download-btn") as HTMLAnchorElement | null;
const ctaLabel = document.getElementById("cta-download-label");
const kbd = document.getElementById("pr-button-kbd");
const platform = detectPlatform();
if (!platform) return;
document.documentElement.dataset.platform = platform.os;
if (label) label.textContent = platform.label;
if (ctaLabel) ctaLabel.textContent = platform.label;
if (kbd && platform.os !== "mac") kbd.textContent = "Ctrl ⏎";
try {
const release = await fetchLatestRelease();
@@ -613,8 +625,9 @@ const mobileEndorsementRows = [
.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); }
.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); }
.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); }
.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); }
.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); }
.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); }
@media (max-width: 1180px) {
.hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }
@@ -623,6 +636,7 @@ const mobileEndorsementRows = [
.hero-float-mark.hf-codex { top: 2%; right: 3%; }
.hero-float-mark.hf-opencode { top: 26%; left: 2%; }
.hero-float-mark.hf-cursor { top: 24%; right: 2%; }
.hero-float-mark.hf-grok { top: 48%; left: 2%; transform: rotate(3deg); }
}
@media (max-width: 820px) {
@@ -657,17 +671,18 @@ const mobileEndorsementRows = [
height: 44px;
}
/* Two above the title, two flanking the call-to-action area. */
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
.hero-float-mark.hf-claude {
top: 44px;
left: 10px;
transform: rotate(-10deg);
}
.hero-float-mark.hf-codex {
top: 44px;
right: 10px;
transform: rotate(8deg);
.hero-float-mark.hf-grok {
top: 240px;
left: 4px;
right: auto;
transform: rotate(-4deg);
}
.hero-float-mark.hf-opencode {
@@ -677,6 +692,12 @@ const mobileEndorsementRows = [
transform: rotate(-6deg);
}
.hero-float-mark.hf-codex {
top: 44px;
right: 10px;
transform: rotate(8deg);
}
.hero-float-mark.hf-cursor {
top: 474px;
right: 4px;
@@ -686,6 +707,14 @@ const mobileEndorsementRows = [
}
@media (max-width: 340px) {
.hero-float-mark.hf-grok {
top: 220px;
left: 0;
width: 52px;
height: 52px;
border-radius: 14px;
}
.hero-float-mark.hf-opencode,
.hero-float-mark.hf-cursor {
top: 580px;
@@ -702,6 +731,7 @@ const mobileEndorsementRows = [
right: 0;
}
.hero-float-mark.hf-grok img,
.hero-float-mark.hf-opencode img,
.hero-float-mark.hf-cursor img {
width: 30px;
@@ -748,7 +778,7 @@ const mobileEndorsementRows = [
.harness-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(5, 1fr);
gap: 0;
border: 1px solid var(--border);
border-radius: var(--radius);
@@ -1203,6 +1233,10 @@ const mobileEndorsementRows = [
.harness-grid { grid-template-columns: 1fr 1fr; }
.harness { border-right: 0; border-bottom: 1px solid var(--border); }
.harness:nth-child(odd) { border-right: 1px solid var(--border); }
.harness:nth-child(5):last-child {
grid-column: 1 / -1;
border-right: 0;
}
.git-inner { grid-template-columns: 1fr; gap: 40px; }
.open-grid { grid-template-columns: 1fr; }
}
+172
View File
@@ -0,0 +1,172 @@
---
import Layout from "../layouts/Layout.astro";
const documents = [
{
number: "01",
title: "Privacy Policy",
description: "How T3 Code handles information, connected services, and your privacy choices.",
href: "/privacy-policy",
},
{
number: "02",
title: "Terms of Service",
description: "The terms that govern your use of T3 Code and T3 Tools-operated services.",
href: "/terms-of-service",
},
{
number: "03",
title: "Security Policy",
description: "Our security practices, responsible disclosure process, and shared responsibilities.",
href: "/security-policy",
},
] as const;
---
<Layout
title="Legal — T3 Code"
description="Privacy, terms, and security documents for T3 Code."
pageClass="legal-document-page"
>
<div class="legal-index">
<header class="legal-index-hero">
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
<h1>Legal</h1>
<p>Policies and terms for T3 Code, collected in one place.</p>
</header>
<nav class="document-list" aria-label="Legal documents">
{documents.map((document) => (
<a href={document.href} class="document-card">
<span class="document-number">{document.number}</span>
<span class="document-copy">
<strong>{document.title}</strong>
<span>{document.description}</span>
</span>
<span class="document-arrow" aria-hidden="true">&#8599;</span>
</a>
))}
</nav>
</div>
</Layout>
<style>
.legal-index {
width: min(960px, calc(100% - 64px));
margin: 0 auto;
padding: clamp(72px, 10vw, 132px) 0 112px;
}
.legal-index-hero {
max-width: 680px;
animation: fade-in 0.7s ease-out both;
}
.legal-index h1 {
margin-top: 18px;
font-size: clamp(4rem, 10vw, 7.4rem);
font-weight: 500;
letter-spacing: -0.04em;
line-height: 0.9;
}
.legal-index-hero > p:last-child {
margin-top: 30px;
color: var(--fg-muted);
font-size: clamp(1.05rem, 2vw, 1.3rem);
line-height: 1.65;
}
.document-list {
display: grid;
margin-top: clamp(64px, 9vw, 96px);
border-top: 1px solid var(--border);
}
.document-card {
display: grid;
grid-template-columns: 42px minmax(0, 1fr) auto;
gap: 24px;
align-items: center;
padding: 30px 8px;
border-bottom: 1px solid var(--border);
transition: background-color 0.18s ease, padding 0.18s ease;
}
.document-number {
color: var(--accent);
font-family: var(--font-mono);
font-size: 0.7rem;
letter-spacing: 0.1em;
}
.document-copy {
display: grid;
gap: 7px;
}
.document-copy strong {
color: var(--fg);
font-size: 1.2rem;
font-weight: 500;
letter-spacing: -0.02em;
}
.document-copy > span {
color: var(--fg-dim);
font-size: 0.9rem;
line-height: 1.55;
}
.document-arrow {
color: var(--fg-dim);
font-size: 1.25rem;
transition: color 0.18s ease, transform 0.18s ease;
}
@media (hover: hover) and (pointer: fine) {
.document-card:hover {
padding-left: 16px;
padding-right: 16px;
background: rgba(255, 255, 255, 0.025);
}
.document-card:hover .document-arrow {
color: var(--fg);
transform: translate(2px, -2px);
}
}
@media (max-width: 820px) {
.legal-index {
width: min(100% - 40px, 720px);
padding-top: 56px;
padding-bottom: 80px;
}
.document-card {
grid-template-columns: 30px minmax(0, 1fr) auto;
gap: 14px;
padding: 24px 4px;
}
}
@media (max-width: 420px) {
.legal-index {
width: calc(100% - 32px);
padding-top: 42px;
}
.legal-index h1 {
font-size: 4.4rem;
}
.document-copy strong {
font-size: 1.08rem;
}
.document-copy > span {
font-size: 0.84rem;
}
}
</style>
@@ -0,0 +1,445 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["information", "Personal information we collect"],
["uses", "How we use your personal information"],
["sharing", "How we share your personal information"],
["choices", "Your choices regarding your personal information"],
["security", "Security of your personal information"],
["international", "International users"],
["children", "Children"],
["do-not-track", "Do Not Track"],
["updates", "Updates to this Privacy Policy"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Privacy Policy — T3 Code"
description="How T3 Tools, Inc. handles information when you use T3 Code, app.t3.codes, and t3.codes."
heading="T3 Code Privacy Policy"
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."
effectiveDate="2026-07-14"
lastUpdated="2026-07-14"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3
Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3
Code desktop and mobile applications, the hosted T3 Code web application located at
{" "}<a href="https://app.t3.codes">https://app.t3.codes</a>, or the optional T3 Connect
service (together, the “Services”), or visit the T3 Code marketing website located at
{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”). This Policy applies to
personal information we collect through the Site and the Services, as well as personal
information you provide to us directly.
</p>
<p>
By using the Site or the Services, you acknowledge the practices described in this
Policy. If you do not agree with this Policy, please do not use the Site or the Services.
This Policy does not govern third-party coding agents, artificial-intelligence providers,
identity providers, or environments that you choose to connect to T3 Code; those third
parties process information under their own terms and privacy policies.
</p>
</section>
<section id="information">
<p class="section-number">02</p>
<h2>Personal Information We Collect</h2>
<p>
We collect personal information about you in different ways depending on how you use
T3 Code and which optional features you enable.
</p>
<h3>Personal Information From Users of T3 Code</h3>
<p>
When you use T3 Code, we may collect the following categories of personal information:
</p>
<ul>
<li>
<strong>Account information.</strong> If you create or sign in to a T3 account, we
receive general identifiers and profile information from our authentication provider
and the identity provider you select. This may include your name, email address,
profile image, user ID, sign-in method, and authentication credentials or tokens.
</li>
<li>
<strong>Environment and device information.</strong> If you enable T3 Connect, we
process information needed to connect and secure your environments and devices,
including identifiers, labels you assign, public keys, connection endpoints,
credential hashes, connection status, app and operating-system versions, and
notification preferences.
</li>
<li>
<strong>Agent activity and notifications.</strong> If you enable notifications or Live
Activities, we process push tokens and limited activity information needed to provide
those features, such as project and thread titles, model name, status, and activity
headline.
</li>
<li>
<strong>Information you provide to us.</strong> We collect information that you choose
to provide when you request support, send feedback, or otherwise communicate with us.
</li>
</ul>
<h3>Personal Information From Users of Our Site Generally</h3>
<p>
When you visit the Site or use online portions of the Services, we and our service
providers may automatically log online identifiers and internet-activity information,
including your Internet Protocol (IP) address, device and operating-system type, browser
or app type and version, pages viewed, access times, request timestamps, connection
events, latency, error details, and diagnostic traces. The amount of information we
collect depends on the Services you use and your device and browser settings.
</p>
<p>
We use operational and diagnostic information to provide, secure, maintain, and
troubleshoot the Services, not for targeted advertising.
</p>
<h3>Information We Get From Others</h3>
<p>
We may receive personal information from service providers that help us operate the
Services, such as authentication and identity providers, app stores, device-platform
providers, and coding-agent providers you choose to use. We may combine this information
with information we collect through the Site and the Services.
</p>
<h3>Cookies and Local Storage</h3>
<p>
The Site and online portions of the Services may use cookies or similar technologies to
operate essential features, maintain sessions, remember preferences, and understand
whether the Services are functioning correctly. T3 Code also stores connection settings,
credentials, preferences, drafts, and cached thread, file, branch, and server metadata on
your device. Credentials and session tokens use platform-provided protected storage where
supported. Information stored only on your device is not collected by T3 Tools unless it
is transmitted as part of a feature you use.
</p>
<h3>Device Permissions</h3>
<ul>
<li>
<strong>Camera.</strong> Used when you choose to scan a pairing QR code. Camera frames
are processed on your device.
</li>
<li>
<strong>Photos and files.</strong> Items you select are accessed only to preview them or
attach them to a request you initiate.
</li>
<li>
<strong>Notifications.</strong> Used only if you enable agent-status notifications or
Live Activities.
</li>
<li>
<strong>Local network.</strong> Used to discover or connect to T3 Code environments
accessible from your machine over the network.
</li>
</ul>
</section>
<section id="uses">
<p class="section-number">03</p>
<h2>How We Use Your Personal Information</h2>
<p>
Subject to this Policy and applicable terms governing third-party applications and
services, we may use personal information for the following purposes:
</p>
<ul>
<li>To establish and verify your identity and authenticate your account;</li>
<li>To link and protect devices and environments and deliver optional notifications;</li>
<li>To process and fulfill requests you make through the Services;</li>
<li>To provide customer service and respond to support requests and feedback;</li>
<li>To communicate with you about the Services and your relationship with us;</li>
<li>To monitor reliability, prevent abuse, and investigate security incidents;</li>
<li>To comply with applicable law and enforce the terms governing the Services; and</li>
<li>
To analyze and improve T3 Code using aggregated, de-identified, or other anonymous
operational information.
</li>
</ul>
<h3>Training of AI Models</h3>
<p>
We do not use your personal information, source code, prompts, or agent responses to
train artificial-intelligence models.
</p>
<h3>Compliance and Protection</h3>
<p>We may use personal information to:</p>
<ul>
<li>Comply with applicable laws, lawful requests, and legal process;</li>
<li>Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;</li>
<li>Audit our internal processes for legal, contractual, and policy compliance;</li>
<li>Enforce the terms and conditions that govern the Site and the Services; and</li>
<li>
Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized,
unethical, or illegal activity, including cyberattacks and identity theft.
</li>
</ul>
<p>
We may also use personal information for other purposes consistent with this Policy or
explained to you when we collect the information.
</p>
</section>
<section id="sharing">
<p class="section-number">04</p>
<h2>How We Share Your Personal Information</h2>
<p>
We may disclose the categories of personal information described above to the following
categories of third parties:
</p>
<h3>Providers You Choose</h3>
<p>
At your direction, prompts, files, and related content are sent to coding agents and
artificial-intelligence providers configured in your environment. Because you bring and
configure your own coding-agent harness and provider, the applicable third parties vary.
Those providers process information under their own terms and privacy policies.
</p>
<h3>Third-Party Service Providers</h3>
<p>
We use third-party service providers to help provide the Services and operate our
business. Depending on the features you use, these providers may include:
</p>
<ul class="provider-list">
<li>
<strong>Clerk</strong> <em>(Clerk, Inc.)</em>.<br />
We use Clerk to provide account authentication.<br />
You can view Clerk's privacy policy here:{" "}<a href="https://clerk.com/legal/privacy"
>https://clerk.com/legal/privacy</a
>.
</li>
<li>
<strong>Cloudflare</strong> <em>(Cloudflare, Inc.)</em>.<br />
We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.<br />
You can view Cloudflare's privacy policy here:{" "}<a
href="https://www.cloudflare.com/policies/privacy/"
>https://www.cloudflare.com/policies/privacy/</a
>.
</li>
<li>
<strong>PlanetScale</strong> <em>(PlanetScale, Inc.)</em>.<br />
We use PlanetScale to host the database that supports T3 Connect.<br />
You can view PlanetScale's privacy policy here:{" "}<a
href="https://planetscale.com/legal/privacy"
>https://planetscale.com/legal/privacy</a
>.
</li>
<li>
<strong>Vercel</strong> <em>(Vercel Inc.)</em>.<br />
We use Vercel to host and deploy the T3 Code Site.<br />
You can view Vercel's privacy notice here:{" "}<a
href="https://vercel.com/legal/privacy-notice"
>https://vercel.com/legal/privacy-notice</a
>.
</li>
<li>
<strong>Axiom</strong> <em>(Axiom, Inc.)</em>.<br />
We use Axiom for operational diagnostics that help us maintain and troubleshoot the
Services.<br />
You can view Axiom's privacy policy here:{" "}<a
href="https://axiom.co/docs/legal/privacy">https://axiom.co/docs/legal/privacy</a
>.
</li>
<li>
<strong>Expo</strong> <em>(650 Industries, Inc.)</em>.<br />
We use Expo for application updates and related mobile-app services.<br />
You can view Expo's privacy policy here:{" "}<a href="https://expo.dev/privacy"
>https://expo.dev/privacy</a
>.
</li>
<li>
<strong>Apple</strong> <em>(Apple Inc.)</em>.<br />
We use Apple services for app distribution, optional authentication, and platform
notifications.<br />
You can view Apple's privacy policy here:{" "}<a
href="https://www.apple.com/legal/privacy/">https://www.apple.com/legal/privacy/</a
>.
</li>
<li>
<strong>Google</strong> <em>(Google LLC)</em>.<br />
We use Google services for app distribution and optional authentication.<br />
You can view Google's privacy policy here:{" "}<a
href="https://policies.google.com/privacy">https://policies.google.com/privacy</a
>.
</li>
</ul>
<p>
These providers process information for us under their own contractual and privacy
obligations.
</p>
<h3>Affiliates and Professional Advisors</h3>
<p>
We may share personal information with our affiliates for purposes consistent with this
Policy and with lawyers, accountants, bankers, and other professional advisors in the
course of the services they provide to us.
</p>
<h3>Corporate Restructuring</h3>
<p>
We may share some or all personal information in connection with or during negotiation of
a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of
assets, or similar transaction. If another company acquires T3 Tools or its assets, that
company may possess the personal information collected by us and assume the rights and
obligations described in this Policy.
</p>
<h3>Legal and Safety Disclosures</h3>
<p>
We may disclose personal information if we believe in good faith that disclosure is
necessary to comply with law or legal process; protect or defend the rights, property, or
safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent
fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the
Services. We may also share personal information at your direction, with your consent, or
as described to you when the information is collected.
</p>
<h3>No Sale of Personal Information</h3>
<p>
We do not sell your personal information or share it for cross-context behavioral or
targeted advertising.
</p>
<h3>Third-Party Websites and Services</h3>
<p>
The Site and the Services may contain links to third-party websites or services. When you
follow a third-party link or connect a third-party service, that third party may collect
personal information from you. We do not control and are not responsible for the privacy
practices or content of third parties.
</p>
</section>
<section id="choices">
<p class="section-number">05</p>
<h2>Your Choices Regarding Your Personal Information</h2>
<h3>Account and Connection Choices</h3>
<p>
You may use local or direct connections without signing in to a T3 account. You can
disconnect environments, sign out, disable optional notifications and Live Activities,
and clear local caches from Settings. You can grant or revoke camera, photo, local-network,
and notification permissions in your device settings.
</p>
<h3>Cookies and Local Data</h3>
<p>
You can use your browser settings to stop accepting or to delete cookies, although some
portions of the Site or the Services may not function correctly as a result. Information
stored only on your device remains there until you clear it, remove the relevant
connection, or uninstall the app. The mobile app provides cache controls under
{" "}<strong>Settings → App → Client Storage</strong>.
</p>
<h3>Retention and Deletion</h3>
<p>
We retain account, environment-link, device-registration, notification, and security
information while your account or the relevant feature is active and for as long as
reasonably necessary to provide the Services, protect them from abuse, comply with law,
and resolve disputes. Operational diagnostic traces are configured to expire after 30
days. Some records may remain longer in backups or where retention is required for
security, fraud prevention, or legal compliance.
</p>
<p>
To request deletion of your T3 account and associated T3 Connect data, email{" "}<a
href="mailto:[email protected]">[email protected]</a
>{" "}from the email address associated with your account. We may need to verify your
identity. Deleting a T3 account does not delete information held by an environment or
coding-agent provider you control; contact those providers or delete that information
directly.
</p>
<h3>Your Privacy Rights</h3>
<p>
Depending on where you live, you may have rights to request access to, correction of,
deletion of, or a portable copy of your personal information, or to restrict or object
to certain processing. You may also have the right to appeal our response or complain to
a data-protection authority. We will honor applicable rights after verifying your
request.
</p>
</section>
<section id="security">
<p class="section-number">06</p>
<h2>Security of Your Personal Information</h2>
<p>
T3 Tools is committed to protecting the security of your personal information. We use
administrative, technical, and organizational safeguards designed to protect personal
information from unauthorized access, use, or disclosure. These safeguards include
encrypted network transport, scoped and proof-bound access tokens for supported
connection flows, protected credential storage, and redaction of authorization headers
from relay diagnostics.
</p>
<p>
No method of transmission over the Internet or method of electronic storage is completely
secure. While we use reasonable efforts to protect personal information, we cannot
guarantee its absolute security. You are responsible for securing the environments,
coding-agent accounts, credentials, and networks that you connect to T3 Code.
</p>
</section>
<section id="international">
<p class="section-number">07</p>
<h2>International Users</h2>
<p>
The Site and the Services are provided from the United States and are governed by United
States law. If you use the Site or the Services from outside the United States, your
personal information may be transferred to and processed in the United States and other
countries where we or our service providers operate. Where required, we use lawful
safeguards for international transfers of personal information.
</p>
</section>
<section id="children">
<p class="section-number">08</p>
<h2>Children</h2>
<p>
The Site and the Services are not intended for children under 13 years of age, and you
must be at least 13 years old to use them. We do not knowingly collect, use, or disclose
personal information from children under 13. If you believe a child under 13 has provided
us with personal information, please contact us so that we can take appropriate action.
</p>
</section>
<section id="do-not-track">
<p class="section-number">09</p>
<h2>Do Not Track</h2>
<p>
We currently do not respond to browser “Do Not Track” signals. T3 Code does not use
personal information for cross-context behavioral or targeted advertising.
</p>
</section>
<section id="updates">
<p class="section-number">10</p>
<h2>Updates to This Privacy Policy</h2>
<p>
We reserve the right to update this Policy from time to time. If we make material changes,
we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date”
above, and provide any additional notice required by law. Except as otherwise indicated,
changes become effective when the revised Policy is posted.
</p>
</section>
<section id="contact">
<p class="section-number">11</p>
<h2>Contact Us</h2>
<p>
If you have questions about this Policy or wish to make a privacy or deletion request,
please contact us at:
</p>
<address>
<strong>T3 Tools, Inc.</strong><br />
2261 Market Street #5309<br />
San Francisco, CA 94114<br />
United States
</address>
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
</section>
</LegalPage>
@@ -0,0 +1,187 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["reporting", "Reporting security issues"],
["safe-harbor", "Responsible research and safe harbor"],
["practices", "Our security practices"],
["responsibilities", "Your responsibilities"],
["updates", "Updates to this policy"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Security Policy — T3 Code"
description="How to report security issues in T3 Code and how T3 Tools approaches product security."
heading="T3 Code Security Policy"
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."
effectiveDate="2026-07-15"
lastUpdated="2026-07-15"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
This Security Policy describes the vulnerability-reporting process and security practices for
the T3 Code desktop and mobile applications, the hosted application at{" "}<a
href="https://app.t3.codes">https://app.t3.codes</a
>, the optional T3 Connect service, and the T3 Code website at{" "}<a href="https://t3.codes"
>https://t3.codes</a
>.
</p>
<p>
T3 Code connects software running on your devices and in environments you control with
coding-agent harnesses and providers you choose. We secure the software and infrastructure
operated by T3 Tools, but we do not control the security of your devices, environments,
repositories, networks, credentials, or third-party providers. Please review the shared
responsibilities below when assessing risk.
</p>
</section>
<section id="reporting">
<p class="section-number">02</p>
<h2>Reporting Security Issues</h2>
<p>
If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated
infrastructure, email{" "}<a href="mailto:[email protected]">[email protected]</a>. Please do not
disclose the issue publicly until we have had a reasonable opportunity to investigate and
remediate it.
</p>
<p>Please include, when available:</p>
<ul>
<li>A description of the issue and its potential impact;</li>
<li>The affected application, version, URL, endpoint, or component;</li>
<li>Clear reproduction steps or a minimal proof of concept;</li>
<li>Relevant logs, screenshots, or request and response details with secrets removed; and</li>
<li>Your preferred contact information and whether you want public credit.</li>
</ul>
<p>
We aim to acknowledge complete reports within one business day, keep reporters informed of
material progress, and coordinate disclosure after a fix is available. Resolution time varies
with severity, complexity, and dependencies on third parties.
</p>
</section>
<section id="safe-harbor">
<p class="section-number">03</p>
<h2>Responsible Research and Safe Harbor</h2>
<p>
We support good-faith security research. If you make a genuine effort to comply with this
policy, avoid harm, respect privacy, and report findings promptly, we will treat your research
as authorized and will not initiate legal action against you for accidental, good-faith
violations of this policy. If a third party initiates legal action concerning compliant
research, we will make our authorization known where appropriate.
</p>
<p>To remain within this safe harbor, you must:</p>
<ul>
<li>Test only accounts, data, and systems you own or have explicit permission to test;</li>
<li>Stop and report immediately if you encounter personal, confidential, or production data;</li>
<li>Access only the minimum information needed to demonstrate the issue;</li>
<li>Avoid disrupting availability, degrading performance, or damaging or deleting data;</li>
<li>Not use social engineering, phishing, physical attacks, or denial-of-service testing;</li>
<li>Not test third-party services or infrastructure outside T3 Tools’ control; and</li>
<li>Give us reasonable time to address the issue before public disclosure.</li>
</ul>
<p>
This safe harbor does not authorize violations of law or activity outside the scope of this
policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools
in its discretion.
</p>
</section>
<section id="practices">
<p class="section-number">04</p>
<h2>Our Security Practices</h2>
<p>
We use administrative, technical, and organizational safeguards designed for the nature of T3
Code and the information processed by T3 Tools-operated services. These practices include:
</p>
<ul>
<li>
<strong>Data minimization.</strong> T3 Code is designed so coding-session content can remain
between your clients, your environment, and the harnesses and providers you configure. We
process information through T3 Tools-operated infrastructure only when needed for a feature
you enable.
</li>
<li>
<strong>Encrypted transport.</strong> T3 Tools-operated network services use encrypted
transport. Supported connection flows use scoped credentials and security controls designed
to reduce unauthorized reuse.
</li>
<li>
<strong>Credential protection.</strong> T3 Code uses platform-provided protected storage for
credentials and session tokens where supported. We design operational logging to avoid
collecting secrets that are not needed to operate or troubleshoot the Services.
</li>
<li>
<strong>Access controls.</strong> Access to production systems and operational data is limited
according to job responsibilities and protected using authentication and authorization
controls.
</li>
<li>
<strong>Maintenance and monitoring.</strong> We monitor T3 Tools-operated services for
reliability and security events, review dependencies, and deploy updates and mitigations as
appropriate.
</li>
<li>
<strong>Established providers.</strong> We use specialized providers for services such as
authentication, hosting, and application distribution and evaluate the controls relevant to
their role.
</li>
</ul>
<p>
No system is completely secure. These practices reduce risk but do not guarantee that the Site
or Services will be free from vulnerabilities or unauthorized access.
</p>
</section>
<section id="responsibilities">
<p class="section-number">05</p>
<h2>Your Responsibilities</h2>
<p>
Because you control much of the T3 Code execution path, you play an important role in securing
it. You are responsible for:
</p>
<ul>
<li>Keeping T3 Code, your operating systems, and connected tools up to date;</li>
<li>Securing your devices, repositories, environments, networks, and backups;</li>
<li>Protecting account, provider, repository, and environment credentials;</li>
<li>Using multi-factor authentication where your identity and coding-agent providers support it;</li>
<li>Granting providers and integrations only the permissions they need;</li>
<li>Reviewing commands, source changes, and other agent output before applying or executing it;</li>
<li>Removing lost or unused devices and revoking credentials you believe may be compromised; and</li>
<li>Following the security policies of your selected harnesses, providers, and infrastructure.</li>
</ul>
<p>
Do not send passwords, API keys, access tokens, or private keys in a vulnerability report.
Revoke any secret that may have been exposed before sharing sanitized evidence with us.
</p>
</section>
<section id="updates">
<p class="section-number">06</p>
<h2>Updates to This Policy</h2>
<p>
We may update this Security Policy as T3 Code, our infrastructure, and security practices
evolve. We will post revisions at this URL and update the dates above. Material changes to the
vulnerability-reporting process or safe-harbor terms will apply prospectively.
</p>
</section>
<section id="contact">
<p class="section-number">07</p>
<h2>Contact Us</h2>
<p>
Report security issues or ask security-related questions at{" "}<a
href="mailto:[email protected]">[email protected]</a
>.
</p>
<p>
For general legal questions, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
For privacy requests, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
</p>
</section>
</LegalPage>
@@ -0,0 +1,396 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["accounts", "Accounts"],
["content", "Your content and providers"],
["rights", "T3 Code and proprietary rights"],
["acceptable-use", "Acceptable use"],
["availability", "Availability and changes"],
["fees", "Fees"],
["privacy", "Privacy"],
["termination", "Suspension and termination"],
["beta", "Beta services"],
["disclaimers", "Disclaimers"],
["liability", "Limitation of liability"],
["indemnification", "Indemnification"],
["copyright", "Copyright complaints"],
["third-parties", "Third-party services"],
["feedback", "Feedback"],
["disputes", "Dispute resolution"],
["miscellaneous", "Miscellaneous"],
["changes", "Changes to these Terms"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Terms of Service — T3 Code"
description="The terms that govern your use of T3 Code, app.t3.codes, T3 Connect, and t3.codes."
heading="T3 Code Terms of Service"
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."
effectiveDate="2026-07-15"
lastUpdated="2026-07-15"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc.
(“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop
and mobile applications, the hosted T3 Code application at{" "}<a href="https://app.t3.codes"
>https://app.t3.codes</a
>, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code
marketing website at{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”).
</p>
<p>
By accessing or using the Site or Services, you agree to these Terms. If you use the Services
for an organization, you represent that you have authority to bind that organization, and
“you” includes the organization. If you do not agree to these Terms, do not use the Site or
Services.
</p>
<p>
You must be at least 13 years old to use the Site or Services. If the law where you live
requires a greater age to enter into these Terms, you must meet that requirement or have a
parent or legal guardian agree on your behalf.
</p>
</section>
<section id="accounts">
<p class="section-number">02</p>
<h2>Accounts</h2>
<p>
You can use some T3 Code features without creating a T3 account. An account may be required
for account-backed features, including T3 Connect. You agree to provide accurate account
information, keep your credentials secure, and promptly notify us if you suspect unauthorized
access. You are responsible for activity performed through your account and connected devices,
except to the extent caused by our failure to use reasonable security measures.
</p>
<p>
You may not share credentials in a way that compromises the Services, impersonate another
person, or create accounts through unauthorized automated means. We may require reasonable
verification before restoring access or acting on an account request.
</p>
</section>
<section id="content">
<p class="section-number">03</p>
<h2>Your Content and Providers</h2>
<p>
T3 Code can help you send prompts, source files, images, attachments, review comments, and
instructions to coding-agent harnesses and providers you choose, and display their responses,
command output, file changes, source code, and diffs (collectively, “User Content”). You retain
all rights you have in your User Content.
</p>
<p>
You bring and configure your own coding-agent harness and provider. Your User Content is
ordinarily processed in the environment you control and by the providers you select, not by
T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User
Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and
process that content only as reasonably necessary to provide, secure, and troubleshoot that
feature. This license ends when the content is no longer needed for those purposes, subject to
reasonable backup, security, and legal-retention requirements.
</p>
<p>
You represent that you have the rights and permissions needed to use and submit User Content
and to direct its processing by your selected harnesses and providers. You are responsible for
reviewing those providers’ terms, privacy practices, data controls, and output before using
them with confidential, proprietary, regulated, or personal information.
</p>
</section>
<section id="rights">
<p class="section-number">04</p>
<h2>T3 Code and Proprietary Rights</h2>
<p>
T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted
infrastructure, documentation, and other materials, excluding User Content and third-party
materials. These Terms do not transfer ownership of either party’s intellectual property.
</p>
<p>
Portions of T3 Code are available as open-source software. Your use, copying, modification, and
distribution of that source code are governed by the license included with the applicable
repository or component. These Terms govern your use of the hosted Services and do not limit
rights granted to you by an applicable open-source license.
</p>
<p>
Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right
to access and use the Services for lawful personal or internal business purposes. You may not
use our trademarks, service marks, or trade dress without written permission.
</p>
</section>
<section id="acceptable-use">
<p class="section-number">05</p>
<h2>Acceptable Use</h2>
<p>You may not use the Site or Services to:</p>
<ul>
<li>Violate applicable law or another person’s rights;</li>
<li>Upload, transmit, or generate content you do not have the right to use;</li>
<li>Distribute malware, exploit code, or harmful content except in authorized security work;</li>
<li>Probe, attack, disrupt, or gain unauthorized access to the Services or another system;</li>
<li>Bypass rate limits, access controls, security measures, or usage restrictions;</li>
<li>Interfere with other users or place an unreasonable load on shared infrastructure;</li>
<li>Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or</li>
<li>Misrepresent that output or activity from a third-party agent was produced or endorsed by us.</li>
</ul>
<p>
Authorized security research must follow our{" "}<a href="/security-policy">Security Policy</a>.
We may investigate suspected violations and take proportionate action to protect users and the
Services.
</p>
</section>
<section id="availability">
<p class="section-number">06</p>
<h2>Availability and Changes</h2>
<p>
We may add, change, suspend, or discontinue features, integrations, or supported platforms. We
aim to provide reasonable notice when a change materially reduces an account-backed feature,
but urgent security, legal, or reliability changes may take effect immediately. The Services
may be unavailable because of maintenance, provider outages, network conditions, or events
outside our control.
</p>
<p>
T3 Code depends on software, environments, networks, and coding-agent providers that you
configure or that third parties operate. We do not control their availability, compatibility,
pricing, or behavior.
</p>
</section>
<section id="fees">
<p class="section-number">07</p>
<h2>Fees</h2>
<p>
T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state
otherwise for a feature. You remain responsible for charges from your coding-agent providers,
cloud infrastructure, network operators, app stores, and other third parties. If we introduce
a paid feature, we will present its price and applicable payment terms before you purchase it.
</p>
</section>
<section id="privacy">
<p class="section-number">08</p>
<h2>Privacy</h2>
<p>
Our{" "}<a href="/privacy-policy">Privacy Policy</a> explains how T3 Tools collects, uses, and
shares personal information when you use the Site and Services. Third-party environments,
harnesses, identity providers, and coding-agent providers process information under their own
terms and privacy policies.
</p>
</section>
<section id="termination">
<p class="section-number">09</p>
<h2>Suspension and Termination</h2>
<p>
You may stop using the Services at any time. You may disconnect environments and devices from
within T3 Code and may request deletion of an account as described in our Privacy Policy.
</p>
<p>
We may suspend or terminate access to account-backed or hosted features if we reasonably
believe you materially violated these Terms, created a security or legal risk, failed to pay an
applicable fee, or used the Services in a way that could harm other users or shared
infrastructure. When practicable, we will give notice and an opportunity to cure. We may act
immediately where needed to prevent harm or comply with law.
</p>
<p>
Provisions that by their nature should survive termination—including ownership, disclaimers,
limitations of liability, indemnification, and dispute terms—will survive.
</p>
</section>
<section id="beta">
<p class="section-number">10</p>
<h2>Beta Services</h2>
<p>
T3 Code is an early-stage product, and some or all features may be identified as alpha, beta,
preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete,
change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole
copy of important work, and review proposed commands and file changes before applying them.
</p>
</section>
<section id="disclaimers">
<p class="section-number">11</p>
<h2>Disclaimers</h2>
<p class="legal-notice">
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SITE AND SERVICES ARE PROVIDED “AS IS” AND “AS
AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
</p>
<p>
Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete,
or harmful output. You are responsible for reviewing output, commands, patches, and other
actions before relying on or executing them. We do not warrant that the Services or third-party
output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose.
</p>
<p>
Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not
apply to you.
</p>
</section>
<section id="liability">
<p class="section-number">12</p>
<h2>Limitation of Liability</h2>
<p class="legal-notice">
TO THE MAXIMUM EXTENT PERMITTED BY LAW, T3 TOOLS AND ITS AFFILIATES, OFFICERS, EMPLOYEES,
AGENTS, AND LICENSORS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,
EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS
OPPORTUNITIES, ARISING FROM OR RELATED TO THE SITE, SERVICES, OR THESE TERMS.
</p>
<p>
To the maximum extent permitted by law, our aggregate liability for all claims arising from or
relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount
you paid directly to T3 Tools for the Services during the 12 months before the event giving rise
to the claim. These limitations apply regardless of the legal theory and even if a remedy fails
of its essential purpose. They do not limit liability that cannot lawfully be limited.
</p>
</section>
<section id="indemnification">
<p class="section-number">13</p>
<h2>Indemnification</h2>
<p>
To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its
affiliates, officers, employees, and agents from third-party claims, damages, losses, and
reasonable legal fees arising from your User Content, your use of the Site or Services in
violation of these Terms or law, or your infringement of another person’s rights. We will
promptly notify you of a covered claim and reasonably cooperate in its defense. You may not
settle a claim in a way that admits fault by or imposes obligations on us without our written
consent.
</p>
</section>
<section id="copyright">
<p class="section-number">14</p>
<h2>Copyright Complaints</h2>
<p>
If you believe material available through a T3 Tools-operated part of the Site or Services
infringes your copyright, send a notice to{" "}<a href="mailto:[email protected]">[email protected]</a
>{" "}identifying the copyrighted work, the allegedly infringing material and its location, your
contact information, a statement of good-faith belief, a statement under penalty of perjury
that the notice is accurate and you are authorized to act, and your physical or electronic
signature.
</p>
<p>
T3 Tools does not control content stored only in a user’s environment or held by a user-selected
provider. Requests concerning that material should be directed to the operator that hosts it.
</p>
</section>
<section id="third-parties">
<p class="section-number">15</p>
<h2>Third-Party Services</h2>
<p>
The Services may connect to or display content from third-party coding agents, model providers,
identity providers, repositories, app stores, websites, and infrastructure. Your use of those
services is governed by their terms. We do not endorse or control third-party services and are
not responsible for their content, security, availability, output, or data practices.
</p>
<p>
Third-party and open-source software included with T3 Code is governed by its applicable
license notices. Where those licenses conflict with these Terms for that software, the
applicable open-source license controls.
</p>
</section>
<section id="feedback">
<p class="section-number">16</p>
<h2>Feedback</h2>
<p>
If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a
perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback
without restriction or compensation. This does not transfer ownership of your User Content.
</p>
</section>
<section id="disputes">
<p class="section-number">17</p>
<h2>Dispute Resolution</h2>
<p class="legal-notice">
PLEASE READ THIS SECTION CAREFULLY. IT REQUIRES MOST DISPUTES TO BE RESOLVED BY INDIVIDUAL
BINDING ARBITRATION AND WAIVES JURY TRIALS AND CLASS OR REPRESENTATIVE ACTIONS.
</p>
<h3>Informal Resolution</h3>
<p>
Before starting arbitration or a court proceeding, the party raising a dispute must send a
written notice describing the dispute and requested relief. Notices to us must be sent to{" "}<a
href="mailto:[email protected]">[email protected]</a
>. The parties will try in good faith to resolve the dispute for at least 30 days.
</p>
<h3>Binding Arbitration</h3>
<p>
Except for disputes eligible for small-claims court and requests for injunctive relief to
protect intellectual property or prevent unauthorized access, unresolved disputes will be
resolved by binding individual arbitration administered by JAMS under its applicable consumer
or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may
take place remotely unless the arbitrator determines that an in-person hearing is necessary.
</p>
<h3>No Class Actions</h3>
<p>
Disputes must be brought only on an individual basis. Neither party may participate in a class,
collective, consolidated, or representative action or arbitration to the extent permitted by
law.
</p>
<h3>Opt Out</h3>
<p>
You may opt out of this arbitration agreement by emailing{" "}<a href="mailto:[email protected]"
>[email protected]</a
> within 30 days after you first accept these Terms. Include your name, the email associated
with your account if any, and a clear statement that you opt out of arbitration.
</p>
<p>
If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the
state and federal courts located in San Francisco County, California, and each party consents
to those courts.
</p>
</section>
<section id="miscellaneous">
<p class="section-number">18</p>
<h2>Miscellaneous</h2>
<p>
California law governs these Terms without regard to conflict-of-law principles, except that
the Federal Arbitration Act governs the arbitration provisions. These Terms and documents
incorporated by reference are the entire agreement between you and us regarding the Site and
Services. If a provision is unenforceable, it will be modified to the minimum extent necessary
or severed, and the remaining provisions will continue in effect.
</p>
<p>
Our failure to enforce a provision is not a waiver. You may not assign these Terms without our
written consent. We may assign them in connection with a merger, acquisition, reorganization,
or sale of assets. We are not liable for delays or failures caused by events beyond our
reasonable control. Headings are for convenience only, and “including” means “including without
limitation.”
</p>
</section>
<section id="changes">
<p class="section-number">19</p>
<h2>Changes to These Terms</h2>
<p>
We may update these Terms from time to time. We will post updated Terms at this URL and update
the dates above. If a change materially affects your rights, we will provide additional notice
when reasonably practicable or as required by law. Changes apply prospectively from their
effective date. Your continued use of the Site or Services after that date means you accept the
updated Terms.
</p>
</section>
<section id="contact">
<p class="section-number">20</p>
<h2>Contact Us</h2>
<p>If you have questions about these Terms, contact us at:</p>
<address>
<strong>T3 Tools, Inc.</strong><br />
2261 Market Street #5309<br />
San Francisco, CA 94114<br />
United States
</address>
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
</section>
</LegalPage>
+24
View File
@@ -34,6 +34,30 @@ Build and run the local iOS dev client:
vp run ios:dev
```
If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
reduced-capability local build. Personal Team builds omit the widget and share extensions, push
entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.
```bash
T3CODE_IOS_PERSONAL_TEAM=1 \
T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code.dev \
vp run ios:dev
```
Build and install a self-contained Release app that does not need Metro:
```bash
vp run ios:release
```
The Personal Team equivalent also needs a unique bundle identifier:
```bash
T3CODE_IOS_PERSONAL_TEAM=1 \
T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code \
vp run ios:release
```
Build and run the local iOS preview app:
```bash
+196 -53
View File
@@ -1,5 +1,6 @@
import type { ExpoConfig } from "expo/config";
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
type AppVariant = "development" | "preview" | "production";
@@ -8,47 +9,82 @@ const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
const VARIANT_CONFIG: Record<
AppVariant,
{
readonly appName: string;
readonly scheme: string;
readonly iosIcon: string;
readonly splashIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
}
> = {
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
if (
isIosPersonalTeamBuild &&
(!personalTeamBundleIdentifier ||
!IOS_BUNDLE_IDENTIFIER_PATTERN.test(personalTeamBundleIdentifier))
) {
throw new Error(
"T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID must be a reverse-DNS identifier such as com.example.t3code when T3CODE_IOS_PERSONAL_TEAM=1.",
);
}
const DEVELOPMENT_ASSETS = {
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.developmentUniversalIconPng),
androidAdaptiveBackgroundColor: "#00639B",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#00639B",
} as const;
const PREVIEW_ASSETS = {
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.nightlyLinuxIconPng),
androidAdaptiveBackgroundColor: "#111533",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#7565C7",
} as const;
const RELEASE_ASSETS = {
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
androidAdaptiveForeground: "./assets/android-icon-mark.png",
androidAdaptiveBackgroundColor: "#000000",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#FFFFFF",
} as const;
const VARIANT_CONFIG = {
development: {
appName: "T3 Code Dev",
scheme: "t3code-dev",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
assets: DEVELOPMENT_ASSETS,
},
preview: {
appName: "T3 Code Preview",
scheme: "t3code-preview",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
assets: PREVIEW_ASSETS,
},
production: {
appName: "T3 Code",
scheme: "t3code",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
assets: RELEASE_ASSETS,
},
};
} as const;
function resolveAppVariant(value: string | undefined): AppVariant {
switch (value) {
@@ -62,6 +98,63 @@ function resolveAppVariant(value: string | undefined): AppVariant {
}
const variant = VARIANT_CONFIG[APP_VARIANT];
const iosBundleIdentifier = isIosPersonalTeamBuild
? personalTeamBundleIdentifier!
: variant.iosBundleIdentifier;
const dmSansFonts = {
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf",
bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf",
} as const;
const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
"expo-widgets",
{
bundleIdentifier: `${iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: true,
widgets: [
{
name: "AgentActivity",
displayName: "Agent Activity",
description: "Shows the current state of active T3 Code agents.",
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
},
],
},
];
const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
"expo-sharing",
{
ios: {
// Personal Teams cannot sign App Groups or extension targets. Keep the
// reduced-capability local build usable while release builds expose the
// real system share target.
enabled: !isIosPersonalTeamBuild,
extensionBundleIdentifier: `${iosBundleIdentifier}.sharing`,
appGroupId: `group.${iosBundleIdentifier}`,
activationRule: {
supportsText: true,
supportsWebUrlWithMaxCount: 1,
supportsImageWithMaxCount: 8,
},
},
android: {
enabled: true,
singleShareMimeTypes: ["text/plain", "image/*"],
multipleShareMimeTypes: ["image/*"],
},
},
];
// These aliases match the fonts' PostScript names on iOS. Register the same
// names on Android so React Native and the native composer use one set of
// family names without waiting for runtime font loading.
const config: ExpoConfig = {
name: variant.appName,
@@ -77,7 +170,7 @@ const config: ExpoConfig = {
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
},
orientation: "portrait",
icon: "./assets/icon.png",
icon: variant.assets.appIcon,
userInterfaceStyle: "automatic",
updates: {
enabled: true,
@@ -86,9 +179,9 @@ const config: ExpoConfig = {
fallbackToCacheTimeout: 0,
},
ios: {
icon: variant.iosIcon,
icon: variant.assets.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
bundleIdentifier: iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
// Sign in with Apple, or push notification entitlements).
@@ -107,40 +200,94 @@ const config: ExpoConfig = {
},
},
android: {
icon: "./assets/icon.png",
icon: variant.assets.appIcon,
package: variant.androidPackage,
adaptiveIcon: {
backgroundColor: "#E6F4FE",
foregroundImage: "./assets/android-icon-foreground.png",
backgroundImage: "./assets/android-icon-background.png",
monochromeImage: "./assets/android-icon-monochrome.png",
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
foregroundImage: variant.assets.androidAdaptiveForeground,
monochromeImage: variant.assets.androidMonochromeIcon,
},
predictiveBackGestureEnabled: false,
// Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
// JS back handling survives it via react-native's Android 16 shim plus
// withAndroidPredictiveBackCompat on Android 13-15.
predictiveBackGestureEnabled: true,
},
web: {
favicon: "./assets/favicon.png",
favicon: variant.assets.appIcon,
},
plugins: [
"expo-font",
"expo-asset",
[
"expo-font",
{
ios: {
fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold],
},
android: {
fonts: [
{
fontFamily: "DMSans-Regular",
fontDefinitions: [{ path: dmSansFonts.regular, weight: 400 }],
},
{
fontFamily: "DMSans-Medium",
fontDefinitions: [{ path: dmSansFonts.medium, weight: 500 }],
},
{
fontFamily: "DMSans-Bold",
fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }],
},
],
},
},
],
"expo-secure-store",
["@clerk/expo", { theme: "./clerk-theme.json" }],
"expo-sqlite",
...(isIosPersonalTeamBuild
? [sharingPlugin]
: ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),
[
"expo-notifications",
{
icon: variant.assets.androidNotificationIcon,
color: variant.assets.androidNotificationColor,
mode: APP_VARIANT === "development" ? "development" : "production",
},
],
// appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before
// plugins earlier in this array, so it cannot strip the entitlement Clerk would add.
["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],
"expo-web-browser",
[
"expo-quick-actions",
{
// Adaptive launcher-shortcut icon; referenced by resource name from
// the shortcut items set in src/features/shortcuts.
androidIcons: {
shortcut_icon: {
foregroundImage: variant.assets.androidAdaptiveForeground,
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
},
},
},
],
[
"expo-camera",
{
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
barcodeScannerEnabled: true,
recordAudioAndroid: false,
},
],
[
"expo-splash-screen",
{
image: variant.splashIcon,
image: variant.assets.splashIcon,
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: variant.splashIcon,
image: variant.assets.splashIcon,
backgroundColor: "#0a0a0a",
},
},
@@ -164,31 +311,18 @@ const config: ExpoConfig = {
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
// would delete the asset catalog) and its xcodeproj mod creates the widget
// target (which must exist before the compile phase can be attached).
"./plugins/withWidgetLogoAsset.cjs",
[
"expo-widgets",
{
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: true,
widgets: [
{
name: "AgentActivity",
displayName: "Agent Activity",
description: "Shows the current state of active T3 Code agents.",
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
},
],
},
],
...(!isIosPersonalTeamBuild ? ["./plugins/withWidgetLogoAsset.cjs", widgetsPlugin] : []),
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
"./plugins/withAndroidGradleHeap.cjs",
"./plugins/withAndroidModernPopupMenu.cjs",
"./plugins/withAndroidModernAlertDialog.cjs",
"./plugins/withAndroidPredictiveBackCompat.cjs",
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
],
extra: {
appVariant: APP_VARIANT,
iosPersonalTeamBuild: isIosPersonalTeamBuild,
relay: {
url: repoEnv.T3CODE_RELAY_URL ?? null,
},
@@ -196,6 +330,15 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
// Native Google sign-in credentials. @clerk/expo reads these from `extra`
// under their exact env-var names (not nested), and its config plugin reads
// the iOS URL scheme at prebuild to register it in Info.plist.
// Unset values must be omitted (not null): the public manifest serializes
// null to {}, which is truthy and would defeat Clerk's fallback checks.
EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 733 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

@@ -1,3 +0,0 @@
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
<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"/>
</svg>

Before

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

+8 -4
View File
@@ -8,7 +8,8 @@
"development": {
"corepack": true,
"env": {
"APP_VARIANT": "development"
"APP_VARIANT": "development",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "development",
"developmentClient": true,
@@ -17,7 +18,8 @@
"preview": {
"corepack": true,
"env": {
"APP_VARIANT": "preview"
"APP_VARIANT": "preview",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "preview",
"environment": "preview",
@@ -27,7 +29,8 @@
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
"MOBILE_VERSION_POLICY": "fingerprint",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "preview",
"environment": "preview",
@@ -40,7 +43,8 @@
"production": {
"corepack": true,
"env": {
"APP_VARIANT": "production"
"APP_VARIANT": "production",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "production",
"environment": "production",
+11 -8
View File
@@ -12,7 +12,7 @@
/* Card / surface */
--color-card: #ffffff;
--color-card-alt: #f5f5f5;
--color-card-translucent: rgba(255, 255, 255, 0.94);
--color-card-translucent: rgba(255, 255, 255, 0.8);
/* Text */
--color-foreground: #262626;
@@ -51,6 +51,7 @@
/* Inputs */
--color-input: #ffffff;
--color-input-border: rgba(0, 0, 0, 0.1);
--color-sidebar-search: rgba(118, 118, 128, 0.12);
--color-placeholder: #a3a3a3;
/* Icons */
@@ -105,7 +106,7 @@
/* Card / surface */
--color-card: #171717;
--color-card-alt: #1c1c1c;
--color-card-translucent: rgba(17, 17, 17, 0.94);
--color-card-translucent: rgba(17, 17, 17, 0.8);
/* Text */
--color-foreground: #f5f5f5;
@@ -144,6 +145,7 @@
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-sidebar-search: rgba(118, 118, 128, 0.24);
--color-placeholder: #8e8e93;
/* Icons */
@@ -194,9 +196,10 @@
/* ─── Typography ────────────────────────────────────────────────────── */
@theme {
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
/* Keep these native family names aligned with app.config.ts. */
--font-sans: "DMSans-Regular";
--font-medium: "DMSans-Medium";
--font-bold: "DMSans-Bold";
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
--text-3xs: 11px;
@@ -221,14 +224,14 @@
/* ─── Custom utilities ──────────────────────────────────────────────── */
@utility font-t3-medium {
font-family: "DMSans_500Medium";
font-family: var(--font-medium);
}
@utility font-t3-bold {
font-family: "DMSans_700Bold";
font-family: var(--font-bold);
}
@utility font-t3-extrabold {
font-family: "DMSans_700Bold";
font-family: var(--font-bold);
font-weight: 800;
}
+5
View File
@@ -1,5 +1,6 @@
import { registerRootComponent } from "expo";
import "react-native-gesture-handler";
import { LogBox } from "react-native";
import { featureFlags } from "react-native-screens";
import App from "./src/App";
@@ -8,4 +9,8 @@ import App from "./src/App";
// native stack is rendered inside a non-fitToContents formSheet.
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
LogBox.ignoreAllLogs();
}
registerRootComponent(App);
+9
View File
@@ -6,6 +6,7 @@ const { withUniwindConfig } = require("uniwind/metro");
/** @type {import("expo/metro-config").MetroConfig} */
const config = getDefaultConfig(__dirname);
const workspaceRoot = path.resolve(__dirname, "../..");
const escapedWorkspaceRoot = workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] }));
const resolveShikiDependencyRoot = (packageName) => {
const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] });
@@ -25,6 +26,14 @@ const resolveShikiDependencyRoot = (packageName) => {
config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
config.resolver = {
...config.resolver,
blockList: [
...(Array.isArray(config.resolver?.blockList)
? config.resolver.blockList
: config.resolver?.blockList
? [config.resolver.blockList]
: []),
new RegExp(`${escapedWorkspaceRoot}[/\\\\]\\.t3[/\\\\].*`),
],
extraNodeModules: {
// oxlint-disable-next-line unicorn/no-useless-fallback-in-spread
...(config.resolver?.extraNodeModules ?? {}),
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.composereditor'
version = '0.0.0'
android {
namespace 'expo.modules.t3composereditor'
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
}
dependencies {
implementation project(':expo-modules-core')
}
@@ -0,0 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,72 @@
package expo.modules.t3composereditor
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3ComposerEditorModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3ComposerEditor")
View(T3ComposerEditorView::class) {
Prop("controlledDocumentJson") { view: T3ComposerEditorView, documentJson: String ->
view.setControlledDocumentJson(documentJson)
}
Prop("themeJson") { view: T3ComposerEditorView, themeJson: String ->
view.setThemeJson(themeJson)
}
Prop("placeholder") { view: T3ComposerEditorView, placeholder: String ->
view.setPlaceholder(placeholder)
}
Prop("fontFamily") { view: T3ComposerEditorView, fontFamily: String ->
view.setFontFamily(fontFamily)
}
Prop("fontSize") { view: T3ComposerEditorView, fontSize: Double ->
view.setFontSize(fontSize.toFloat())
}
Prop("lineHeight") { view: T3ComposerEditorView, lineHeight: Double ->
view.setLineHeight(lineHeight.toFloat())
}
Prop("contentInsetVertical") { view: T3ComposerEditorView, contentInsetVertical: Double ->
view.setContentInsetVertical(contentInsetVertical.toInt())
}
Prop("singleLineCentered") { view: T3ComposerEditorView, singleLineCentered: Boolean ->
view.setSingleLineCentered(singleLineCentered)
}
Prop("editable") { view: T3ComposerEditorView, editable: Boolean ->
view.setEditable(editable)
}
Prop("scrollEnabled") { view: T3ComposerEditorView, scrollEnabled: Boolean ->
view.setScrollEnabled(scrollEnabled)
}
Prop("autoFocus") { view: T3ComposerEditorView, autoFocus: Boolean ->
view.setAutoFocus(autoFocus)
}
Prop("autoCorrect") { view: T3ComposerEditorView, autoCorrect: Boolean ->
view.setAutoCorrect(autoCorrect)
}
Prop("spellCheck") { view: T3ComposerEditorView, spellCheck: Boolean ->
view.setSpellCheck(spellCheck)
}
Events(
"onComposerChange",
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
AsyncFunction("focus") { view: T3ComposerEditorView ->
view.focusEditor()
}
AsyncFunction("blur") { view: T3ComposerEditorView ->
view.blurEditor()
}
AsyncFunction("setSelection") { view: T3ComposerEditorView, start: Int, end: Int ->
view.setSelection(start, end)
}
}
}
}
@@ -0,0 +1,480 @@
package expo.modules.t3composereditor
import android.content.Context
import android.content.ClipboardManager
import android.graphics.Color
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Typeface
import android.text.Editable
import android.text.InputType
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ReplacementSpan
import android.view.Gravity
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
import org.json.JSONObject
import kotlin.math.max
class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
context,
appContext
) {
private val editor = SelectionAwareEditText(context)
private val onComposerChange by EventDispatcher()
private val onComposerSelectionChange by EventDispatcher()
private val onComposerFocus by EventDispatcher()
private val onComposerBlur by EventDispatcher()
private val onComposerPasteImages by EventDispatcher()
private val onComposerContentSizeChange by EventDispatcher()
private var applyingNativeValue = false
private var desiredLineHeightPx = 0
private var lastContentHeight = 0
private var contentInsetVertical = 0
private var tokensJson = "[]"
private var tokens: List<ComposerToken> = emptyList()
private var chipTheme = ComposerChipTheme.default()
private var autoCorrect = true
private var spellCheck = true
private var nativeEventCount = 0
init {
editor.setBackgroundColor(Color.TRANSPARENT)
editor.gravity = Gravity.TOP or Gravity.START
editor.includeFontPadding = false
editor.isSingleLine = false
editor.minLines = 1
editor.inputType =
InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_FLAG_MULTI_LINE or
InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
editor.setTextColor(Color.BLACK)
editor.setHintTextColor(Color.GRAY)
editor.setPadding(0, 0, 0, 0)
editor.selectionListener = { start, end ->
if (!applyingNativeValue) {
emitSelectionChange(start, end)
}
}
editor.pasteImagesListener = { uris ->
onComposerPasteImages(mapOf("uris" to uris))
}
editor.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
onComposerFocus(emptyMap<String, Any>())
} else {
onComposerBlur(emptyMap<String, Any>())
}
}
editor.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(
text: CharSequence?,
start: Int,
count: Int,
after: Int
) = Unit
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(editable: Editable?) {
if (applyingNativeValue) return
val nextValue = editable.toString()
val selection = currentSelectionPayload()
nativeEventCount += 1
onComposerChange(
mapOf(
"value" to nextValue,
"selection" to selection,
"eventCount" to nativeEventCount,
),
)
emitContentSizeIfNeeded()
}
},
)
editor.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> emitContentSizeIfNeeded() }
addView(
editor,
LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
)
}
@Suppress("ReturnCount")
fun setControlledDocumentJson(documentJson: String) {
val document = try {
JSONObject(documentJson)
} catch (_: Exception) {
return
}
val mostRecentEventCount = document.optInt("mostRecentEventCount", -1)
if (mostRecentEventCount < nativeEventCount) return
val value = document.optString("value")
if (document.optBoolean("isNativeEcho") && editor.text.toString() != value) return
val nextTokensJson = document.optString("tokensJson", "[]")
val nextTokens = if (nextTokensJson == tokensJson) tokens else parseTokens(nextTokensJson)
val requestedSelection = document.optJSONObject("selection")
val previousSelectionStart = editor.selectionStart.coerceAtLeast(0)
val previousSelectionEnd = editor.selectionEnd.coerceAtLeast(0)
val valueChanged = editor.text.toString() != value
applyingNativeValue = true
try {
if (valueChanged) {
editor.setText(value)
}
tokensJson = nextTokensJson
tokens = nextTokens
applyTokenSpans()
if (requestedSelection != null) {
applySelection(
requestedSelection.optInt("start", previousSelectionStart),
requestedSelection.optInt("end", previousSelectionEnd),
)
} else if (valueChanged) {
applySelection(previousSelectionStart, previousSelectionEnd)
}
} finally {
applyingNativeValue = false
}
emitContentSizeIfNeeded()
}
fun setThemeJson(themeJson: String) {
try {
val theme = JSONObject(themeJson)
editor.setTextColor(parseColor(theme.optString("text"), Color.BLACK))
editor.setHintTextColor(parseColor(theme.optString("placeholder"), Color.GRAY))
chipTheme = ComposerChipTheme(
chipBackground = parseColor(theme.optString("chipBackground"), chipTheme.chipBackground),
chipBorder = parseColor(theme.optString("chipBorder"), chipTheme.chipBorder),
chipText = parseColor(theme.optString("chipText"), chipTheme.chipText),
skillBackground = parseColor(
theme.optString("skillBackground"),
chipTheme.skillBackground,
),
skillBorder = parseColor(theme.optString("skillBorder"), chipTheme.skillBorder),
skillText = parseColor(theme.optString("skillText"), chipTheme.skillText),
)
applyTokenSpans()
} catch (_: Exception) {
}
}
fun setPlaceholder(placeholder: String) {
editor.hint = placeholder
}
fun setFontFamily(fontFamily: String) {
editor.typeface = if (fontFamily.contains("Mono", ignoreCase = true)) {
Typeface.MONOSPACE
} else {
Typeface.DEFAULT
}
}
fun setFontSize(fontSize: Float) {
editor.textSize = fontSize
applyLineHeight()
}
fun setLineHeight(lineHeight: Float) {
desiredLineHeightPx = (lineHeight * resources.displayMetrics.density).toInt()
applyLineHeight()
}
fun setSingleLineCentered(centered: Boolean) {
editor.gravity = if (centered) {
Gravity.CENTER_VERTICAL or Gravity.START
} else {
Gravity.TOP or Gravity.START
}
}
fun setContentInsetVertical(contentInsetVertical: Int) {
this.contentInsetVertical =
max(0, (contentInsetVertical * resources.displayMetrics.density).toInt())
editor.setPadding(0, this.contentInsetVertical, 0, this.contentInsetVertical)
emitContentSizeIfNeeded()
}
fun setEditable(editable: Boolean) {
editor.isEnabled = editable
editor.isFocusable = editable
editor.isFocusableInTouchMode = editable
editor.isCursorVisible = editable
}
fun setScrollEnabled(scrollEnabled: Boolean) {
editor.isVerticalScrollBarEnabled = scrollEnabled
}
fun setAutoFocus(autoFocus: Boolean) {
if (autoFocus) {
post { focusEditor() }
}
}
fun setAutoCorrect(autoCorrect: Boolean) {
this.autoCorrect = autoCorrect
updateInputFlags()
}
fun setSpellCheck(spellCheck: Boolean) {
this.spellCheck = spellCheck
updateInputFlags()
}
fun focusEditor() {
editor.requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(editor, InputMethodManager.SHOW_IMPLICIT)
}
fun blurEditor() {
editor.clearFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(editor.windowToken, 0)
}
fun setSelection(start: Int, end: Int) {
applySelection(start, end)
}
private fun applySelection(start: Int, end: Int) {
val textLength = editor.text?.length ?: 0
val safeStart = start.coerceIn(0, textLength)
val safeEnd = end.coerceIn(0, textLength)
editor.setSelection(safeStart, safeEnd)
}
private fun updateInputFlags() {
var flags =
InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_FLAG_MULTI_LINE or
InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
flags = if (autoCorrect && spellCheck) {
flags or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
} else {
flags or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
}
editor.inputType = flags
}
private fun applyLineHeight() {
if (desiredLineHeightPx <= 0) return
val fontHeight = editor.paint.fontMetricsInt.descent - editor.paint.fontMetricsInt.ascent
editor.setLineSpacing(max(0, desiredLineHeightPx - fontHeight).toFloat(), 1f)
}
private fun currentSelectionPayload(): Map<String, Int> =
mapOf(
"start" to editor.selectionStart.coerceAtLeast(0),
"end" to editor.selectionEnd.coerceAtLeast(0),
)
private fun emitSelectionChange(start: Int, end: Int) {
onComposerSelectionChange(
mapOf(
"value" to editor.text.toString(),
"selection" to mapOf("start" to start, "end" to end),
"eventCount" to nativeEventCount,
),
)
}
private fun emitContentSizeIfNeeded() {
val height = editor.layout?.height ?: editor.measuredHeight
val contentHeight = height + contentInsetVertical * 2
if (contentHeight == lastContentHeight) return
lastContentHeight = contentHeight
onComposerContentSizeChange(
mapOf("height" to contentHeight / resources.displayMetrics.density),
)
}
private fun applyTokenSpans() {
val editable = editor.text ?: return
editable.getSpans(
0,
editable.length,
ComposerChipSpan::class.java
).forEach(editable::removeSpan)
tokens.forEach { token ->
if (token.start < 0 || token.end <= token.start || token.end > editable.length) return@forEach
val expectedSource = editable.substring(token.start, token.end)
if (expectedSource != token.source) return@forEach
editable.setSpan(
ComposerChipSpan(
token.label,
token.type == "skill",
chipTheme,
resources.displayMetrics.density
),
token.start,
token.end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}
editor.invalidate()
}
private fun parseColor(value: String, fallback: Int): Int =
try {
Color.parseColor(value)
} catch (_: Exception) {
fallback
}
}
private data class ComposerToken(
val type: String,
val source: String,
val label: String,
val start: Int,
val end: Int
)
private data class ComposerChipTheme(
val chipBackground: Int,
val chipBorder: Int,
val chipText: Int,
val skillBackground: Int,
val skillBorder: Int,
val skillText: Int
) {
companion object {
fun default() = ComposerChipTheme(
chipBackground = Color.rgb(238, 240, 243),
chipBorder = Color.rgb(210, 214, 220),
chipText = Color.rgb(35, 39, 45),
skillBackground = Color.rgb(233, 239, 255),
skillBorder = Color.rgb(185, 200, 245),
skillText = Color.rgb(45, 72, 155),
)
}
}
private class ComposerChipSpan(
private val label: String,
private val skill: Boolean,
private val theme: ComposerChipTheme,
density: Float
) : ReplacementSpan() {
private val horizontalPadding = 7f * density
private val verticalPadding = 2f * density
private val cornerRadius = 6f * density
private val borderWidth = density
override fun getSize(
paint: Paint,
text: CharSequence,
start: Int,
end: Int,
fontMetrics: Paint.FontMetricsInt?
): Int {
fontMetrics?.let {
val extra = verticalPadding.toInt()
val base = paint.fontMetricsInt
it.top = base.top - extra
it.ascent = base.ascent - extra
it.descent = base.descent + extra
it.bottom = base.bottom + extra
}
return (paint.measureText(label) + horizontalPadding * 2).toInt()
}
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
val width = paint.measureText(label) + horizontalPadding * 2
val metrics = paint.fontMetrics
val rect = RectF(
x,
y + metrics.ascent - verticalPadding,
x + width,
y + metrics.descent + verticalPadding,
)
val originalColor = paint.color
val originalStyle = paint.style
val originalStrokeWidth = paint.strokeWidth
paint.color = if (skill) theme.skillBackground else theme.chipBackground
paint.style = Paint.Style.FILL
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
paint.color = if (skill) theme.skillBorder else theme.chipBorder
paint.style = Paint.Style.STROKE
paint.strokeWidth = borderWidth
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
paint.color = if (skill) theme.skillText else theme.chipText
paint.style = Paint.Style.FILL
canvas.drawText(label, x + horizontalPadding, y.toFloat(), paint)
paint.color = originalColor
paint.style = originalStyle
paint.strokeWidth = originalStrokeWidth
}
}
private fun parseTokens(value: String): List<ComposerToken> = try {
val array = org.json.JSONArray(value)
List(array.length()) { index ->
val token = array.getJSONObject(index)
ComposerToken(
type = token.optString("type"),
source = token.optString("source"),
label = token.optString("label"),
start = token.optInt("start"),
end = token.optInt("end"),
)
}
} catch (_: Exception) {
emptyList()
}
private class SelectionAwareEditText(context: Context) : EditText(context) {
var selectionListener: ((Int, Int) -> Unit)? = null
var pasteImagesListener: ((List<String>) -> Unit)? = null
override fun onSelectionChanged(selStart: Int, selEnd: Int) {
super.onSelectionChanged(selStart, selEnd)
selectionListener?.invoke(selStart, selEnd)
}
override fun onTextContextMenuItem(id: Int): Boolean {
if (id == android.R.id.paste || id == android.R.id.pasteAsPlainText) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
val clip = clipboard?.primaryClip
val imageUris = buildList {
if (clip != null) {
for (index in 0 until clip.itemCount) {
clip.getItemAt(index).uri?.let { uri ->
val mimeType = context.contentResolver.getType(uri)
if (mimeType?.startsWith("image/") == true) add(uri.toString())
}
}
}
}
if (imageUris.isNotEmpty()) {
pasteImagesListener?.invoke(imageUris)
return true
}
}
return super.onTextContextMenuItem(id)
}
}
@@ -1,6 +1,9 @@
{
"platforms": ["apple"],
"platforms": ["apple", "android"],
"apple": {
"modules": ["T3ComposerEditorModule"]
},
"android": {
"modules": ["expo.modules.t3composereditor.T3ComposerEditorModule"]
}
}
@@ -300,7 +300,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
skillText: "#a21caf",
fileTint: "#737373"
)
private var fontFamily = "DMSans_400Regular"
private var fontFamily = "DMSans-Regular"
private var fontSize: CGFloat = 14
private var lineHeight: CGFloat = 20
private var contentInsetVertical: CGFloat = 0
@@ -608,7 +608,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
iconImage: UIImage?,
style: ComposerChipStyle
) -> UIImage {
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
let font = UIFont(name: "DMSans-Medium", size: max(12, fontSize - 2))
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
let fallbackIcon = UIImage(
systemName: iconName,
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.nativecontrols'
version = '0.0.0'
android {
namespace 'expo.modules.t3nativecontrols'
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
}
dependencies {
implementation project(':expo-modules-core')
}
@@ -0,0 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,97 @@
package expo.modules.t3nativecontrols
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
private val iconView = HeaderIconView(context)
private val onTriggered by EventDispatcher()
init {
isClickable = true
isFocusable = true
setOnClickListener {
onTriggered(emptyMap<String, Any>())
}
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
fun setLabel(label: String) {
contentDescription = label
}
fun setSystemImage(systemImage: String) {
iconView.systemImage = systemImage
}
}
private class HeaderIconView(context: Context) : View(context) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#6B7280")
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
strokeWidth = 3f * resources.displayMetrics.density
style = Paint.Style.STROKE
}
var systemImage: String = "gearshape"
set(value) {
field = value
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val cx = width / 2f
val cy = height / 2f
val size = minOf(width, height).toFloat()
if (systemImage == "square.and.pencil") {
drawNewTask(canvas, cx, cy, size)
} else {
drawSettings(canvas, cx, cy, size)
}
}
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val radius = size * 0.12f
canvas.drawCircle(cx, cy, radius, paint)
for (index in 0 until 8) {
val angle = Math.PI * index / 4.0
val inner = size * 0.19f
val outer = size * 0.27f
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
canvas.drawLine(sx, sy, ex, ey, paint)
}
}
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val left = cx - size * 0.2f
val top = cy - size * 0.16f
val right = cx + size * 0.14f
val bottom = cy + size * 0.2f
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
canvas.drawLine(
cx - size * 0.02f,
cy + size * 0.13f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
canvas.drawLine(
cx + size * 0.17f,
cy - size * 0.2f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
}
}
@@ -0,0 +1,47 @@
package expo.modules.t3nativecontrols
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3NativeControlsModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3NativeControls")
Function("getShowcasePairingUrl") {
appContext.currentActivity?.intent?.getStringExtra("showcasePairingUrl")
}
Function("getShowcaseScene") {
val storedScene = appContext.reactContext
?.filesDir
?.resolve("t3-showcase-scene")
?.takeIf { it.isFile }
?.readText()
?.trim()
?.takeIf { it.isNotEmpty() }
storedScene ?: appContext.currentActivity?.intent?.getStringExtra("showcaseScene")
}
Function("prepareShowcaseCapture") {
// Android app data is cleared by the host runner before launch.
}
Function("markShowcaseReady") { scene: String ->
appContext.reactContext
?.filesDir
?.resolve("t3-showcase-ready")
?.writeText(scene)
}
View(T3HeaderButtonView::class) {
Prop("label") { view: T3HeaderButtonView, label: String ->
view.setLabel(label)
}
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
@@ -1,6 +1,9 @@
{
"platforms": ["apple"],
"platforms": ["apple", "android"],
"apple": {
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
},
"android": {
"modules": ["expo.modules.t3nativecontrols.T3NativeControlsModule"]
}
}
@@ -1,9 +1,48 @@
import ExpoModulesCore
import Security
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3NativeControls")
Function("getShowcasePairingUrl") {
let arguments = ProcessInfo.processInfo.arguments
guard
let flagIndex = arguments.firstIndex(of: "--showcasePairingUrl"),
arguments.indices.contains(flagIndex + 1)
else {
return nil as String?
}
return arguments[flagIndex + 1]
}
Function("getShowcaseScene") { () -> String? in
let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
.trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
return storedScene
}
let arguments = ProcessInfo.processInfo.arguments
guard
let flagIndex = arguments.firstIndex(of: "--showcaseScene"),
arguments.indices.contains(flagIndex + 1)
else {
return nil as String?
}
return arguments[flagIndex + 1]
}
Function("prepareShowcaseCapture") {
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
}
}
Function("markShowcaseReady") { (scene: String) in
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
}
View(T3HeaderButtonView.self) {
Prop("label") { (view: T3HeaderButtonView, label: String) in
view.setLabel(label)
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.reviewdiff'
version = '0.0.0'
android {
namespace 'expo.modules.t3reviewdiff'
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
}
dependencies {
implementation project(':expo-modules-core')
}
@@ -0,0 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,315 @@
package expo.modules.t3reviewdiff
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import kotlin.math.max
import kotlin.math.min
internal class ReviewDiffCanvasDrawing(context: Context) {
private val density = context.resources.displayMetrics.density
var theme: DiffTheme = DiffTheme.fallback("light")
val backgroundPaint = Paint()
val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
hinting = Paint.HINTING_ON
isSubpixelText = false
clearShadowLayer()
}
val uiPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
hinting = Paint.HINTING_ON
isSubpixelText = false
clearShadowLayer()
}
private val italicCodeTypeface by lazy {
Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC)
}
private val boldItalicCodeTypeface by lazy {
Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC)
}
init {
textPaint.typeface = ReviewDiffTypefaces.regular
uiPaint.typeface = Typeface.DEFAULT_BOLD
}
fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF {
val centerY = (top + bottom) / 2f
val left = style.fileHeaderHorizontalPaddingPx
return RectF(left, centerY - 10f * density, left + 20f * density, centerY + 10f * density)
}
fun fileHeaderIconRect(top: Int, bottom: Int, style: DiffStyle): RectF {
val chevron = fileHeaderChevronRect(top, bottom, style)
return RectF(
chevron.right + 8f * density,
chevron.top,
chevron.right + 28f * density,
chevron.bottom,
)
}
fun fileHeaderCheckboxRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF {
val centerY = (top + bottom) / 2f
val right = width - style.fileHeaderHorizontalPaddingPx
return RectF(
right - 20f * density,
centerY - 10f * density,
right,
centerY + 10f * density,
)
}
fun drawDisclosureChevron(
canvas: Canvas,
rect: RectF,
color: Int,
collapsed: Boolean
) {
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 2f * density
borderPaint.strokeCap = Paint.Cap.ROUND
borderPaint.strokeJoin = Paint.Join.ROUND
val path = Path()
if (collapsed) {
path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f)
path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY())
path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f)
} else {
path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f)
path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
}
canvas.drawPath(path, borderPaint)
borderPaint.style = Paint.Style.FILL
}
fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) {
val color = when (changeType) {
"new" -> theme.addText
"deleted" -> theme.deleteText
else -> theme.hunkText
}
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 2f * density
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") {
drawRenameChevronIcon(canvas, rect, color)
} else {
backgroundPaint.color = color
canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint)
}
borderPaint.style = Paint.Style.FILL
}
fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) {
if (checked) {
backgroundPaint.color = theme.hunkText
canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint)
}
borderPaint.style = Paint.Style.STROKE
borderPaint.color = if (checked) theme.hunkText else theme.mutedText
borderPaint.strokeWidth = 1.8f * density
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
if (checked) {
borderPaint.color = theme.background
borderPaint.strokeWidth = 2f * density
borderPaint.strokeCap = Paint.Cap.ROUND
borderPaint.strokeJoin = Paint.Join.ROUND
val path = Path().apply {
moveTo(rect.left + rect.width() * 0.28f, rect.centerY())
lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f)
lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f)
}
canvas.drawPath(path, borderPaint)
}
borderPaint.style = Paint.Style.FILL
}
fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) {
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 1.7f * density
borderPaint.strokeCap = Paint.Cap.ROUND
canvas.drawOval(rect, borderPaint)
canvas.drawLine(
rect.centerX(),
rect.top + rect.height() * 0.3f,
rect.centerX(),
rect.top + rect.height() * 0.58f,
borderPaint,
)
borderPaint.style = Paint.Style.FILL
canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint)
}
fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) {
paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
configureTextPaint(paint, color, size)
}
fun configureMonospacePaint(color: Int, size: Float, weight: String) {
textPaint.typeface = ReviewDiffTypefaces.forWeight(weight)
configureTextPaint(textPaint, color, size)
}
fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) {
val tokenBold = fontStyle and 2 != 0
val italic = fontStyle and 1 != 0
textPaint.typeface = when {
tokenBold && italic -> boldItalicCodeTypeface
tokenBold -> ReviewDiffTypefaces.bold
italic -> italicCodeTypeface
else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight)
}
configureTextPaint(textPaint, color, style.codeFontSizePx)
textPaint.isUnderlineText = fontStyle and 4 != 0
}
fun lineNumberColor(change: String): Int = when (change) {
"add" -> theme.addText
"delete" -> theme.deleteText
else -> theme.mutedText
}
fun drawDeleteStripes(
canvas: Canvas,
top: Int,
bottom: Int,
width: Float,
color: Int
) {
backgroundPaint.color = color
var y = top.toFloat()
while (y < bottom) {
canvas.drawRect(0f, y, width, min(bottom.toFloat(), y + density), backgroundPaint)
y += 2f * density
}
}
fun drawWordDiffRanges(
canvas: Canvas,
row: DiffRow,
codeX: Float,
top: Int,
bottom: Int
) {
if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return
val color = if (row.change == "add") theme.addBar else theme.deleteBar
backgroundPaint.color = withAlpha(color, 71)
val characterWidth = textPaint.measureText("M")
val fontHeight = textPaint.fontMetrics.run { descent - ascent }
val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight))
val highlightTop = (top + bottom - highlightHeight) / 2f
row.wordDiffRanges.forEach { range ->
val left = codeX + range.start * characterWidth
val right = max(left + 2f * density, codeX + range.end * characterWidth)
canvas.drawRoundRect(
RectF(left, highlightTop, right, highlightTop + highlightHeight),
3f * density,
3f * density,
backgroundPaint,
)
}
}
fun drawFileHeaderPathScrollFades(
canvas: Canvas,
pathRect: RectF,
horizontalOffset: Int,
maxOffset: Int
) {
if (maxOffset <= 0 || pathRect.width() <= 0f) return
val fadeWidth = min(28f * density, pathRect.width() / 3f)
if (horizontalOffset > 0) {
drawHorizontalFade(
canvas,
RectF(pathRect.left, pathRect.top, pathRect.left + fadeWidth, pathRect.bottom),
fadesToRight = false,
)
}
if (horizontalOffset < maxOffset) {
drawHorizontalFade(
canvas,
RectF(pathRect.right - fadeWidth, pathRect.top, pathRect.right, pathRect.bottom),
fadesToRight = true,
)
}
}
private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) {
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 1.8f * density
borderPaint.strokeCap = Paint.Cap.ROUND
borderPaint.strokeJoin = Paint.Join.ROUND
val chevronWidth = 3.6f * density
val chevronHeight = 8f * density
val gap = 2.4f * density
val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f
val path = Path()
for (x in listOf(startX, startX + chevronWidth + gap)) {
path.moveTo(x, rect.centerY() - chevronHeight / 2f)
path.lineTo(x + chevronWidth, rect.centerY())
path.lineTo(x, rect.centerY() + chevronHeight / 2f)
}
canvas.drawPath(path, borderPaint)
}
private fun configureTextPaint(paint: Paint, color: Int, size: Float) {
paint.textSize = size
paint.color = color
paint.style = Paint.Style.FILL
paint.textAlign = Paint.Align.LEFT
paint.isUnderlineText = false
paint.isFakeBoldText = false
paint.clearShadowLayer()
}
private fun drawHorizontalFade(canvas: Canvas, rect: RectF, fadesToRight: Boolean) {
val opaque = theme.headerBackground
val transparent = Color.argb(0, Color.red(opaque), Color.green(opaque), Color.blue(opaque))
backgroundPaint.shader = LinearGradient(
rect.left,
rect.centerY(),
rect.right,
rect.centerY(),
if (fadesToRight) transparent else opaque,
if (fadesToRight) opaque else transparent,
Shader.TileMode.CLAMP,
)
canvas.drawRect(rect, backgroundPaint)
backgroundPaint.shader = null
}
private fun isBoldFontWeight(weight: String): Boolean = when (weight.lowercase()) {
"medium", "semibold", "semi-bold", "bold", "heavy", "black" -> true
else -> false
}
private fun withAlpha(color: Int, alpha: Int): Int =
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
}
private object ReviewDiffTypefaces {
val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL)
private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL)
val bold: Typeface = Typeface.create("monospace", Typeface.BOLD)
fun forWeight(weight: String): Typeface = when (weight.lowercase()) {
"medium", "semibold", "semi-bold" -> medium
"bold", "heavy", "black" -> bold
else -> regular
}
}
@@ -0,0 +1,78 @@
package expo.modules.t3reviewdiff
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3ReviewDiffModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3ReviewDiffSurface")
View(T3ReviewDiffView::class) {
Prop("tokensResetKey") { view: T3ReviewDiffView, tokensResetKey: String ->
view.setTokensResetKey(tokensResetKey)
}
Prop("contentResetKey") { view: T3ReviewDiffView, contentResetKey: String ->
view.setContentResetKey(contentResetKey)
}
Prop("collapsedFileIdsJson") { view: T3ReviewDiffView, collapsedFileIdsJson: String ->
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
}
Prop("viewedFileIdsJson") { view: T3ReviewDiffView, viewedFileIdsJson: String ->
view.setViewedFileIdsJson(viewedFileIdsJson)
}
Prop("selectedRowIdsJson") { view: T3ReviewDiffView, selectedRowIdsJson: String ->
view.setSelectedRowIdsJson(selectedRowIdsJson)
}
Prop("collapsedCommentIdsJson") { view: T3ReviewDiffView, collapsedCommentIdsJson: String ->
view.setCollapsedCommentIdsJson(collapsedCommentIdsJson)
}
Prop("appearanceScheme") { view: T3ReviewDiffView, appearanceScheme: String ->
view.setAppearanceScheme(appearanceScheme)
}
Prop("themeJson") { view: T3ReviewDiffView, themeJson: String ->
view.setThemeJson(themeJson)
}
Prop("styleJson") { view: T3ReviewDiffView, styleJson: String ->
view.setStyleJson(styleJson)
}
Prop("rowHeight") { view: T3ReviewDiffView, rowHeight: Double ->
view.setRowHeight(rowHeight.toFloat())
}
Prop("contentWidth") { view: T3ReviewDiffView, contentWidth: Double ->
view.setContentWidth(contentWidth.toFloat())
}
Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double ->
view.setInitialRowIndex(initialRowIndex)
}
Events(
"onDebug",
"onVisibleFileChange",
"onToggleFile",
"onToggleViewedFile",
"onPressLine",
"onToggleComment",
)
AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean ->
view.scrollToFile(fileId, animated)
}
AsyncFunction("scrollToTop") { view: T3ReviewDiffView, animated: Boolean ->
view.scrollToTop(animated)
}
AsyncFunction("setRowsJson") { view: T3ReviewDiffView, rowsJson: String ->
view.setRowsJson(rowsJson)
}
AsyncFunction("setTokensJson") { view: T3ReviewDiffView, tokensJson: String ->
view.setTokensJson(tokensJson)
}
AsyncFunction("setTokensPatchJson") { view: T3ReviewDiffView, tokensPatchJson: String ->
view.setTokensPatchJson(tokensPatchJson)
}
OnViewDestroys { view: T3ReviewDiffView ->
view.cleanup()
}
}
}
}
@@ -1,7 +1,10 @@
{
"platforms": ["apple"],
"platforms": ["apple", "android"],
"apple": {
"modules": ["T3ReviewDiffModule"],
"podspecPath": "T3ReviewDiffNative.podspec"
},
"android": {
"modules": ["expo.modules.t3reviewdiff.T3ReviewDiffModule"]
}
}
@@ -7,6 +7,11 @@
"modules": [
"T3ReviewDiffModule"
]
},
"android": {
"modules": [
"expo.modules.t3reviewdiff.T3ReviewDiffModule"
]
}
}
}
+15 -3
View File
@@ -18,9 +18,9 @@ uses that callback I/O model:
4. send user input back to JS with the write callback
5. emit Ghostty's measured terminal size through `onResize`
Android currently implements the same view name (`T3TerminalSurface`) and event payloads so the
React Native screen and RPC code stay platform-neutral. The renderer backend can be replaced with a
future Android Ghostty build without changing JS.
Android implements the same view contract with upstream `libghostty-vt` for terminal state, parsing,
reflow, and scrollback. An Android Canvas view renders compact snapshots produced by the JNI bridge,
so the React Native screen and RPC code stay platform-neutral.
Vendored Ghostty revision and license details are in `THIRD_PARTY_NOTICES.md`.
@@ -36,3 +36,15 @@ apps/mobile/modules/t3-terminal/scripts/build-libghostty-ios16.sh
The script builds Ghostty with Zig 0.15.2, strips the iOS archives, and replaces only the
`ios-arm64` and `ios-arm64-simulator` slices. Xcode's Metal toolchain must be installed; if `metal`
fails, run `xcodebuild -downloadComponent MetalToolchain`.
## Rebuilding libghostty-vt for Android
The checked-in Android shared libraries and headers are pinned to the revision recorded in
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
```bash
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
```
The script downloads Zig 0.15.2 when needed, checks out the pinned upstream Ghostty revision, and
rebuilds all four Android ABIs with 16 KB page-size support.
@@ -14,3 +14,21 @@ iOS 16 support fork. That fork was created from VVTerm's custom-I/O Ghostty fork
Ghostty's MIT license applies to the vendored framework. Keep this notice in sync when updating
`Vendor/libghostty`.
## Ghostty / libghostty-vt
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
- Upstream project: https://github.com/ghostty-org/ghostty
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
- License: MIT
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
updating `Vendor/libghostty-vt`.
## MesloLGS NF (Android terminal font)
- Files: `android/src/main/assets/fonts/MesloLGS-NF-{Regular,Bold}.ttf`
- Source: https://github.com/romkatv/powerlevel10k-media (Meslo LG patched with Nerd Fonts glyphs)
- Upstream: Meslo LG by André Berg (customization of Apple's Menlo), Nerd Fonts patcher
- License: Apache License 2.0
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1 @@
9f62873bf195e4d8a762d768a1405a5f2f7b1697
@@ -0,0 +1,154 @@
/**
* @file vt.h
*
* libghostty-vt - Virtual terminal emulator library
*
* This library provides functionality for parsing and handling terminal
* escape sequences as well as maintaining terminal state such as styles,
* cursor position, screen, scrollback, and more.
*
* WARNING: This is an incomplete, work-in-progress API. It is not yet
* stable and is definitely going to change.
*/
/**
* @mainpage libghostty-vt - Virtual Terminal Emulator Library
*
* libghostty-vt is a C library which implements a modern terminal emulator,
* extracted from the [Ghostty](https://ghostty.org) terminal emulator.
*
* libghostty-vt contains the logic for handling the core parts of a terminal
* emulator: parsing terminal escape sequences, maintaining terminal state,
* encoding input events, etc. It can handle scrollback, line wrapping,
* reflow on resize, and more.
*
* @warning This library is currently in development and the API is not yet stable.
* Breaking changes are expected in future versions. Use with caution in production code.
*
* @section groups_sec API Reference
*
* The API is organized into the following groups:
* - @ref terminal "Terminal" - Complete terminal emulator state and rendering
* - @ref render "Render State" - Incremental render state updates for custom renderers
* - @ref formatter "Formatter" - Format terminal content as plain text, VT sequences, or HTML
* - @ref osc "OSC Parser" - Parse OSC (Operating System Command) sequences
* - @ref sgr "SGR Parser" - Parse SGR (Select Graphic Rendition) sequences
* - @ref paste "Paste Utilities" - Validate paste data safety
* - @ref build_info "Build Info" - Query compile-time build configuration
* - @ref allocator "Memory Management" - Memory management and custom allocators
* - @ref wasm "WebAssembly Utilities" - WebAssembly convenience functions
*
* Encoding related APIs:
* - @ref focus "Focus Encoding" - Encode focus in/out events into terminal sequences
* - @ref key "Key Encoding" - Encode key events into terminal sequences
* - @ref mouse "Mouse Encoding" - Encode mouse events into terminal sequences
*
* @section examples_sec Examples
*
* Complete working examples:
* - @ref c-vt-build-info/src/main.c - Build info query example
* - @ref c-vt/src/main.c - OSC parser example
* - @ref c-vt-encode-key/src/main.c - Key encoding example
* - @ref c-vt-encode-mouse/src/main.c - Mouse encoding example
* - @ref c-vt-paste/src/main.c - Paste safety check example
* - @ref c-vt-sgr/src/main.c - SGR parser example
* - @ref c-vt-formatter/src/main.c - Terminal formatter example
* - @ref c-vt-grid-traverse/src/main.c - Grid traversal example using grid refs
* - @ref c-vt-grid-ref-tracked/src/main.c - Tracked grid ref example
*
*/
/** @example c-vt-build-info/src/main.c
* This example demonstrates how to query compile-time build configuration
* such as SIMD support, Kitty graphics, and tmux control mode availability.
*/
/** @example c-vt/src/main.c
* This example demonstrates how to use the OSC parser to parse an OSC sequence,
* extract command information, and retrieve command-specific data like window titles.
*/
/** @example c-vt-encode-key/src/main.c
* This example demonstrates how to use the key encoder to convert key events
* into terminal escape sequences using the Kitty keyboard protocol.
*/
/** @example c-vt-encode-mouse/src/main.c
* This example demonstrates how to use the mouse encoder to convert mouse events
* into terminal escape sequences using the SGR mouse format.
*/
/** @example c-vt-paste/src/main.c
* This example demonstrates how to use the paste utilities to check if
* paste data is safe before sending it to the terminal.
*/
/** @example c-vt-sgr/src/main.c
* This example demonstrates how to use the SGR parser to parse terminal
* styling sequences and extract text attributes like colors and underline styles.
*/
/** @example c-vt-formatter/src/main.c
* This example demonstrates how to use the terminal and formatter APIs to
* create a terminal, write VT-encoded content into it, and format the screen
* contents as plain text.
*/
/** @example c-vt-grid-traverse/src/main.c
* This example demonstrates how to traverse the entire terminal grid using
* grid refs to inspect cell codepoints, row wrap state, and cell styles.
*/
/** @example c-vt-grid-ref-tracked/src/main.c
* This example demonstrates how to track a grid ref as the terminal scrolls,
* detect when it loses its value, and move it to a new point.
*/
/** @example c-vt-selection-gesture/src/main.c
* This example demonstrates how to use synthetic selection gesture events to
* derive drag and deep-press selection snapshots.
*/
/** @example c-vt-kitty-graphics/src/main.c
* This example demonstrates how to use the system interface to install a
* PNG decoder callback and send a Kitty Graphics Protocol image.
*/
#ifndef GHOSTTY_VT_H
#define GHOSTTY_VT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <ghostty/vt/types.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/build_info.h>
#include <ghostty/vt/color.h>
#include <ghostty/vt/device.h>
#include <ghostty/vt/focus.h>
#include <ghostty/vt/formatter.h>
#include <ghostty/vt/render.h>
#include <ghostty/vt/terminal.h>
#include <ghostty/vt/grid_ref.h>
#include <ghostty/vt/grid_ref_tracked.h>
#include <ghostty/vt/osc.h>
#include <ghostty/vt/sgr.h>
#include <ghostty/vt/style.h>
#include <ghostty/vt/sys.h>
#include <ghostty/vt/key.h>
#include <ghostty/vt/kitty_graphics.h>
#include <ghostty/vt/modes.h>
#include <ghostty/vt/mouse.h>
#include <ghostty/vt/paste.h>
#include <ghostty/vt/point.h>
#include <ghostty/vt/screen.h>
#include <ghostty/vt/selection.h>
#include <ghostty/vt/size_report.h>
#include <ghostty/vt/wasm.h>
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_H */
@@ -0,0 +1,255 @@
/**
* @file allocator.h
*
* Memory management interface for libghostty-vt.
*/
#ifndef GHOSTTY_VT_ALLOCATOR_H
#define GHOSTTY_VT_ALLOCATOR_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
/** @defgroup allocator Memory Management
*
* libghostty-vt does require memory allocation for various operations,
* but is resilient to allocation failures and will gracefully handle
* out-of-memory situations by returning error codes.
*
* The exact memory management semantics are documented in the relevant
* functions and data structures.
*
* libghostty-vt uses explicit memory allocation via an allocator
* interface provided by GhosttyAllocator. The interface is based on the
* [Zig](https://ziglang.org) allocator interface, since this has been
* shown to be a flexible and powerful interface in practice and enables
* a wide variety of allocation strategies.
*
* **For the common case, you can pass NULL as the allocator for any
* function that accepts one,** and libghostty will use a default allocator.
* The default allocator will be libc malloc/free if libc is linked.
* Otherwise, a custom allocator is used (currently Zig's SMP allocator)
* that doesn't require any external dependencies.
*
* ## Basic Usage
*
* For simple use cases, you can ignore this interface entirely by passing NULL
* as the allocator parameter to functions that accept one. This will use the
* default allocator (typically libc malloc/free, if libc is linked, but
* we provide our own default allocator if libc isn't linked).
*
* To use a custom allocator:
* 1. Implement the GhosttyAllocatorVtable function pointers
* 2. Create a GhosttyAllocator struct with your vtable and context
* 3. Pass the allocator to functions that accept one
*
* ## Alloc/Free Helpers
*
* ghostty_alloc() and ghostty_free() provide a simple malloc/free-style
* interface for allocating and freeing byte buffers through the library's
* allocator. These are useful when:
*
* - You need to allocate a buffer to pass into a libghostty-vt function
* (e.g. preparing input data for ghostty_terminal_vt_write()).
* - You need to free a buffer returned by a libghostty-vt function
* (e.g. the output of ghostty_formatter_format_alloc()).
* - You are on a platform where the library's internal allocator differs
* from the consumer's C runtime (e.g. Windows, where Zig's libc and
* MSVC's CRT maintain separate heaps), so calling the standard C
* free() on library-allocated memory would be undefined behavior.
*
* Always use the same allocator (or NULL) for both the allocation and
* the corresponding free.
*
* @{
*/
/**
* Function table for custom memory allocator operations.
*
* This vtable defines the interface for a custom memory allocator. All
* function pointers must be valid and non-NULL.
*
* @ingroup allocator
*
* If you're not going to use a custom allocator, you can ignore all of
* this. All functions that take an allocator pointer allow NULL to use a
* default allocator.
*
* The interface is based on the Zig allocator interface. I'll say up front
* that it is easy to look at this interface and think "wow, this is really
* overcomplicated". The reason for this complexity is well thought out by
* the Zig folks, and it enables a diverse set of allocation strategies
* as shown by the Zig ecosystem. As a consolation, please note that many
* of the arguments are only needed for advanced use cases and can be
* safely ignored in simple implementations. For example, if you look at
* the Zig implementation of the libc allocator in `lib/std/heap.zig`
* (search for CAllocator), you'll see it is very simple.
*
* We chose to align with the Zig allocator interface because:
*
* 1. It is a proven interface that serves a wide variety of use cases
* in the real world via the Zig ecosystem. It's shown to work.
*
* 2. Our core implementation itself is Zig, and this lets us very
* cheaply and easily convert between C and Zig allocators.
*
* NOTE(mitchellh): In the future, we can have default implementations of
* resize/remap and allow those to be null.
*/
typedef struct {
/**
* Return a pointer to `len` bytes with specified `alignment`, or return
* `NULL` indicating the allocation failed.
*
* @param ctx The allocator context
* @param len Number of bytes to allocate
* @param alignment Required alignment for the allocation. Guaranteed to
* be a power of two between 1 and 16 inclusive.
* @param ret_addr First return address of the allocation call stack (0 if not provided)
* @return Pointer to allocated memory, or NULL if allocation failed
*/
void* (*alloc)(void *ctx, size_t len, uint8_t alignment, uintptr_t ret_addr);
/**
* Attempt to expand or shrink memory in place.
*
* `memory_len` must equal the length requested from the most recent
* successful call to `alloc`, `resize`, or `remap`. `alignment` must
* equal the same value that was passed as the `alignment` parameter to
* the original `alloc` call.
*
* `new_len` must be greater than zero.
*
* @param ctx The allocator context
* @param memory Pointer to the memory block to resize
* @param memory_len Current size of the memory block
* @param alignment Alignment (must match original allocation)
* @param new_len New requested size
* @param ret_addr First return address of the allocation call stack (0 if not provided)
* @return true if resize was successful in-place, false if relocation would be required
*/
bool (*resize)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr);
/**
* Attempt to expand or shrink memory, allowing relocation.
*
* `memory_len` must equal the length requested from the most recent
* successful call to `alloc`, `resize`, or `remap`. `alignment` must
* equal the same value that was passed as the `alignment` parameter to
* the original `alloc` call.
*
* A non-`NULL` return value indicates the resize was successful. The
* allocation may have same address, or may have been relocated. In either
* case, the allocation now has size of `new_len`. A `NULL` return value
* indicates that the resize would be equivalent to allocating new memory,
* copying the bytes from the old memory, and then freeing the old memory.
* In such case, it is more efficient for the caller to perform the copy.
*
* `new_len` must be greater than zero.
*
* @param ctx The allocator context
* @param memory Pointer to the memory block to remap
* @param memory_len Current size of the memory block
* @param alignment Alignment (must match original allocation)
* @param new_len New requested size
* @param ret_addr First return address of the allocation call stack (0 if not provided)
* @return Pointer to resized memory (may be relocated), or NULL if manual copy is needed
*/
void* (*remap)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr);
/**
* Free and invalidate a region of memory.
*
* `memory_len` must equal the length requested from the most recent
* successful call to `alloc`, `resize`, or `remap`. `alignment` must
* equal the same value that was passed as the `alignment` parameter to
* the original `alloc` call.
*
* @param ctx The allocator context
* @param memory Pointer to the memory block to free
* @param memory_len Size of the memory block
* @param alignment Alignment (must match original allocation)
* @param ret_addr First return address of the allocation call stack (0 if not provided)
*/
void (*free)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, uintptr_t ret_addr);
} GhosttyAllocatorVtable;
/**
* Custom memory allocator.
*
* For functions that take an allocator pointer, a NULL pointer indicates
* that the default allocator should be used. The default allocator will
* be libc malloc/free if we're linking to libc. If libc isn't linked,
* a custom allocator is used (currently Zig's SMP allocator).
*
* @ingroup allocator
*
* Usage example:
* @code
* GhosttyAllocator allocator = {
* .vtable = &my_allocator_vtable,
* .ctx = my_allocator_state
* };
* @endcode
*/
typedef struct GhosttyAllocator {
/**
* Opaque context pointer passed to all vtable functions.
* This allows the allocator implementation to maintain state
* or reference external resources needed for memory management.
*/
void *ctx;
/**
* Pointer to the allocator's vtable containing function pointers
* for memory operations (alloc, resize, remap, free).
*/
const GhosttyAllocatorVtable *vtable;
} GhosttyAllocator;
/**
* Allocate a buffer of `len` bytes.
*
* Uses the provided allocator, or the default allocator if NULL is passed.
* The returned buffer must be freed with ghostty_free() using the same
* allocator.
*
* @param allocator Pointer to the allocator to use, or NULL for the default
* @param len Number of bytes to allocate
* @return Pointer to the allocated buffer, or NULL if allocation failed
*
* @ingroup allocator
*/
GHOSTTY_API uint8_t* ghostty_alloc(const GhosttyAllocator* allocator, size_t len);
/**
* Free memory that was allocated by a libghostty-vt function.
*
* Use this to free buffers returned by functions such as
* ghostty_formatter_format_alloc(). Pass the same allocator that was
* used for the allocation, or NULL if the default allocator was used.
*
* On platforms where the library's internal allocator differs from the
* consumer's C runtime (e.g. Windows, where Zig's libc and MSVC's CRT
* maintain separate heaps), calling the standard C free() on memory
* allocated by the library causes undefined behavior. This function
* guarantees the correct allocator is used regardless of platform.
*
* It is safe to pass a NULL pointer; the call is a no-op in that case.
*
* @param allocator Pointer to the allocator that was used to allocate the
* memory, or NULL if the default allocator was used
* @param ptr Pointer to the memory to free (may be NULL)
* @param len Length of the allocation in bytes (must match the original
* allocation size)
*
* @ingroup allocator
*/
GHOSTTY_API void ghostty_free(const GhosttyAllocator* allocator, uint8_t* ptr, size_t len);
/** @} */
#endif /* GHOSTTY_VT_ALLOCATOR_H */
@@ -0,0 +1,150 @@
/**
* @file build_info.h
*
* Build info - query compile-time build configuration of libghostty-vt.
*/
#ifndef GHOSTTY_VT_BUILD_INFO_H
#define GHOSTTY_VT_BUILD_INFO_H
/** @defgroup build_info Build Info
*
* Query compile-time build configuration of libghostty-vt.
*
* These values reflect the options the library was built with and are
* constant for the lifetime of the process.
*
* ## Basic Usage
*
* Use ghostty_build_info() to query individual build options:
*
* @snippet c-vt-build-info/src/main.c build-info-query
*
* @{
*/
#include <stddef.h>
#include <stdbool.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Build optimization mode.
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_OPTIMIZE_DEBUG = 0,
GHOSTTY_OPTIMIZE_RELEASE_SAFE = 1,
GHOSTTY_OPTIMIZE_RELEASE_SMALL = 2,
GHOSTTY_OPTIMIZE_RELEASE_FAST = 3,
GHOSTTY_OPTIMIZE_MODE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyOptimizeMode;
/**
* Build info data types that can be queried.
*
* Each variant documents the expected output pointer type.
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid data type. Never results in any data extraction. */
GHOSTTY_BUILD_INFO_INVALID = 0,
/**
* Whether SIMD-accelerated code paths are enabled.
*
* Output type: bool *
*/
GHOSTTY_BUILD_INFO_SIMD = 1,
/**
* Whether Kitty graphics protocol support is available.
*
* Output type: bool *
*/
GHOSTTY_BUILD_INFO_KITTY_GRAPHICS = 2,
/**
* Whether tmux control mode support is available.
*
* Output type: bool *
*/
GHOSTTY_BUILD_INFO_TMUX_CONTROL_MODE = 3,
/**
* The optimization mode the library was built with.
*
* Output type: GhosttyOptimizeMode *
*/
GHOSTTY_BUILD_INFO_OPTIMIZE = 4,
/**
* The full version string (e.g. "1.2.3" or "1.2.3-dev+abcdef").
*
* Output type: GhosttyString *
*/
GHOSTTY_BUILD_INFO_VERSION_STRING = 5,
/**
* The major version number.
*
* Output type: size_t *
*/
GHOSTTY_BUILD_INFO_VERSION_MAJOR = 6,
/**
* The minor version number.
*
* Output type: size_t *
*/
GHOSTTY_BUILD_INFO_VERSION_MINOR = 7,
/**
* The patch version number.
*
* Output type: size_t *
*/
GHOSTTY_BUILD_INFO_VERSION_PATCH = 8,
/**
* The pre metadata string (e.g. "alpha", "beta", "dev"). Has zero length if
* no pre metadata is present.
*
* Output type: GhosttyString *
*/
GHOSTTY_BUILD_INFO_VERSION_PRE = 9,
/**
* The build metadata string (e.g. commit hash). Has zero length if
* no build metadata is present.
*
* Output type: GhosttyString *
*/
GHOSTTY_BUILD_INFO_VERSION_BUILD = 10,
GHOSTTY_BUILD_INFO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyBuildInfo;
/**
* Query a compile-time build configuration value.
*
* The caller must pass a pointer to the correct output type for the
* requested data (see GhosttyBuildInfo variants for types).
*
* @param data The build info field to query
* @param out Pointer to store the result (type depends on data parameter)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
* data type is invalid
*
* @ingroup build_info
*/
GHOSTTY_API GhosttyResult ghostty_build_info(GhosttyBuildInfo data, void *out);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_BUILD_INFO_H */
@@ -0,0 +1,97 @@
/**
* @file color.h
*
* Color types and utilities.
*/
#ifndef GHOSTTY_VT_COLOR_H
#define GHOSTTY_VT_COLOR_H
#include <stdint.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* RGB color value.
*
* @ingroup sgr
*/
typedef struct {
uint8_t r; /**< Red component (0-255) */
uint8_t g; /**< Green component (0-255) */
uint8_t b; /**< Blue component (0-255) */
} GhosttyColorRgb;
/**
* Palette color index (0-255).
*
* @ingroup sgr
*/
typedef uint8_t GhosttyColorPaletteIndex;
/** @addtogroup sgr
* @{
*/
/** Black color (0) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BLACK 0
/** Red color (1) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_RED 1
/** Green color (2) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_GREEN 2
/** Yellow color (3) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_YELLOW 3
/** Blue color (4) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BLUE 4
/** Magenta color (5) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_MAGENTA 5
/** Cyan color (6) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_CYAN 6
/** White color (7) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_WHITE 7
/** Bright black color (8) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_BLACK 8
/** Bright red color (9) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_RED 9
/** Bright green color (10) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_GREEN 10
/** Bright yellow color (11) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_YELLOW 11
/** Bright blue color (12) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_BLUE 12
/** Bright magenta color (13) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_MAGENTA 13
/** Bright cyan color (14) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_CYAN 14
/** Bright white color (15) @ingroup sgr */
#define GHOSTTY_COLOR_NAMED_BRIGHT_WHITE 15
/** @} */
/**
* Get the RGB color components.
*
* This function extracts the individual red, green, and blue components
* from a GhosttyColorRgb value. Primarily useful in WebAssembly environments
* where accessing struct fields directly is difficult.
*
* @param color The RGB color value
* @param r Pointer to store the red component (0-255)
* @param g Pointer to store the green component (0-255)
* @param b Pointer to store the blue component (0-255)
*
* @ingroup sgr
*/
GHOSTTY_API void ghostty_color_rgb_get(GhosttyColorRgb color,
uint8_t* r,
uint8_t* g,
uint8_t* b);
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_COLOR_H */
@@ -0,0 +1,151 @@
/**
* @file device.h
*
* Device types used by the terminal for device status and device attribute
* queries.
*/
#ifndef GHOSTTY_VT_DEVICE_H
#define GHOSTTY_VT_DEVICE_H
#include <stddef.h>
#include <stdint.h>
/* DA1 conformance levels (Pp parameter). */
#define GHOSTTY_DA_CONFORMANCE_VT100 1
#define GHOSTTY_DA_CONFORMANCE_VT101 1
#define GHOSTTY_DA_CONFORMANCE_VT102 6
#define GHOSTTY_DA_CONFORMANCE_VT125 12
#define GHOSTTY_DA_CONFORMANCE_VT131 7
#define GHOSTTY_DA_CONFORMANCE_VT132 4
#define GHOSTTY_DA_CONFORMANCE_VT220 62
#define GHOSTTY_DA_CONFORMANCE_VT240 62
#define GHOSTTY_DA_CONFORMANCE_VT320 63
#define GHOSTTY_DA_CONFORMANCE_VT340 63
#define GHOSTTY_DA_CONFORMANCE_VT420 64
#define GHOSTTY_DA_CONFORMANCE_VT510 65
#define GHOSTTY_DA_CONFORMANCE_VT520 65
#define GHOSTTY_DA_CONFORMANCE_VT525 65
#define GHOSTTY_DA_CONFORMANCE_LEVEL_2 62
#define GHOSTTY_DA_CONFORMANCE_LEVEL_3 63
#define GHOSTTY_DA_CONFORMANCE_LEVEL_4 64
#define GHOSTTY_DA_CONFORMANCE_LEVEL_5 65
/* DA1 feature codes (Ps parameters). */
#define GHOSTTY_DA_FEATURE_COLUMNS_132 1
#define GHOSTTY_DA_FEATURE_PRINTER 2
#define GHOSTTY_DA_FEATURE_REGIS 3
#define GHOSTTY_DA_FEATURE_SIXEL 4
#define GHOSTTY_DA_FEATURE_SELECTIVE_ERASE 6
#define GHOSTTY_DA_FEATURE_USER_DEFINED_KEYS 8
#define GHOSTTY_DA_FEATURE_NATIONAL_REPLACEMENT 9
#define GHOSTTY_DA_FEATURE_TECHNICAL_CHARACTERS 15
#define GHOSTTY_DA_FEATURE_LOCATOR 16
#define GHOSTTY_DA_FEATURE_TERMINAL_STATE 17
#define GHOSTTY_DA_FEATURE_WINDOWING 18
#define GHOSTTY_DA_FEATURE_HORIZONTAL_SCROLLING 21
#define GHOSTTY_DA_FEATURE_ANSI_COLOR 22
#define GHOSTTY_DA_FEATURE_RECTANGULAR_EDITING 28
#define GHOSTTY_DA_FEATURE_ANSI_TEXT_LOCATOR 29
#define GHOSTTY_DA_FEATURE_CLIPBOARD 52
/* DA2 device type identifiers (Pp parameter). */
#define GHOSTTY_DA_DEVICE_TYPE_VT100 0
#define GHOSTTY_DA_DEVICE_TYPE_VT220 1
#define GHOSTTY_DA_DEVICE_TYPE_VT240 2
#define GHOSTTY_DA_DEVICE_TYPE_VT330 18
#define GHOSTTY_DA_DEVICE_TYPE_VT340 19
#define GHOSTTY_DA_DEVICE_TYPE_VT320 24
#define GHOSTTY_DA_DEVICE_TYPE_VT382 32
#define GHOSTTY_DA_DEVICE_TYPE_VT420 41
#define GHOSTTY_DA_DEVICE_TYPE_VT510 61
#define GHOSTTY_DA_DEVICE_TYPE_VT520 64
#define GHOSTTY_DA_DEVICE_TYPE_VT525 65
#ifdef __cplusplus
extern "C" {
#endif
/**
* Color scheme reported in response to a CSI ? 996 n query.
*
* @ingroup terminal
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_COLOR_SCHEME_LIGHT = 0,
GHOSTTY_COLOR_SCHEME_DARK = 1,
GHOSTTY_COLOR_SCHEME_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyColorScheme;
/**
* Primary device attributes (DA1) response data.
*
* Returned as part of GhosttyDeviceAttributes in response to a CSI c query.
* The conformance_level is the Pp parameter and features contains the Ps
* feature codes.
*
* @ingroup terminal
*/
typedef struct {
/** Conformance level (Pp parameter). E.g. 62 for VT220. */
uint16_t conformance_level;
/** DA1 feature codes. Only the first num_features entries are valid. */
uint16_t features[64];
/** Number of valid entries in the features array. */
size_t num_features;
} GhosttyDeviceAttributesPrimary;
/**
* Secondary device attributes (DA2) response data.
*
* Returned as part of GhosttyDeviceAttributes in response to a CSI > c query.
* Response format: CSI > Pp ; Pv ; Pc c
*
* @ingroup terminal
*/
typedef struct {
/** Terminal type identifier (Pp). E.g. 1 for VT220. */
uint16_t device_type;
/** Firmware/patch version number (Pv). */
uint16_t firmware_version;
/** ROM cartridge registration number (Pc). Always 0 for emulators. */
uint16_t rom_cartridge;
} GhosttyDeviceAttributesSecondary;
/**
* Tertiary device attributes (DA3) response data.
*
* Returned as part of GhosttyDeviceAttributes in response to a CSI = c query.
* Response format: DCS ! | D...D ST (DECRPTUI).
*
* @ingroup terminal
*/
typedef struct {
/** Unit ID encoded as 8 uppercase hex digits in the response. */
uint32_t unit_id;
} GhosttyDeviceAttributesTertiary;
/**
* Device attributes response data for all three DA levels.
*
* Filled by the device_attributes callback in response to CSI c,
* CSI > c, or CSI = c queries. The terminal uses whichever sub-struct
* matches the request type.
*
* @ingroup terminal
*/
typedef struct {
GhosttyDeviceAttributesPrimary primary;
GhosttyDeviceAttributesSecondary secondary;
GhosttyDeviceAttributesTertiary tertiary;
} GhosttyDeviceAttributes;
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_DEVICE_H */
@@ -0,0 +1,76 @@
/**
* @file focus.h
*
* Focus encoding - encode focus in/out events into terminal escape sequences.
*/
#ifndef GHOSTTY_VT_FOCUS_H
#define GHOSTTY_VT_FOCUS_H
/** @defgroup focus Focus Encoding
*
* Utilities for encoding focus gained/lost events into terminal escape
* sequences (CSI I / CSI O) for focus reporting mode (mode 1004).
*
* ## Basic Usage
*
* Use ghostty_focus_encode() to encode a focus event into a caller-provided
* buffer. If the buffer is too small, the function returns
* GHOSTTY_OUT_OF_SPACE and sets the required size in the output parameter.
*
* ## Example
*
* @snippet c-vt-encode-focus/src/main.c focus-encode
*
* @{
*/
#include <stddef.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Focus event types for focus reporting mode (mode 1004).
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Terminal window gained focus */
GHOSTTY_FOCUS_GAINED = 0,
/** Terminal window lost focus */
GHOSTTY_FOCUS_LOST = 1,
GHOSTTY_FOCUS_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyFocusEvent;
/**
* Encode a focus event into a terminal escape sequence.
*
* Encodes a focus gained (CSI I) or focus lost (CSI O) report into the
* provided buffer.
*
* If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
* and writes the required buffer size to @p out_written. The caller can
* then retry with a sufficiently sized buffer.
*
* @param event The focus event to encode
* @param buf Output buffer to write the encoded sequence into (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_written On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
* is too small
*/
GHOSTTY_API GhosttyResult ghostty_focus_encode(
GhosttyFocusEvent event,
char* buf,
size_t buf_len,
size_t* out_written);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_FOCUS_H */
@@ -0,0 +1,207 @@
/**
* @file formatter.h
*
* Format terminal content as plain text, VT sequences, or HTML.
*/
#ifndef GHOSTTY_VT_FORMATTER_H
#define GHOSTTY_VT_FORMATTER_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/selection.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/terminal.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup formatter Formatter
*
* Format terminal content as plain text, VT sequences, or HTML.
*
* A formatter captures a reference to a terminal and formatting options.
* It can be used repeatedly to produce output that reflects the current
* terminal state at the time of each format call.
*
* The terminal must outlive the formatter.
*
* @{
*/
/**
* Extra screen state to include in styled output.
*
* @ingroup formatter
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterScreenExtra). */
size_t size;
/** Emit cursor position using CUP (CSI H). */
bool cursor;
/** Emit current SGR style state based on the cursor's active style_id. */
bool style;
/** Emit current hyperlink state using OSC 8 sequences. */
bool hyperlink;
/** Emit character protection mode using DECSCA. */
bool protection;
/** Emit Kitty keyboard protocol state using CSI > u and CSI = sequences. */
bool kitty_keyboard;
/** Emit character set designations and invocations. */
bool charsets;
} GhosttyFormatterScreenExtra;
/**
* Extra terminal state to include in styled output.
*
* @ingroup formatter
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalExtra). */
size_t size;
/** Emit the palette using OSC 4 sequences. */
bool palette;
/** Emit terminal modes that differ from their defaults using CSI h/l. */
bool modes;
/** Emit scrolling region state using DECSTBM and DECSLRM sequences. */
bool scrolling_region;
/** Emit tabstop positions by clearing all tabs and setting each one. */
bool tabstops;
/** Emit the present working directory using OSC 7. */
bool pwd;
/** Emit keyboard modes such as ModifyOtherKeys. */
bool keyboard;
/** Screen-level extras. */
GhosttyFormatterScreenExtra screen;
} GhosttyFormatterTerminalExtra;
/**
* Options for creating a terminal formatter.
*
* @ingroup formatter
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalOptions). */
size_t size;
/** Output format to emit. */
GhosttyFormatterFormat emit;
/** Whether to unwrap soft-wrapped lines. */
bool unwrap;
/** Whether to trim trailing whitespace on non-blank lines. */
bool trim;
/** Extra terminal state to include in styled output. */
GhosttyFormatterTerminalExtra extra;
/** Optional selection to restrict output to a range.
* If NULL, the entire screen is formatted. */
const GhosttySelection *selection;
} GhosttyFormatterTerminalOptions;
/**
* Create a formatter for a terminal's active screen.
*
* The terminal must outlive the formatter. The formatter stores a borrowed
* reference to the terminal and reads its current state on each format call.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param formatter Pointer to store the created formatter handle
* @param terminal The terminal to format (must not be NULL)
* @param options Formatting options
* @return GHOSTTY_SUCCESS on success, or an error code on failure
*
* @ingroup formatter
*/
GHOSTTY_API GhosttyResult ghostty_formatter_terminal_new(
const GhosttyAllocator* allocator,
GhosttyFormatter* formatter,
GhosttyTerminal terminal,
GhosttyFormatterTerminalOptions options);
/**
* Run the formatter and produce output into the caller-provided buffer.
*
* Each call formats the current terminal state. Pass NULL for buf to
* query the required buffer size without writing any output; in that case
* out_written receives the required size and the return value is
* GHOSTTY_OUT_OF_SPACE.
*
* If the buffer is too small, returns GHOSTTY_OUT_OF_SPACE and sets
* out_written to the required size. The caller can then retry with a
* larger buffer.
*
* @param formatter The formatter handle (must not be NULL)
* @param buf Pointer to the output buffer, or NULL to query size
* @param buf_len Length of the output buffer in bytes
* @param out_written Pointer to receive the number of bytes written,
* or the required size on failure
* @return GHOSTTY_SUCCESS on success, or an error code on failure
*
* @ingroup formatter
*/
GHOSTTY_API GhosttyResult ghostty_formatter_format_buf(GhosttyFormatter formatter,
uint8_t* buf,
size_t buf_len,
size_t* out_written);
/**
* Run the formatter and return an allocated buffer with the output.
*
* Each call formats the current terminal state. The buffer is allocated
* using the provided allocator (or the default allocator if NULL).
* The caller is responsible for freeing the returned buffer with
* ghostty_free(), passing the same allocator (or NULL for the default)
* that was used for the allocation.
*
* @param formatter The formatter handle (must not be NULL)
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param out_ptr Pointer to receive the allocated buffer
* @param out_len Pointer to receive the length of the output in bytes
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
* failure
*
* @ingroup formatter
*/
GHOSTTY_API GhosttyResult ghostty_formatter_format_alloc(GhosttyFormatter formatter,
const GhosttyAllocator* allocator,
uint8_t** out_ptr,
size_t* out_len);
/**
* Free a formatter instance.
*
* Releases all resources associated with the formatter. After this call,
* the formatter handle becomes invalid.
*
* @param formatter The formatter handle to free (may be NULL)
*
* @ingroup formatter
*/
GHOSTTY_API void ghostty_formatter_free(GhosttyFormatter formatter);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_FORMATTER_H */
@@ -0,0 +1,212 @@
/**
* @file grid_ref.h
*
* Terminal grid reference type for referencing a resolved position in the
* terminal grid.
*/
#ifndef GHOSTTY_VT_GRID_REF_H
#define GHOSTTY_VT_GRID_REF_H
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/screen.h>
#include <ghostty/vt/style.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup grid_ref Grid Reference
*
* A grid reference is a reference to a specific cell position in the
* terminal. Obtain a grid reference from `ghostty_terminal_grid_ref`
* for untracked or `ghostty_terminal_grid_ref_track` for tracked. Untracked
* vs tracked is explained next.
*
* Important: The grid reference APIs are not meant to be used as the core of a render
* loop. They are not built to sustain the framerates needed for rendering large
* screens. Use the render state API for that.
*
* ## Untracked vs Tracked References
*
* ### Untracked Reference
*
* An untracked grid reference is a value type that snapshots a specific
* cell. It is only valid until the next update to the terminal instance.
* There is no guarantee that it will remain valid after any operation,
* even if a seemingly unrelated part of the grid is changed. These are meant
* to be read and have their values cached immediately after obtaining it.
*
* An untracked grid reference has a performance cost in its initial lookup,
* but doesn't affect the ongoing performance of the terminal in any way,
* since it is a one-time snapshot.
*
* ### Tracked Reference
*
* A tracked grid reference follows its cell across normal screen operations.
* For example scrolling, scrollback pruning, resize/reflow, and other
* terminal mutations update the tracked reference automatically.
*
* A tracked reference can still lose its original semantic location. This can
* happen when the underlying grid is reset, pruned, or otherwise discarded in a
* way that cannot be mapped to a meaningful new cell. In that state,
* ghostty_tracked_grid_ref_has_value() returns false and
* ghostty_tracked_grid_ref_snapshot() / ghostty_tracked_grid_ref_point() return
* GHOSTTY_NO_VALUE. The handle remains valid, and callers may move it to a new
* point with ghostty_tracked_grid_ref_set().
*
* To read cell data from a tracked reference, first snapshot it with
* ghostty_tracked_grid_ref_snapshot(). The returned `GhosttyGridRef` is again
* an untracked reference and follows the same short lifetime rules as any other
* untracked grid reference.
*
* A tracked reference belongs to the terminal screen/page-list that was active
* when it was created or last set. Converting it to a point uses that owning
* screen/page-list, even if the terminal has since switched between primary and
* alternate screens. Calling ghostty_tracked_grid_ref_set() resolves the new
* point against the terminal's currently active screen/page-list and may move
* the tracked reference between screens.
*
* Tracked references are owned by the caller and must be freed with
* ghostty_tracked_grid_ref_free(). If the terminal that created a tracked
* reference is freed first, the handle remains valid only for tracked-grid-ref
* APIs: it reports no value and can still be freed.
*
* Each tracked reference adds bookkeeping to terminal mutations. Use them
* sparingly for long-lived anchors such as selections, search state, marks,
* or application-side bookmarks.
*
* ## Lifetime
*
* An untracked reference is a snapshot. It doesn't need to be freed.
* The safety of accessing the value is documented explicitly above: it
* is only safe to access any data until the next terminal mutating
* operation (including free).
*
* A tracked reference is allocated and must be freed when it is no
* longer needed. A tracked reference may outlive the terminal that created it;
* after terminal free, it reports no value and can still be freed.
*
* ## Examples
*
* @snippet c-vt-grid-traverse/src/main.c grid-ref-traverse
* @snippet c-vt-grid-ref-tracked/src/main.c grid-ref-tracked
*
* @{
*/
/**
* A resolved reference to a terminal cell position.
*
* This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
*
* @ingroup grid_ref
*/
typedef struct {
size_t size;
void *node;
uint16_t x;
uint16_t y;
} GhosttyGridRef;
/**
* Get the cell from a grid reference.
*
* @param ref Pointer to the grid reference
* @param[out] out_cell On success, set to the cell at the ref's position (may be NULL)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_cell(const GhosttyGridRef *ref,
GhosttyCell *out_cell);
/**
* Get the row from a grid reference.
*
* @param ref Pointer to the grid reference
* @param[out] out_row On success, set to the row at the ref's position (may be NULL)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_row(const GhosttyGridRef *ref,
GhosttyRow *out_row);
/**
* Get the grapheme cluster codepoints for the cell at the grid reference's
* position.
*
* Writes the full grapheme cluster (the cell's primary codepoint followed by
* any combining codepoints) into the provided buffer. If the cell has no text,
* out_len is set to 0 and GHOSTTY_SUCCESS is returned.
*
* If the buffer is too small (or NULL), the function returns
* GHOSTTY_OUT_OF_SPACE and writes the required number of codepoints to
* out_len. The caller can then retry with a sufficiently sized buffer.
*
* @param ref Pointer to the grid reference
* @param buf Output buffer of uint32_t codepoints (may be NULL)
* @param buf_len Number of uint32_t elements in the buffer
* @param[out] out_len On success, the number of codepoints written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size in codepoints.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_graphemes(const GhosttyGridRef *ref,
uint32_t *buf,
size_t buf_len,
size_t *out_len);
/**
* Get the hyperlink URI for the cell at the grid reference's position.
*
* Writes the URI bytes into the provided buffer. If the cell has no
* hyperlink, out_len is set to 0 and GHOSTTY_SUCCESS is returned.
*
* If the buffer is too small (or NULL), the function returns
* GHOSTTY_OUT_OF_SPACE and writes the required number of bytes to
* out_len. The caller can then retry with a sufficiently sized buffer.
*
* @param ref Pointer to the grid reference
* @param buf Output buffer for the URI bytes (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_len On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size in bytes.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_hyperlink_uri(
const GhosttyGridRef *ref,
uint8_t *buf,
size_t buf_len,
size_t *out_len);
/**
* Get the style of the cell at the grid reference's position.
*
* @param ref Pointer to the grid reference
* @param[out] out_style On success, set to the cell's style (may be NULL)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_style(const GhosttyGridRef *ref,
GhosttyStyle *out_style);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_GRID_REF_H */
@@ -0,0 +1,139 @@
/**
* @file grid_ref_tracked.h
*
* Tracked terminal grid references.
*/
#ifndef GHOSTTY_VT_GRID_REF_TRACKED_H
#define GHOSTTY_VT_GRID_REF_TRACKED_H
#include <stdbool.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/grid_ref.h>
#include <ghostty/vt/point.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Tracked grid references are owned grid references that move with the
* terminal. See @ref grid_ref for the full overview of tracked and untracked
* grid reference behavior.
*
* @ingroup grid_ref
*/
/**
* Free a tracked grid reference.
*
* Passing NULL is allowed and has no effect. A tracked reference may be freed
* after the terminal that created it is freed.
*
* @param ref Tracked grid reference to free.
*
* @ingroup grid_ref
*/
GHOSTTY_API void ghostty_tracked_grid_ref_free(GhosttyTrackedGridRef ref);
/**
* Return whether a tracked grid reference currently has a meaningful value.
*
* If the terminal that created the tracked reference has been freed, this
* returns false.
*
* @param ref Tracked grid reference.
* @return true if the reference currently has a meaningful value.
*
* @ingroup grid_ref
*/
GHOSTTY_API bool ghostty_tracked_grid_ref_has_value(
GhosttyTrackedGridRef ref);
/**
* Convert a tracked grid reference to a point in the requested coordinate
* space.
*
* This is the tracked equivalent of ghostty_terminal_point_from_grid_ref().
* Unlike snapshotting, this does not expose an intermediate untracked
* GhosttyGridRef.
*
* A tracked reference is resolved against the terminal screen/page-list that
* currently owns the reference. If the terminal has switched between primary
* and alternate screens since the reference was created or last set, this may
* be different from the terminal's currently active screen.
*
* If the tracked reference no longer has a meaningful value, this returns
* GHOSTTY_NO_VALUE. GHOSTTY_NO_VALUE is also returned when the reference cannot
* be represented in the requested coordinate space, including after the
* terminal that created the tracked reference has been freed.
*
* @param ref Tracked grid reference.
* @param tag Coordinate space to convert into.
* @param[out] out_point On success, receives the coordinate. May be NULL.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
* or GHOSTTY_NO_VALUE if there is no representable value.
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_point(
GhosttyTrackedGridRef ref,
GhosttyPointTag tag,
GhosttyPointCoordinate *out_point);
/**
* Move an existing tracked grid reference to a new terminal point.
*
* On success, the tracked reference begins tracking the new point and any prior
* "no value" state is cleared. On GHOSTTY_OUT_OF_MEMORY, the original tracked
* reference is left unchanged.
*
* The terminal must be the same terminal that created the tracked reference.
* The point is resolved against the terminal screen/page-list that is active at
* the time this function is called. If the terminal has switched between
* primary and alternate screens, this may move the tracked reference from one
* screen/page-list to the other.
*
* @param ref Tracked grid reference.
* @param terminal Terminal instance that owns the reference.
* @param point New point to track.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref, terminal,
* or point is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation fails.
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_set(
GhosttyTrackedGridRef ref,
GhosttyTerminal terminal,
GhosttyPoint point);
/**
* Snapshot a tracked grid reference into a regular GhosttyGridRef.
*
* The returned GhosttyGridRef is an untracked snapshot and has the same
* lifetime rules as ghostty_terminal_grid_ref(): it is only valid until the
* next terminal update. Snapshot immediately before calling
* ghostty_grid_ref_cell(), ghostty_grid_ref_row(),
* ghostty_grid_ref_graphemes(), ghostty_grid_ref_hyperlink_uri(), or
* ghostty_grid_ref_style().
*
* If the tracked reference no longer has a meaningful value, this returns
* GHOSTTY_NO_VALUE. This includes references whose owning terminal has been
* freed.
*
* @param ref Tracked grid reference.
* @param[out] out_ref On success, receives an untracked snapshot. May be NULL.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
* or GHOSTTY_NO_VALUE if the tracked location was discarded.
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_snapshot(
GhosttyTrackedGridRef ref,
GhosttyGridRef *out_ref);
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_GRID_REF_TRACKED_H */
@@ -0,0 +1,73 @@
/**
* @file key.h
*
* Key encoding module - encode key events into terminal escape sequences.
*/
#ifndef GHOSTTY_VT_KEY_H
#define GHOSTTY_VT_KEY_H
/** @defgroup key Key Encoding
*
* Utilities for encoding key events into terminal escape sequences,
* supporting both legacy encoding as well as Kitty Keyboard Protocol.
*
* ## Basic Usage
*
* 1. Create an encoder instance with ghostty_key_encoder_new()
* 2. Configure encoder options with ghostty_key_encoder_setopt()
* or ghostty_key_encoder_setopt_from_terminal() if you have a
* GhosttyTerminal.
* 3. For each key event:
* - Create a key event with ghostty_key_event_new()
* - Set event properties (action, key, modifiers, etc.)
* - Encode with ghostty_key_encoder_encode()
* - Free the event with ghostty_key_event_free()
* - Note: You can also reuse the same key event multiple times by
* changing its properties.
* 4. Free the encoder with ghostty_key_encoder_free() when done
*
* For a complete working example, see example/c-vt-encode-key in the
* repository.
*
* ## Example
*
* @snippet c-vt-encode-key/src/main.c key-encode
*
* ## Example: Encoding with Terminal State
*
* When you have a GhosttyTerminal, you can sync its modes (cursor key
* application, Kitty flags, etc.) into the encoder automatically:
*
* @code{.c}
* // Create a terminal and feed it some VT data that changes modes
* GhosttyTerminal terminal;
* ghostty_terminal_new(NULL, &terminal,
* (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0});
*
* // Application might write data that enables Kitty keyboard protocol, etc.
* ghostty_terminal_vt_write(terminal, vt_data, vt_len);
*
* // Create an encoder and sync its options from the terminal
* GhosttyKeyEncoder encoder;
* ghostty_key_encoder_new(NULL, &encoder);
* ghostty_key_encoder_setopt_from_terminal(encoder, terminal);
*
* // Encode a key event using the terminal-derived options
* char buf[128];
* size_t written = 0;
* ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);
*
* ghostty_key_encoder_free(encoder);
* ghostty_terminal_free(terminal);
* @endcode
*
* @{
*/
#include <ghostty/vt/key/event.h>
#include <ghostty/vt/key/encoder.h>
/** @} */
#endif /* GHOSTTY_VT_KEY_H */
@@ -0,0 +1,255 @@
/**
* @file encoder.h
*
* Key event encoding to terminal escape sequences.
*/
#ifndef GHOSTTY_VT_KEY_ENCODER_H
#define GHOSTTY_VT_KEY_ENCODER_H
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/terminal.h>
#include <ghostty/vt/key/event.h>
/**
* Opaque handle to a key encoder instance.
*
* This handle represents a key encoder that converts key events into terminal
* escape sequences.
*
* @ingroup key
*/
typedef struct GhosttyKeyEncoderImpl *GhosttyKeyEncoder;
/**
* Kitty keyboard protocol flags.
*
* Bitflags representing the various modes of the Kitty keyboard protocol.
* These can be combined using bitwise OR operations. Valid values all
* start with `GHOSTTY_KITTY_KEY_`.
*
* @ingroup key
*/
typedef uint8_t GhosttyKittyKeyFlags;
/** Kitty keyboard protocol disabled (all flags off) */
#define GHOSTTY_KITTY_KEY_DISABLED 0
/** Disambiguate escape codes */
#define GHOSTTY_KITTY_KEY_DISAMBIGUATE (1 << 0)
/** Report key press and release events */
#define GHOSTTY_KITTY_KEY_REPORT_EVENTS (1 << 1)
/** Report alternate key codes */
#define GHOSTTY_KITTY_KEY_REPORT_ALTERNATES (1 << 2)
/** Report all key events including those normally handled by the terminal */
#define GHOSTTY_KITTY_KEY_REPORT_ALL (1 << 3)
/** Report associated text with key events */
#define GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED (1 << 4)
/** All Kitty keyboard protocol flags enabled */
#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)
/**
* macOS option key behavior.
*
* Determines whether the "option" key on macOS is treated as "alt" or not.
* See the Ghostty `macos-option-as-alt` configuration option for more details.
*
* @ingroup key
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Option key is not treated as alt */
GHOSTTY_OPTION_AS_ALT_FALSE = 0,
/** Option key is treated as alt */
GHOSTTY_OPTION_AS_ALT_TRUE = 1,
/** Only left option key is treated as alt */
GHOSTTY_OPTION_AS_ALT_LEFT = 2,
/** Only right option key is treated as alt */
GHOSTTY_OPTION_AS_ALT_RIGHT = 3,
GHOSTTY_OPTION_AS_ALT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyOptionAsAlt;
/**
* Key encoder option identifiers.
*
* These values are used with ghostty_key_encoder_setopt() to configure
* the behavior of the key encoder.
*
* @ingroup key
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Terminal DEC mode 1: cursor key application mode (value: bool) */
GHOSTTY_KEY_ENCODER_OPT_CURSOR_KEY_APPLICATION = 0,
/** Terminal DEC mode 66: keypad key application mode (value: bool) */
GHOSTTY_KEY_ENCODER_OPT_KEYPAD_KEY_APPLICATION = 1,
/** Terminal DEC mode 1035: ignore keypad with numlock (value: bool) */
GHOSTTY_KEY_ENCODER_OPT_IGNORE_KEYPAD_WITH_NUMLOCK = 2,
/** Terminal DEC mode 1036: alt sends escape prefix (value: bool) */
GHOSTTY_KEY_ENCODER_OPT_ALT_ESC_PREFIX = 3,
/** xterm modifyOtherKeys mode 2 (value: bool) */
GHOSTTY_KEY_ENCODER_OPT_MODIFY_OTHER_KEYS_STATE_2 = 4,
/** Kitty keyboard protocol flags (value: GhosttyKittyKeyFlags bitmask) */
GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS = 5,
/** macOS option-as-alt setting (value: GhosttyOptionAsAlt) */
GHOSTTY_KEY_ENCODER_OPT_MACOS_OPTION_AS_ALT = 6,
/** Backarrow key mode (value: bool)
* See https://vt100.net/dec/ek-vt3xx-tp-002.pdf page 170
* If `false` (the default), `backspace` emits 0x7f
* If `true`, `backspace` emits 0x08
*/
GHOSTTY_KEY_ENCODER_OPT_BACKARROW_KEY_MODE = 7,
GHOSTTY_KEY_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKeyEncoderOption;
/**
* Create a new key encoder instance.
*
* Creates a new key encoder with default options. The encoder can be configured
* using ghostty_key_encoder_setopt() and must be freed using
* ghostty_key_encoder_free() when no longer needed.
*
* @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
* @param encoder Pointer to store the created encoder handle
* @return GHOSTTY_SUCCESS on success, or an error code on failure
*
* @ingroup key
*/
GHOSTTY_API GhosttyResult ghostty_key_encoder_new(const GhosttyAllocator *allocator, GhosttyKeyEncoder *encoder);
/**
* Free a key encoder instance.
*
* Releases all resources associated with the key encoder. After this call,
* the encoder handle becomes invalid and must not be used.
*
* @param encoder The encoder handle to free (may be NULL)
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_encoder_free(GhosttyKeyEncoder encoder);
/**
* Set an option on the key encoder.
*
* Configures the behavior of the key encoder. Options control various aspects
* of encoding such as terminal modes (cursor key application mode, keypad mode),
* protocol selection (Kitty keyboard protocol flags), and platform-specific
* behaviors (macOS option-as-alt).
*
* If you are using a terminal instance, you can set the key encoding
* options based on the active terminal state (e.g. legacy vs Kitty mode
* and associated flags) with ghostty_key_encoder_setopt_from_terminal().
*
* A null pointer value does nothing. It does not reset the value to the
* default. The setopt call will do nothing.
*
* @param encoder The encoder handle, must not be NULL
* @param option The option to set
* @param value Pointer to the value to set (type depends on the option)
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value);
/**
* Set encoder options from a terminal's current state.
*
* Reads the terminal's current modes and flags and applies them to the
* encoder's options. This sets cursor key application mode, keypad mode,
* alt escape prefix, modifyOtherKeys state, and Kitty keyboard protocol
* flags from the terminal state.
*
* Note that the `macos_option_as_alt` option cannot be determined from
* terminal state and is reset to `GHOSTTY_OPTION_AS_ALT_FALSE` by this
* call. Use ghostty_key_encoder_setopt() to set it afterward if needed.
*
* @param encoder The encoder handle, must not be NULL
* @param terminal The terminal handle, must not be NULL
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_encoder_setopt_from_terminal(GhosttyKeyEncoder encoder, GhosttyTerminal terminal);
/**
* Encode a key event into a terminal escape sequence.
*
* Converts a key event into the appropriate terminal escape sequence based on
* the encoder's current options. The sequence is written to the provided buffer.
*
* Not all key events produce output. For example, unmodified modifier keys
* typically don't generate escape sequences. Check the out_len parameter to
* determine if any data was written.
*
* If the output buffer is too small, this function returns GHOSTTY_OUT_OF_SPACE
* and out_len will contain the required buffer size. The caller can then
* allocate a larger buffer and call the function again.
*
* @param encoder The encoder handle, must not be NULL
* @param event The key event to encode, must not be NULL
* @param out_buf Buffer to write the encoded sequence to
* @param out_buf_size Size of the output buffer in bytes
* @param out_len Pointer to store the number of bytes written (may be NULL)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer too small, or other error code
*
* ## Example: Calculate required buffer size
*
* @code{.c}
* // Query the required size with a NULL buffer (always returns OUT_OF_SPACE)
* size_t required = 0;
* GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required);
* assert(result == GHOSTTY_OUT_OF_SPACE);
*
* // Allocate buffer of required size
* char *buf = malloc(required);
*
* // Encode with properly sized buffer
* size_t written = 0;
* result = ghostty_key_encoder_encode(encoder, event, buf, required, &written);
* assert(result == GHOSTTY_SUCCESS);
*
* // Use the encoded sequence...
*
* free(buf);
* @endcode
*
* ## Example: Direct encoding with static buffer
*
* @code{.c}
* // Most escape sequences are short, so a static buffer often suffices
* char buf[128];
* size_t written = 0;
* GhosttyResult result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);
*
* if (result == GHOSTTY_SUCCESS) {
* // Write the encoded sequence to the terminal
* write(pty_fd, buf, written);
* } else if (result == GHOSTTY_OUT_OF_SPACE) {
* // Buffer too small, written contains required size
* char *dynamic_buf = malloc(written);
* result = ghostty_key_encoder_encode(encoder, event, dynamic_buf, written, &written);
* assert(result == GHOSTTY_SUCCESS);
* write(pty_fd, dynamic_buf, written);
* free(dynamic_buf);
* }
* @endcode
*
* @ingroup key
*/
GHOSTTY_API GhosttyResult ghostty_key_encoder_encode(GhosttyKeyEncoder encoder, GhosttyKeyEvent event, char *out_buf, size_t out_buf_size, size_t *out_len);
#endif /* GHOSTTY_VT_KEY_ENCODER_H */
@@ -0,0 +1,482 @@
/**
* @file event.h
*
* Key event representation and manipulation.
*/
#ifndef GHOSTTY_VT_KEY_EVENT_H
#define GHOSTTY_VT_KEY_EVENT_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/allocator.h>
/**
* Opaque handle to a key event.
*
* This handle represents a keyboard input event containing information about
* the physical key pressed, modifiers, and generated text.
*
* @ingroup key
*/
typedef struct GhosttyKeyEventImpl *GhosttyKeyEvent;
/**
* Keyboard input event types.
*
* @ingroup key
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Key was released */
GHOSTTY_KEY_ACTION_RELEASE = 0,
/** Key was pressed */
GHOSTTY_KEY_ACTION_PRESS = 1,
/** Key is being repeated (held down) */
GHOSTTY_KEY_ACTION_REPEAT = 2,
GHOSTTY_KEY_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKeyAction;
/**
* Keyboard modifier keys bitmask.
*
* A bitmask representing all keyboard modifiers. This tracks which modifier keys
* are pressed and, where supported by the platform, which side (left or right)
* of each modifier is active.
*
* Use the GHOSTTY_MODS_* constants to test and set individual modifiers.
*
* Modifier side bits are only meaningful when the corresponding modifier bit is set.
* Not all platforms support distinguishing between left and right modifier
* keys and Ghostty is built to expect that some platforms may not provide this
* information.
*
* @ingroup key
*/
typedef uint16_t GhosttyMods;
/** Shift key is pressed */
#define GHOSTTY_MODS_SHIFT (1 << 0)
/** Control key is pressed */
#define GHOSTTY_MODS_CTRL (1 << 1)
/** Alt/Option key is pressed */
#define GHOSTTY_MODS_ALT (1 << 2)
/** Super/Command/Windows key is pressed */
#define GHOSTTY_MODS_SUPER (1 << 3)
/** Caps Lock is active */
#define GHOSTTY_MODS_CAPS_LOCK (1 << 4)
/** Num Lock is active */
#define GHOSTTY_MODS_NUM_LOCK (1 << 5)
/**
* Right shift is pressed (0 = left, 1 = right).
* Only meaningful when GHOSTTY_MODS_SHIFT is set.
*/
#define GHOSTTY_MODS_SHIFT_SIDE (1 << 6)
/**
* Right ctrl is pressed (0 = left, 1 = right).
* Only meaningful when GHOSTTY_MODS_CTRL is set.
*/
#define GHOSTTY_MODS_CTRL_SIDE (1 << 7)
/**
* Right alt is pressed (0 = left, 1 = right).
* Only meaningful when GHOSTTY_MODS_ALT is set.
*/
#define GHOSTTY_MODS_ALT_SIDE (1 << 8)
/**
* Right super is pressed (0 = left, 1 = right).
* Only meaningful when GHOSTTY_MODS_SUPER is set.
*/
#define GHOSTTY_MODS_SUPER_SIDE (1 << 9)
/**
* Physical key codes.
*
* The set of key codes that Ghostty is aware of. These represent physical keys
* on the keyboard and are layout-independent. For example, the "a" key on a US
* keyboard is the same as the "ф" key on a Russian keyboard, but both will
* report the same key_a value.
*
* Layout-dependent strings are provided separately as UTF-8 text and are produced
* by the platform. These values are based on the W3C UI Events KeyboardEvent code
* standard. See: https://www.w3.org/TR/uievents-code
*
* @ingroup key
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_KEY_UNIDENTIFIED = 0,
// Writing System Keys (W3C § 3.1.1)
GHOSTTY_KEY_BACKQUOTE,
GHOSTTY_KEY_BACKSLASH,
GHOSTTY_KEY_BRACKET_LEFT,
GHOSTTY_KEY_BRACKET_RIGHT,
GHOSTTY_KEY_COMMA,
GHOSTTY_KEY_DIGIT_0,
GHOSTTY_KEY_DIGIT_1,
GHOSTTY_KEY_DIGIT_2,
GHOSTTY_KEY_DIGIT_3,
GHOSTTY_KEY_DIGIT_4,
GHOSTTY_KEY_DIGIT_5,
GHOSTTY_KEY_DIGIT_6,
GHOSTTY_KEY_DIGIT_7,
GHOSTTY_KEY_DIGIT_8,
GHOSTTY_KEY_DIGIT_9,
GHOSTTY_KEY_EQUAL,
GHOSTTY_KEY_INTL_BACKSLASH,
GHOSTTY_KEY_INTL_RO,
GHOSTTY_KEY_INTL_YEN,
GHOSTTY_KEY_A,
GHOSTTY_KEY_B,
GHOSTTY_KEY_C,
GHOSTTY_KEY_D,
GHOSTTY_KEY_E,
GHOSTTY_KEY_F,
GHOSTTY_KEY_G,
GHOSTTY_KEY_H,
GHOSTTY_KEY_I,
GHOSTTY_KEY_J,
GHOSTTY_KEY_K,
GHOSTTY_KEY_L,
GHOSTTY_KEY_M,
GHOSTTY_KEY_N,
GHOSTTY_KEY_O,
GHOSTTY_KEY_P,
GHOSTTY_KEY_Q,
GHOSTTY_KEY_R,
GHOSTTY_KEY_S,
GHOSTTY_KEY_T,
GHOSTTY_KEY_U,
GHOSTTY_KEY_V,
GHOSTTY_KEY_W,
GHOSTTY_KEY_X,
GHOSTTY_KEY_Y,
GHOSTTY_KEY_Z,
GHOSTTY_KEY_MINUS,
GHOSTTY_KEY_PERIOD,
GHOSTTY_KEY_QUOTE,
GHOSTTY_KEY_SEMICOLON,
GHOSTTY_KEY_SLASH,
// Functional Keys (W3C § 3.1.2)
GHOSTTY_KEY_ALT_LEFT,
GHOSTTY_KEY_ALT_RIGHT,
GHOSTTY_KEY_BACKSPACE,
GHOSTTY_KEY_CAPS_LOCK,
GHOSTTY_KEY_CONTEXT_MENU,
GHOSTTY_KEY_CONTROL_LEFT,
GHOSTTY_KEY_CONTROL_RIGHT,
GHOSTTY_KEY_ENTER,
GHOSTTY_KEY_META_LEFT,
GHOSTTY_KEY_META_RIGHT,
GHOSTTY_KEY_SHIFT_LEFT,
GHOSTTY_KEY_SHIFT_RIGHT,
GHOSTTY_KEY_SPACE,
GHOSTTY_KEY_TAB,
GHOSTTY_KEY_CONVERT,
GHOSTTY_KEY_KANA_MODE,
GHOSTTY_KEY_NON_CONVERT,
// Control Pad Section (W3C § 3.2)
GHOSTTY_KEY_DELETE,
GHOSTTY_KEY_END,
GHOSTTY_KEY_HELP,
GHOSTTY_KEY_HOME,
GHOSTTY_KEY_INSERT,
GHOSTTY_KEY_PAGE_DOWN,
GHOSTTY_KEY_PAGE_UP,
// Arrow Pad Section (W3C § 3.3)
GHOSTTY_KEY_ARROW_DOWN,
GHOSTTY_KEY_ARROW_LEFT,
GHOSTTY_KEY_ARROW_RIGHT,
GHOSTTY_KEY_ARROW_UP,
// Numpad Section (W3C § 3.4)
GHOSTTY_KEY_NUM_LOCK,
GHOSTTY_KEY_NUMPAD_0,
GHOSTTY_KEY_NUMPAD_1,
GHOSTTY_KEY_NUMPAD_2,
GHOSTTY_KEY_NUMPAD_3,
GHOSTTY_KEY_NUMPAD_4,
GHOSTTY_KEY_NUMPAD_5,
GHOSTTY_KEY_NUMPAD_6,
GHOSTTY_KEY_NUMPAD_7,
GHOSTTY_KEY_NUMPAD_8,
GHOSTTY_KEY_NUMPAD_9,
GHOSTTY_KEY_NUMPAD_ADD,
GHOSTTY_KEY_NUMPAD_BACKSPACE,
GHOSTTY_KEY_NUMPAD_CLEAR,
GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY,
GHOSTTY_KEY_NUMPAD_COMMA,
GHOSTTY_KEY_NUMPAD_DECIMAL,
GHOSTTY_KEY_NUMPAD_DIVIDE,
GHOSTTY_KEY_NUMPAD_ENTER,
GHOSTTY_KEY_NUMPAD_EQUAL,
GHOSTTY_KEY_NUMPAD_MEMORY_ADD,
GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR,
GHOSTTY_KEY_NUMPAD_MEMORY_RECALL,
GHOSTTY_KEY_NUMPAD_MEMORY_STORE,
GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT,
GHOSTTY_KEY_NUMPAD_MULTIPLY,
GHOSTTY_KEY_NUMPAD_PAREN_LEFT,
GHOSTTY_KEY_NUMPAD_PAREN_RIGHT,
GHOSTTY_KEY_NUMPAD_SUBTRACT,
GHOSTTY_KEY_NUMPAD_SEPARATOR,
GHOSTTY_KEY_NUMPAD_UP,
GHOSTTY_KEY_NUMPAD_DOWN,
GHOSTTY_KEY_NUMPAD_RIGHT,
GHOSTTY_KEY_NUMPAD_LEFT,
GHOSTTY_KEY_NUMPAD_BEGIN,
GHOSTTY_KEY_NUMPAD_HOME,
GHOSTTY_KEY_NUMPAD_END,
GHOSTTY_KEY_NUMPAD_INSERT,
GHOSTTY_KEY_NUMPAD_DELETE,
GHOSTTY_KEY_NUMPAD_PAGE_UP,
GHOSTTY_KEY_NUMPAD_PAGE_DOWN,
// Function Section (W3C § 3.5)
GHOSTTY_KEY_ESCAPE,
GHOSTTY_KEY_F1,
GHOSTTY_KEY_F2,
GHOSTTY_KEY_F3,
GHOSTTY_KEY_F4,
GHOSTTY_KEY_F5,
GHOSTTY_KEY_F6,
GHOSTTY_KEY_F7,
GHOSTTY_KEY_F8,
GHOSTTY_KEY_F9,
GHOSTTY_KEY_F10,
GHOSTTY_KEY_F11,
GHOSTTY_KEY_F12,
GHOSTTY_KEY_F13,
GHOSTTY_KEY_F14,
GHOSTTY_KEY_F15,
GHOSTTY_KEY_F16,
GHOSTTY_KEY_F17,
GHOSTTY_KEY_F18,
GHOSTTY_KEY_F19,
GHOSTTY_KEY_F20,
GHOSTTY_KEY_F21,
GHOSTTY_KEY_F22,
GHOSTTY_KEY_F23,
GHOSTTY_KEY_F24,
GHOSTTY_KEY_F25,
GHOSTTY_KEY_FN,
GHOSTTY_KEY_FN_LOCK,
GHOSTTY_KEY_PRINT_SCREEN,
GHOSTTY_KEY_SCROLL_LOCK,
GHOSTTY_KEY_PAUSE,
// Media Keys (W3C § 3.6)
GHOSTTY_KEY_BROWSER_BACK,
GHOSTTY_KEY_BROWSER_FAVORITES,
GHOSTTY_KEY_BROWSER_FORWARD,
GHOSTTY_KEY_BROWSER_HOME,
GHOSTTY_KEY_BROWSER_REFRESH,
GHOSTTY_KEY_BROWSER_SEARCH,
GHOSTTY_KEY_BROWSER_STOP,
GHOSTTY_KEY_EJECT,
GHOSTTY_KEY_LAUNCH_APP_1,
GHOSTTY_KEY_LAUNCH_APP_2,
GHOSTTY_KEY_LAUNCH_MAIL,
GHOSTTY_KEY_MEDIA_PLAY_PAUSE,
GHOSTTY_KEY_MEDIA_SELECT,
GHOSTTY_KEY_MEDIA_STOP,
GHOSTTY_KEY_MEDIA_TRACK_NEXT,
GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS,
GHOSTTY_KEY_POWER,
GHOSTTY_KEY_SLEEP,
GHOSTTY_KEY_AUDIO_VOLUME_DOWN,
GHOSTTY_KEY_AUDIO_VOLUME_MUTE,
GHOSTTY_KEY_AUDIO_VOLUME_UP,
GHOSTTY_KEY_WAKE_UP,
// Legacy, Non-standard, and Special Keys (W3C § 3.7)
GHOSTTY_KEY_COPY,
GHOSTTY_KEY_CUT,
GHOSTTY_KEY_PASTE,
GHOSTTY_KEY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKey;
/**
* Create a new key event instance.
*
* Creates a new key event with default values. The event must be freed using
* ghostty_key_event_free() when no longer needed.
*
* @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
* @param event Pointer to store the created key event handle
* @return GHOSTTY_SUCCESS on success, or an error code on failure
*
* @ingroup key
*/
GHOSTTY_API GhosttyResult ghostty_key_event_new(const GhosttyAllocator *allocator, GhosttyKeyEvent *event);
/**
* Free a key event instance.
*
* Releases all resources associated with the key event. After this call,
* the event handle becomes invalid and must not be used.
*
* @param event The key event handle to free (may be NULL)
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_free(GhosttyKeyEvent event);
/**
* Set the key action (press, release, repeat).
*
* @param event The key event handle, must not be NULL
* @param action The action to set
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_set_action(GhosttyKeyEvent event, GhosttyKeyAction action);
/**
* Get the key action (press, release, repeat).
*
* @param event The key event handle, must not be NULL
* @return The key action
*
* @ingroup key
*/
GHOSTTY_API GhosttyKeyAction ghostty_key_event_get_action(GhosttyKeyEvent event);
/**
* Set the physical key code.
*
* @param event The key event handle, must not be NULL
* @param key The physical key code to set
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_set_key(GhosttyKeyEvent event, GhosttyKey key);
/**
* Get the physical key code.
*
* @param event The key event handle, must not be NULL
* @return The physical key code
*
* @ingroup key
*/
GHOSTTY_API GhosttyKey ghostty_key_event_get_key(GhosttyKeyEvent event);
/**
* Set the modifier keys bitmask.
*
* @param event The key event handle, must not be NULL
* @param mods The modifier keys bitmask to set
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_set_mods(GhosttyKeyEvent event, GhosttyMods mods);
/**
* Get the modifier keys bitmask.
*
* @param event The key event handle, must not be NULL
* @return The modifier keys bitmask
*
* @ingroup key
*/
GHOSTTY_API GhosttyMods ghostty_key_event_get_mods(GhosttyKeyEvent event);
/**
* Set the consumed modifiers bitmask.
*
* @param event The key event handle, must not be NULL
* @param consumed_mods The consumed modifiers bitmask to set
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_set_consumed_mods(GhosttyKeyEvent event, GhosttyMods consumed_mods);
/**
* Get the consumed modifiers bitmask.
*
* @param event The key event handle, must not be NULL
* @return The consumed modifiers bitmask
*
* @ingroup key
*/
GHOSTTY_API GhosttyMods ghostty_key_event_get_consumed_mods(GhosttyKeyEvent event);
/**
* Set whether the key event is part of a composition sequence.
*
* @param event The key event handle, must not be NULL
* @param composing Whether the key event is part of a composition sequence
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_set_composing(GhosttyKeyEvent event, bool composing);
/**
* Get whether the key event is part of a composition sequence.
*
* @param event The key event handle, must not be NULL
* @return Whether the key event is part of a composition sequence
*
* @ingroup key
*/
GHOSTTY_API bool ghostty_key_event_get_composing(GhosttyKeyEvent event);
/**
* Set the UTF-8 text generated by the key for the current keyboard layout.
*
* Must contain the unmodified character before any Ctrl/Meta transformations.
* The encoder derives modifier sequences from the logical key and mods
* bitmask, not from this text. Do not pass C0 control characters
* (U+0000-U+001F, U+007F) or platform function key codes (e.g. macOS PUA
* U+F700-U+F8FF); pass NULL instead and let the encoder use the logical key.
*
* The key event does NOT take ownership of the text pointer. The caller
* must ensure the string remains valid for the lifetime needed by the event.
*
* @param event The key event handle, must not be NULL
* @param utf8 The UTF-8 text to set (or NULL for empty)
* @param len Length of the UTF-8 text in bytes
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_set_utf8(GhosttyKeyEvent event, const char *utf8, size_t len);
/**
* Get the UTF-8 text generated by the key event.
*
* The returned pointer is valid until the event is freed or the UTF-8 text is modified.
*
* @param event The key event handle, must not be NULL
* @param len Pointer to store the length of the UTF-8 text in bytes (may be NULL)
* @return The UTF-8 text (or NULL for empty)
*
* @ingroup key
*/
GHOSTTY_API const char *ghostty_key_event_get_utf8(GhosttyKeyEvent event, size_t *len);
/**
* Set the unshifted Unicode codepoint.
*
* @param event The key event handle, must not be NULL
* @param codepoint The unshifted Unicode codepoint to set
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_event_set_unshifted_codepoint(GhosttyKeyEvent event, uint32_t codepoint);
/**
* Get the unshifted Unicode codepoint.
*
* @param event The key event handle, must not be NULL
* @return The unshifted Unicode codepoint
*
* @ingroup key
*/
GHOSTTY_API uint32_t ghostty_key_event_get_unshifted_codepoint(GhosttyKeyEvent event);
#endif /* GHOSTTY_VT_KEY_EVENT_H */
@@ -0,0 +1,775 @@
/**
* @file kitty_graphics.h
*
* Kitty graphics protocol
*
* See @ref kitty_graphics for a full usage guide.
*/
#ifndef GHOSTTY_VT_KITTY_GRAPHICS_H
#define GHOSTTY_VT_KITTY_GRAPHICS_H
#include <stdbool.h>
#include <stdint.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/selection.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup kitty_graphics Kitty Graphics
*
* API for inspecting images and placements stored via the
* [Kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/).
*
* The central object is @ref GhosttyKittyGraphics, an opaque handle to
* the image storage associated with a terminal's active screen. From it
* you can iterate over placements and look up individual images.
*
* ## Obtaining a KittyGraphics Handle
*
* A @ref GhosttyKittyGraphics handle is obtained from a terminal via
* ghostty_terminal_get() with @ref GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS.
* The handle is borrowed from the terminal and remains valid until the
* next mutating terminal call (e.g. ghostty_terminal_vt_write() or
* ghostty_terminal_reset()).
*
* Before images can be stored, Kitty graphics must be enabled on the
* terminal by setting a non-zero storage limit with
* @ref GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT, and a PNG
* decoder callback must be installed via ghostty_sys_set() with
* @ref GHOSTTY_SYS_OPT_DECODE_PNG.
*
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png
*
* ## Iterating Placements
*
* Placements are inspected through a @ref GhosttyKittyGraphicsPlacementIterator.
* The typical workflow is:
*
* 1. Create an iterator with ghostty_kitty_graphics_placement_iterator_new().
* 2. Populate it from the storage with ghostty_kitty_graphics_get() using
* @ref GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
* 3. Optionally filter by z-layer with
* ghostty_kitty_graphics_placement_iterator_set().
* 4. Advance with ghostty_kitty_graphics_placement_next() and read
* per-placement data with ghostty_kitty_graphics_placement_get().
* 5. For each placement, look up its image with
* ghostty_kitty_graphics_image() to access pixel data and dimensions.
* 6. Free the iterator with ghostty_kitty_graphics_placement_iterator_free().
*
* ## Looking Up Images
*
* Given an image ID (obtained from a placement via
* @ref GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID), call
* ghostty_kitty_graphics_image() to get a @ref GhosttyKittyGraphicsImage
* handle. From this handle, ghostty_kitty_graphics_image_get() provides
* the image dimensions, pixel format, compression, and a borrowed pointer
* to the raw pixel data.
*
* ## Rendering Helpers
*
* Several functions assist with rendering a placement:
*
* - ghostty_kitty_graphics_placement_pixel_size() — rendered pixel
* dimensions accounting for source rect and aspect ratio.
* - ghostty_kitty_graphics_placement_grid_size() — number of grid
* columns and rows the placement occupies.
* - ghostty_kitty_graphics_placement_viewport_pos() — viewport-relative
* grid position (may be negative for partially scrolled placements).
* - ghostty_kitty_graphics_placement_source_rect() — resolved source
* rectangle in pixels, clamped to image bounds.
* - ghostty_kitty_graphics_placement_rect() — bounding rectangle as a
* @ref GhosttySelection.
*
* ## Lifetime and Thread Safety
*
* All handles borrowed from the terminal (GhosttyKittyGraphics,
* GhosttyKittyGraphicsImage) are invalidated by any mutating terminal
* call. The placement iterator is independently owned and must be freed
* by the caller, but the data it yields is only valid while the
* underlying terminal is not mutated.
*
* ## Example
*
* The following example creates a terminal, sends a Kitty graphics
* image, then iterates placements and prints image metadata:
*
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main
*
* @{
*/
/**
* Queryable data kinds for ghostty_kitty_graphics_get().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_KITTY_GRAPHICS_DATA_INVALID = 0,
/**
* Populate a pre-allocated placement iterator with placement data from
* the storage. Iterator data is only valid as long as the underlying
* terminal is not mutated.
*
* Output type: GhosttyKittyGraphicsPlacementIterator *
*/
GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR = 1,
GHOSTTY_KITTY_GRAPHICS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsData;
/**
* Queryable data kinds for ghostty_kitty_graphics_placement_get().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_INVALID = 0,
/**
* The image ID this placement belongs to.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID = 1,
/**
* The placement ID.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_PLACEMENT_ID = 2,
/**
* Whether this is a virtual placement (unicode placeholder).
*
* Output type: bool *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IS_VIRTUAL = 3,
/**
* Pixel offset from the left edge of the cell.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_X_OFFSET = 4,
/**
* Pixel offset from the top edge of the cell.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Y_OFFSET = 5,
/**
* Source rectangle x origin in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_X = 6,
/**
* Source rectangle y origin in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_Y = 7,
/**
* Source rectangle width in pixels (0 = full image width).
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_WIDTH = 8,
/**
* Source rectangle height in pixels (0 = full image height).
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_HEIGHT = 9,
/**
* Number of columns this placement occupies.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_COLUMNS = 10,
/**
* Number of rows this placement occupies.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_ROWS = 11,
/**
* Z-index for this placement.
*
* Output type: int32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Z = 12,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsPlacementData;
/**
* Z-layer classification for kitty graphics placements.
*
* Based on the kitty protocol z-index conventions:
* - BELOW_BG: z < INT32_MIN/2 (drawn below cell background)
* - BELOW_TEXT: INT32_MIN/2 <= z < 0 (above background, below text)
* - ABOVE_TEXT: z >= 0 (above text)
* - ALL: no filtering (current behavior)
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_KITTY_PLACEMENT_LAYER_ALL = 0,
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_BG = 1,
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_TEXT = 2,
GHOSTTY_KITTY_PLACEMENT_LAYER_ABOVE_TEXT = 3,
GHOSTTY_KITTY_PLACEMENT_LAYER_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyPlacementLayer;
/**
* Settable options for ghostty_kitty_graphics_placement_iterator_set().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/**
* Set the z-layer filter for the iterator.
*
* Input type: GhosttyKittyPlacementLayer *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER = 0,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsPlacementIteratorOption;
/**
* Pixel format of a Kitty graphics image.
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_KITTY_IMAGE_FORMAT_RGB = 0,
GHOSTTY_KITTY_IMAGE_FORMAT_RGBA = 1,
GHOSTTY_KITTY_IMAGE_FORMAT_PNG = 2,
GHOSTTY_KITTY_IMAGE_FORMAT_GRAY_ALPHA = 3,
GHOSTTY_KITTY_IMAGE_FORMAT_GRAY = 4,
GHOSTTY_KITTY_IMAGE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyImageFormat;
/**
* Compression of a Kitty graphics image.
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_KITTY_IMAGE_COMPRESSION_NONE = 0,
GHOSTTY_KITTY_IMAGE_COMPRESSION_ZLIB_DEFLATE = 1,
GHOSTTY_KITTY_IMAGE_COMPRESSION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyImageCompression;
/**
* Queryable data kinds for ghostty_kitty_graphics_image_get().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_KITTY_IMAGE_DATA_INVALID = 0,
/**
* The image ID.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_ID = 1,
/**
* The image number.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_NUMBER = 2,
/**
* Image width in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_WIDTH = 3,
/**
* Image height in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_HEIGHT = 4,
/**
* Pixel format of the image.
*
* Output type: GhosttyKittyImageFormat *
*/
GHOSTTY_KITTY_IMAGE_DATA_FORMAT = 5,
/**
* Compression of the image.
*
* Output type: GhosttyKittyImageCompression *
*/
GHOSTTY_KITTY_IMAGE_DATA_COMPRESSION = 6,
/**
* Borrowed pointer to the raw pixel data. Valid as long as the
* underlying terminal is not mutated.
*
* Output type: const uint8_t **
*/
GHOSTTY_KITTY_IMAGE_DATA_DATA_PTR = 7,
/**
* Length of the raw pixel data in bytes.
*
* Output type: size_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_DATA_LEN = 8,
GHOSTTY_KITTY_IMAGE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsImageData;
/**
* Combined rendering geometry for a placement in a single sized struct.
*
* Combines the results of ghostty_kitty_graphics_placement_pixel_size(),
* ghostty_kitty_graphics_placement_grid_size(),
* ghostty_kitty_graphics_placement_viewport_pos(), and
* ghostty_kitty_graphics_placement_source_rect() into one call. This is
* an optimization over calling those four functions individually,
* particularly useful in environments with high per-call overhead such
* as FFI or Cgo.
*
* This struct uses the sized-struct ABI pattern. Initialize with
* GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo) before calling
* ghostty_kitty_graphics_placement_render_info().
*
* @ingroup kitty_graphics
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyKittyGraphicsPlacementRenderInfo). */
size_t size;
/** Rendered width in pixels. */
uint32_t pixel_width;
/** Rendered height in pixels. */
uint32_t pixel_height;
/** Number of grid columns the placement occupies. */
uint32_t grid_cols;
/** Number of grid rows the placement occupies. */
uint32_t grid_rows;
/** Viewport-relative column (may be negative for partially visible placements). */
int32_t viewport_col;
/** Viewport-relative row (may be negative for partially visible placements). */
int32_t viewport_row;
/** False when the placement is fully off-screen or virtual. */
bool viewport_visible;
/** Resolved source rectangle x origin in pixels. */
uint32_t source_x;
/** Resolved source rectangle y origin in pixels. */
uint32_t source_y;
/** Resolved source rectangle width in pixels. */
uint32_t source_width;
/** Resolved source rectangle height in pixels. */
uint32_t source_height;
} GhosttyKittyGraphicsPlacementRenderInfo;
/**
* Get data from a kitty graphics storage instance.
*
* The output pointer must be of the appropriate type for the requested
* data kind.
*
* Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
*
* @param graphics The kitty graphics handle
* @param data The type of data to extract
* @param[out] out Pointer to store the extracted data
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_get(
GhosttyKittyGraphics graphics,
GhosttyKittyGraphicsData data,
void* out);
/**
* Look up a Kitty graphics image by its image ID.
*
* Returns NULL if no image with the given ID exists or if Kitty graphics
* are disabled at build time.
*
* @param graphics The kitty graphics handle
* @param image_id The image ID to look up
* @return An opaque image handle, or NULL if not found
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyKittyGraphicsImage ghostty_kitty_graphics_image(
GhosttyKittyGraphics graphics,
uint32_t image_id);
/**
* Get data from a Kitty graphics image.
*
* The output pointer must be of the appropriate type for the requested
* data kind.
*
* @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param data The data kind to query
* @param[out] out Pointer to receive the queried value
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get(
GhosttyKittyGraphicsImage image,
GhosttyKittyGraphicsImageData data,
void* out);
/**
* Get multiple data fields from a Kitty graphics image in a single call.
*
* This is an optimization over calling ghostty_kitty_graphics_image_get()
* repeatedly, particularly useful in environments with high per-call
* overhead such as FFI or Cgo.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
* The type of each values[i] pointer must match the output type
* documented for keys[i].
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get_multi(
GhosttyKittyGraphicsImage image,
size_t count,
const GhosttyKittyGraphicsImageData* keys,
void** values,
size_t* out_written);
/**
* Create a new placement iterator instance.
*
* All fields except the allocator are left undefined until populated
* via ghostty_kitty_graphics_get() with
* GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param[out] out_iterator On success, receives the created iterator handle
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
* failure
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_new(
const GhosttyAllocator* allocator,
GhosttyKittyGraphicsPlacementIterator* out_iterator);
/**
* Free a placement iterator.
*
* @param iterator The iterator handle to free (may be NULL)
*
* @ingroup kitty_graphics
*/
GHOSTTY_API void ghostty_kitty_graphics_placement_iterator_free(
GhosttyKittyGraphicsPlacementIterator iterator);
/**
* Set an option on a placement iterator.
*
* Use GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER with a
* GhosttyKittyPlacementLayer value to filter placements by z-layer.
* The filter is applied during iteration: ghostty_kitty_graphics_placement_next()
* will skip placements that do not match the configured layer.
*
* The default layer is GHOSTTY_KITTY_PLACEMENT_LAYER_ALL (no filtering).
*
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param option The option to set
* @param value Pointer to the value (type depends on option; NULL returns
* GHOSTTY_INVALID_VALUE)
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_set(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsPlacementIteratorOption option,
const void* value);
/**
* Advance the placement iterator to the next placement.
*
* If a layer filter has been set via
* ghostty_kitty_graphics_placement_iterator_set(), only placements
* matching that layer are returned.
*
* @param iterator The iterator handle (may be NULL)
* @return true if advanced to the next placement, false if at the end
*
* @ingroup kitty_graphics
*/
GHOSTTY_API bool ghostty_kitty_graphics_placement_next(
GhosttyKittyGraphicsPlacementIterator iterator);
/**
* Get data from the current placement in a placement iterator.
*
* Call ghostty_kitty_graphics_placement_next() at least once before
* calling this function.
*
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param data The data kind to query
* @param[out] out Pointer to receive the queried value
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
* iterator is NULL or not positioned on a placement
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsPlacementData data,
void* out);
/**
* Get multiple data fields from the current placement in a single call.
*
* This is an optimization over calling ghostty_kitty_graphics_placement_get()
* repeatedly, particularly useful in environments with high per-call
* overhead such as FFI or Cgo.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
* The type of each values[i] pointer must match the output type
* documented for keys[i].
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get_multi(
GhosttyKittyGraphicsPlacementIterator iterator,
size_t count,
const GhosttyKittyGraphicsPlacementData* keys,
void** values,
size_t* out_written);
/**
* Compute the grid rectangle occupied by the current placement.
*
* Uses the placement's pin, the image dimensions, and the terminal's
* cell/pixel geometry to calculate the bounding rectangle. Virtual
* placements (unicode placeholders) return GHOSTTY_NO_VALUE.
*
* @param terminal The terminal handle
* @param image The image handle for this placement's image
* @param iterator The placement iterator positioned on a placement
* @param[out] out_selection On success, receives the bounding rectangle
* as a selection with rectangle=true
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE for
* virtual placements or when Kitty graphics are disabled
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_rect(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
GhosttySelection* out_selection);
/**
* Compute the rendered pixel size of the current placement.
*
* Takes into account the placement's source rectangle, specified
* columns/rows, and aspect ratio to calculate the final rendered
* pixel dimensions.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_width On success, receives the width in pixels
* @param[out] out_height On success, receives the height in pixels
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
* Kitty graphics are disabled
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_pixel_size(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
uint32_t* out_width,
uint32_t* out_height);
/**
* Compute the grid cell size of the current placement.
*
* Returns the number of columns and rows that the placement occupies
* in the terminal grid. If the placement specifies explicit columns
* and rows, those are returned directly; otherwise they are calculated
* from the pixel size and cell dimensions.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_cols On success, receives the number of columns
* @param[out] out_rows On success, receives the number of rows
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
* Kitty graphics are disabled
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_grid_size(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
uint32_t* out_cols,
uint32_t* out_rows);
/**
* Get the viewport-relative grid position of the current placement.
*
* Converts the placement's internal pin to viewport-relative column and
* row coordinates. The returned coordinates represent the top-left
* corner of the placement in the viewport's grid coordinate space.
*
* The row value can be negative when the placement's origin has
* scrolled above the top of the viewport. For example, a 4-row
* image that has scrolled up by 2 rows returns row=-2, meaning
* its top 2 rows are above the visible area but its bottom 2 rows
* are still on screen. Embedders should use these coordinates
* directly when computing the destination rectangle for rendering;
* the embedder is responsible for clipping the portion of the image
* that falls outside the viewport.
*
* Returns GHOSTTY_SUCCESS for any placement that is at least
* partially visible in the viewport. Returns GHOSTTY_NO_VALUE when
* the placement is completely outside the viewport (its bottom edge
* is above the viewport or its top edge is at or below the last
* viewport row), or when the placement is a virtual (unicode
* placeholder) placement.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_col On success, receives the viewport-relative column
* @param[out] out_row On success, receives the viewport-relative row
* (may be negative for partially visible placements)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if fully
* off-screen or virtual, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_viewport_pos(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
int32_t* out_col,
int32_t* out_row);
/**
* Get the resolved source rectangle for the current placement.
*
* Applies kitty protocol semantics: a width or height of 0 in the
* placement means "use the full image dimension", and the resulting
* rectangle is clamped to the actual image bounds. The returned
* values are in pixels and are ready to use for texture sampling.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param[out] out_x Source rect x origin in pixels
* @param[out] out_y Source rect y origin in pixels
* @param[out] out_width Source rect width in pixels
* @param[out] out_height Source rect height in pixels
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any
* handle is NULL or the iterator is not positioned
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_source_rect(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
uint32_t* out_x,
uint32_t* out_y,
uint32_t* out_width,
uint32_t* out_height);
/**
* Get all rendering geometry for a placement in a single call.
*
* Combines pixel size, grid size, viewport position, and source
* rectangle into one struct. Initialize with
* GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo).
*
* When viewport_visible is false, the placement is fully off-screen
* or is a virtual placement; viewport_col and viewport_row may
* contain meaningless values in that case.
*
* @param iterator The iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_info Pointer to receive the rendering geometry
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_render_info(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
GhosttyKittyGraphicsPlacementRenderInfo* out_info);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_KITTY_GRAPHICS_H */
@@ -0,0 +1,198 @@
/**
* @file modes.h
*
* Terminal mode utilities - pack and unpack ANSI/DEC mode identifiers.
*/
#ifndef GHOSTTY_VT_MODES_H
#define GHOSTTY_VT_MODES_H
/** @defgroup modes Mode Utilities
*
* Utilities for working with terminal modes. A mode is a compact
* 16-bit representation of a terminal mode identifier that encodes both
* the numeric mode value (up to 15 bits) and whether the mode is an ANSI
* mode or a DEC private mode (?-prefixed).
*
* The packed layout (least-significant bit first) is:
* - Bits 0–14: mode value (u15)
* - Bit 15: ANSI flag (0 = DEC private mode, 1 = ANSI mode)
*
* ## Example
*
* @snippet c-vt-modes/src/main.c modes-pack-unpack
*
* ## DECRPM Report Encoding
*
* Use ghostty_mode_report_encode() to encode a DECRPM response into a
* caller-provided buffer:
*
* @snippet c-vt-modes/src/main.c modes-decrpm
*
* @{
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @name ANSI Modes
* Modes for standard ANSI modes.
* @{
*/
#define GHOSTTY_MODE_KAM (ghostty_mode_new(2, true)) /**< Keyboard action (disable keyboard) */
#define GHOSTTY_MODE_INSERT (ghostty_mode_new(4, true)) /**< Insert mode */
#define GHOSTTY_MODE_SRM (ghostty_mode_new(12, true)) /**< Send/receive mode */
#define GHOSTTY_MODE_LINEFEED (ghostty_mode_new(20, true)) /**< Linefeed/new line mode */
/** @} */
/** @name DEC Private Modes
* Modes for DEC private modes (?-prefixed).
* @{
*/
#define GHOSTTY_MODE_DECCKM (ghostty_mode_new(1, false)) /**< Cursor keys */
#define GHOSTTY_MODE_132_COLUMN (ghostty_mode_new(3, false)) /**< 132/80 column mode */
#define GHOSTTY_MODE_SLOW_SCROLL (ghostty_mode_new(4, false)) /**< Slow scroll */
#define GHOSTTY_MODE_REVERSE_COLORS (ghostty_mode_new(5, false)) /**< Reverse video */
#define GHOSTTY_MODE_ORIGIN (ghostty_mode_new(6, false)) /**< Origin mode */
#define GHOSTTY_MODE_WRAPAROUND (ghostty_mode_new(7, false)) /**< Auto-wrap mode */
#define GHOSTTY_MODE_AUTOREPEAT (ghostty_mode_new(8, false)) /**< Auto-repeat keys */
#define GHOSTTY_MODE_X10_MOUSE (ghostty_mode_new(9, false)) /**< X10 mouse reporting */
#define GHOSTTY_MODE_CURSOR_BLINKING (ghostty_mode_new(12, false)) /**< Cursor blink */
#define GHOSTTY_MODE_CURSOR_VISIBLE (ghostty_mode_new(25, false)) /**< Cursor visible (DECTCEM) */
#define GHOSTTY_MODE_ENABLE_MODE_3 (ghostty_mode_new(40, false)) /**< Allow 132 column mode */
#define GHOSTTY_MODE_REVERSE_WRAP (ghostty_mode_new(45, false)) /**< Reverse wrap */
#define GHOSTTY_MODE_ALT_SCREEN_LEGACY (ghostty_mode_new(47, false)) /**< Alternate screen (legacy) */
#define GHOSTTY_MODE_KEYPAD_KEYS (ghostty_mode_new(66, false)) /**< Application keypad */
#define GHOSTTY_MODE_BACKARROW_KEY_MODE (ghostty_mode_new(67, false)) /**< Backarrow key mode (DECBKM) */
#define GHOSTTY_MODE_LEFT_RIGHT_MARGIN (ghostty_mode_new(69, false)) /**< Left/right margin mode */
#define GHOSTTY_MODE_NORMAL_MOUSE (ghostty_mode_new(1000, false)) /**< Normal mouse tracking */
#define GHOSTTY_MODE_BUTTON_MOUSE (ghostty_mode_new(1002, false)) /**< Button-event mouse tracking */
#define GHOSTTY_MODE_ANY_MOUSE (ghostty_mode_new(1003, false)) /**< Any-event mouse tracking */
#define GHOSTTY_MODE_FOCUS_EVENT (ghostty_mode_new(1004, false)) /**< Focus in/out events */
#define GHOSTTY_MODE_UTF8_MOUSE (ghostty_mode_new(1005, false)) /**< UTF-8 mouse format */
#define GHOSTTY_MODE_SGR_MOUSE (ghostty_mode_new(1006, false)) /**< SGR mouse format */
#define GHOSTTY_MODE_ALT_SCROLL (ghostty_mode_new(1007, false)) /**< Alternate scroll mode */
#define GHOSTTY_MODE_URXVT_MOUSE (ghostty_mode_new(1015, false)) /**< URxvt mouse format */
#define GHOSTTY_MODE_SGR_PIXELS_MOUSE (ghostty_mode_new(1016, false)) /**< SGR-Pixels mouse format */
#define GHOSTTY_MODE_NUMLOCK_KEYPAD (ghostty_mode_new(1035, false)) /**< Ignore keypad with NumLock */
#define GHOSTTY_MODE_ALT_ESC_PREFIX (ghostty_mode_new(1036, false)) /**< Alt key sends ESC prefix */
#define GHOSTTY_MODE_ALT_SENDS_ESC (ghostty_mode_new(1039, false)) /**< Alt sends escape */
#define GHOSTTY_MODE_REVERSE_WRAP_EXT (ghostty_mode_new(1045, false)) /**< Extended reverse wrap */
#define GHOSTTY_MODE_ALT_SCREEN (ghostty_mode_new(1047, false)) /**< Alternate screen */
#define GHOSTTY_MODE_SAVE_CURSOR (ghostty_mode_new(1048, false)) /**< Save cursor (DECSC) */
#define GHOSTTY_MODE_ALT_SCREEN_SAVE (ghostty_mode_new(1049, false)) /**< Alt screen + save cursor + clear */
#define GHOSTTY_MODE_BRACKETED_PASTE (ghostty_mode_new(2004, false)) /**< Bracketed paste mode */
#define GHOSTTY_MODE_SYNC_OUTPUT (ghostty_mode_new(2026, false)) /**< Synchronized output */
#define GHOSTTY_MODE_GRAPHEME_CLUSTER (ghostty_mode_new(2027, false)) /**< Grapheme cluster mode */
#define GHOSTTY_MODE_COLOR_SCHEME_REPORT (ghostty_mode_new(2031, false)) /**< Report color scheme */
#define GHOSTTY_MODE_IN_BAND_RESIZE (ghostty_mode_new(2048, false)) /**< In-band size reports */
/** @} */
/**
* A packed 16-bit terminal mode.
*
* Encodes a mode value (bits 0–14) and an ANSI flag (bit 15) into a
* single 16-bit integer. Use the inline helper functions to construct
* and inspect modes rather than manipulating bits directly.
*/
typedef uint16_t GhosttyMode;
/**
* Create a mode from a mode value and ANSI flag.
*
* @param value The numeric mode value (0–32767)
* @param ansi true for an ANSI mode, false for a DEC private mode
* @return The packed mode
*
* @ingroup modes
*/
static inline GhosttyMode ghostty_mode_new(uint16_t value, bool ansi) {
return (GhosttyMode)((value & 0x7FFF) | ((uint16_t)ansi << 15));
}
/**
* Extract the numeric mode value from a mode.
*
* @param mode The mode
* @return The mode value (0–32767)
*
* @ingroup modes
*/
static inline uint16_t ghostty_mode_value(GhosttyMode mode) {
return mode & 0x7FFF;
}
/**
* Check whether a mode represents an ANSI mode.
*
* @param mode The mode
* @return true if this is an ANSI mode, false if it is a DEC private mode
*
* @ingroup modes
*/
static inline bool ghostty_mode_ansi(GhosttyMode mode) {
return (mode >> 15) != 0;
}
/**
* DECRPM report state values.
*
* These correspond to the Ps2 parameter in a DECRPM response
* sequence (CSI ? Ps1 ; Ps2 $ y).
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Mode is not recognized */
GHOSTTY_MODE_REPORT_NOT_RECOGNIZED = 0,
/** Mode is set (enabled) */
GHOSTTY_MODE_REPORT_SET = 1,
/** Mode is reset (disabled) */
GHOSTTY_MODE_REPORT_RESET = 2,
/** Mode is permanently set */
GHOSTTY_MODE_REPORT_PERMANENTLY_SET = 3,
/** Mode is permanently reset */
GHOSTTY_MODE_REPORT_PERMANENTLY_RESET = 4,
GHOSTTY_MODE_REPORT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyModeReportState;
/**
* Encode a DECRPM (DEC Private Mode Report) response sequence.
*
* Writes a mode report escape sequence into the provided buffer.
* The generated sequence has the form:
* - DEC private mode: CSI ? Ps1 ; Ps2 $ y
* - ANSI mode: CSI Ps1 ; Ps2 $ y
*
* If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
* and writes the required buffer size to @p out_written. The caller can
* then retry with a sufficiently sized buffer.
*
* @param mode The mode identifying the mode to report on
* @param state The report state for this mode
* @param buf Output buffer to write the encoded sequence into (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_written On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
* is too small
*/
GHOSTTY_API GhosttyResult ghostty_mode_report_encode(
GhosttyMode mode,
GhosttyModeReportState state,
char* buf,
size_t buf_len,
size_t* out_written);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_MODES_H */
Loaded 100 of 572 files, more files were not shown because too many files have changed in this diff. Show more