Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex f7607138c5 Fix macOS helper bundle identities
Co-authored-by: codex <[email protected]>
2026-04-29 16:33:15 -07:00
8d1d699f88 Refactor provider model selections to option arrays (#2246)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
Co-authored-by: codex <[email protected]>
2026-04-23 09:35:40 -04:00
Raul Pereira da Silvaandmacroscopeapp[bot] b0b7b38da1 fix(server): detect localized Windows command errors (#2152)
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-04-23 04:42:19 +00:00
Bas Milius fd3b96b487 Add IntelliJ project icon to the list of possible favicon paths (#1651) 2026-04-23 04:40:27 +00:00
Hauke Schnau aa2d385a62 fix(server): restore CODEX_HOME tilde expansion for Codex launches (#2255) 2026-04-23 00:37:58 -04:00
e25db3a572 Fix provider cache atomic write temp path collisions (#2291)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-23 00:33:16 -04:00
Heinz-GandHeinz Gericke b8305afa29 fix: increase Claude auth probe timeout to 10s (#2272)
Co-authored-by: Heinz Gericke <[email protected]>
2026-04-22 01:04:50 +00:00
Julius MarmingeandCursor Agent b7c89cf496 Refresh Codex protocol bindings to be75785504ff152fa6333e380a2d50642f42fba0 (#2276)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-21 15:30:54 -07:00
NoxireandJulius Marminge 3a1daa87ac Add close buttons to toasts (#2023)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-21 08:32:08 -07:00
Mike Olson 055897f0ea fix: enforce opencode >= 1.14.19 and reveal window on Wayland (#2262) 2026-04-21 08:15:41 -07:00
Adin Schmidt 40b3a80034 fix(server): trim OpenCode provider model names (#2252) 2026-04-21 02:45:56 +00:00
Adam Mansfield f6978db605 chore(turbo): pass through PATHEXT (#2184) 2026-04-19 23:35:37 -07:00
Mike Olson de05b0c94e fix(web): restore manual sort drag and keep per-group expand state (#2221) 2026-04-19 23:29:56 -07:00
CraigandJulius Marminge 6d1505c9fb fix: Change right panel sheet to be below title bar / action bar (#2224)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 23:25:39 -07:00
Julius MarmingeandClaude Opus 4.7 306ec4bb84 Refactor OpenCode lifecycle and structured output handling (#2218)
Co-authored-by: Claude Opus 4.7 <[email protected]>
2026-04-19 22:56:44 -07:00
Julius Marmingeandcodex 3b98fe3548 effect-codex-app-server (#1942)
Co-authored-by: codex <[email protected]>
2026-04-19 21:46:40 -07:00
Ellie GummereandJulius Marminge 66c326b8c4 Redesign model picker with favorites and search (#2153)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 17:43:40 -07:00
8dbcf92a0d fix(server): prevent probeClaudeCapabilities from wasting API requests (#2192)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-20 00:13:20 +00:00
Abdul Azeez 37965da01d fix(server): handle OpenCode text response format in commit message g… (#2202) 2026-04-20 00:12:35 +00:00
Kyle Gottfried 57b59b5bf2 Devcontainer / IDE updates (#2208) 2026-04-19 17:07:12 -07:00
20f346d8ef Expand leading ~ in Codex home paths before exporting CODEX_HOME (#2210)
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: = <=>
2026-04-20 00:06:19 +00:00
Efe Baran Durmaz c83bc5d48a fix(release): use v<semver> tag format for nightly releases (#2186) 2026-04-19 10:58:04 -07:00
Julius Marminge 9df3c64021 Use GitHub App token for release uploads (#2149) 2026-04-17 16:52:56 -07:00
Julius Marminge 8ac57f7944 Guard release workflow jobs on upstream success (#2147) 2026-04-17 16:40:43 -07:00
Julius Marminge 29cb917ac4 Guard release workflow jobs from upstream failures (#2146) 2026-04-17 16:34:19 -07:00
9c64f12ea0 Add ACP support with Cursor provider (#1355)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-17 16:21:31 -07:00
Matt Van HornandMatt Van Horn 0f184c28b0 fix(web): use capture-phase keydown listener so CTRL+J toggles terminal from terminal focus on Windows (#2113) (#2142)
Co-authored-by: Matt Van Horn <[email protected]>
2026-04-17 23:07:04 +00:00
Julius Marminge a3b1df5224 Add Claude Opus 4.5 to built-in Claude models (#2143) 2026-04-17 16:02:41 -07:00
4e0c003e78 fix(web): allow deleting non-empty projects from the warning toast (#1264)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 15:05:56 -07:00
Utkarsh Patil 60387f67e9 fix: show restore defaults only on General settings (#1710) 2026-04-17 13:49:18 -07:00
ce94feeea1 feat: add opencode provider support (#1758)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-04-17 13:31:41 -07:00
Ariaj 39ca3ee858 fix(web): bypass xterm for global terminal shortcuts (#1580) 2026-04-17 13:11:04 -07:00
Julius Marminge 52a6067802 Throttle nightly release workflow to every 3 hours (#2134) 2026-04-17 11:39:20 -07:00
721b6b4c6f Preserve provider bindings when stopping sessions (#2125)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 11:27:12 -07:00
Julius Marminge 40009735ee Extract backend startup readiness coordination (#2133) 2026-04-17 11:09:26 -07:00
df9d34004f Modernize release workflow runners (#2129)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-17 16:23:02 +00:00
Julius Marminge f297e30e4c Clean up invalid pending approval projections (#2106) 2026-04-16 23:26:28 -07:00
Evan YuandJulius Marminge a7a44d0662 Fix Windows PATH hydration and repair (#1729)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-17 06:12:17 +00:00
Jono Kemball d8d329691a Show thread status in command palette (#2107) 2026-04-16 22:21:57 -07:00
Julius Marminge 54179c86b8 Update workflow to use ubuntu-24.04 runner (#2110) 2026-04-16 22:16:13 -07:00
Julius Marminge 8dba2d6484 Adopt Node-native TypeScript for desktop and server (#2098) 2026-04-16 22:14:35 -07:00
Nathan HarmonandJulius Marminge ed6b7fbf27 fix(server): honor gitignored files in workspace search (#2078)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 21:19:14 -07:00
Julius Marminge b991b9b9e6 Revert to Github Runner for Windows (#2103) 2026-04-16 20:35:56 -07:00
Julius Marminge 505db9f696 try out blacksmith for releases (#2101) 2026-04-16 20:12:09 -07:00
t3-code[bot] 2d87574e62 chore(release): prepare v0.0.20 2026-04-17 03:00:57 +00:00
Julius Marminge b2cca674df ci(release): install deps before finalize version bump (#2100) 2026-04-16 19:42:17 -07:00
Julius Marminge 549043863a fix: guard against missing sidebarProjectGroupingOverrides in client settings (#2099) 2026-04-17 02:36:39 +00:00
Julius Marminge b7df3dfca0 [codex] Fix Windows release manifest publishing (#2095) 2026-04-16 17:56:16 -07:00
Evan YuandJulius Marminge 6891c77d3e Build for Windows ARM (#2080)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 17:01:27 -07:00
m9d5m d90e15d1d7 fix(server): extend negative repository identity cache ttl (#2083) 2026-04-16 16:57:39 -07:00
e0117b271a Fix Claude Process leak[MEMORY INTENSIVE], archiving, and stale claude session monitoring. (#2042)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:30:56 -07:00
188a40c315 feat: configurable project grouping (#2055)
Co-authored-by: tlh38 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:29:25 -07:00
Utkarsh Patil 7a08fcf2e8 fix(server): drop stale text generation options when resetting text-gen model selection (#2076) 2026-04-16 20:01:35 +00:00
Utkarsh Patil 19d47408a5 fix(web): prevent composer controls overlap on narrow windows (make plan sidebar responsive) (#1198) 2026-04-16 11:13:59 -07:00
Ibrahim ElkamaliandJulius Marminge 3e07f5a6a4 feat: add Claude Opus 4.7 to built-in models (#2072)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 11:11:59 -07:00
Marcus Grando d22c6f5280 fix: prevent user-input activities from leaking into pending approvals projection (#2051) 2026-04-16 05:09:29 +00:00
Marcus Grando 5e13f53571 fix: remove trailing newline from CLAUDE.md symlink (#2052) 2026-04-15 22:05:10 -07:00
f9580ff088 Default nightly desktop builds to the nightly update channel (#2049)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-15 21:31:24 -07:00
AndreiandJulius Marminge 5e1dd56d2c feat: add Launch Args setting for Claude provider (#1971)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 21:26:36 +00:00
legsandJulius Marminge 68061af042 Improve markdown file link UX (#1956)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 14:20:28 -07:00
Guilherme Vieira 28cb9db20b feat(web): add tooltip to composer file mention pill (#1944) 2026-04-15 13:29:13 -07:00
SakethandJulius Marminge 7968f278ee Fix terminal Cmd+Backspace on macOS (#2027)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 06:29:45 +00:00
44afe784a3 Add filesystem browse API and command palette project picker (#2024)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-14 23:26:05 -07:00
Julius Marmingeandcodex 9ff31f8c35 Fix nightly desktop product name (#2025)
Co-authored-by: codex <[email protected]>
2026-04-14 19:12:36 -07:00
409ff90a14 Nightly release channel (#2012)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-14 18:18:37 -07:00
576 changed files with 96276 additions and 33694 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
plans/
+11 -4
View File
@@ -2,15 +2,22 @@
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers-extra/features/bun:1": {},
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers-extra/features/bun:1": {
"version": "1.3.11"
},
"ghcr.io/devcontainers/features/node:1": {
"version": "24",
"nodeGypDependencies": true
"version": "24.13.1"
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.12"
"version": "3.10",
"installTools": false
}
},
"overrideFeatureInstallOrder": [
"ghcr.io/devcontainers/features/git",
"ghcr.io/devcontainers-extra/features/bun"
],
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
+7 -4
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -71,12 +71,12 @@ jobs:
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -92,5 +92,8 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+252 -47
View File
@@ -1,14 +1,25 @@
name: Release Desktop
name: Release
on:
push:
tags:
- "v*.*.*"
- "!v*-nightly.*"
schedule:
- cron: "0 */3 * * *"
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: false
default: stable
type: choice
options:
- stable
- nightly
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: true
required: false
type: string
permissions:
@@ -16,45 +27,63 @@ permissions:
id-token: write
jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: check
name: Compare HEAD to last nightly tag
run: |
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
if [[ -z "$last_nightly_tag" ]]; then
echo "No previous nightly tag found. Proceeding with release."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
exit 0
fi
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
head_sha=$(git rev-parse HEAD)
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
preflight:
name: Preflight
runs-on: ubuntu-24.04
needs: [check_changes]
if: |
!failure() && !cancelled() &&
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
outputs:
release_channel: ${{ steps.release_meta.outputs.release_channel }}
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
release_name: ${{ steps.release_meta.outputs.name }}
short_sha: ${{ steps.release_meta.outputs.short_sha }}
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
with:
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -69,6 +98,60 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- id: release_meta
name: Resolve release version
shell: bash
env:
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
DISPATCH_VERSION: ${{ github.event.inputs.version }}
NIGHTLY_DATE: ${{ github.run_started_at }}
NIGHTLY_SHA: ${{ github.sha }}
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
run: |
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
node scripts/resolve-nightly-release.ts \
--date "$nightly_date" \
--run-number "$NIGHTLY_RUN_NUMBER" \
--sha "$NIGHTLY_SHA" \
--github-output
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
else
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${DISPATCH_VERSION}"
if [[ -z "$raw" ]]; then
echo "workflow_dispatch stable releases require the version input." >&2
exit 1
fi
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
fi
- name: Lint
run: bun run lint
@@ -78,9 +161,18 @@ jobs:
- name: Test
run: bun run test
- id: previous_tag
name: Resolve previous release tag
run: |
node scripts/resolve-previous-release-tag.ts \
--channel "${{ steps.release_meta.outputs.release_channel }}" \
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
@@ -88,25 +180,30 @@ jobs:
matrix:
include:
- label: macOS arm64
runner: macos-14
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: macos-15-intel
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: ubuntu-24.04
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
# target: nsis
# arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -130,6 +227,23 @@ jobs:
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
run: |
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$installPath = & $vswhere -products * -latest -property installationPath
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
$proc = Start-Process -FilePath $setupExe `
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
-Wait -PassThru -NoNewWindow
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
Write-Error "Visual Studio Installer failed with exit code $code"
exit $code
}
- name: Build desktop artifact
shell: bash
env:
@@ -206,18 +320,31 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/latest*.yml"; do
"release/*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
fi
# Enable if Windows arm64 builds are enabled.
# Windows updater metadata is channel-specific (for example
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
# release job can merge matching arm64/x64 manifests back into one
# canonical manifest per channel.
# if [[ "${{ matrix.platform }}" == "win" ]]; then
# shopt -s nullglob
# for manifest in release-publish/*.yml; do
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
# done
# fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -228,7 +355,8 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -257,24 +385,41 @@ jobs:
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
with:
@@ -284,17 +429,72 @@ jobs:
- name: Merge macOS updater manifests
run: |
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
shopt -s nullglob
for x64_manifest in release-assets/*-mac-x64.yml; do
arm64_manifest="${x64_manifest%-x64.yml}.yml"
if [[ -f "$arm64_manifest" ]]; then
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
rm -f "$x64_manifest"
fi
done
# - name: Merge Windows updater manifests
# run: |
# shopt -s nullglob
# found_windows_manifest=false
# for x64_manifest in release-assets/*-win-x64.yml; do
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
# continue
# fi
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
# if [[ ! -f "$arm64_manifest" ]]; then
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
# exit 1
# fi
# found_windows_manifest=true
# node scripts/merge-update-manifests.ts --platform win \
# "$arm64_manifest" \
# "$x64_manifest" \
# "$output_manifest"
# rm -f "$arm64_manifest" "$x64_manifest"
# done
# if [[ "$found_windows_manifest" != true ]]; then
# echo "No Windows updater manifests found to merge." >&2
# exit 1
# fi
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: T3 Code v${{ needs.preflight.outputs.version }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
@@ -304,13 +504,15 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/latest*.yml
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
finalize:
name: Finalize release
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
needs: [preflight, release]
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
@@ -349,6 +551,9 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- id: update_versions
name: Update version strings
env:
+10 -2
View File
@@ -11,7 +11,15 @@
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"apps/mobile/uniwind-types.d.ts"
"*.icon/**"
],
"sortPackageJson": {}
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
+1 -3
View File
@@ -6,8 +6,7 @@
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/mobile/uniwind-types.d.ts"
"**/routeTree.gen.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
@@ -16,7 +15,6 @@
"perf": "warn"
},
"rules": {
"unicorn/no-array-sort": "off",
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
+1 -1
View File
@@ -5,5 +5,5 @@
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn",
"typescript.tsdk": "node_modules/typescript/lib"
"js/ts.tsdk.path": "node_modules/typescript/lib"
}
+6 -4
View File
@@ -1,14 +1,15 @@
{
"name": "@t3tools/desktop",
"version": "0.0.17",
"version": "0.0.20",
"private": true,
"main": "dist-electron/main.js",
"type": "module",
"main": "dist-electron/main.cjs",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"dev:electron": "node scripts/dev-electron.mjs",
"build": "tsdown",
"start": "bun run scripts/start-electron.mjs",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
@@ -22,6 +23,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+4 -4
View File
@@ -17,12 +17,12 @@ if (!Number.isInteger(port) || port <= 0) {
}
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"dist-electron/main.cjs",
"dist-electron/preload.cjs",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
@@ -69,7 +69,7 @@ function startApp() {
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
{
cwd: desktopDir,
env: childEnv,
+79 -6
View File
@@ -6,6 +6,7 @@ import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
@@ -19,10 +20,13 @@ import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const LAUNCHER_VERSION = 3;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
@@ -43,6 +47,68 @@ function setPlistString(plistPath, key, value) {
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
runChecked("sips", [
"-z",
String(size),
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
runChecked("sips", [
"-z",
String(retinaSize),
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
return generatedIconPath;
} catch (error) {
console.warn(
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
error,
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
@@ -62,10 +128,11 @@ function patchHelperBundleInfoPlists(appBundlePath) {
}
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
continue;
}
if (!entry.name.startsWith("Electron Helper")) {
if (
!entry.isDirectory() ||
!entry.name.startsWith("Electron Helper") ||
!entry.name.endsWith(".app")
) {
continue;
}
@@ -102,7 +169,7 @@ function buildMacLauncher(electronBinaryPath) {
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = join(desktopDir, "resources", "icon.icns");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
@@ -140,5 +207,11 @@ export function resolveElectronPath() {
return electronBinaryPath;
}
// Dev launches do not need a renamed app bundle badly enough to risk breaking
// Electron helper resource lookup on macOS.
if (isDevelopment) {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
+1 -1
View File
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";
describe("resolveDesktopAppStageLabel", () => {
it("uses Dev in desktop development", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: true,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Dev");
});
it("uses Nightly for packaged nightly builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Nightly");
});
it("uses Alpha for packaged stable builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17",
}),
).toBe("Alpha");
});
});
describe("resolveDesktopAppBranding", () => {
it("returns a complete desktop branding payload", () => {
expect(
resolveDesktopAppBranding({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toEqual({
baseName: "T3 Code",
stageLabel: "Nightly",
displayName: "T3 Code (Nightly)",
});
});
});
+28
View File
@@ -0,0 +1,28 @@
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
import { isNightlyDesktopVersion } from "./updateChannels.ts";
const APP_BASE_NAME = "T3 Code";
export function resolveDesktopAppStageLabel(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppStageLabel {
if (input.isDevelopment) {
return "Dev";
}
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
}
export function resolveDesktopAppBranding(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppBranding {
const stageLabel = resolveDesktopAppStageLabel(input);
return {
baseName: APP_BASE_NAME,
stageLabel,
displayName: `${APP_BASE_NAME} (${stageLabel})`,
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDesktopBackendPort } from "./backendPort";
import { resolveDesktopBackendPort } from "./backendPort.ts";
describe("resolveDesktopBackendPort", () => {
it("returns the starting port when it is available", async () => {
+1 -1
View File
@@ -4,7 +4,7 @@ import {
BackendReadinessAbortedError,
isBackendReadinessAborted,
waitForHttpReady,
} from "./backendReadiness";
} from "./backendReadiness.ts";
describe("waitForHttpReady", () => {
it("returns once the backend serves the requested readiness path", async () => {
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from "vitest";
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
describe("waitForBackendStartupReady", () => {
it("falls back to the HTTP probe when no listening signal exists", async () => {
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
const cancelHttpWait = vi.fn();
await expect(
waitForBackendStartupReady({
waitForHttpReady,
cancelHttpWait,
}),
).resolves.toBe("http");
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
expect(cancelHttpWait).not.toHaveBeenCalled();
});
it("uses the listening signal and cancels the HTTP probe", async () => {
let rejectHttpWait: ((error: unknown) => void) | null = null;
const waitForHttpReady = vi.fn(
() =>
new Promise<void>((_resolve, reject) => {
rejectHttpWait = reject;
}),
);
const cancelHttpWait = vi.fn(() => {
rejectHttpWait?.(new BackendReadinessAbortedError());
});
await expect(
waitForBackendStartupReady({
listeningPromise: Promise.resolve(),
waitForHttpReady,
cancelHttpWait,
}),
).resolves.toBe("listening");
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
});
it("rejects when the listening signal fails before HTTP readiness", async () => {
const error = new Error("backend exited");
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
await expect(
waitForBackendStartupReady({
listeningPromise: Promise.reject(error),
waitForHttpReady,
cancelHttpWait: vi.fn(),
}),
).rejects.toBe(error);
});
});
@@ -0,0 +1,56 @@
import { isBackendReadinessAborted } from "./backendReadiness.ts";
export interface WaitForBackendStartupReadyOptions {
readonly listeningPromise?: Promise<void> | null;
readonly waitForHttpReady: () => Promise<void>;
readonly cancelHttpWait: () => void;
}
export async function waitForBackendStartupReady(
options: WaitForBackendStartupReadyOptions,
): Promise<"listening" | "http"> {
const httpReadyPromise = options.waitForHttpReady();
const listeningPromise = options.listeningPromise;
if (!listeningPromise) {
await httpReadyPromise;
return "http";
}
return await new Promise<"listening" | "http">((resolve, reject) => {
let settled = false;
const settleResolve = (source: "listening" | "http") => {
if (settled) {
return;
}
settled = true;
if (source === "listening") {
options.cancelHttpWait();
}
resolve(source);
};
const settleReject = (error: unknown) => {
if (settled) {
return;
}
settled = true;
reject(error);
};
listeningPromise.then(
() => settleResolve("listening"),
(error) => settleReject(error),
);
httpReadyPromise.then(
() => settleResolve("http"),
(error) => {
if (settled && isBackendReadinessAborted(error)) {
return;
}
settleReject(error);
},
);
});
}
+6 -1
View File
@@ -18,7 +18,7 @@ import {
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence";
} from "./clientPersistence.ts";
const tempDirectories: string[] = [];
@@ -52,6 +52,11 @@ const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
favorites: [],
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
+15 -2
View File
@@ -1,8 +1,13 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import {
ClientSettingsSchema,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { Predicate } from "effect";
import * as Schema from "effect/Schema";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
@@ -83,7 +88,15 @@ function toPersistedSavedEnvironmentRecord(
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
if (!raw) {
return null;
}
try {
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
} catch {
return null;
}
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
+1 -1
View File
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
+87 -4
View File
@@ -7,9 +7,11 @@ import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
} from "./desktopSettings.ts";
const tempDirectories: string[] = [];
@@ -27,7 +29,15 @@ function makeSettingsPath() {
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("persists and reloads the configured server exposure mode", () => {
@@ -35,10 +45,14 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath)).toEqual({
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
@@ -47,11 +61,32 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"network-accessible",
),
).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested nightly update channel", () => {
expect(
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"nightly",
),
).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
});
@@ -59,6 +94,54 @@ describe("desktopSettings", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("preserves an explicit stable choice on nightly builds", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
});
+45 -4
View File
@@ -1,15 +1,28 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
...DEFAULT_DESKTOP_SETTINGS,
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
};
}
export function setDesktopServerExposurePreference(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
@@ -22,23 +35,51 @@ export function setDesktopServerExposurePreference(
};
}
export function readDesktopSettings(settingsPath: string): DesktopSettings {
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
): DesktopSettings {
return {
...settings,
updateChannel: requestedChannel,
updateChannelConfiguredByUser: true,
};
}
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
try {
if (!FS.existsSync(settingsPath)) {
return DEFAULT_DESKTOP_SETTINGS;
return defaultSettings;
}
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
const parsedUpdateChannel =
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
? parsed.updateChannel
: null;
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && parsedUpdateChannel === "nightly");
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
};
} catch {
return DEFAULT_DESKTOP_SETTINGS;
return defaultSettings;
}
}
+231 -119
View File
@@ -18,12 +18,14 @@ import {
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions } from "electron";
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
import type {
ClientSettings,
DesktopTheme,
DesktopAppBranding,
DesktopServerExposureMode,
DesktopServerExposureState,
DesktopUpdateChannel,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
@@ -34,13 +36,14 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
} from "./desktopSettings.ts";
import {
readClientSettings,
readSavedEnvironmentRegistry,
@@ -49,13 +52,15 @@ import {
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
} from "./clientPersistence";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { resolveDesktopServerExposure } from "./serverExposure";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import { ServerListeningDetector } from "./serverListeningDetector";
} from "./clientPersistence.ts";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { resolveDesktopServerExposure } from "./serverExposure.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -67,8 +72,10 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
} from "./updateMachine.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
syncShellEnvironment();
@@ -80,9 +87,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -101,7 +110,11 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
});
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
@@ -116,8 +129,32 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
if (typeof rawOptions !== "object" || rawOptions === null) {
return undefined;
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return undefined;
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return undefined;
}
if (trimmedPath === "~") {
return OS.homedir();
}
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
return Path.join(OS.homedir(), trimmedPath.slice(2));
}
return Path.resolve(trimmedPath);
}
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
const TITLEBAR_HEIGHT = 40;
@@ -125,6 +162,35 @@ const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linu
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
for (const sourceItem of source) {
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
};
if (sourceItem.children) {
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
if (normalizedChildren.length === 0) {
continue;
}
normalizedItem.children = normalizedChildren;
}
normalizedItems.push(normalizedItem);
}
return normalizedItems;
}
type WindowTitleBarOptions = Pick<
BrowserWindowConstructorOptions,
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
@@ -156,7 +222,7 @@ let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
@@ -167,7 +233,11 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
createInitialDesktopUpdateState(
app.getVersion(),
desktopRuntimeInfo,
desktopSettings.updateChannel,
);
function logTimestamp(): string {
return new Date().toISOString();
@@ -391,51 +461,13 @@ function cancelBackendReadinessWait(): void {
}
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
});
const listeningPromise = backendListeningDetector?.promise;
if (!listeningPromise) {
await httpReadyPromise;
return "http";
}
return await new Promise<"listening" | "http">((resolve, reject) => {
let settled = false;
const settleResolve = (source: "listening" | "http") => {
if (settled) {
return;
}
settled = true;
if (source === "listening") {
cancelBackendReadinessWait();
}
resolve(source);
};
const settleReject = (error: unknown) => {
if (settled) {
return;
}
settled = true;
reject(error);
};
listeningPromise.then(
() => settleResolve("listening"),
(error) => settleReject(error),
);
httpReadyPromise.then(
() => settleResolve("http"),
(error) => {
if (settled && isBackendReadinessAborted(error)) {
return;
}
settleReject(error);
},
);
return await waitForBackendStartupReady({
listeningPromise: backendListeningDetector?.promise ?? null,
waitForHttpReady: () =>
waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
}),
cancelHttpWait: cancelBackendReadinessWait,
});
}
@@ -975,6 +1007,18 @@ function resolveResourcePath(fileName: string): string | null {
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
if (isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = Path.join(
ROOT_DIR,
"assets",
"dev",
"blueprint-macos-1024.png",
);
if (FS.existsSync(developmentDockIconPath)) {
return developmentDockIconPath;
}
}
return resolveResourcePath(`icon.${ext}`);
}
@@ -1074,6 +1118,26 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
emitUpdateState();
}
function createBaseUpdateState(
channel: DesktopUpdateChannel,
enabled: boolean,
): DesktopUpdateState {
return {
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo, channel),
enabled,
status: enabled ? "idle" : "disabled",
};
}
function applyAutoUpdaterChannel(channel: DesktopUpdateChannel): void {
autoUpdater.channel = channel;
autoUpdater.allowPrerelease = channel === "nightly";
autoUpdater.allowDowngrade = channel === "nightly";
console.info(
`[desktop-updater] Using update channel '${channel}' (allowPrerelease=${channel === "nightly"}, allowDowngrade=${channel === "nightly"}).`,
);
}
function shouldEnableAutoUpdates(): boolean {
const hasUpdateFeedConfig =
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
@@ -1193,11 +1257,7 @@ function configureAutoUpdater(): void {
}
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
if (!enabled) {
return;
}
@@ -1205,10 +1265,7 @@ function configureAutoUpdater(): void {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
// Keep alpha branding, but force all installs onto the stable update track.
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
applyAutoUpdaterChannel(desktopSettings.updateChannel);
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
@@ -1222,6 +1279,15 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
if (!doesVersionMatchDesktopUpdateChannel(info.version, updateState.channel)) {
console.info(
`[desktop-updater] Ignoring ${info.version} because it does not match the selected '${updateState.channel}' channel.`,
);
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
return;
}
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
@@ -1486,6 +1552,11 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
ipcMain.removeAllListeners(GET_APP_BRANDING_CHANNEL);
ipcMain.on(GET_APP_BRANDING_CHANNEL, (event) => {
event.returnValue = desktopAppBranding;
});
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
event.returnValue = {
@@ -1599,15 +1670,16 @@ function registerIpcHandlers(): void {
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
const openDialogOptions: OpenDialogOptions = {
properties: ["openDirectory", "createDirectory"],
...(defaultPath ? { defaultPath } : {}),
};
const result = owner
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
? await dialog.showOpenDialog(owner, openDialogOptions)
: await dialog.showOpenDialog(openDialogOptions);
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
@@ -1636,14 +1708,7 @@ function registerIpcHandlers(): void {
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
const normalizedItems = normalizeContextMenuItems(items);
if (normalizedItems.length === 0) {
return null;
}
@@ -1664,28 +1729,37 @@ function registerIpcHandlers(): void {
if (!window) return null;
return new Promise<string | null>((resolve) => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
const buildTemplate = (
entries: readonly ContextMenuItem[],
): MenuItemConstructorOptions[] => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children);
} else {
itemOption.click = () => resolve(item.id);
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
template.push(itemOption);
}
return template;
};
const menu = Menu.buildFromTemplate(template);
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
menu.popup({
window,
...popupPosition,
@@ -1713,6 +1787,43 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
ipcMain.removeHandler(UPDATE_SET_CHANNEL_CHANNEL);
ipcMain.handle(UPDATE_SET_CHANNEL_CHANNEL, async (_event, rawChannel: unknown) => {
if (rawChannel !== "latest" && rawChannel !== "nightly") {
throw new Error("Invalid desktop update channel input.");
}
if (updateCheckInFlight || updateDownloadInFlight || updateInstallInFlight) {
throw new Error("Cannot change update tracks while an update action is in progress.");
}
const nextChannel = rawChannel as DesktopUpdateChannel;
desktopSettings = setDesktopUpdateChannelPreference(desktopSettings, nextChannel);
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
if (nextChannel === updateState.channel) {
return updateState;
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(nextChannel, enabled));
if (!enabled || !updaterConfigured) {
return updateState;
}
applyAutoUpdaterChannel(nextChannel);
const allowDowngrade = autoUpdater.allowDowngrade;
// An explicit channel switch should allow the immediate nightly->stable rollback path.
autoUpdater.allowDowngrade = true;
try {
await checkForUpdates("channel-change");
} finally {
autoUpdater.allowDowngrade = allowDowngrade;
}
return updateState;
});
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
const result = await downloadAvailableUpdate();
@@ -1820,7 +1931,7 @@ function createWindow(): BrowserWindow {
title: APP_DISPLAY_NAME,
...getWindowTitleBarOptions(),
webPreferences: {
preload: Path.join(__dirname, "preload.js"),
preload: Path.join(__dirname, "preload.cjs"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
@@ -1888,16 +1999,17 @@ function createWindow(): BrowserWindow {
emitUpdateState();
});
let initialRevealScheduled = false;
const revealInitialWindow = () => {
if (initialRevealScheduled) {
return;
}
initialRevealScheduled = true;
revealWindow(window);
};
window.once("ready-to-show", revealInitialWindow);
// On Linux/Wayland with `show: false`, Electron's `ready-to-show` only
// fires after `show()` is called, deadlocking the standard "wait for
// ready, then show" pattern. Add `did-finish-load` as a Linux-only
// fallback so the window still surfaces once the renderer has loaded
// the page. Other platforms keep the no-flash `ready-to-show` path,
// since `did-finish-load` typically fires before the first paint there.
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
if (process.platform === "linux") {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => revealWindow(window));
if (isDevelopment) {
void window.loadURL(resolveDesktopDevServerUrl());
@@ -1972,9 +2084,9 @@ async function bootstrap(): Promise<void> {
if (isDevelopment) {
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
void waitForBackendHttpReady(backendHttpUrl)
.then(() => {
writeDesktopLogHeader("bootstrap backend ready");
void waitForBackendWindowReady(backendHttpUrl)
.then((source) => {
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
})
.catch((error) => {
if (isBackendReadinessAborted(error)) {
+11 -1
View File
@@ -9,9 +9,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -24,6 +26,13 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
@@ -44,7 +53,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
@@ -61,6 +70,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
describe("resolveDesktopRuntimeInfo", () => {
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { ServerListeningDetector } from "./serverListeningDetector";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
describe("ServerListeningDetector", () => {
it("resolves when the server logs the listening line", async () => {
+121 -3
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
@@ -148,7 +148,7 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
it("does nothing outside macOS and linux", () => {
it("does nothing on unsupported platforms", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
@@ -160,7 +160,7 @@ describe("syncShellEnvironment", () => {
}));
syncShellEnvironment(env, {
platform: "win32",
platform: "freebsd",
readEnvironment,
});
@@ -168,4 +168,122 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(() => ({
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
}));
const isWindowsCommandAvailable = vi.fn(() => true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
});
it("loads the PowerShell profile on Windows when node is not available", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile
? {
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
}
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
);
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
].join(";"),
);
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
expect(env.FNM_MULTISHELL_PATH).toBe(
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
);
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
2,
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
{ loadProfile: true },
);
});
it("preserves baseline Windows env when the profile probe fails", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
if (options?.loadProfile) {
throw new Error("profile load failed");
}
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
},
);
const isWindowsCommandAvailable = vi.fn(() => false);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(env.SSH_AUTH_SOCK).toBeUndefined();
});
});
+32 -2
View File
@@ -3,8 +3,18 @@ import {
mergePathEntries,
readPathFromLaunchctl,
readEnvironmentFromLoginShell,
ShellEnvironmentReader,
resolveWindowsEnvironment,
} from "@t3tools/shared/shell";
import type {
CommandAvailabilityOptions,
ShellEnvironmentReader,
WindowsShellEnvironmentReader,
} from "@t3tools/shared/shell";
type WindowsCommandAvailabilityChecker = (
command: string,
options?: CommandAvailabilityOptions,
) => boolean;
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
@@ -25,19 +35,39 @@ export function syncShellEnvironment(
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
readWindowsEnvironment?: WindowsShellEnvironmentReader;
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
readLaunchctlPath?: typeof readPathFromLaunchctl;
userShell?: string;
logWarning?: (message: string, error?: unknown) => void;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
const shellEnvironment: Partial<Record<string, string>> = {};
try {
if (platform === "win32") {
const repairedEnvironment = resolveWindowsEnvironment(env, {
...(options.readWindowsEnvironment
? { readEnvironment: options.readWindowsEnvironment }
: {}),
...(options.isWindowsCommandAvailable
? { commandAvailable: options.isWindowsCommandAvailable }
: {}),
});
for (const [key, value] of Object.entries(repairedEnvironment)) {
if (value !== undefined) {
env[key] = value;
}
}
return;
}
if (platform !== "darwin" && platform !== "linux") return;
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
try {
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import {
doesVersionMatchDesktopUpdateChannel,
isNightlyDesktopVersion,
resolveDefaultDesktopUpdateChannel,
} from "./updateChannels.ts";
describe("isNightlyDesktopVersion", () => {
it("detects packaged nightly versions", () => {
expect(isNightlyDesktopVersion("0.0.17-nightly.20260415.1")).toBe(true);
});
it("does not flag stable versions as nightly", () => {
expect(isNightlyDesktopVersion("0.0.17")).toBe(false);
});
});
describe("resolveDefaultDesktopUpdateChannel", () => {
it("defaults stable builds to latest", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17")).toBe("latest");
});
it("defaults nightly builds to nightly", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17-nightly.20260415.1")).toBe("nightly");
});
});
describe("doesVersionMatchDesktopUpdateChannel", () => {
it("accepts nightly releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "nightly")).toBe(true);
});
it("rejects stable releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17", "nightly")).toBe(false);
});
it("rejects nightly releases on the stable channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "latest")).toBe(false);
});
});
+18
View File
@@ -0,0 +1,18 @@
import type { DesktopUpdateChannel } from "@t3tools/contracts";
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
export function isNightlyDesktopVersion(version: string): boolean {
return NIGHTLY_VERSION_PATTERN.test(version);
}
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
}
export function doesVersionMatchDesktopUpdateChannel(
version: string,
channel: DesktopUpdateChannel,
): boolean {
return resolveDefaultDesktopUpdateChannel(version) === channel;
}
+8 -7
View File
@@ -11,7 +11,7 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
} from "./updateMachine.ts";
const runtimeInfo = {
hostArch: "x64",
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "error",
message: "network",
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "checking",
},
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "checking",
},
@@ -131,6 +131,7 @@ describe("updateMachine", () => {
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
+8 -2
View File
@@ -1,14 +1,20 @@
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateState,
} from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
channel: DesktopUpdateChannel,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
channel,
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
+2 -1
View File
@@ -6,11 +6,12 @@ import {
getAutoUpdateDisabledReason,
nextStatusAfterDownloadFailure,
shouldBroadcastDownloadProgress,
} from "./updateState";
} from "./updateState.ts";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
+74
View File
@@ -0,0 +1,74 @@
import { EventEmitter } from "node:events";
import { describe, expect, it, vi } from "vitest";
import { bindFirstRevealTrigger } from "./windowReveal.ts";
describe("bindFirstRevealTrigger", () => {
it("reveals when the first trigger fires", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
webContents.emit("did-finish-load");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("only reveals once when multiple triggers fire", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
webContents.emit("did-finish-load");
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("subscribers using `once` ignore re-emitted events after reveal", () => {
const window = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal);
window.emit("ready-to-show");
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
});
+28
View File
@@ -0,0 +1,28 @@
export type RevealSubscription = (listener: () => void) => void;
/**
* Wire a reveal callback to fire exactly once, on whichever of the provided
* event subscribers fires first. Each subscriber is responsible for binding
* its own event source.
*
* Used by the desktop main window's first-paint reveal logic. The standard
* Electron pattern is to wait for `ready-to-show` before calling `show()`,
* but on Linux/Wayland with `show: false`, `ready-to-show` only fires after
* `show()` is called, deadlocking that pattern. Subscribing to both
* `ready-to-show` and `did-finish-load` (or any other "renderer is alive"
* signal) lets the window surface reliably across platforms.
*/
export function bindFirstRevealTrigger(
subscribers: readonly RevealSubscription[],
reveal: () => void,
): void {
let revealed = false;
const fire = () => {
if (revealed) return;
revealed = true;
reveal();
};
for (const subscribe of subscribers) {
subscribe(fire);
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node", "electron"],
"lib": ["ES2023", "DOM", "esnext.disposable"]
"lib": ["ESNext", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
+2 -2
View File
@@ -4,7 +4,7 @@ const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
outExtensions: () => ({ js: ".cjs" }),
};
export default defineConfig([
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
},
{
...shared,
-41
View File
@@ -1,41 +0,0 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo
.expo/
dist/
web-build/
expo-env.d.ts
# Native
.kotlin/
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
# generated native folders
/ios
/android
-15
View File
@@ -1,15 +0,0 @@
- Expo Router for navigation
- / (Home, list of recent threads)
- /connections (Connections, list of connected environments)
- /connections/new (Add backend, QR code scanner, manual input)
- /new (New thread)
- /new (Sheet, select project)
- /draft (New thread, prompt, select model, environment, workspace etc)
These two is 2 pages in one sheet with sliding animation between them
- effect/rpc for typed rpc
- Uniwind?
- Theme it like the desktop app
- Share more code between web and mobile using @t3tools/client-runtime
- Make sure model list, options etc are server authorative and not hardcoded in the client
- Fix bug where sheet content doesn't scroll
- Allow pasting images into text input
-81
View File
@@ -1,81 +0,0 @@
{
"expo": {
"name": "T3 Code",
"slug": "t3-code",
"scheme": "t3code",
"version": "0.1.0",
"runtimeVersion": {
"policy": "appVersion"
},
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "automatic",
"updates": {
"enabled": true,
"url": "https://u.expo.dev/d763fcb8-d37c-41ea-a773-b54a0ab4a454",
"checkAutomatically": "ON_LOAD",
"fallbackToCacheTimeout": 0
},
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"ios": {
"icon": "./assets/icon.png",
"supportsTablet": true,
"bundleIdentifier": "com.t3tools.t3code",
"infoPlist": {
"NSAppTransportSecurity": {
"NSAllowsArbitraryLoads": true
},
"ITSAppUsesNonExemptEncryption": false
}
},
"android": {
"icon": "./assets/icon.png",
"package": "com.t3tools.t3code",
"adaptiveIcon": {
"backgroundColor": "#E6F4FE",
"foregroundImage": "./assets/android-icon-foreground.png",
"backgroundImage": "./assets/android-icon-background.png",
"monochromeImage": "./assets/android-icon-monochrome.png"
},
"predictiveBackGestureEnabled": false
},
"web": {
"favicon": "./assets/favicon.png"
},
"plugins": [
[
"expo-camera",
{
"cameraPermission": "Allow T3 Code to access your camera so you can scan pairing QR codes.",
"barcodeScannerEnabled": true
}
],
[
"expo-splash-screen",
{
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff",
"imageWidth": 220,
"dark": {
"image": "./assets/splash-icon.png",
"backgroundColor": "#0a0a0a"
}
}
],
"expo-secure-store",
"expo-router",
"./plugins/withAndroidCleartextTraffic.cjs"
],
"extra": {
"eas": {
"projectId": "d763fcb8-d37c-41ea-a773-b54a0ab4a454"
}
},
"owner": "pingdotgg"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

-6
View File
@@ -1,6 +0,0 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]],
};
};
-28
View File
@@ -1,28 +0,0 @@
{
"cli": {
"version": ">= 18.4.0",
"appVersionSource": "remote"
},
"build": {
"development": {
"channel": "development",
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"channel": "preview",
"distribution": "internal"
},
"production": {
"channel": "production",
"autoIncrement": true
}
},
"submit": {
"production": {
"ios": {
"ascAppId": "6761315631"
}
}
}
}
-192
View File
@@ -1,192 +0,0 @@
@import "tailwindcss";
@import "uniwind";
/* ─── Theme tokens ──────────────────────────────────────────────────── */
@layer theme {
:root {
@variant light {
/* Page backgrounds */
--color-screen: #f2f2f7;
--color-sheet: rgba(242, 242, 247, 0.98);
/* Card / surface */
--color-card: #ffffff;
--color-card-alt: #f5f5f5;
--color-card-translucent: rgba(255, 255, 255, 0.94);
/* Text */
--color-foreground: #262626;
--color-foreground-secondary: #525252;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #a3a3a3;
/* Borders & separators */
--color-border: rgba(0, 0, 0, 0.08);
--color-border-subtle: rgba(0, 0, 0, 0.06);
--color-separator: rgba(0, 0, 0, 0.04);
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(0, 0, 0, 0.04);
--color-subtle-strong: rgba(0, 0, 0, 0.08);
/* Primary action */
--color-primary: #262626;
--color-primary-foreground: #ffffff;
--color-primary-shadow: rgba(0, 0, 0, 0.18);
/* Secondary action */
--color-secondary: #ffffff;
--color-secondary-foreground: #262626;
--color-secondary-border: rgba(0, 0, 0, 0.08);
/* Danger */
--color-danger: #fef2f2;
--color-danger-border: rgba(239, 68, 68, 0.12);
--color-danger-foreground: #dc2626;
/* Inputs */
--color-input: #ffffff;
--color-input-border: rgba(0, 0, 0, 0.1);
--color-placeholder: #a3a3a3;
/* Icons */
--color-icon: #262626;
--color-icon-muted: #525252;
--color-icon-subtle: #a3a3a3;
/* Header / glass chrome */
--color-header: rgba(255, 255, 255, 0.97);
--color-header-border: rgba(0, 0, 0, 0.06);
/* StatusBar */
--color-status-bar: #f2f2f7;
/* Markdown */
--color-md-body: #262626;
--color-md-strong: #171717;
--color-md-link: #2563eb;
--color-md-blockquote-border: rgba(0, 0, 0, 0.08);
--color-md-blockquote-bg: rgba(0, 0, 0, 0.02);
--color-md-code-bg: rgba(0, 0, 0, 0.04);
--color-md-code-text: #262626;
--color-md-user-code-bg: rgba(255, 255, 255, 0.55);
--color-md-user-code-text: #262626;
--color-md-user-fence-bg: rgba(0, 0, 0, 0.04);
--color-md-user-fence-text: #1e3a5f;
--color-md-hr: rgba(0, 0, 0, 0.08);
/* Drawer / modal backdrop */
--color-backdrop: rgba(0, 0, 0, 0.22);
--color-drawer: rgba(255, 255, 255, 0.99);
--color-drawer-shadow: rgba(0, 0, 0, 0.12);
/* Misc */
--color-dot-separator: rgba(0, 0, 0, 0.2);
--color-wordmark: #262626;
--color-chevron: rgba(0, 0, 0, 0.2);
}
@variant dark {
/* Page backgrounds */
--color-screen: #0a0a0a;
--color-sheet: rgba(14, 14, 14, 0.98);
/* Card / surface */
--color-card: #171717;
--color-card-alt: #1c1c1c;
--color-card-translucent: rgba(17, 17, 17, 0.94);
/* Text */
--color-foreground: #f5f5f5;
--color-foreground-secondary: #a3a3a3;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #525252;
/* Borders & separators */
--color-border: rgba(255, 255, 255, 0.06);
--color-border-subtle: rgba(255, 255, 255, 0.04);
--color-separator: rgba(255, 255, 255, 0.03);
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(255, 255, 255, 0.04);
--color-subtle-strong: rgba(255, 255, 255, 0.08);
/* Primary action */
--color-primary: #f5f5f5;
--color-primary-foreground: #0a0a0a;
--color-primary-shadow: rgba(0, 0, 0, 0.22);
/* Secondary action */
--color-secondary: rgba(255, 255, 255, 0.04);
--color-secondary-foreground: #f5f5f5;
--color-secondary-border: rgba(255, 255, 255, 0.06);
/* Danger */
--color-danger: rgba(239, 68, 68, 0.14);
--color-danger-border: rgba(248, 113, 113, 0.18);
--color-danger-foreground: #fca5a5;
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-placeholder: #737373;
/* Icons */
--color-icon: #f5f5f5;
--color-icon-muted: #a3a3a3;
--color-icon-subtle: #737373;
/* Header / glass chrome */
--color-header: rgba(10, 10, 10, 0.97);
--color-header-border: rgba(255, 255, 255, 0.06);
/* StatusBar */
--color-status-bar: #0a0a0a;
/* Markdown */
--color-md-body: #e5e5e5;
--color-md-strong: #f5f5f5;
--color-md-link: #60a5fa;
--color-md-blockquote-border: rgba(255, 255, 255, 0.1);
--color-md-blockquote-bg: rgba(255, 255, 255, 0.03);
--color-md-code-bg: rgba(255, 255, 255, 0.06);
--color-md-code-text: #e5e5e5;
--color-md-user-code-bg: rgba(255, 255, 255, 0.1);
--color-md-user-code-text: #e5e5e5;
--color-md-user-fence-bg: rgba(255, 255, 255, 0.08);
--color-md-user-fence-text: #e5e5e5;
--color-md-hr: rgba(255, 255, 255, 0.08);
/* Drawer / modal backdrop */
--color-backdrop: rgba(0, 0, 0, 0.48);
--color-drawer: rgba(14, 14, 14, 0.99);
--color-drawer-shadow: rgba(0, 0, 0, 0.32);
/* Misc */
--color-dot-separator: rgba(255, 255, 255, 0.2);
--color-wordmark: #f5f5f5;
--color-chevron: rgba(255, 255, 255, 0.2);
}
}
}
/* ─── Font family ───────────────────────────────────────────────────── */
@theme {
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
}
/* ─── Custom utilities ──────────────────────────────────────────────── */
@utility font-t3-medium {
font-family: "DMSans_500Medium";
}
@utility font-t3-bold {
font-family: "DMSans_700Bold";
}
@utility font-t3-extrabold {
font-family: "DMSans_700Bold";
font-weight: 800;
}
-2
View File
@@ -1,2 +0,0 @@
import "react-native-gesture-handler";
import "expo-router/entry";
-14
View File
@@ -1,14 +0,0 @@
const path = require("node:path");
const { getDefaultConfig } = require("expo/metro-config");
const { withUniwindConfig } = require("uniwind/metro");
/** @type {import("expo/metro-config").MetroConfig} */
const config = getDefaultConfig(__dirname);
const workspaceRoot = path.resolve(__dirname, "../..");
config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
module.exports = withUniwindConfig(config, {
cssEntryFile: "./global.css",
polyfills: { rem: 14 },
});
-64
View File
@@ -1,64 +0,0 @@
{
"name": "@t3tools/mobile",
"version": "0.0.0",
"private": true,
"main": "index.ts",
"scripts": {
"dev": "expo start --clear",
"start": "expo start",
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"ios": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"web": "expo start --web",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@callstack/liquid-glass": "^0.7.1",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@legendapp/list": "3.0.0-beta.44",
"@react-native-menu/menu": "^2.0.0",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"clsx": "^2.1.1",
"effect": "catalog:",
"expo": "~55.0.14",
"expo-camera": "~55.0.15",
"expo-clipboard": "~55.0.9",
"expo-constants": "^55.0.9",
"expo-dev-client": "~55.0.26",
"expo-file-system": "~55.0.16",
"expo-font": "^55.0.4",
"expo-glass-effect": "~55.0.8",
"expo-haptics": "^55.0.9",
"expo-image-picker": "~55.0.14",
"expo-linking": "~55.0.12",
"expo-paste-input": "^0.1.15",
"expo-router": "~55.0.12",
"expo-secure-store": "~55.0.9",
"expo-splash-screen": "~55.0.13",
"expo-symbols": "~55.0.5",
"expo-updates": "~55.0.16",
"react": "19.2.5",
"react-dom": "19.2.5",
"react-native": "0.83.4",
"react-native-gesture-handler": "~2.30.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.20.7",
"react-native-nitro-markdown": "^0.5.3",
"react-native-nitro-modules": "^0.35.4",
"react-native-reanimated": "4.2.1",
"react-native-safe-area-context": "~5.6.2",
"react-native-screens": "~4.23.0",
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2"
},
"devDependencies": {
"@types/react": "~19.2.0",
"babel-preset-expo": "~55.0.8",
"tailwindcss": "^4.0.0",
"typescript": "catalog:"
}
}
@@ -1,18 +0,0 @@
const { withAndroidManifest } = require("expo/config-plugins");
module.exports = function withAndroidCleartextTraffic(config) {
return withAndroidManifest(config, (nextConfig) => {
const application = nextConfig.modResults.manifest.application?.[0];
if (application == null) {
throw new Error(
"AndroidManifest.xml is missing the application element required for cleartext traffic configuration.",
);
}
application.$ ??= {};
application.$["android:usesCleartextTraffic"] = "true";
return nextConfig;
});
};
-43
View File
@@ -1,43 +0,0 @@
import { Link } from "expo-router";
import { Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "../components/AppText";
export default function NotFoundRoute() {
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
gap: 16,
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-[28px] font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Link href="/" asChild>
<Pressable
style={[
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]}
>
<Text className="text-[16px] font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</Link>
</ScrollView>
);
}
-104
View File
@@ -1,104 +0,0 @@
import "../../global.css";
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import Stack from "expo-router/stack";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { useCSSVariable, useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import {
useRemoteEnvironmentBootstrap,
useRemoteEnvironmentState,
} from "../state/use-remote-environment-registry";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
function AppNavigator() {
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const colorScheme = useColorScheme();
const statusBarBg = useCSSVariable("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
const newTaskScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
};
const connectionSheetScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
};
if (isLoadingSavedConnection) {
return <LoadingScreen message="Loading remote workspace…" />;
}
return (
<>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={statusBarBg as string}
translucent
/>
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
<Stack.Screen name="new" options={newTaskScreenOptions} />
<Stack.Screen
name="threads/[environmentId]/[threadId]"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "transparent" },
gestureEnabled: true,
headerShown: false,
}}
/>
</Stack>
</>
);
}
export default function RootLayout() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
useRemoteEnvironmentBootstrap();
return (
<RegistryContext value={appAtomRegistry}>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? <AppNavigator /> : <LoadingScreen message="Loading remote workspace…" />}
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</RegistryContext>
);
}
@@ -1,30 +0,0 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function ConnectionsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const connSheetBg = String(useThemeColor("--color-sheet"));
const headerTint = String(useThemeColor("--color-icon"));
return (
<Stack
screenOptions={{
contentStyle,
headerStyle: { backgroundColor: connSheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
headerShadowVisible: false,
headerBackButtonDisplayMode: "minimal",
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
-102
View File
@@ -1,102 +0,0 @@
import { Link, Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
export default function ConnectionsRouteScreen() {
const {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<string | null>(null);
const primaryFg = useThemeColor("--color-primary-foreground");
const accentColor = useThemeColor("--color-icon-muted");
const handleToggle = useCallback((environmentId: string) => {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
}, []);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Backends",
headerRight: () => (
<Link href="/connections/new" asChild>
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary active:opacity-70">
<SymbolView
name="plus"
size={18}
tintColor={primaryFg}
type="monochrome"
weight="semibold"
/>
</Pressable>
</Link>
),
}}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
{hasEnvironments ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{connectedEnvironments.map((environment, index) => (
<View
key={environment.environmentId}
collapsable={false}
style={{
borderTopWidth: index === 0 ? 0 : 1,
}}
className={cn(index !== 0 && "border-border")}
>
<ConnectionEnvironmentRow
environment={environment}
expanded={expandedId === environment.environmentId}
onToggle={() => handleToggle(environment.environmentId)}
onReconnect={onReconnectEnvironment}
onRemove={onRemoveEnvironmentPress}
onUpdate={onUpdateEnvironment}
/>
</View>
))}
</View>
) : (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
<View className="h-12 w-12 items-center justify-center rounded-[16px] bg-subtle">
<SymbolView
name="point.3.connected.trianglepath.dotted"
size={20}
tintColor={accentColor}
type="monochrome"
/>
</View>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
No backends connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold text-foreground">+</Text> to add one.
</Text>
</View>
)}
</ScrollView>
</View>
);
}
-253
View File
@@ -1,253 +0,0 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useState } from "react";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
import { ConnectionSheetButton } from "../../features/connection/ConnectionSheetButton";
import { extractPairingUrlFromQrPayload } from "../../features/connection/pairing";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pairing";
export default function ConnectionsNewRouteScreen() {
const {
connectionError,
connectionPairingUrl,
connectionState,
onChangeConnectionPairingUrl,
onConnectPress,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
const insets = useSafeAreaInsets();
const [hostInput, setHostInput] = useState("");
const [codeInput, setCodeInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled =
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
useEffect(() => {
const { host, code } = parsePairingUrl(connectionPairingUrl);
setHostInput(host);
setCodeInput(code);
}, [connectionPairingUrl]);
useEffect(() => {
if (connectionError) {
setIsSubmitting(false);
}
}, [connectionError]);
const handleHostChange = useCallback((value: string) => {
setHostInput(value);
}, []);
const handleCodeChange = useCallback((value: string) => {
setCodeInput(value);
}, []);
const openScanner = useCallback(async () => {
if (cameraPermission?.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
const permission = await requestCameraPermission();
if (permission.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
}, [cameraPermission?.granted, requestCameraPermission]);
const closeScanner = useCallback(() => {
setShowScanner(false);
setScannerLocked(false);
}, []);
const handleQrScan = useCallback(
({ data }: { readonly data: string }) => {
if (scannerLocked) {
return;
}
setScannerLocked(true);
try {
const pairingUrl = extractPairingUrlFromQrPayload(data);
const { host, code } = parsePairingUrl(pairingUrl);
setHostInput(host);
setCodeInput(code);
onChangeConnectionPairingUrl(pairingUrl);
setShowScanner(false);
} catch (error) {
Alert.alert(
"Invalid QR code",
error instanceof Error ? error.message : "Scanned QR code was not recognized.",
);
} finally {
setTimeout(() => {
setScannerLocked(false);
}, 600);
}
},
[onChangeConnectionPairingUrl, scannerLocked],
);
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
dismissRoute(router);
} catch {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Backend",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
onPress={() => {
if (showScanner) {
closeScanner();
} else {
void openScanner();
}
}}
>
<SymbolView
name={showScanner ? "xmark" : "qrcode.viewfinder"}
size={showScanner ? 14 : 18}
tintColor={textColor}
type="monochrome"
weight="semibold"
/>
</Pressable>
),
}}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
<View collapsable={false} className="gap-5">
{showScanner ? (
cameraPermission?.granted ? (
<View
className="overflow-hidden rounded-[24px]"
style={{ borderCurve: "continuous" }}
>
<CameraView
barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
onBarcodeScanned={handleQrScan}
style={{ aspectRatio: 1, width: "100%" }}
/>
</View>
) : (
<View
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
<ConnectionSheetButton
compact
icon="camera"
label="Allow camera"
tone="secondary"
onPress={() => {
void openScanner();
}}
/>
</View>
)
) : (
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Host
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={hostInput}
onChangeText={handleHostChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Pairing code
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
placeholder="abc-123-xyz"
placeholderTextColor={placeholderColor}
value={codeInput}
onChangeText={handleCodeChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
{connectionError ? <ErrorBanner message={connectionError} /> : null}
<ConnectionSheetButton
icon="plus"
label={
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
}
disabled={connectDisabled}
tone="primary"
onPress={() => {
void handleSubmit();
}}
/>
</View>
)}
</View>
</ScrollView>
</View>
);
}
-139
View File
@@ -1,139 +0,0 @@
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { buildThreadRoutePath } from "../lib/routes";
import { ConnectionStatusDot } from "../features/connection/ConnectionStatusDot";
import { useRemoteCatalog } from "../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { EnvironmentConnectionState } from "@t3tools/client-runtime";
/* ─── Connection pill label ──────────────────────────────────────────── */
const CONNECTION_LABEL: Record<EnvironmentConnectionState, string> = {
ready: "Connected",
connecting: "Connecting",
reconnecting: "Reconnecting",
disconnected: "Offline",
idle: "No backends",
};
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const { connectionState, hasRemoteActivity, projects, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
return (
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerRight: () => (
<Pressable
onPress={() => router.push("/connections")}
hitSlop={8}
style={{
flexDirection: "row",
alignItems: "center",
gap: 8,
paddingHorizontal: 4,
paddingVertical: 4,
}}
>
<ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 12,
color: secondaryFg,
}}
>
{CONNECTION_LABEL[connectionState]}
</RNText>
</Pressable>
),
headerSearchBarOptions: {
placeholder: "Search threads",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
allowToolbarIntegration: true,
},
}}
/>
{/* Header left: plain text, no Liquid Glass button chrome */}
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 17,
color: iconColor,
letterSpacing: -0.4,
}}
>
T3 Code
</RNText>
<View
style={{
backgroundColor: isDark ? "rgba(255,255,255,0.04)" : "rgba(0,0,0,0.04)",
borderRadius: 99,
paddingHorizontal: 8,
paddingVertical: 3,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 10,
color: "#737373",
letterSpacing: 1.1,
textTransform: "uppercase",
}}
>
Alpha
</RNText>
</View>
</View>
</Stack.Toolbar.View>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
icon="square.and.pencil"
onPress={() => router.push("/new")}
separateBackground
/>
</Stack.Toolbar>
<HomeScreen
projects={projects}
threads={threads}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
/>
</>
);
}
-25
View File
@@ -1,25 +0,0 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
export const unstable_settings = {
anchor: "index",
};
export default function NewTaskLayout() {
const sheetStyle = useResolveClassNames("bg-sheet");
return (
<NewTaskFlowProvider>
<Stack
screenOptions={{
contentStyle: sheetStyle,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="draft" options={{ animation: "slide_from_right" }} />
</Stack>
</NewTaskFlowProvider>
);
}
-24
View File
@@ -1,24 +0,0 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen";
export default function NewTaskDraftRoute() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
projectId?: string | string[];
}>();
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<NewTaskDraftScreen
initialProjectRef={{
environmentId: Array.isArray(params.environmentId)
? params.environmentId[0]
: params.environmentId,
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
}}
/>
</>
);
}
-135
View File
@@ -1,135 +0,0 @@
import { Link, Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useMemo } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
export default function NewTaskRoute() {
const { projects, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const items = useMemo(
() =>
repositoryGroups
.map((group) => {
const project = group.projects[0]?.project;
if (!project) {
return null;
}
return {
environmentId: project.environmentId,
id: project.id,
key: group.key,
title: project.title,
workspaceRoot: project.workspaceRoot,
};
})
.filter((entry) => entry !== null),
[repositoryGroups],
);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ headerShown: false }} />
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Choose project</Text>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
{items.length === 0 ? (
<View collapsable={false} className="items-center rounded-[24px] bg-card px-6 py-8">
<Text className="text-[16px] font-medium text-foreground-muted">
Loading projects...
</Text>
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
return (
<Link
key={item.key}
href={{
pathname: "/new/draft",
params: {
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
},
}}
asChild
>
<Pressable
className="bg-card"
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: isFirst ? 0 : 1,
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: isLast ? 24 : 0,
borderBottomRightRadius: isLast ? 24 : 0,
}}
>
<View className="flex-row items-center justify-between gap-3">
<ProjectFavicon
size={22}
projectTitle={item.title}
httpBaseUrl={savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null}
workspaceRoot={item.workspaceRoot}
bearerToken={savedConnectionsById[item.environmentId]?.bearerToken ?? null}
/>
<View className="flex-1">
<Text className="text-[18px] font-t3-bold">{item.title}</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</View>
</Pressable>
</Link>
);
})}
</View>
)}
</ScrollView>
</View>
);
}
@@ -1,43 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export default function ThreadLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="git"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.85],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="git-confirm"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.4],
sheetGrabberVisible: true,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
export default function GitConfirmRoute() {
return <GitConfirmSheet />;
}
@@ -1,47 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export const unstable_settings = {
anchor: "index",
};
export default function GitSheetLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerShown: false,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="commit"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Commit changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="branches"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Branches & worktrees",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
export default function GitBranchesRoute() {
return <GitBranchesSheet />;
}
@@ -1,5 +0,0 @@
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
export default function GitCommitRoute() {
return <GitCommitSheet />;
}
@@ -1,5 +0,0 @@
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
export default function GitRoute() {
return <GitOverviewSheet />;
}
@@ -1,5 +0,0 @@
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
export default function ThreadRoute() {
return <ThreadRouteScreen />;
}
-40
View File
@@ -1,40 +0,0 @@
import {
Text as RNText,
TextInput as RNTextInput,
type TextInputProps as RNTextInputProps,
type TextProps as RNTextProps,
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
export type AppTextProps = RNTextProps & { readonly className?: string };
/**
* Thin wrapper around RN Text with default font-family and foreground color.
* Uses Uniwind className — no manual style parsing.
*/
export function AppText({ className, ...props }: AppTextProps) {
return <RNText className={cn("font-sans text-foreground", className)} {...props} />;
}
export type AppTextInputProps = RNTextInputProps & { readonly className?: string };
/**
* Thin wrapper around RN TextInput with default input styling.
* Uses Uniwind className — no manual style parsing.
*/
export function AppTextInput({ className, placeholderTextColor, ...props }: AppTextInputProps) {
const placeholderColor = useThemeColor("--color-placeholder");
return (
<RNTextInput
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-[15px] text-foreground",
className,
)}
placeholderTextColor={placeholderTextColor ?? placeholderColor}
{...props}
/>
);
}
-48
View File
@@ -1,48 +0,0 @@
import { Image, View } from "react-native";
import { AppText as Text } from "./AppText";
const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
const compact = props.compact ?? false;
const iconSize = compact ? 32 : 44;
const stageLabel = props.stageLabel ?? "Alpha";
return (
<View className="flex-row items-center gap-3">
<Image
source={BRAND_MARK_SOURCE}
accessibilityIgnoresInvertColors
style={{
width: iconSize,
height: iconSize,
borderRadius: compact ? 10 : 14,
}}
/>
<View className="gap-1">
<View className="flex-row items-center gap-2">
<Text
className="text-[17px] font-t3-bold text-foreground"
style={{ letterSpacing: -0.4 }}
>
T3 Code
</Text>
<View className="rounded-full bg-subtle px-2 py-1">
<Text
className="text-[10px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1.1 }}
>
{stageLabel}
</Text>
</View>
</View>
{!compact ? (
<Text className="text-[12px] font-medium text-foreground-muted">
Mobile control surface for your live coding environments
</Text>
) : null}
</View>
</View>
);
}
@@ -1,85 +0,0 @@
import { SymbolView } from "expo-symbols";
import { Image, Pressable, ScrollView, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
export interface ComposerAttachmentStripProps {
/** Attachment images to display. */
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
/** Called when the user taps the remove button on an image. */
readonly onRemove: (imageId: string) => void;
/** Called when the user taps on an image thumbnail to preview it. */
readonly onPressImage?: (previewUri: string) => void;
/** Image thumbnail size in points. Defaults to 72. */
readonly imageSize?: number;
/** Border radius of each image thumbnail. Defaults to 16. */
readonly imageBorderRadius?: number;
}
/**
* A horizontally-scrollable strip of image attachment thumbnails with remove
* buttons. Used by both the thread composer and the new-task draft screen.
*/
export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
const subtleBg = useThemeColor("--color-subtle");
const size = props.imageSize ?? 72;
const radius = props.imageBorderRadius ?? 16;
if (props.attachments.length === 0) {
return null;
}
return (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps="always"
style={{ flexGrow: 0 }}
>
<View style={{ flexDirection: "row", gap: 10 }}>
{props.attachments.map((image) => (
<View key={image.id} style={{ position: "relative" }}>
<Pressable
onPress={props.onPressImage ? () => props.onPressImage!(image.previewUri) : undefined}
>
<Image
source={{ uri: image.previewUri }}
style={{
width: size,
height: size,
borderRadius: radius,
backgroundColor: subtleBg,
}}
resizeMode="cover"
/>
</Pressable>
<Pressable
style={{
position: "absolute",
top: 4,
right: 4,
width: 22,
height: 22,
borderRadius: 11,
backgroundColor: "rgba(0,0,0,0.55)",
alignItems: "center",
justifyContent: "center",
}}
hitSlop={6}
onPress={() => props.onRemove(image.id)}
>
<SymbolView
name="xmark"
size={9}
tintColor="#ffffff"
type="monochrome"
weight="bold"
/>
</Pressable>
</View>
))}
</View>
</ScrollView>
);
}
@@ -1,67 +0,0 @@
import type { ComponentProps, ReactNode } from "react";
import { Pressable, View } from "react-native";
import { SymbolView } from "expo-symbols";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
import { AppText as Text } from "./AppText";
export function ControlPill(props: {
readonly icon?: ComponentProps<typeof SymbolView>["name"];
readonly iconNode?: ReactNode;
readonly label?: string;
readonly onPress?: () => void;
readonly variant?: "circle" | "pill" | "primary" | "danger";
readonly disabled?: boolean;
}) {
const variant = props.variant ?? "circle";
const iconColor = useThemeColor("--color-icon");
const iconSubtle = useThemeColor("--color-icon-subtle");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const iconTintColor =
variant === "primary"
? props.disabled
? iconSubtle
: primaryFg
: variant === "danger"
? dangerFg
: iconColor;
const isCircle =
variant === "circle" || variant === "danger" || (variant === "primary" && !props.label);
const containerClassName = cn(
isCircle
? "h-11 w-11 items-center justify-center rounded-full"
: variant === "primary"
? "h-11 flex-row items-center justify-center gap-2 rounded-full px-5"
: "h-11 flex-row items-center justify-center gap-2 rounded-full px-3.5",
variant === "primary"
? props.disabled
? "bg-subtle-strong"
: "bg-primary"
: variant === "danger"
? "bg-danger"
: "bg-subtle",
);
const labelClassName = cn(
"text-center text-[12px] font-t3-bold",
variant === "primary"
? props.disabled
? "text-foreground-muted"
: "text-primary-foreground"
: "",
);
return (
<Pressable onPress={props.onPress} disabled={props.disabled} className={containerClassName}>
{props.iconNode ? (
<View className="h-4 w-4 items-center justify-center">{props.iconNode}</View>
) : props.icon ? (
<SymbolView name={props.icon} size={16} tintColor={iconTintColor} type="monochrome" />
) : null}
{props.label ? <Text className={labelClassName}>{props.label}</Text> : null}
</Pressable>
);
}
-14
View File
@@ -1,14 +0,0 @@
import { View } from "react-native";
import { AppText as Text } from "./AppText";
export function EmptyState(props: { readonly title: string; readonly detail: string }) {
return (
<View className="rounded-[22px] border border-border bg-card p-5">
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
{props.detail}
</Text>
</View>
);
}
@@ -1,12 +0,0 @@
import { View } from "react-native";
import { AppText as Text } from "./AppText";
export function ErrorBanner(props: { readonly message: string }) {
return (
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
<Text className="font-t3-medium text-[13px] leading-[18px] text-rose-700 dark:text-rose-300">
{props.message}
</Text>
</View>
);
}
@@ -1,59 +0,0 @@
import type { ReactNode } from "react";
import { useColorScheme, View, type StyleProp, type ViewStyle } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { GlassSurface } from "./GlassSurface";
export interface GlassSafeAreaViewProps {
readonly leftSlot?: ReactNode;
readonly centerSlot?: ReactNode;
readonly rightSlot?: ReactNode;
readonly style?: StyleProp<ViewStyle>;
}
export function GlassSafeAreaView({
leftSlot,
centerSlot,
rightSlot,
style,
}: GlassSafeAreaViewProps) {
const isDarkMode = useColorScheme() === "dark";
const insets = useSafeAreaInsets();
const headerPaddingTop = insets.top + 16;
const surfaceStyle = {
borderRadius: 0,
backgroundColor: isDarkMode ? "rgba(10,10,10,0.97)" : "rgba(255,255,255,0.97)",
borderBottomWidth: 1,
borderBottomColor: isDarkMode ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",
} as const;
return (
<View style={[surfaceStyle, style]}>
<GlassSurface
chrome="none"
glassEffectStyle="regular"
tintColor={isDarkMode ? "rgba(15,23,42,0.24)" : "rgba(255,255,255,0.18)"}
style={{ borderRadius: 0, backgroundColor: "transparent" }}
>
<View
style={{
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 20,
paddingTop: headerPaddingTop,
paddingBottom: 16,
gap: 10,
}}
>
<View style={{ alignItems: "flex-start", justifyContent: "center" }}>{leftSlot}</View>
<View
style={{ flex: 1, alignItems: "center", justifyContent: "center", overflow: "hidden" }}
>
{centerSlot}
</View>
<View style={{ alignItems: "flex-end", justifyContent: "center" }}>{rightSlot}</View>
</View>
</GlassSurface>
</View>
);
}
@@ -1,73 +0,0 @@
import { GlassView, isGlassEffectAPIAvailable } from "expo-glass-effect";
import type { ReactNode } from "react";
import { Platform, useColorScheme, View, type ViewProps, type ViewStyle } from "react-native";
export interface GlassSurfaceProps extends ViewProps {
readonly children: ReactNode;
readonly glassEffectStyle?: "clear" | "regular" | "none";
readonly tintColor?: string;
readonly chrome?: "default" | "none";
}
export function GlassSurface({
children,
glassEffectStyle = "regular",
chrome = "default",
tintColor,
style,
...props
}: GlassSurfaceProps) {
const isDarkMode = useColorScheme() === "dark";
const supportsGlass = Platform.OS === "ios" && isGlassEffectAPIAvailable();
const surfaceStyle: ViewStyle = {
borderRadius: 32,
overflow: "hidden",
borderWidth: chrome === "none" ? 0 : 1,
borderColor:
chrome === "none"
? "transparent"
: isDarkMode
? "rgba(255,255,255,0.08)"
: "rgba(226,232,240,0.9)",
backgroundColor:
chrome === "none"
? "transparent"
: isDarkMode
? "rgba(15,23,42,0.78)"
: "rgba(255,255,255,0.72)",
shadowColor: chrome === "none" ? "transparent" : "#020617",
shadowOpacity: chrome === "none" ? 0 : isDarkMode ? 0.22 : 0.08,
shadowRadius: chrome === "none" ? 0 : 28,
shadowOffset:
chrome === "none"
? {
width: 0,
height: 0,
}
: {
width: 0,
height: 14,
},
elevation: chrome === "none" ? 0 : 12,
};
if (supportsGlass) {
return (
<GlassView
{...props}
glassEffectStyle={glassEffectStyle}
tintColor={tintColor ?? (isDarkMode ? "rgba(15,23,42,0.18)" : "rgba(255,255,255,0.18)")}
colorScheme={isDarkMode ? "dark" : "light"}
style={[surfaceStyle, style]}
>
{children}
</GlassView>
);
}
return (
<View {...props} style={[surfaceStyle, style]}>
{children}
</View>
);
}
@@ -1,27 +0,0 @@
import { ActivityIndicator, StatusBar, View, useColorScheme } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../lib/useThemeColor";
import { AppText as Text } from "./AppText";
import { BrandMark } from "./BrandMark";
export function LoadingScreen(props: { readonly message: string }) {
const colorScheme = useColorScheme();
const screenBg = useThemeColor("--color-screen");
const insets = useSafeAreaInsets();
return (
<View className="flex-1 bg-screen" style={{ paddingTop: insets.top }}>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={screenBg as string}
translucent
/>
<View className="flex-1 items-center justify-center gap-5 px-6">
<BrandMark compact />
<ActivityIndicator size="large" />
<Text className="font-t3-bold text-lg text-foreground">{props.message}</Text>
</View>
</View>
);
}
@@ -1,70 +0,0 @@
import { SymbolView } from "expo-symbols";
import { useState } from "react";
import { Image, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
const loadedFaviconUrls = new Set<string>();
/* ─── Component ──────────────────────────────────────────────────────── */
export function ProjectFavicon(props: {
readonly size?: number;
readonly projectTitle: string;
readonly httpBaseUrl?: string | null;
readonly workspaceRoot?: string | null;
readonly bearerToken?: string | null;
}) {
const size = props.size ?? 42;
const iconMuted = useThemeColor("--color-icon-subtle");
const faviconUrl =
props.httpBaseUrl && props.workspaceRoot
? `${props.httpBaseUrl}/api/project-favicon?cwd=${encodeURIComponent(props.workspaceRoot)}`
: null;
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
faviconUrl && loadedFaviconUrls.has(faviconUrl) ? "loaded" : "loading",
);
const showImage = faviconUrl && status === "loaded";
return (
<View
style={{
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
}}
>
{/* Folder icon fallback (matches web's FolderIcon) */}
{!showImage ? (
<SymbolView name="folder.fill" size={size * 0.78} tintColor={iconMuted} type="monochrome" />
) : null}
{/* Favicon image (hidden until loaded) */}
{faviconUrl ? (
<Image
source={{
uri: faviconUrl,
...(props.bearerToken
? { headers: { Authorization: `Bearer ${props.bearerToken}` } }
: {}),
}}
style={{
width: size,
height: size,
borderRadius: size * 0.16,
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
}}
resizeMode="contain"
onLoad={() => {
if (faviconUrl) loadedFaviconUrls.add(faviconUrl);
setStatus("loaded");
}}
onError={() => setStatus("error")}
/>
) : null}
</View>
);
}
@@ -1,32 +0,0 @@
import { useColorScheme } from "react-native";
import { Path, Svg } from "react-native-svg";
type ProviderIconProps = {
readonly provider: string | null | undefined;
readonly size?: number;
};
export function ProviderIcon(props: ProviderIconProps) {
const isDarkMode = useColorScheme() === "dark";
const size = props.size ?? 16;
if (props.provider === "claudeAgent") {
return (
<Svg width={size} height={size} viewBox="0 0 256 257" fill="none">
<Path
fill="#D97757"
d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"
/>
</Svg>
);
}
return (
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
<Path
fill={isDarkMode ? "#e2e8f0" : "#171717"}
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
/>
</Svg>
);
}
-37
View File
@@ -1,37 +0,0 @@
import { View } from "react-native";
import { AppText as Text } from "./AppText";
import { cn } from "../lib/cn";
export interface StatusTone {
readonly label: string;
readonly pillClassName: string;
readonly textClassName: string;
}
export function StatusPill(
props: StatusTone & {
readonly size?: "default" | "compact";
},
) {
const size = props.size ?? "default";
return (
<View
className={cn(
"rounded-full",
size === "compact" ? "px-2.5 py-1" : "px-3 py-1.5",
props.pillClassName,
)}
>
<Text
className={cn(
"font-t3-bold",
size === "compact" ? "text-[11px]" : "text-xs",
props.textClassName,
)}
>
{props.label}
</Text>
</View>
);
}
@@ -1,157 +0,0 @@
import { SymbolView } from "expo-symbols";
import { useCallback, useState } from "react";
import { Pressable, View } from "react-native";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
export function ConnectionEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly expanded: boolean;
readonly onToggle: () => void;
readonly onReconnect: (environmentId: string) => void;
readonly onRemove: (environmentId: string) => void;
readonly onUpdate: (
environmentId: string,
updates: { readonly label: string; readonly displayUrl: string },
) => void;
}) {
const [label, setLabel] = useState(props.environment.environmentLabel);
const [url, setUrl] = useState(props.environment.displayUrl);
const mutedColor = useThemeColor("--color-icon-subtle");
const placeholderColor = useThemeColor("--color-placeholder");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const handleSave = useCallback(() => {
props.onUpdate(props.environment.environmentId, {
label: label.trim(),
displayUrl: url.trim(),
});
props.onToggle();
}, [label, url, props]);
return (
<Animated.View layout={LinearTransition.duration(250)} className="bg-card">
<Pressable
className="flex-row items-center gap-3 px-4 py-3.5 active:opacity-70"
onPress={props.onToggle}
>
<ConnectionStatusDot state={props.environment.connectionState} pulse={false} size={8} />
<View className="flex-1 gap-0.5">
<Text
className="text-[16px] font-t3-bold leading-[21px] text-foreground"
numberOfLines={1}
>
{props.environment.environmentLabel}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{props.environment.displayUrl}
</Text>
{props.environment.connectionError ? (
<Text
className="text-[12px] leading-[16px] text-rose-500 dark:text-rose-400"
numberOfLines={2}
>
{props.environment.connectionError}
</Text>
) : null}
</View>
<SymbolView
name="chevron.down"
size={12}
tintColor={mutedColor}
type="monochrome"
style={{
transform: [{ rotate: props.expanded ? "180deg" : "0deg" }],
}}
/>
</Pressable>
{props.expanded ? (
<Animated.View
entering={FadeIn.duration(200)}
exiting={FadeOut.duration(150)}
className="gap-3 px-4 pb-4"
>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Label
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
URL
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="flex-row gap-2">
<Pressable
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"
onPress={handleSave}
>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text
className="text-[12px] font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
>
Save
</Text>
</Pressable>
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70"
onPress={() => props.onReconnect(props.environment.environmentId)}
>
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={mutedColor}
type="monochrome"
/>
</Pressable>
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-danger-border bg-danger active:opacity-70"
onPress={() => props.onRemove(props.environment.environmentId)}
>
<SymbolView name="trash" size={14} tintColor={dangerFg} type="monochrome" />
</Pressable>
</View>
</Animated.View>
) : null}
</Animated.View>
);
}
@@ -1,92 +0,0 @@
import { SymbolView } from "expo-symbols";
import { Platform, Pressable } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
export function ConnectionSheetButton(props: {
readonly icon: React.ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly disabled?: boolean;
readonly tone?: "primary" | "secondary" | "danger";
readonly compact?: boolean;
readonly onPress: () => void;
}) {
const tone = props.tone ?? "secondary";
const primaryBg = useThemeColor("--color-primary");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerBg = useThemeColor("--color-danger");
const dangerBorderColor = useThemeColor("--color-danger-border");
const dangerFg = useThemeColor("--color-danger-foreground");
const secondaryBg = useThemeColor("--color-secondary");
const secondaryFg = useThemeColor("--color-secondary-foreground");
const borderColor = useThemeColor("--color-border");
const colors =
tone === "primary"
? {
backgroundColor: primaryBg,
borderColor: "transparent",
textColor: primaryFg,
}
: tone === "danger"
? {
backgroundColor: dangerBg,
borderColor: dangerBorderColor,
textColor: dangerFg,
}
: {
backgroundColor: secondaryBg,
borderColor: borderColor,
textColor: secondaryFg,
};
const primaryShadow =
tone === "primary"
? Platform.select({
ios: {
shadowColor: "#000",
shadowOffset: { width: 0, height: 3 },
shadowOpacity: 0.14,
shadowRadius: 6,
},
android: { elevation: 3 },
})
: undefined;
return (
<Pressable
className={cn(
props.compact
? "min-h-[42px] flex-row items-center justify-center gap-1.5 rounded-[14px] px-3.5 py-2.5"
: "min-h-[48px] flex-row items-center justify-center gap-2 rounded-[16px] px-4 py-3",
)}
disabled={props.disabled}
onPress={props.onPress}
style={[
{
backgroundColor: colors.backgroundColor,
borderWidth: tone === "primary" ? 0 : 1,
borderColor: colors.borderColor,
opacity: props.disabled ? 0.5 : 1,
},
primaryShadow,
]}
>
<SymbolView
name={props.icon}
size={props.compact ? 13 : 14}
tintColor={colors.textColor}
type="monochrome"
/>
<Text
className="text-[12px] font-t3-bold uppercase"
style={{ color: colors.textColor, letterSpacing: 0.8 }}
>
{props.label}
</Text>
</Pressable>
);
}
@@ -1,112 +0,0 @@
import { useEffect } from "react";
import { View } from "react-native";
import Animated, {
cancelAnimation,
Easing,
useAnimatedStyle,
useSharedValue,
withRepeat,
withTiming,
} from "react-native-reanimated";
import type { RemoteClientConnectionState } from "../../lib/connection";
function statusDotTone(state: RemoteClientConnectionState): {
readonly dotColor: string;
readonly haloColor: string;
} {
switch (state) {
case "ready":
return {
dotColor: "#34d399",
haloColor: "rgba(52,211,153,0.48)",
};
case "connecting":
case "reconnecting":
return {
dotColor: "#f59e0b",
haloColor: "rgba(245,158,11,0.5)",
};
case "idle":
case "disconnected":
return {
dotColor: "#ef4444",
haloColor: "rgba(239,68,68,0.48)",
};
}
}
function usePulseAnimation(pulse: boolean) {
const pulseProgress = useSharedValue(0);
useEffect(() => {
if (pulse) {
pulseProgress.value = withRepeat(
withTiming(1, {
duration: 1100,
easing: Easing.out(Easing.cubic),
}),
-1,
false,
);
return;
}
cancelAnimation(pulseProgress);
pulseProgress.value = withTiming(0, {
duration: 180,
easing: Easing.out(Easing.quad),
});
}, [pulse, pulseProgress]);
return pulseProgress;
}
export function ConnectionStatusDot(props: {
readonly state: RemoteClientConnectionState;
readonly pulse: boolean;
readonly size?: number;
}) {
const pulseProgress = usePulseAnimation(props.pulse);
const tone = statusDotTone(props.state);
const dotSize = props.size ?? 10;
const haloSize = dotSize + 4;
const containerSize = haloSize + 4;
const haloStyle = useAnimatedStyle(() => ({
opacity: props.pulse ? 0.14 + (1 - pulseProgress.value) * 0.3 : 0,
transform: [{ scale: 0.78 + pulseProgress.value * 1.16 }],
}));
return (
<View
style={{
width: containerSize,
height: containerSize,
alignItems: "center",
justifyContent: "center",
}}
>
<Animated.View
style={[
haloStyle,
{
position: "absolute",
width: haloSize,
height: haloSize,
borderRadius: haloSize / 2,
backgroundColor: tone.haloColor,
},
]}
/>
<View
style={{
width: dotSize,
height: dotSize,
borderRadius: dotSize / 2,
backgroundColor: tone.dotColor,
}}
/>
</View>
);
}
@@ -1,253 +0,0 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useState } from "react";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
import { ConnectionSheetButton } from "./ConnectionSheetButton";
import { extractPairingUrlFromQrPayload } from "./pairing";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { buildPairingUrl, parsePairingUrl } from "./pairing";
export function NewConnectionRouteScreen() {
const {
connectionError,
connectionPairingUrl,
connectionState,
onChangeConnectionPairingUrl,
onConnectPress,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
const insets = useSafeAreaInsets();
const [hostInput, setHostInput] = useState("");
const [codeInput, setCodeInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled =
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
useEffect(() => {
const { host, code } = parsePairingUrl(connectionPairingUrl);
setHostInput(host);
setCodeInput(code);
}, [connectionPairingUrl]);
useEffect(() => {
if (connectionError) {
setIsSubmitting(false);
}
}, [connectionError]);
const handleHostChange = useCallback((value: string) => {
setHostInput(value);
}, []);
const handleCodeChange = useCallback((value: string) => {
setCodeInput(value);
}, []);
const openScanner = useCallback(async () => {
if (cameraPermission?.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
const permission = await requestCameraPermission();
if (permission.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
}, [cameraPermission?.granted, requestCameraPermission]);
const closeScanner = useCallback(() => {
setShowScanner(false);
setScannerLocked(false);
}, []);
const handleQrScan = useCallback(
({ data }: { readonly data: string }) => {
if (scannerLocked) {
return;
}
setScannerLocked(true);
try {
const pairingUrl = extractPairingUrlFromQrPayload(data);
const { host, code } = parsePairingUrl(pairingUrl);
setHostInput(host);
setCodeInput(code);
onChangeConnectionPairingUrl(pairingUrl);
setShowScanner(false);
} catch (error) {
Alert.alert(
"Invalid QR code",
error instanceof Error ? error.message : "Scanned QR code was not recognized.",
);
} finally {
setTimeout(() => {
setScannerLocked(false);
}, 600);
}
},
[onChangeConnectionPairingUrl, scannerLocked],
);
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
dismissRoute(router);
} catch {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Backend",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
onPress={() => {
if (showScanner) {
closeScanner();
} else {
void openScanner();
}
}}
>
<SymbolView
name={showScanner ? "xmark" : "qrcode.viewfinder"}
size={showScanner ? 14 : 18}
tintColor={textColor}
type="monochrome"
weight="semibold"
/>
</Pressable>
),
}}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
<View collapsable={false} className="gap-5">
{showScanner ? (
cameraPermission?.granted ? (
<View
className="overflow-hidden rounded-[24px]"
style={{ borderCurve: "continuous" }}
>
<CameraView
barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
onBarcodeScanned={handleQrScan}
style={{ aspectRatio: 1, width: "100%" }}
/>
</View>
) : (
<View
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
<ConnectionSheetButton
compact
icon="camera"
label="Allow camera"
tone="secondary"
onPress={() => {
void openScanner();
}}
/>
</View>
)
) : (
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Host
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={hostInput}
onChangeText={handleHostChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Pairing code
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
placeholder="abc-123-xyz"
placeholderTextColor={placeholderColor}
value={codeInput}
onChangeText={handleCodeChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
{connectionError ? <ErrorBanner message={connectionError} /> : null}
<ConnectionSheetButton
icon="plus"
label={
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
}
disabled={connectDisabled}
tone="primary"
onPress={() => {
void handleSubmit();
}}
/>
</View>
)}
</View>
</ScrollView>
</View>
);
}
@@ -1,37 +0,0 @@
import type { StatusTone } from "../../components/StatusPill";
import type { RemoteClientConnectionState } from "../../lib/connection";
export function connectionTone(state: RemoteClientConnectionState): StatusTone {
switch (state) {
case "ready":
return {
label: "Connected",
pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16",
textClassName: "text-emerald-700 dark:text-emerald-300",
};
case "reconnecting":
return {
label: "Reconnecting",
pillClassName: "bg-amber-500/12 dark:bg-amber-500/16",
textClassName: "text-amber-700 dark:text-amber-300",
};
case "connecting":
return {
label: "Connecting",
pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
textClassName: "text-sky-700 dark:text-sky-300",
};
case "disconnected":
return {
label: "Disconnected",
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
textClassName: "text-rose-700 dark:text-rose-300",
};
case "idle":
return {
label: "Idle",
pillClassName: "bg-neutral-500/10 dark:bg-neutral-500/16",
textClassName: "text-neutral-600 dark:text-neutral-300",
};
}
}
@@ -1,25 +0,0 @@
import { describe, expect, it } from "vitest";
import { extractPairingUrlFromQrPayload } from "./pairing";
describe("extractPairingUrlFromQrPayload", () => {
it("trims raw pairing urls from qr payloads", () => {
expect(
extractPairingUrlFromQrPayload(" https://remote.example.com/pair#token=pairing-token "),
).toBe("https://remote.example.com/pair#token=pairing-token");
});
it("unwraps mobile deep links that carry an encoded pairing url", () => {
expect(
extractPairingUrlFromQrPayload(
"t3code://pair?pairingUrl=https%3A%2F%2Fremote.example.com%2Fpair%23token%3Dpairing-token",
),
).toBe("https://remote.example.com/pair#token=pairing-token");
});
it("rejects empty qr payloads", () => {
expect(() => extractPairingUrlFromQrPayload(" ")).toThrow(
"Scanned QR code did not contain a pairing URL.",
);
});
});
@@ -1,57 +0,0 @@
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
export function buildPairingUrl(host: string, code: string): string {
const h = host.trim();
const c = code.trim();
if (!h) return "";
if (!c) return h;
try {
const url = new URL(h.includes("://") ? h : `https://${h}`);
url.hash = new URLSearchParams([["token", c]]).toString();
return url.toString();
} catch {
return `${h}#token=${c}`;
}
}
export function parsePairingUrl(url: string): { host: string; code: string } {
const trimmed = url.trim();
if (!trimmed) return { host: "", code: "" };
try {
const parsed = new URL(trimmed);
const hashParams = new URLSearchParams(parsed.hash.slice(1));
const hashToken = hashParams.get("token");
const queryToken = parsed.searchParams.get("token");
const code = hashToken || queryToken || "";
parsed.hash = "";
parsed.search = "";
parsed.pathname = "/";
return { host: parsed.toString().replace(/\/$/, ""), code };
} catch {
return { host: trimmed, code: "" };
}
}
export function extractPairingUrlFromQrPayload(payload: string): string {
const trimmed = payload.trim();
if (!trimmed) {
throw new Error("Scanned QR code did not contain a pairing URL.");
}
try {
const url = new URL(trimmed);
if (url.protocol === "t3code:") {
const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? "";
if (pairingUrl.length > 0) {
return pairingUrl;
}
}
} catch {
// Treat non-URL payloads as raw pairing-url text so the normal input validation can decide.
}
return trimmed;
}
@@ -1,346 +0,0 @@
import type {
EnvironmentScopedProjectShell,
EnvironmentScopedThreadShell,
GitStatusState,
} from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { useGitStatus } from "../../state/use-git-status";
import { threadStatusTone } from "../threads/threadPresentation";
/* ─── Types ──────────────────────────────────────────────────────────── */
interface HomeScreenProps {
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string;
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
}
interface ProjectGroup {
readonly key: string;
readonly project: EnvironmentScopedProjectShell;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
}
/* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: string } {
switch (thread.session?.status) {
case "running":
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
case "ready":
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
case "starting":
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
case "error":
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
default:
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
}
}
const COLLAPSED_THREAD_LIMIT = 6;
/* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: {
readonly project: EnvironmentScopedProjectShell;
readonly totalThreadCount: number;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
}) {
const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
return (
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
size={18}
projectTitle={props.project.title}
httpBaseUrl={props.httpBaseUrl}
workspaceRoot={props.project.workspaceRoot}
bearerToken={props.bearerToken}
/>
<Text
className="flex-1 text-[13px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.6 }}
numberOfLines={1}
>
{props.project.title}
</Text>
{hiddenCount > 0 ? (
<Pressable onPress={props.onToggleExpand} hitSlop={8}>
<Text
className="text-[13px] font-t3-bold text-foreground-muted"
style={{ letterSpacing: 0.6 }}
>
{props.isExpanded ? "Show less" : `${hiddenCount} more`}
</Text>
</Pressable>
) : null}
</View>
);
}
/* ─── Git summary line ──────────────────────────────────────────────── */
function gitSummaryParts(gitStatus: GitStatusState): ReadonlyArray<string> {
if (!gitStatus.data) return [];
const { data } = gitStatus;
const parts: string[] = [];
if (data.hasWorkingTreeChanges) {
parts.push(`${data.workingTree.files.length} changed`);
}
if (data.aheadCount > 0) parts.push(`${data.aheadCount} ahead`);
if (data.behindCount > 0) parts.push(`${data.behindCount} behind`);
if (data.pr?.state === "open") parts.push(`PR #${data.pr.number}`);
return parts;
}
/* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: {
readonly thread: EnvironmentScopedThreadShell;
readonly projectCwd: string | null;
readonly onPress: () => void;
readonly isLast: boolean;
}) {
const separatorColor = useThemeColor("--color-separator");
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
const branch = props.thread.branch;
// Subscribe to live git status — only when thread has a branch set.
// Threads sharing the same cwd share one WS subscription via ref-counting.
const cwd = branch ? (props.thread.worktreePath ?? props.projectCwd) : null;
const gitStatus = useGitStatus({
environmentId: cwd ? props.thread.environmentId : null,
cwd,
});
const gitParts = gitSummaryParts(gitStatus);
return (
<Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
<View
style={{
flexDirection: "row",
paddingLeft: 16,
paddingRight: 16,
paddingVertical: 10,
gap: 12,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
}}
>
{/* Git status indicator */}
<View
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
}}
>
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
{/* Content */}
<View style={{ flex: 1, gap: 3 }}>
{/* Title + Status + Timestamp */}
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
</View>
{/* Branch + git info */}
{branch ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor="#737373"
type="monochrome"
/>
<Text
className="text-[11px] text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{branch}
</Text>
{gitParts.length > 0 ? (
<Text className="text-[11px] text-foreground-tertiary">
{" · " + gitParts.join(" · ")}
</Text>
) : null}
</View>
) : null}
</View>
</View>
</Pressable>
);
}
/* ─── Main screen ────────────────────────────────────────────────────── */
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const toggleExpanded = useCallback((key: string) => {
setExpandedProjects((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}, []);
/* Build project title lookup for search */
const projectTitleByKey = useMemo(() => {
const map = new Map<string, string>();
for (const p of props.projects) {
map.set(scopedProjectKey(p.environmentId, p.id), p.title);
}
return map;
}, [props.projects]);
/* Filter threads by search query */
const filteredThreads = useMemo(() => {
const q = props.searchQuery.trim().toLowerCase();
if (!q) return props.threads;
return props.threads.filter((t) => {
if (t.title.toLowerCase().includes(q)) return true;
const key = scopedProjectKey(t.environmentId, t.projectId);
return projectTitleByKey.get(key)?.toLowerCase().includes(q) ?? false;
});
}, [props.threads, props.searchQuery, projectTitleByKey]);
/* Group filtered threads by project */
const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
const byProject = new Map<string, EnvironmentScopedThreadShell[]>();
for (const thread of filteredThreads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = byProject.get(key);
if (existing) existing.push(thread);
else byProject.set(key, [thread]);
}
const groups: ProjectGroup[] = [];
for (const project of props.projects) {
const key = scopedProjectKey(project.environmentId, project.id);
const threads = byProject.get(key);
if (threads && threads.length > 0) {
groups.push({ key, project, threads });
}
}
groups.sort((a, b) => {
const aTime = new Date(a.threads[0]!.updatedAt ?? a.threads[0]!.createdAt).getTime();
const bTime = new Date(b.threads[0]!.updatedAt ?? b.threads[0]!.createdAt).getTime();
return bTime - aTime;
});
return groups;
}, [props.projects, filteredThreads]);
/* Empty states */
const hasAnyThreads = props.threads.length > 0;
const hasResults = filteredThreads.length > 0;
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
className="flex-1 bg-screen"
contentContainerStyle={{
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
gap: 20,
}}
>
{!hasAnyThreads ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session in one of your connected projects."
/>
) : !hasResults ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : (
projectGroups.map((group) => {
const connection = props.savedConnectionsById[group.project.environmentId];
const isExpanded = expandedProjects.has(group.key);
const visibleThreads = isExpanded
? group.threads
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
<View key={group.key}>
<ProjectGroupLabel
project={group.project}
totalThreadCount={group.threads.length}
httpBaseUrl={connection?.httpBaseUrl ?? null}
bearerToken={connection?.bearerToken ?? null}
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
/>
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{visibleThreads.map((thread, i) => (
<ThreadRow
key={`${thread.environmentId}:${thread.id}`}
thread={thread}
projectCwd={group.project.workspaceRoot}
onPress={() => props.onSelectThread(thread)}
isLast={i === visibleThreads.length - 1}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
);
}
@@ -1,211 +0,0 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger";
import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo } from "react";
import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native";
import { AppText as Text } from "../../components/AppText";
export type ComposerCommandItem =
| {
readonly id: string;
readonly type: "path";
readonly path: string;
readonly kind: "file" | "directory";
readonly label: string;
readonly description: string;
}
| {
readonly id: string;
readonly type: "slash-command";
readonly command: string;
readonly label: string;
readonly description: string;
}
| {
readonly id: string;
readonly type: "provider-slash-command";
readonly command: ServerProviderSlashCommand;
readonly label: string;
readonly description: string;
}
| {
readonly id: string;
readonly type: "skill";
readonly skill: ServerProviderSkill;
readonly label: string;
readonly description: string;
};
interface ComposerCommandPopoverProps {
readonly items: ReadonlyArray<ComposerCommandItem>;
readonly triggerKind: ComposerTriggerKind | null;
readonly isLoading: boolean;
readonly onSelect: (item: ComposerCommandItem) => void;
}
function PopoverSurface(props: {
readonly children: React.ReactNode;
readonly isDarkMode: boolean;
readonly style?: ViewStyle;
}) {
const baseStyle: ViewStyle = {
borderRadius: 16,
overflow: "hidden",
...props.style,
};
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="clear"
interactive={false}
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
colorScheme={props.isDarkMode ? "dark" : "light"}
style={baseStyle}
>
{props.children}
</LiquidGlassView>
);
}
return (
<View
style={[
baseStyle,
{
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
borderWidth: 1,
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
},
]}
>
{props.children}
</View>
);
}
function itemIcon(item: ComposerCommandItem) {
switch (item.type) {
case "path":
return item.kind === "directory" ? ("folder" as const) : ("doc" as const);
case "slash-command":
case "provider-slash-command":
return "terminal" as const;
case "skill":
return "cube" as const;
}
}
function groupLabel(triggerKind: ComposerTriggerKind | null): string | null {
switch (triggerKind) {
case "slash-command":
return "Commands";
case "skill":
return "Skills";
case "path":
return "Files";
default:
return null;
}
}
function emptyText(triggerKind: ComposerTriggerKind | null, isLoading: boolean): string {
if (isLoading) {
return triggerKind === "path" ? "Searching files…" : "Loading…";
}
switch (triggerKind) {
case "path":
return "No matching files or folders.";
case "skill":
return "No skills found.";
case "slash-command":
return "No matching commands.";
default:
return "No results.";
}
}
const CommandRow = memo(function CommandRow(props: {
readonly item: ComposerCommandItem;
readonly onPress: () => void;
readonly isLast: boolean;
}) {
const iconName = itemIcon(props.item);
const iconColor = "#a1a1aa";
return (
<Pressable
onPress={props.onPress}
style={({ pressed }) => ({
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 14,
paddingVertical: 10,
gap: 10,
opacity: pressed ? 0.6 : 1,
borderBottomWidth: props.isLast ? 0 : 0.5,
borderBottomColor: "rgba(255,255,255,0.1)",
})}
>
<SymbolView name={iconName} size={14} tintColor={iconColor} type="monochrome" />
<Text
className="text-[14px] font-t3-medium text-foreground"
numberOfLines={1}
style={{ flexShrink: 0 }}
>
{props.item.label}
</Text>
{props.item.description ? (
<Text numberOfLines={1} style={{ flex: 1, minWidth: 0, fontSize: 12, color: "#a1a1aa" }}>
{props.item.description}
</Text>
) : null}
</Pressable>
);
});
export const ComposerCommandPopover = memo(function ComposerCommandPopover(
props: ComposerCommandPopoverProps,
) {
const isDarkMode = useColorScheme() === "dark";
const label = groupLabel(props.triggerKind);
return (
<PopoverSurface isDarkMode={isDarkMode}>
{label ? (
<View style={{ paddingHorizontal: 14, paddingTop: 10, paddingBottom: 4 }}>
<Text
className="text-[10px] font-t3-bold text-foreground-muted"
style={{ letterSpacing: 0.8, textTransform: "uppercase" }}
>
{label}
</Text>
</View>
) : null}
{props.items.length > 0 ? (
<ScrollView
style={{ maxHeight: 180 }}
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={false}
>
{props.items.map((item, index) => (
<CommandRow
key={item.id}
item={item}
onPress={() => props.onSelect(item)}
isLast={index === props.items.length - 1}
/>
))}
</ScrollView>
) : (
<View style={{ paddingHorizontal: 14, paddingVertical: 10 }}>
<Text className="text-[12px] text-foreground-tertiary">
{emptyText(props.triggerKind, props.isLoading)}
</Text>
</View>
)}
</PopoverSurface>
);
});
@@ -1,121 +0,0 @@
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useRef } from "react";
import { ActivityIndicator, Linking, Pressable, View } from "react-native";
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import type { GitActionProgress } from "../../state/use-git-action-state";
export function GitActionProgressOverlay(props: {
readonly progress: GitActionProgress;
readonly onDismiss: () => void;
}) {
const { progress, onDismiss } = props;
const insets = useSafeAreaInsets();
const prevPhaseRef = useRef(progress.phase);
useEffect(() => {
const prev = prevPhaseRef.current;
prevPhaseRef.current = progress.phase;
if (prev === "running" && progress.phase === "success") {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
} else if (prev === "running" && progress.phase === "error") {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
}
}, [progress.phase]);
const handlePress = useCallback(() => {
if (progress.prUrl) {
void Linking.openURL(progress.prUrl);
return;
}
if (progress.phase === "success" || progress.phase === "error") {
onDismiss();
}
}, [onDismiss, progress.phase, progress.prUrl]);
if (progress.phase === "idle") {
return null;
}
return (
<Animated.View
entering={FadeIn.duration(200)}
exiting={FadeOut.duration(150)}
style={{ top: insets.top + 48, left: 12, right: 12, position: "absolute", zIndex: 100 }}
pointerEvents="box-none"
>
<Pressable onPress={handlePress}>
<OverlayContent progress={progress} />
</Pressable>
</Animated.View>
);
}
function OverlayContent(props: { readonly progress: GitActionProgress }) {
const { progress } = props;
const iconColor = useThemeColor("--color-icon");
const bgClass =
progress.phase === "error"
? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
: "bg-card border-border";
return (
<View
className={`flex-row items-center gap-2.5 rounded-2xl border px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
>
<OverlayIcon phase={progress.phase} iconColor={iconColor} />
<View className="flex-1 gap-0.5">
{progress.label ? (
<Text className="text-[13px] font-t3-bold text-foreground" numberOfLines={1}>
{progress.label}
</Text>
) : null}
{progress.description ? (
<Text className="text-[11px] text-foreground-muted" numberOfLines={1}>
{progress.description}
</Text>
) : null}
</View>
{progress.prUrl ? (
<SymbolView name="arrow.up.right" size={13} tintColor={iconColor} type="monochrome" />
) : null}
</View>
);
}
function OverlayIcon(props: {
readonly phase: GitActionProgress["phase"];
readonly iconColor: ReturnType<typeof useThemeColor>;
}) {
switch (props.phase) {
case "running":
return <ActivityIndicator size="small" />;
case "success":
return (
<View className="h-6 w-6 items-center justify-center rounded-full bg-green-500">
<SymbolView name="checkmark" size={12} tintColor="white" type="monochrome" />
</View>
);
case "error":
return (
<View className="h-6 w-6 items-center justify-center rounded-full bg-red-500">
<SymbolView
name="exclamationmark.triangle"
size={12}
tintColor="white"
type="monochrome"
/>
</View>
);
default:
return null;
}
}
@@ -1,514 +0,0 @@
import { MenuView } from "@react-native-menu/menu";
import { useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { TextInputWrapper } from "expo-paste-input";
import { useCallback, useEffect, useMemo } from "react";
import { Pressable, View, useColorScheme } from "react-native";
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
import { CLAUDE_CODE_EFFORT_OPTIONS } from "@t3tools/contracts";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { buildThreadRoutePath } from "../../lib/routes";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useNativePaste } from "../../hooks/useNativePaste";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useProjectActions } from "./use-project-actions";
export function NewTaskDraftScreen(props: {
readonly initialProjectRef?: {
readonly environmentId?: string;
readonly projectId?: string;
};
}) {
const { projects } = useRemoteCatalog();
const { onCreateThreadWithOptions } = useProjectActions();
const flow = useNewTaskFlow();
const router = useRouter();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const keyboard = useAnimatedKeyboard();
const containerAnimatedStyle = useAnimatedStyle(() => ({
paddingBottom: keyboard.height.value,
}));
const controlsBottomPadding = useAnimatedStyle(() => ({
paddingBottom: keyboard.height.value > 0 ? 4 : Math.max(insets.bottom, 10),
}));
const { logicalProjects, selectedProject, setProject } = flow;
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
useEffect(() => {
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
const directProject =
projects.find(
(project) =>
project.environmentId === props.initialProjectRef?.environmentId &&
project.id === props.initialProjectRef?.projectId,
) ?? null;
if (directProject) {
setProject(directProject);
return;
}
}
if (selectedProject) {
return;
}
if (logicalProjects.length === 1) {
setProject(logicalProjects[0]!.project);
return;
}
router.replace("/new");
}, [
logicalProjects,
projects,
props.initialProjectRef?.environmentId,
props.initialProjectRef?.projectId,
router,
selectedProject,
setProject,
]);
useEffect(() => {
if (!selectedProject) {
return;
}
void flow.loadBranches();
}, [flow, selectedProject]);
const environmentMenuActions = useMemo(
() =>
flow.environments.map((environment) => ({
id: `environment:${environment.environmentId}`,
title: environment.environmentLabel,
state:
flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
})),
[flow.environments, flow.selectedEnvironmentId],
);
const modelMenuActions = useMemo(
() =>
flow.providerGroups.map((group) => ({
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: group.models.find(
(model) =>
flow.selectedModel &&
model.selection.provider === flow.selectedModel.provider &&
model.selection.model === flow.selectedModel.model,
)?.label,
subactions: group.models.map((option) => ({
id: `model:${option.key}`,
title: option.label,
state:
flow.selectedModel &&
option.selection.provider === flow.selectedModel.provider &&
option.selection.model === flow.selectedModel.model
? ("on" as const)
: undefined,
})),
})),
[flow.providerGroups, flow.selectedModel],
);
const optionsMenuActions = useMemo(
() => [
{
id: "options-effort",
title: "Effort",
subtitle: `${flow.effort.charAt(0).toUpperCase()}${flow.effort.slice(1)}`,
subactions: CLAUDE_CODE_EFFORT_OPTIONS.map((level) => ({
id: `options:effort:${level}`,
title: `${level}${level === "high" ? " (default)" : ""}`,
state: flow.effort === level ? ("on" as const) : undefined,
})),
},
{
id: "options-fast-mode",
title: "Fast Mode",
subtitle: flow.fastMode ? "On" : "Off",
subactions: ([false, true] as const).map((value) => ({
id: `options:fast-mode:${value ? "on" : "off"}`,
title: value ? "On" : "Off",
state: flow.fastMode === value ? ("on" as const) : undefined,
})),
},
{
id: "options-context-window",
title: "Context Window",
subtitle: flow.contextWindow,
subactions: (["200k", "1M"] as const).map((value) => ({
id: `options:context-window:${value}`,
title: `${value}${value === "1M" ? " (default)" : ""}`,
state: flow.contextWindow === value ? ("on" as const) : undefined,
})),
},
{
id: "options-runtime",
title: "Runtime",
subtitle:
flow.runtimeMode === "approval-required"
? "Approve actions"
: flow.runtimeMode === "auto-accept-edits"
? "Auto-accept edits"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: flow.runtimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: flow.interactionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[flow.contextWindow, flow.effort, flow.fastMode, flow.interactionMode, flow.runtimeMode],
);
const workspaceMenuActions = useMemo(() => {
const branchActions =
flow.availableBranches.length === 0
? [
{
id: "workspace:branch:none",
title: flow.branchesLoading ? "Loading branches…" : "No branches available",
attributes: { disabled: true },
},
]
: flow.availableBranches.slice(0, 12).map((branch) => {
const badge = branchBadgeLabel({
branch,
project: flow.selectedProject,
});
return {
id: `workspace:branch:${branch.name}`,
title: branch.name,
subtitle: badge ? badge.toUpperCase() : undefined,
state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
};
});
return [
{
id: "workspace:mode",
title: "Mode",
subtitle: flow.workspaceMode === "local" ? "Local" : "Worktree",
subactions: (["local", "worktree"] as const).map((value) => ({
id: `workspace:mode:${value}`,
title: value === "local" ? "Local" : "Worktree",
state: flow.workspaceMode === value ? ("on" as const) : undefined,
})),
},
{
id: "workspace:branch",
title: "Branch",
subtitle: flow.selectedBranchName ?? "Choose branch",
subactions: branchActions,
},
];
}, [
flow.availableBranches,
flow.branchesLoading,
flow.selectedBranchName,
flow.selectedProject,
flow.workspaceMode,
]);
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
}
// Defer state update so the native menu dismiss animation completes
// before re-rendering the menu actions (prevents submenu jump).
setTimeout(() => {
flow.setSelectedModelKey(event.slice("model:".length));
}, 150);
}
function handleEnvironmentMenuAction(event: string) {
if (!event.startsWith("environment:")) {
return;
}
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleOptionsMenuAction(event: string) {
if (event.startsWith("options:effort:")) {
flow.setEffort(event.slice("options:effort:".length) as typeof flow.effort);
return;
}
if (event.startsWith("options:fast-mode:")) {
flow.setFastMode(event.endsWith(":on"));
return;
}
if (event.startsWith("options:context-window:")) {
flow.setContextWindow(event.slice("options:context-window:".length));
return;
}
if (event.startsWith("options:runtime:")) {
flow.setRuntimeMode(
event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
);
return;
}
if (event.startsWith("options:interaction:")) {
flow.setInteractionMode(
event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
);
}
}
function handleWorkspaceMenuAction(event: string) {
if (event.startsWith("workspace:mode:")) {
flow.setWorkspaceMode(
event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
);
return;
}
if (event.startsWith("workspace:branch:")) {
const branchName = event.slice("workspace:branch:".length);
const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
if (branch) {
flow.selectBranch(branch);
}
}
}
async function handlePickImages(): Promise<void> {
const result = await pickComposerImages({ existingCount: flow.attachments.length });
if (result.images.length > 0) {
flow.appendAttachments(result.images);
}
}
const handleNativePasteImages = useCallback(
async (uris: ReadonlyArray<string>) => {
try {
const images = await convertPastedImagesToAttachments({
uris,
existingCount: flow.attachments.length,
});
if (images.length > 0) {
flow.appendAttachments(images);
}
} catch (error) {
console.error("[native paste] error converting images", error);
}
},
[flow],
);
const handleNativePaste = useNativePaste((uris) => {
void handleNativePasteImages(uris);
});
async function handleStart(): Promise<void> {
if (
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
) {
return;
}
flow.setSubmitting(true);
try {
const modelWithOptions: ModelSelection =
flow.selectedModel.provider === "claudeAgent"
? {
...flow.selectedModel,
options: {
effort: flow.effort,
fastMode: flow.fastMode || undefined,
contextWindow: flow.contextWindow,
},
}
: flow.selectedModel.provider === "codex"
? { ...flow.selectedModel, options: { fastMode: flow.fastMode || undefined } }
: flow.selectedModel;
const createdThread = await onCreateThreadWithOptions({
project: flow.selectedProject,
modelSelection: modelWithOptions,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
});
if (createdThread) {
router.replace(buildThreadRoutePath(createdThread));
}
} finally {
flow.setSubmitting(false);
}
}
if (!selectedProject) {
return (
<View className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Loading task</Text>
</View>
</View>
);
}
return (
<Animated.View className="flex-1 bg-sheet" style={containerAnimatedStyle}>
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
{flow.logicalProjects.length > 1 ? (
<Pressable
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1 }}
onPress={() => router.back()}
>
<SymbolView
name="chevron.left"
size={16}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">{selectedProject.title}</Text>
</View>
<View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
<TextInputWrapper onPaste={(payload) => void handleNativePaste(payload)}>
<TextInput
multiline
value={flow.prompt}
onChangeText={flow.setPrompt}
placeholder={`Describe a coding task in ${selectedProject.title}`}
textAlignVertical="top"
className="flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
/>
</TextInputWrapper>
</View>
<Animated.View
style={[
{
borderTopWidth: 1,
borderTopColor: borderColor,
},
controlsBottomPadding,
]}
>
{flow.attachments.length > 0 ? (
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={flow.removeAttachment}
imageSize={88}
imageBorderRadius={20}
/>
</View>
) : null}
<View className="flex-row items-center justify-between gap-2 px-4 pb-1 pt-4">
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
<MenuView
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill
iconNode={<ProviderIcon provider={flow.selectedModel?.provider} size={16} />}
/>
</MenuView>
<MenuView
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="slider.horizontal.3" />
</MenuView>
<MenuView
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="desktopcomputer" />
</MenuView>
<MenuView
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
</MenuView>
<ControlPill
icon="arrow.up"
label={flow.submitting ? "Starting" : "Start"}
onPress={() => void handleStart()}
variant="primary"
disabled={
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
}
/>
</View>
</Animated.View>
</Animated.View>
);
}
@@ -1,57 +0,0 @@
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import type { PendingApproval } from "../../lib/threadActivity";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly onRespond: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
}
export function PendingApprovalCard(props: PendingApprovalCardProps) {
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-[11px] uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
{props.approval.requestKind}
</Text>
{props.approval.detail ? (
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
{props.approval.detail}
</Text>
) : null}
<View className="flex-row flex-wrap gap-2.5">
<Pressable
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
>
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
>
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
Allow session
</Text>
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
>
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
</Pressable>
</View>
</View>
);
}
@@ -1,101 +0,0 @@
import type { ApprovalRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (requestId: string, questionId: string, label: string) => void;
readonly onChangeCustomAnswer: (
requestId: string,
questionId: string,
customAnswer: string,
) => void;
readonly onSubmit: () => Promise<void>;
}
export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-[11px] uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
Fill in the pending answers
</Text>
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
<View key={question.id} className="gap-2 pt-1">
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
{question.header}
</Text>
<Text className="font-sans text-[15px] leading-[21px] text-neutral-950 dark:text-neutral-50">
{question.question}
</Text>
<View className="flex-row flex-wrap gap-2.5">
{question.options.map((option) => {
const selected =
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
return (
<Pressable
key={option.label}
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
)}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
question.id,
option.label,
)
}
>
<Text
className={cn(
"font-t3-bold text-[13px]",
selected
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
)}
>
{option.label}
</Text>
</Pressable>
);
})}
</View>
<TextInput
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
}
placeholder="Or type a custom answer"
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-[15px] text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
/>
</View>
);
})}
<Pressable
className={cn(
"items-center justify-center rounded-2xl px-4 py-3.5",
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
)}
disabled={
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
}
onPress={() => void props.onSubmit()}
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</View>
);
}
@@ -1,853 +0,0 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import { MenuView } from "@react-native-menu/menu";
import type {
ModelSelection,
OrchestrationThread,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import { CLAUDE_CODE_EFFORT_OPTIONS } from "@t3tools/contracts";
import {
detectComposerTrigger,
replaceTextRange,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import { TextInputWrapper } from "expo-paste-input";
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Image,
Pressable,
TextInput as RNTextInput,
useColorScheme,
View,
type NativeSyntheticEvent,
type TextInputSelectionChangeEventData,
type ViewStyle,
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import type { RemoteClientConnectionState } from "../../lib/connection";
import { useNativePaste } from "../../hooks/useNativePaste";
import {
insertRankedSearchResult,
normalizeSearchQuery,
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
/**
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
* Exported so the parent can compute feed overlap / content insets.
*/
export const COMPOSER_COLLAPSED_CHROME = 68;
/**
* Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
* Used by the parent to compute the larger feed bottom inset when the composer is focused.
*/
export const COMPOSER_EXPANDED_CHROME = 174;
export interface ThreadComposerProps {
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly placeholder: string;
readonly bottomInset?: number;
readonly connectionState: RemoteClientConnectionState;
readonly selectedThread: OrchestrationThread;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
readonly environmentId: string;
readonly projectCwd: string | null;
readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onRefresh: () => Promise<void>;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => Promise<void>;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => Promise<void>;
readonly onExpandedChange?: (expanded: boolean) => void;
}
/**
* The pill / card container — renders as LiquidGlassView on supported
* iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
*/
function ComposerSurface(props: {
readonly children: ReactNode;
readonly style: ViewStyle;
readonly isDarkMode: boolean;
}) {
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="clear"
interactive
tintColor={props.isDarkMode ? "rgba(44,44,46,0.5)" : "rgba(255,255,255,0.45)"}
colorScheme={props.isDarkMode ? "dark" : "light"}
style={props.style}
>
{props.children}
</LiquidGlassView>
);
}
return (
<View
style={[
props.style,
{
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
borderWidth: 1,
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
},
]}
>
{props.children}
</View>
);
}
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
const isDarkMode = useColorScheme() === "dark";
const themePlaceholderColor = useThemeColor("--color-placeholder");
const placeholderColor = isDarkMode ? "#a1a1aa" : themePlaceholderColor;
const foregroundColor = useThemeColor("--color-foreground");
const inputRef = useRef<RNTextInput>(null);
const [isFocused, setIsFocused] = useState(false);
const wasExpandedBeforePreviewRef = useRef(false);
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const isExpanded = isFocused;
const canSend = props.connectionState === "ready" && hasContent;
const onPressImage = useCallback(
(uri: string) => {
wasExpandedBeforePreviewRef.current = isFocused;
setPreviewImageUri(uri);
},
[isFocused],
);
const closePreview = useCallback(() => {
setPreviewImageUri(null);
if (wasExpandedBeforePreviewRef.current) {
setTimeout(() => inputRef.current?.focus(), 100);
}
}, []);
useEffect(() => {
onExpandedChange?.(isExpanded);
}, [isExpanded, onExpandedChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting" ||
props.queueCount > 0;
const sendLabel = props.activeThreadBusy || props.queueCount > 0 ? "Queue" : "Send";
const modelProvider = props.selectedThread.modelSelection?.provider ?? null;
const currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
// Extract current model options (effort, fastMode, contextWindow)
const currentEffort =
currentModelSelection.provider === "claudeAgent"
? (currentModelSelection.options?.effort ?? "high")
: "high";
const currentFastMode =
currentModelSelection.options && "fastMode" in currentModelSelection.options
? (currentModelSelection.options.fastMode ?? false)
: false;
const currentContextWindow =
currentModelSelection.provider === "claudeAgent"
? (currentModelSelection.options?.contextWindow ?? "1M")
: "1M";
const handleNativePaste = useNativePaste((uris) => {
void props.onNativePasteImages(uris);
});
// ── Trigger detection ────────────────────────────────────
const [cursorPosition, setCursorPosition] = useState(0);
const [composerTrigger, setComposerTrigger] = useState<ComposerTrigger | null>(null);
const [pathSearchResults, setPathSearchResults] = useState<
ReadonlyArray<{ path: string; kind: "file" | "directory" }>
>([]);
const [pathSearchLoading, setPathSearchLoading] = useState(false);
const pathSearchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleSelectionChange = useCallback(
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
const { start } = event.nativeEvent.selection;
setCursorPosition(start);
},
[],
);
useEffect(() => {
const trigger = detectComposerTrigger(props.draftMessage, cursorPosition);
setComposerTrigger(trigger);
}, [props.draftMessage, cursorPosition]);
// ── File search (debounced) ──────────────────────────────
useEffect(() => {
if (pathSearchTimerRef.current) {
clearTimeout(pathSearchTimerRef.current);
pathSearchTimerRef.current = null;
}
if (composerTrigger?.kind !== "path" || !composerTrigger.query || !props.projectCwd) {
setPathSearchResults([]);
setPathSearchLoading(false);
return;
}
setPathSearchLoading(true);
const query = composerTrigger.query;
const cwd = props.projectCwd;
const envId = props.environmentId;
pathSearchTimerRef.current = setTimeout(() => {
const client = getEnvironmentClient(envId);
if (!client) {
setPathSearchLoading(false);
return;
}
void client.projects
.searchEntries({ cwd, query, limit: 20 })
.then((result) => {
setPathSearchResults(
result.entries.map((entry) => ({
path: entry.path,
kind: entry.kind === "directory" ? ("directory" as const) : ("file" as const),
})),
);
})
.catch(() => {
setPathSearchResults([]);
})
.finally(() => {
setPathSearchLoading(false);
});
}, 200);
return () => {
if (pathSearchTimerRef.current) {
clearTimeout(pathSearchTimerRef.current);
}
};
}, [composerTrigger?.kind, composerTrigger?.query, props.projectCwd, props.environmentId]);
// ── Build menu items ─────────────────────────────────────
const selectedProviderStatus = useMemo(() => {
if (!props.serverConfig) return null;
return (
props.serverConfig.providers.find(
(p) => p.provider === props.selectedThread.modelSelection.provider,
) ?? null
);
}, [props.serverConfig, props.selectedThread.modelSelection.provider]);
const composerMenuItems: ComposerCommandItem[] = useMemo(() => {
if (!composerTrigger) return [];
if (composerTrigger.kind === "slash-command") {
const q = composerTrigger.query.toLowerCase();
const allBuiltIn = [
{
id: "cmd:model",
type: "slash-command" as const,
command: "model",
label: "/model",
description: "Switch model",
},
{
id: "cmd:plan",
type: "slash-command" as const,
command: "plan",
label: "/plan",
description: "Switch to plan mode",
},
{
id: "cmd:default",
type: "slash-command" as const,
command: "default",
label: "/default",
description: "Switch to default mode",
},
];
const builtIn = allBuiltIn.filter((item) => item.command.includes(q));
const providerCommands: ComposerCommandItem[] = (selectedProviderStatus?.slashCommands ?? [])
.filter((cmd) => cmd.name.toLowerCase().includes(q))
.map((cmd) => ({
id: `pcmd:${cmd.name}`,
type: "provider-slash-command" as const,
command: cmd,
label: `/${cmd.name}`,
description: cmd.description ?? "",
}));
return [...builtIn, ...providerCommands];
}
if (composerTrigger.kind === "skill") {
const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((s) => s.enabled);
const normalizedQuery = normalizeSearchQuery(composerTrigger.query, {
trimLeadingPattern: /^\$+/,
});
if (!normalizedQuery) {
return enabledSkills.slice(0, 20).map((skill) => ({
id: `skill:${skill.name}`,
type: "skill" as const,
skill,
label: skill.displayName ?? skill.name,
description: skill.shortDescription ?? skill.description ?? "",
}));
}
const ranked: Array<{
item: (typeof enabledSkills)[number];
score: number;
tieBreaker: string;
}> = [];
for (const skill of enabledSkills) {
const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
const scores = [
scoreQueryMatch({
value: skill.name.toLowerCase(),
query: normalizedQuery,
exactBase: 0,
prefixBase: 2,
boundaryBase: 4,
includesBase: 6,
fuzzyBase: 100,
boundaryMarkers: ["-", "_", "/"],
}),
scoreQueryMatch({
value: displayLabel,
query: normalizedQuery,
exactBase: 1,
prefixBase: 3,
boundaryBase: 5,
includesBase: 7,
fuzzyBase: 110,
}),
scoreQueryMatch({
value: skill.shortDescription?.toLowerCase() ?? "",
query: normalizedQuery,
exactBase: 20,
prefixBase: 22,
boundaryBase: 24,
includesBase: 26,
}),
scoreQueryMatch({
value: skill.description?.toLowerCase() ?? "",
query: normalizedQuery,
exactBase: 30,
prefixBase: 32,
boundaryBase: 34,
includesBase: 36,
}),
].filter((s): s is number => s !== null);
if (scores.length > 0) {
insertRankedSearchResult(
ranked,
{
item: skill,
score: Math.min(...scores),
tieBreaker: `${displayLabel}\u0000${skill.name}`,
},
20,
);
}
}
return ranked.map(({ item: skill }) => ({
id: `skill:${skill.name}`,
type: "skill" as const,
skill,
label: skill.displayName ?? skill.name,
description: skill.shortDescription ?? skill.description ?? "",
}));
}
if (composerTrigger.kind === "path") {
return pathSearchResults.map((entry) => {
const parts = entry.path.split("/");
return {
id: `path:${entry.path}`,
type: "path" as const,
path: entry.path,
kind: entry.kind,
label: parts[parts.length - 1] ?? entry.path,
description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
};
});
}
return [];
}, [composerTrigger, selectedProviderStatus, pathSearchResults]);
// ── Handle command selection ──────────────────────────────
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
const handleSend = useCallback(() => {
onSendMessage();
inputRef.current?.blur();
}, [onSendMessage]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
if (!composerTrigger) return;
if (
item.type === "slash-command" &&
(item.command === "plan" || item.command === "default")
) {
const result = replaceTextRange(
draftMessage,
composerTrigger.rangeStart,
composerTrigger.rangeEnd,
"",
);
setCursorPosition(result.cursor);
onChangeDraftMessage(result.text);
void onUpdateInteractionMode(item.command);
return;
}
let replacement = "";
if (item.type === "path") {
replacement = `@${item.path} `;
} else if (item.type === "skill") {
replacement = `$${item.skill.name} `;
} else if (item.type === "slash-command") {
replacement = `/${item.command} `;
} else if (item.type === "provider-slash-command") {
replacement = `/${item.command.name} `;
}
const result = replaceTextRange(
draftMessage,
composerTrigger.rangeStart,
composerTrigger.rangeEnd,
replacement,
);
setCursorPosition(result.cursor);
onChangeDraftMessage(result.text);
},
[composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode],
);
// ── Model menu ───────────────────────────────────────────
const providerGroups = useMemo(() => {
const options = buildModelOptions(props.serverConfig, currentModelSelection);
return groupByProvider(options);
}, [props.serverConfig, currentModelSelection]);
const modelMenuActions = useMemo(
() =>
providerGroups.map((group) => ({
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: group.models.find(
(model) =>
model.selection.provider === currentModelSelection.provider &&
model.selection.model === currentModelSelection.model,
)?.label,
subactions: group.models.map((option) => ({
id: `model:${option.key}`,
title: option.label,
state:
option.selection.provider === currentModelSelection.provider &&
option.selection.model === currentModelSelection.model
? ("on" as const)
: undefined,
})),
})),
[providerGroups, currentModelSelection],
);
// ── Options menu ─────────────────────────────────────────
const optionsMenuActions = useMemo(
() => [
{
id: "options-effort",
title: "Effort",
subtitle: `${currentEffort.charAt(0).toUpperCase()}${currentEffort.slice(1)}`,
subactions: CLAUDE_CODE_EFFORT_OPTIONS.map((level) => ({
id: `options:effort:${level}`,
title: `${level}${level === "high" ? " (default)" : ""}`,
state: currentEffort === level ? ("on" as const) : undefined,
})),
},
{
id: "options-fast-mode",
title: "Fast Mode",
subtitle: currentFastMode ? "On" : "Off",
subactions: ([false, true] as const).map((value) => ({
id: `options:fast-mode:${value ? "on" : "off"}`,
title: value ? "On" : "Off",
state: currentFastMode === value ? ("on" as const) : undefined,
})),
},
{
id: "options-context-window",
title: "Context Window",
subtitle: currentContextWindow,
subactions: (["200k", "1M"] as const).map((value) => ({
id: `options:context-window:${value}`,
title: `${value}${value === "1M" ? " (default)" : ""}`,
state: currentContextWindow === value ? ("on" as const) : undefined,
})),
},
{
id: "options-runtime",
title: "Runtime",
subtitle:
currentRuntimeMode === "approval-required"
? "Approve actions"
: currentRuntimeMode === "auto-accept-edits"
? "Auto-accept edits"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: currentRuntimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: currentInteractionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[
currentEffort,
currentFastMode,
currentContextWindow,
currentRuntimeMode,
currentInteractionMode,
],
);
// ── Menu handlers ────────────────────────────────────────
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
}
const modelKey = event.slice("model:".length);
const options = buildModelOptions(props.serverConfig, currentModelSelection);
const option = options.find((o) => o.key === modelKey);
if (option) {
void props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
if (event.startsWith("options:effort:")) {
const effort = event.slice("options:effort:".length);
const updated: ModelSelection =
currentModelSelection.provider === "claudeAgent"
? {
...currentModelSelection,
options: { ...currentModelSelection.options, effort: effort as typeof currentEffort },
}
: currentModelSelection;
void props.onUpdateModelSelection(updated);
return;
}
if (event.startsWith("options:fast-mode:")) {
const fastMode = event.endsWith(":on");
const updated: ModelSelection = {
...currentModelSelection,
options: { ...currentModelSelection.options, fastMode: fastMode || undefined },
};
void props.onUpdateModelSelection(updated);
return;
}
if (event.startsWith("options:context-window:")) {
const contextWindow = event.slice("options:context-window:".length);
const updated: ModelSelection =
currentModelSelection.provider === "claudeAgent"
? {
...currentModelSelection,
options: { ...currentModelSelection.options, contextWindow },
}
: currentModelSelection;
void props.onUpdateModelSelection(updated);
return;
}
if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
void props.onUpdateRuntimeMode(runtimeMode);
return;
}
if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
void props.onUpdateInteractionMode(interactionMode);
}
}
return (
<View
style={{
paddingHorizontal: 16,
paddingTop: isExpanded ? 12 : 10,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 4 : 10),
experimental_backgroundImage: isDarkMode
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
}}
>
<View className="w-full" style={{ position: "relative" }}>
{composerTrigger && composerMenuItems.length > 0 ? (
<View
style={{
position: "absolute",
bottom: "100%",
left: 0,
right: 0,
marginBottom: 8,
zIndex: 10,
}}
>
<ComposerCommandPopover
items={composerMenuItems}
triggerKind={composerTrigger.kind}
isLoading={pathSearchLoading}
onSelect={handleCommandSelect}
/>
</View>
) : null}
<ComposerSurface
isDarkMode={isDarkMode}
style={
isExpanded
? {
borderRadius: 20,
overflow: "hidden" as const,
paddingHorizontal: 14,
paddingVertical: 12,
}
: {
borderRadius: 999,
overflow: "hidden" as const,
flexDirection: "row" as const,
alignItems: "center" as const,
paddingLeft: 18,
paddingRight: 5,
paddingVertical: 5,
}
}
>
{/* Attachment strip — inside the card, above the text input */}
{isExpanded ? (
<View style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}>
<ComposerAttachmentStrip
attachments={props.draftAttachments}
onRemove={props.onRemoveDraftImage}
onPressImage={onPressImage}
/>
</View>
) : null}
<View style={isExpanded ? undefined : { flex: 1, minWidth: 0 }}>
<TextInputWrapper onPaste={handleNativePaste}>
<RNTextInput
ref={inputRef}
multiline
value={props.draftMessage}
onChangeText={props.onChangeDraftMessage}
onSelectionChange={handleSelectionChange}
placeholder={props.placeholder}
placeholderTextColor={placeholderColor}
editable={props.connectionState === "ready"}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
textAlignVertical={isExpanded ? "top" : "center"}
style={
isExpanded
? {
minHeight: 80,
maxHeight: 160,
paddingHorizontal: 4,
paddingVertical: 4,
fontSize: 15,
lineHeight: 22,
color: foregroundColor,
fontFamily: "DMSans_400Regular",
}
: {
maxHeight: 36,
paddingVertical: 6,
fontSize: 15,
lineHeight: 20,
color: foregroundColor,
fontFamily: "DMSans_400Regular",
}
}
/>
</TextInputWrapper>
</View>
{!isExpanded && props.draftAttachments.length > 0 ? (
<View style={{ flexDirection: "row", gap: 4, paddingLeft: 4 }}>
{props.draftAttachments.slice(0, 3).map((image) => (
<Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
<Image
source={{ uri: image.previewUri }}
className="bg-subtle"
style={{
width: 30,
height: 30,
borderRadius: 8,
}}
resizeMode="cover"
/>
</Pressable>
))}
{props.draftAttachments.length > 3 ? (
<View
className="bg-subtle-strong"
style={{
width: 30,
height: 30,
borderRadius: 8,
alignItems: "center",
justifyContent: "center",
}}
>
<Text className="text-foreground-muted text-[11px] font-t3-bold">
+{props.draftAttachments.length - 3}
</Text>
</View>
) : null}
</View>
) : null}
{!isExpanded ? (
showStopAction ? (
<ControlPill
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
/>
) : (
<ControlPill
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
/>
)
) : null}
</ComposerSurface>
{/* Toolbar row — matches draft page layout (expanded only) */}
{isExpanded ? (
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingTop: 10,
gap: 8,
}}
>
<ControlPill icon="plus" onPress={() => void props.onPickDraftImages()} />
<MenuView
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill iconNode={<ProviderIcon provider={modelProvider} size={16} />} />
</MenuView>
<MenuView
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="slider.horizontal.3" />
</MenuView>
<ControlPill icon="arrow.clockwise" onPress={() => void props.onRefresh()} />
{showStopAction ? (
<ControlPill
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
/>
) : null}
<ControlPill
icon="arrow.up"
label={sendLabel}
variant="primary"
disabled={!canSend}
onPress={handleSend}
/>
</View>
) : null}
{/* Queue count */}
{props.queueCount > 0 ? (
<Text
className="text-foreground-muted"
style={{
fontSize: 12,
lineHeight: 18,
paddingTop: 8,
}}
>
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
) : null}
</View>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
imageIndex={0}
visible={previewImageUri !== null}
onRequestClose={closePreview}
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
);
});
@@ -1,338 +0,0 @@
import type {
ApprovalRequestId,
ModelSelection,
OrchestrationThread,
ProviderApprovalDecision,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { View, type LayoutChangeEvent } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { runOnJS } from "react-native-reanimated";
import { AppText as Text } from "../../components/AppText";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import type {
PendingApproval,
PendingUserInput,
PendingUserInputDraftAnswer,
ThreadFeedEntry,
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { PendingUserInputCard } from "./PendingUserInputCard";
import {
COMPOSER_COLLAPSED_CHROME,
COMPOSER_EXPANDED_CHROME,
ThreadComposer,
} from "./ThreadComposer";
import { ThreadFeed } from "./ThreadFeed";
export interface ThreadDetailScreenProps {
readonly selectedThread: OrchestrationThread;
readonly screenTone: StatusTone;
readonly connectionError: string | null;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
readonly activeWorkStartedAt: string | null;
readonly activePendingApproval: PendingApproval | null;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
readonly activePendingUserInputAnswers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle";
readonly activeThreadBusy: boolean;
readonly environmentId: string;
readonly projectWorkspaceRoot: string | null;
readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: MobileLayoutVariant;
readonly onOpenDrawer: () => void;
readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onRefresh: () => Promise<void>;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
readonly onUpdateThreadInteractionMode: (
interactionMode: ProviderInteractionMode,
) => Promise<void>;
readonly onRespondToApproval: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
readonly onSelectUserInputOption: (requestId: string, questionId: string, label: string) => void;
readonly onChangeUserInputCustomAnswer: (
requestId: string,
questionId: string,
customAnswer: string,
) => void;
readonly onSubmitUserInput: () => Promise<void>;
readonly showContent?: boolean;
}
function latestStreamingAssistantMessage(
feed: ReadonlyArray<ThreadFeedEntry>,
): { readonly id: string; readonly textLength: number } | null {
for (let index = feed.length - 1; index >= 0; index -= 1) {
const entry = feed[index];
if (entry?.type !== "message") {
continue;
}
if (entry.message.role !== "assistant" || !entry.message.streaming) {
continue;
}
return {
id: entry.message.id,
textLength: entry.message.text.length,
};
}
return null;
}
function useStreamingHaptics(threadId: string, feed: ReadonlyArray<ThreadFeedEntry>) {
const lastStreamingAssistantRef = useRef<{
readonly id: string;
readonly textLength: number;
} | null>(null);
const lastStreamHapticAtRef = useRef(0);
const hydratedRef = useRef(false);
const previousThreadIdRef = useRef(threadId);
useEffect(() => {
if (previousThreadIdRef.current !== threadId) {
previousThreadIdRef.current = threadId;
hydratedRef.current = false;
}
const latestStreamingMessage = latestStreamingAssistantMessage(feed);
if (!hydratedRef.current) {
hydratedRef.current = true;
lastStreamingAssistantRef.current = latestStreamingMessage;
return;
}
if (!latestStreamingMessage) {
lastStreamingAssistantRef.current = null;
return;
}
const previousStreamingMessage = lastStreamingAssistantRef.current;
lastStreamingAssistantRef.current = latestStreamingMessage;
const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
const textGrew =
previousStreamingMessage?.id === latestStreamingMessage.id &&
latestStreamingMessage.textLength > previousStreamingMessage.textLength;
if (!isNewStream && !textGrew) {
return;
}
const now = Date.now();
if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
return;
}
lastStreamHapticAtRef.current = now;
void Haptics.selectionAsync();
}, [threadId, feed]);
}
const WORKING_INDICATOR_HEIGHT = 44;
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
readonly startedAt: string;
}) {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const intervalId = setInterval(() => {
setNowMs(Date.now());
}, 1_000);
return () => clearInterval(intervalId);
}, [props.startedAt]);
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
return (
<View className="px-4 pb-2" style={{ flexShrink: 0 }}>
<View className="self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]">
<View className="flex-row items-center gap-2">
<View className="flex-row items-center gap-1">
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
</View>
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
Working for {durationLabel}
</Text>
</View>
</View>
</View>
);
});
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const { onOpenDrawer, onRefresh } = props;
const insets = useSafeAreaInsets();
const agentLabel = `${props.selectedThread.modelSelection.provider} agent`;
const composerBottomInset = Math.max(insets.bottom, 12);
const [composerExpanded, setComposerExpanded] = useState(false);
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
const [refreshing, setRefreshing] = useState(false);
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
const feedBottomInset = Math.max(estimatedOverlayHeight, measuredOverlayHeight) + 8;
const completeDrawerGesture = useCallback(() => {
void Haptics.selectionAsync();
onOpenDrawer();
}, [onOpenDrawer]);
const handleRefresh = useCallback(async (): Promise<void> => {
if (refreshing) {
return;
}
setRefreshing(true);
try {
await onRefresh();
} finally {
setRefreshing(false);
}
}, [onRefresh, refreshing]);
const drawerGestureThreshold = 80;
const headerDrawerGesture = useMemo(
() =>
Gesture.Pan()
.enabled(!isSplitLayout)
.hitSlop({ left: 0, width: 40 })
.activeOffsetX([10, 999])
.failOffsetY([-24, 24])
.onEnd((event) => {
const translationX = Math.max(event.translationX, 0);
if (event.y < drawerGestureThreshold && translationX > 56) {
runOnJS(completeDrawerGesture)();
}
}),
[completeDrawerGesture, isSplitLayout],
);
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
setMeasuredOverlayHeight((current) =>
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
);
}, []);
return (
<GestureDetector gesture={headerDrawerGesture}>
<View className="flex-1">
{showContent ? (
<ThreadFeed
threadId={props.selectedThread.id}
feed={props.selectedThreadFeed}
httpBaseUrl={props.httpBaseUrl}
bearerToken={props.bearerToken}
agentLabel={agentLabel}
contentBottomInset={feedBottomInset}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
refreshing={refreshing}
onRefresh={handleRefresh}
/>
) : (
<View style={{ flex: 1 }} />
)}
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View onLayout={handleOverlayLayout}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
) : null}
<ThreadComposer
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
connectionState={props.connectionStateLabel}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onRefresh={props.onRefresh}
onStopThread={props.onStopThread}
onSendMessage={props.onSendMessage}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
</View>
</KeyboardStickyView>
) : null}
</View>
</GestureDetector>
);
});
@@ -1,685 +0,0 @@
import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Markdown,
type CustomRenderers,
type NodeStyleOverrides,
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import {
Image,
Pressable,
ScrollView,
Text as NativeText,
type ColorValue,
View,
} from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { cn } from "../../lib/cn";
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import type { ThreadFeedEntry } from "../../lib/threadActivity";
import { relativeTime } from "../../lib/time";
import { messageImageUrl } from "./threadPresentation";
export interface ThreadFeedProps {
readonly threadId: string;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly agentLabel: string;
readonly contentBottomInset?: number;
readonly refreshing?: boolean;
readonly onRefresh?: () => void;
readonly layoutVariant?: MobileLayoutVariant;
readonly composerExpanded?: boolean;
}
function stripShellWrapper(value: string): string {
const trimmed = value.trim();
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
return (match?.[1] ?? trimmed).trim();
}
function compactActivityDetail(detail: string | null): string | null {
if (!detail) {
return null;
}
const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
return cleaned.length > 0 ? cleaned : null;
}
function buildActivityRows(
activities: ReadonlyArray<{
readonly id: string;
readonly createdAt: string;
readonly summary: string;
readonly detail: string | null;
readonly status: string | null;
}>,
) {
return activities.map<{
id: string;
createdAt: string;
summary: string;
detail: string | null;
status: string | null;
}>((activity) => ({
id: activity.id,
createdAt: activity.createdAt,
summary: activity.summary,
detail: compactActivityDetail(activity.detail),
status: activity.status,
}));
}
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
function toMarkdownThemeColor(value: ColorValue): string {
return value as string;
}
interface MarkdownStyleSets {
readonly user: MarkdownStyleSet;
readonly assistant: MarkdownStyleSet;
}
interface MarkdownStyleSet {
readonly theme: PartialMarkdownTheme;
readonly styles: NodeStyleOverrides;
readonly renderers: CustomRenderers;
}
function useMarkdownStyles(): MarkdownStyleSets {
const bodyColor = useThemeColor("--color-md-body");
const strongColor = useThemeColor("--color-md-strong");
const linkColor = useThemeColor("--color-md-link");
const blockquoteBg = useThemeColor("--color-md-blockquote-bg");
const blockquoteBorder = useThemeColor("--color-md-blockquote-border");
const codeBg = useThemeColor("--color-md-code-bg");
const codeText = useThemeColor("--color-md-code-text");
const hrColor = useThemeColor("--color-md-hr");
const userCodeBg = useThemeColor("--color-md-user-code-bg");
const userCodeText = useThemeColor("--color-md-user-code-text");
const userFenceBg = useThemeColor("--color-md-user-fence-bg");
const userFenceText = useThemeColor("--color-md-user-fence-text");
return useMemo(() => {
const markdownBodyColor = toMarkdownThemeColor(bodyColor);
const markdownStrongColor = toMarkdownThemeColor(strongColor);
const markdownLinkColor = toMarkdownThemeColor(linkColor);
const markdownBlockquoteBg = toMarkdownThemeColor(blockquoteBg);
const markdownBlockquoteBorder = toMarkdownThemeColor(blockquoteBorder);
const markdownCodeBg = toMarkdownThemeColor(codeBg);
const markdownCodeText = toMarkdownThemeColor(codeText);
const markdownHrColor = toMarkdownThemeColor(hrColor);
const markdownUserCodeBg = toMarkdownThemeColor(userCodeBg);
const markdownUserCodeText = toMarkdownThemeColor(userCodeText);
const markdownUserFenceBg = toMarkdownThemeColor(userFenceBg);
const markdownUserFenceText = toMarkdownThemeColor(userFenceText);
const baseTheme: PartialMarkdownTheme = {
colors: {
text: markdownBodyColor,
heading: markdownStrongColor,
link: markdownLinkColor,
blockquote: markdownBlockquoteBorder,
border: markdownHrColor,
surfaceLight: markdownBlockquoteBg,
accent: markdownLinkColor,
tableBorder: markdownHrColor,
tableHeader: markdownBlockquoteBg,
tableHeaderText: markdownStrongColor,
tableRowOdd: "transparent",
tableRowEven: "transparent",
},
spacing: {
xs: 4,
s: 4,
m: 8,
l: 8,
xl: 16,
},
fontSizes: {
s: 13,
m: 15,
h1: 22,
h2: 19,
h3: 17,
h4: 15,
h5: 15,
h6: 15,
},
fontFamilies: {
regular: "DMSans_400Regular",
heading: "DMSans_700Bold",
mono: "ui-monospace",
},
headingWeight: "700",
borderRadius: {
s: 4,
m: 8,
l: 12,
},
showCodeLanguage: false,
};
const baseStyles: NodeStyleOverrides = {
document: { flexShrink: 1 },
paragraph: { marginTop: 0, marginBottom: 8 },
list: { marginTop: 4, marginBottom: 4 },
list_item: { marginTop: 0, marginBottom: 4 },
task_list_item: { marginTop: 0, marginBottom: 4 },
bold: { fontWeight: "700", color: markdownStrongColor, fontFamily: "DMSans_700Bold" },
italic: { fontStyle: "italic" },
link: { color: markdownLinkColor, textDecorationLine: "underline" as const },
blockquote: {
borderLeftWidth: 3,
borderLeftColor: markdownBlockquoteBorder,
backgroundColor: markdownBlockquoteBg,
paddingLeft: 12,
paddingVertical: 6,
marginLeft: 0,
marginVertical: 4,
borderRadius: 4,
},
heading: {
fontFamily: "DMSans_700Bold",
color: markdownStrongColor,
marginTop: 12,
marginBottom: 6,
},
horizontal_rule: {
backgroundColor: markdownHrColor,
height: 1,
marginVertical: 12,
},
};
const createCodeRenderers = (
inlineBackgroundColor: string,
inlineTextColor: string,
blockBackgroundColor: string,
blockTextColor: string,
): CustomRenderers => ({
code_inline: ({ content }) => (
<NativeText
style={{
backgroundColor: inlineBackgroundColor,
color: inlineTextColor,
borderRadius: 5,
paddingHorizontal: 5,
paddingVertical: 1,
fontFamily: "ui-monospace",
fontSize: 13,
}}
>
{content}
</NativeText>
),
code_block: ({ content }) => (
<View
style={{
backgroundColor: blockBackgroundColor,
borderRadius: 12,
padding: 12,
marginVertical: 8,
}}
>
<ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
<NativeText
selectable
style={{
color: blockTextColor,
fontFamily: "ui-monospace",
fontSize: 13,
lineHeight: 19,
}}
>
{content}
</NativeText>
</ScrollView>
</View>
),
});
const userTheme: PartialMarkdownTheme = {
...baseTheme,
colors: {
...baseTheme.colors,
code: markdownUserCodeText,
codeBackground: markdownUserCodeBg,
border: markdownUserFenceBg,
},
};
const userStyles: NodeStyleOverrides = {
...baseStyles,
paragraph: { marginTop: 0, marginBottom: 0 },
};
const assistantTheme: PartialMarkdownTheme = {
...baseTheme,
colors: {
...baseTheme.colors,
code: markdownCodeText,
codeBackground: markdownCodeBg,
border: markdownCodeBg,
},
};
const assistantStyles: NodeStyleOverrides = {
...baseStyles,
};
return {
user: {
theme: userTheme,
styles: userStyles,
renderers: createCodeRenderers(
markdownUserCodeBg,
markdownUserCodeText,
markdownUserFenceBg,
markdownUserFenceText,
),
},
assistant: {
theme: assistantTheme,
styles: assistantStyles,
renderers: createCodeRenderers(
markdownCodeBg,
markdownCodeText,
markdownCodeBg,
markdownCodeText,
),
},
};
}, [
blockquoteBg,
blockquoteBorder,
bodyColor,
codeBg,
codeText,
hrColor,
linkColor,
strongColor,
userCodeBg,
userCodeText,
userFenceBg,
userFenceText,
]);
}
function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number },
props: Pick<ThreadFeedProps, "bearerToken" | "httpBaseUrl"> & {
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
readonly onCopyWorkRow: (rowId: string, value: string) => void;
readonly onToggleWorkGroup: (groupId: string) => void;
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
readonly iconSubtleColor: string | import("react-native").ColorValue;
readonly markdownStyles: MarkdownStyleSets;
},
) {
const entry = info.item;
const { markdownStyles, iconSubtleColor } = props;
if (entry.type === "message") {
const { message } = entry;
const isUser = message.role === "user";
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
const timestampLabel = `${relativeTime(message.createdAt)}${message.streaming ? " • live" : ""}`;
const attachments = message.attachments ?? [];
if (isUser) {
return (
<View className="mb-3.5 items-end gap-1.5">
<View className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[10px] border border-blue-300/50 bg-blue-50/80 px-4 py-4 dark:border-blue-400/20 dark:bg-blue-500/12">
{message.text.trim().length > 0 ? (
<Markdown
options={{ gfm: true }}
renderers={styles.renderers}
styles={styles.styles}
theme={styles.theme}
>
{message.text}
</Markdown>
) : null}
{attachments.map((attachment) => {
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
if (!uri) {
return null;
}
const headers = props.bearerToken
? { Authorization: `Bearer ${props.bearerToken}` }
: undefined;
return (
<TouchableOpacity
key={attachment.id}
activeOpacity={0.7}
onPress={() => props.onPressImage(uri, headers)}
>
<Image
source={{ uri, ...(headers ? { headers } : {}) }}
className="aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
resizeMode="cover"
/>
</TouchableOpacity>
);
})}
</View>
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
{timestampLabel}
</Text>
</View>
);
}
// Skip empty assistant messages (no text, no attachments) — they would
// render as an orphaned timestamp and break adjacent activity-group merging.
if (message.text.trim().length === 0 && attachments.length === 0) {
return null;
}
return (
<View className="mb-3.5 gap-1.5 px-1">
{message.text.trim().length > 0 ? (
<Markdown
options={{ gfm: true }}
renderers={styles.renderers}
styles={styles.styles}
theme={styles.theme}
>
{message.text}
</Markdown>
) : null}
{attachments.map((attachment) => {
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
if (!uri) {
return null;
}
const headers = props.bearerToken
? { Authorization: `Bearer ${props.bearerToken}` }
: undefined;
return (
<TouchableOpacity
key={attachment.id}
activeOpacity={0.7}
onPress={() => props.onPressImage(uri, headers)}
>
<Image
source={{ uri, ...(headers ? { headers } : {}) }}
className="aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
resizeMode="cover"
/>
</TouchableOpacity>
);
})}
<Text className="font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
{timestampLabel}
</Text>
</View>
);
}
if (entry.type === "queued-message") {
return (
<View className="mb-3.5 gap-1.5 items-end">
<View className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[10px] border border-sky-300/60 bg-sky-100/75 px-4 py-4 dark:border-sky-300/20 dark:bg-sky-400/10">
<Text className="font-sans text-[15px] leading-[22px] text-neutral-950 dark:text-neutral-50">
{entry.queuedMessage.text}
</Text>
{entry.queuedMessage.attachments.length > 0 ? (
<Text className="font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
{entry.queuedMessage.attachments.length} image
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
</Text>
) : null}
</View>
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
</Text>
</View>
);
}
const rows = buildActivityRows(entry.activities);
const isExpanded = props.expandedWorkGroups[entry.id] ?? false;
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const showHeader = hasOverflow;
return (
<View className="mb-3 rounded-[20px] border border-neutral-200/80 bg-neutral-50/85 px-3 py-2 dark:border-white/[0.06] dark:bg-white/[0.025]">
{showHeader ? (
<View className="mb-1.5 flex-row items-center justify-between gap-3 px-0.5">
<Text className="font-t3-bold text-[10px] uppercase tracking-[0.8px] text-neutral-500 dark:text-neutral-500">
Tool calls ({rows.length})
</Text>
<Pressable onPress={() => props.onToggleWorkGroup(entry.id)}>
<Text className="font-t3-medium text-[10px] uppercase tracking-[0.8px] text-neutral-500 dark:text-neutral-500">
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</Text>
</Pressable>
</View>
) : null}
{visibleRows.map((row, index) => (
<View
key={row.id}
className={cn(
"flex-row items-center gap-2 rounded-lg px-1 py-1",
index > 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
)}
>
<View className="items-center justify-center pt-0.5">
<SymbolView name="terminal" size={13} tintColor={iconSubtleColor} type="monochrome" />
</View>
<ScrollView
horizontal
nestedScrollEnabled
directionalLockEnabled
showsHorizontalScrollIndicator={false}
bounces={false}
className="flex-1"
contentContainerStyle={{ paddingRight: 12 }}
style={{ flex: 1 }}
>
<Text
className="text-[12px] leading-[18px] text-neutral-600 dark:text-neutral-400"
onLongPress={() => {
const copyValue = row.detail ?? row.summary;
props.onCopyWorkRow(row.id, copyValue);
}}
style={{
fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, monospace",
}}
>
{row.detail ? `${row.summary} - ${row.detail}` : row.summary}
</Text>
</ScrollView>
{props.copiedRowId === row.id ? (
<Text className="shrink-0 font-t3-medium text-[10px] uppercase tracking-[0.8px] text-emerald-600 dark:text-emerald-400">
Copied
</Text>
) : null}
</View>
))}
</View>
);
}
const IOS_NAV_BAR_HEIGHT = 44;
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [expandedImage, setExpandedImage] = useState<{
uri: string;
headers?: Record<string, string>;
} | null>(null);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const insets = useSafeAreaInsets();
const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const markdownStyles = useMarkdownStyles();
useEffect(() => {
setCopiedRowId(null);
setExpandedWorkGroups({});
}, [props.threadId]);
// Scroll to end when the composer expands (keyboard opens) so the latest
// message stays visible above the taller composer + keyboard.
useEffect(() => {
if (props.composerExpanded && props.feed.length > 0) {
// Small delay to let KAV + layout settle before scrolling
const timer = setTimeout(() => {
void listRef.current?.scrollToEnd({ animated: true });
}, 100);
return () => clearTimeout(timer);
}
}, [props.composerExpanded, props.feed.length]);
useEffect(() => {
return () => {
if (copyFeedbackTimeoutRef.current) {
clearTimeout(copyFeedbackTimeoutRef.current);
}
};
}, []);
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
void Clipboard.setStringAsync(value);
void Haptics.selectionAsync();
setCopiedRowId(rowId);
if (copyFeedbackTimeoutRef.current) {
clearTimeout(copyFeedbackTimeoutRef.current);
}
copyFeedbackTimeoutRef.current = setTimeout(() => {
setCopiedRowId((current) => (current === rowId ? null : current));
copyFeedbackTimeoutRef.current = null;
}, 1200);
}, []);
const onToggleWorkGroup = useCallback((groupId: string) => {
setExpandedWorkGroups((current) => ({
...current,
[groupId]: !(current[groupId] ?? false),
}));
}, []);
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
setExpandedImage({ uri, headers });
}, []);
const renderItem = useCallback(
(info: { item: ThreadFeedEntry; index: number }) =>
renderFeedEntry(info, {
bearerToken: props.bearerToken,
copiedRowId,
httpBaseUrl: props.httpBaseUrl,
expandedWorkGroups,
onCopyWorkRow,
onToggleWorkGroup,
onPressImage,
iconSubtleColor,
markdownStyles,
}),
[
copiedRowId,
expandedWorkGroups,
iconSubtleColor,
markdownStyles,
onCopyWorkRow,
onPressImage,
onToggleWorkGroup,
props.bearerToken,
props.httpBaseUrl,
],
);
if (props.feed.length === 0) {
return (
<ScrollView
style={{ flex: 1 }}
contentInsetAdjustmentBehavior="never"
contentInset={{ top: topContentInset }}
contentOffset={{ x: 0, y: -topContentInset }}
scrollIndicatorInsets={{ top: topContentInset }}
contentContainerStyle={{
flexGrow: 1,
paddingHorizontal: horizontalPadding,
paddingBottom: props.contentBottomInset ?? 18,
}}
>
<EmptyState
title="No conversation yet"
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
/>
</ScrollView>
);
}
return (
<>
<KeyboardAvoidingLegendList
ref={listRef}
key={props.threadId}
style={{ flex: 1 }}
alignItemsAtEnd
contentInsetAdjustmentBehavior="never"
contentInset={{ top: topContentInset }}
scrollIndicatorInsets={{ top: topContentInset }}
data={props.feed as ThreadFeedEntry[]}
renderItem={renderItem}
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
keyboardShouldPersistTaps="handled"
estimatedItemSize={80}
initialScrollAtEnd
maintainScrollAtEnd={{ on: { layout: true, itemLayout: true, dataChange: true } }}
maintainScrollAtEndThreshold={0.1}
refreshing={props.refreshing ?? false}
onRefresh={props.onRefresh}
safeAreaInsetBottom={insets.bottom}
contentContainerStyle={{
paddingTop: 12,
paddingHorizontal: horizontalPadding,
paddingBottom: props.contentBottomInset ?? 18,
}}
/>
<ImageViewing
images={
expandedImage
? [
{
uri: expandedImage.uri,
headers: expandedImage.headers,
},
]
: []
}
imageIndex={0}
visible={expandedImage !== null}
onRequestClose={() => setExpandedImage(null)}
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</>
);
});
@@ -1,201 +0,0 @@
import type { GitRunStackedActionResult, GitStatusResult } from "@t3tools/contracts";
import {
type GitActionRequestInput,
requiresDefaultBranchConfirmation,
resolveQuickAction,
} from "@t3tools/client-runtime";
import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react";
import { Alert, Linking } from "react-native";
function truncateMiddle(value: string, maxLength: number): string {
if (value.length <= maxLength) {
return value;
}
const headLength = Math.ceil((maxLength - 1) / 2);
const tailLength = Math.floor((maxLength - 1) / 2);
return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`;
}
function compactMenuBranchLabel(branch: string): string {
return truncateMiddle(branch, 24);
}
function compactMenuStatus(gitStatus: GitStatusResult | null): string {
if (!gitStatus) {
return "Checking status";
}
if (!gitStatus.isRepo) {
return "Not a repo";
}
const parts: string[] = [];
if (gitStatus.hasWorkingTreeChanges) {
parts.push(`${gitStatus.workingTree.files.length} changed`);
} else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
parts.push("Clean");
}
if (gitStatus.aheadCount > 0) {
parts.push(`${gitStatus.aheadCount} ahead`);
}
if (gitStatus.behindCount > 0) {
parts.push(`${gitStatus.behindCount} behind`);
}
if (gitStatus.pr?.state === "open") {
parts.push(`PR #${gitStatus.pr.number}`);
}
return parts.join(" · ");
}
export function ThreadGitControls(props: {
readonly currentBranch: string | null;
readonly gitStatus: GitStatusResult | null;
readonly gitOperationLabel: string | null;
readonly onPull: () => Promise<void>;
readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
}) {
const router = useRouter();
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: string;
threadId: string;
}>();
const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
const currentBranchLabel = gitStatus?.branch ?? props.currentBranch ?? "Detached HEAD";
const busy = gitOperationLabel !== null;
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
const isDefaultBranch = gitStatus?.isDefaultBranch ?? false;
const quickAction = useMemo(
() =>
isRepo
? resolveQuickAction(gitStatus, busy, isDefaultBranch, hasOriginRemote)
: {
label: "Git unavailable",
disabled: true,
kind: "show_hint" as const,
hint: "This workspace is not a git repository.",
},
[busy, gitStatus, hasOriginRemote, isDefaultBranch, isRepo],
);
const quickActionHint = quickAction.disabled
? (quickAction.hint ?? "This action is unavailable.")
: null;
const quickActionIcon = (() => {
if (quickAction.kind === "run_pull") return "arrow.down.circle";
if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return "checkmark.circle";
if (quickAction.action === "push" || quickAction.action === "commit_push")
return "arrow.up.circle";
}
return "arrow.up.right.circle";
})();
const openExistingPr = useCallback(async () => {
const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
if (!prUrl) {
Alert.alert("No open PR", "This branch does not have an open pull request.");
return;
}
try {
await Linking.openURL(prUrl);
} catch (error) {
Alert.alert(
"Unable to open PR",
error instanceof Error ? error.message : "An error occurred.",
);
}
}, [gitStatus]);
const runActionWithPrompt = useCallback(
async (input: GitActionRequestInput) => {
const confirmableAction =
input.action === "push" ||
input.action === "create_pr" ||
input.action === "commit_push" ||
input.action === "commit_push_pr"
? input.action
: null;
const branchName = gitStatus?.branch;
if (
branchName &&
confirmableAction &&
!input.featureBranch &&
requiresDefaultBranchConfirmation(input.action, isDefaultBranch)
) {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git-confirm",
params: {
environmentId,
threadId,
confirmAction: confirmableAction,
branchName,
includesCommit: String(
input.action === "commit_push" || input.action === "commit_push_pr",
),
},
});
return;
}
await onRunAction(input);
},
[environmentId, gitStatus, isDefaultBranch, onRunAction, router, threadId],
);
const runQuickAction = useCallback(async () => {
if (quickAction.kind === "open_pr") {
await openExistingPr();
return;
}
if (quickAction.kind === "run_pull") {
await onPull();
return;
}
if (quickAction.kind === "run_action" && quickAction.action) {
await runActionWithPrompt({ action: quickAction.action });
}
}, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
return (
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
<Stack.Toolbar.MenuAction
icon="point.topleft.down.curvedto.point.bottomright.up"
disabled
onPress={() => {}}
subtitle={compactMenuStatus(gitStatus)}
>
<Stack.Toolbar.Label>{compactMenuBranchLabel(currentBranchLabel)}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon={quickActionIcon}
disabled={quickAction.disabled}
onPress={() => void runQuickAction()}
subtitle={quickActionHint ?? undefined}
>
<Stack.Toolbar.Label>{quickAction.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="ellipsis.circle"
onPress={() =>
router.push({
pathname: "/threads/[environmentId]/[threadId]/git",
params: { environmentId, threadId },
})
}
subtitle="Commit, files, branches"
>
<Stack.Toolbar.Label>More</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
);
}
@@ -1,254 +0,0 @@
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Modal, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
runOnJS,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "./threadPresentation";
import {
EnvironmentScopedProjectShell,
EnvironmentScopedThreadShell,
} from "@t3tools/client-runtime";
function compareThreadActivity(
left: EnvironmentScopedThreadShell,
right: EnvironmentScopedThreadShell,
): number {
return (
new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime() || left.title.localeCompare(right.title)
);
}
export function ThreadNavigationDrawer(props: {
readonly visible: boolean;
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
readonly onStartNewTask: () => void;
}) {
const insets = useSafeAreaInsets();
const { width } = useWindowDimensions();
const drawerWidth = Math.min(width * 0.84, 360);
const [mounted, setMounted] = useState(props.visible);
const translateX = useSharedValue(-drawerWidth);
const overlayOpacity = useSharedValue(0);
const backdropColor = useThemeColor("--color-backdrop");
const drawerBg = useThemeColor("--color-drawer");
const drawerShadow = useThemeColor("--color-drawer-shadow");
const primaryForeground = useThemeColor("--color-primary-foreground");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
[props.projects, props.threads],
);
const groupedThreads = useMemo(
() =>
repositoryGroups.map((group) => ({
key: group.key,
title: group.projects[0]?.project.title ?? group.title,
threads: group.projects
.flatMap((projectGroup) => projectGroup.threads)
.sort(compareThreadActivity),
})),
[repositoryGroups],
);
useEffect(() => {
if (props.visible) {
setMounted(true);
translateX.value = withTiming(0, { duration: 240 });
overlayOpacity.value = withTiming(1, { duration: 220 });
return;
}
overlayOpacity.value = withTiming(0, { duration: 180 });
translateX.value = withTiming(-drawerWidth, { duration: 220 }, (finished) => {
if (finished) {
runOnJS(setMounted)(false);
}
});
}, [drawerWidth, overlayOpacity, props.visible, translateX]);
const closeDrawer = useCallback(() => {
props.onClose();
}, [props]);
const panGesture = useMemo(
() =>
Gesture.Pan()
.activeOffsetX([-12, 12])
.failOffsetY([-24, 24])
.onUpdate((event) => {
translateX.value = Math.min(0, event.translationX);
})
.onEnd((event) => {
const shouldClose = event.translationX < -drawerWidth * 0.2 || event.velocityX < -500;
if (shouldClose) {
runOnJS(closeDrawer)();
return;
}
translateX.value = withTiming(0, { duration: 180 });
}),
[closeDrawer, drawerWidth, translateX],
);
const drawerStyle = useAnimatedStyle(() => ({
transform: [{ translateX: translateX.value }],
}));
const backdropStyle = useAnimatedStyle(() => ({
opacity: overlayOpacity.value,
}));
if (!mounted) {
return null;
}
return (
<Modal transparent visible={mounted} onRequestClose={props.onClose} statusBarTranslucent>
<View style={{ flex: 1 }}>
<Animated.View
pointerEvents="none"
style={[
{
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundColor: backdropColor,
},
backdropStyle,
]}
/>
<Pressable
style={{ position: "absolute", left: 0, right: 0, top: 0, bottom: 0 }}
onPress={props.onClose}
/>
<GestureDetector gesture={panGesture}>
<Animated.View
style={[
{
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: drawerWidth,
backgroundColor: drawerBg,
paddingTop: insets.top + 10,
paddingBottom: Math.max(insets.bottom, 18),
boxShadow: `20px 0 36px ${String(drawerShadow)}`,
},
drawerStyle,
]}
>
<View className="flex-row items-center justify-between px-4 pb-5">
<Text className="text-[26px] font-t3-bold">Threads</Text>
<Pressable
onPress={() => {
props.onClose();
props.onStartNewTask();
}}
className="h-11 w-11 items-center justify-center rounded-full bg-primary"
>
<SymbolView
name="square.and.pencil"
size={17}
tintColor={primaryForeground}
type="monochrome"
/>
</Pressable>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
gap: 20,
paddingHorizontal: 14,
paddingBottom: Math.max(insets.bottom, 18) + 12,
}}
>
{groupedThreads.map((group) => (
<View key={group.key} className="gap-3">
<Text
className="px-1 text-[15px] font-t3-bold text-foreground-muted"
style={{ letterSpacing: -0.2 }}
>
{group.title}
</Text>
<View className="overflow-hidden rounded-[22px] bg-card">
{group.threads.length === 0 ? (
<View className="px-4 py-4">
<Text className="text-[14px] font-medium text-foreground-tertiary">
No threads yet
</Text>
</View>
) : (
group.threads.map((thread, index) => {
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
const selected = props.selectedThreadKey === threadKey;
return (
<Pressable
key={threadKey}
onPress={() => {
props.onSelectThread(thread);
props.onClose();
}}
style={{
paddingHorizontal: 16,
paddingVertical: 15,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: borderSubtleColor,
backgroundColor: selected ? undefined : "transparent",
}}
className={selected ? "bg-subtle" : undefined}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text className="text-[16px] font-t3-bold" numberOfLines={1}>
{thread.title}
</Text>
<Text
className="text-[13px] font-medium text-foreground-muted"
numberOfLines={1}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
<StatusPill {...threadStatusTone(thread)} />
</View>
</Pressable>
);
})
)}
</View>
</View>
))}
</ScrollView>
</Animated.View>
</GestureDetector>
</View>
</Modal>
);
}
@@ -1,287 +0,0 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Arr from "effect/Array";
import * as Option from "effect/Option";
import { pipe } from "effect/Function";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { useGitStatus, gitStatusManager } from "../../state/use-git-status";
import { dismissGitActionResult, useGitActionProgress } from "../../state/use-git-action-state";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { buildThreadRoutePath } from "../../lib/routes";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { connectionTone } from "../connection/connectionTone";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import {
useRemoteConnectionStatus,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useThreadSelection } from "../../state/use-thread-selection";
import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { useSelectedThreadCommands } from "./use-selected-thread-commands";
import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "./use-selected-thread-git-state";
import { useThreadComposerState } from "./use-thread-composer-state";
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
return value[0] ?? null;
}
return value ?? null;
}
export function ThreadRouteScreen() {
const { isLoadingSavedConnection, environmentStateById, pendingConnectionError } =
useRemoteEnvironmentState();
const { connectionState, connectionError: aggregateConnectionError } =
useRemoteConnectionStatus();
const { projects, threads } = useRemoteCatalog();
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const commands = useSelectedThreadCommands({
activePendingUserInput: composer.activePendingUserInput,
activePendingUserInputAnswers: composer.activePendingUserInputAnswers,
refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
});
const refreshSelectedThread = commands.onRefresh;
const router = useRouter();
const params = useLocalSearchParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
const [drawerVisible, setDrawerVisible] = useState(false);
const environmentId = firstRouteParam(params.environmentId);
const threadId = firstRouteParam(params.threadId);
const routeEnvironmentRuntime = environmentId
? (environmentStateById[environmentId] ?? null)
: null;
const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? connectionState;
const routeConnectionError =
pendingConnectionError ?? routeEnvironmentRuntime?.connectionError ?? aggregateConnectionError;
/* ─── Native header theming ──────────────────────────────────────── */
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
/* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useGitStatus({
environmentId: selectedThread?.environmentId ?? "",
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
/* ─── Git action progress (for overlay banner) ──────────────────── */
const gitActionProgressTarget = useMemo(
() => ({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
}),
[
selectedThread?.environmentId,
selectedThread?.worktreePath,
selectedThreadProject?.workspaceRoot,
],
);
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
const handleRefreshGitStatus = useCallback(async () => {
if (!selectedThread) return;
await gitStatusManager.refresh({
environmentId: selectedThread.environmentId,
cwd: selectedThread.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
}, [selectedThread, selectedThreadProject?.workspaceRoot]);
/** Wraps thread refresh + git status refresh for pull-to-refresh */
const handleRefreshAll = useCallback(async () => {
await refreshSelectedThread();
await handleRefreshGitStatus();
}, [handleRefreshGitStatus, refreshSelectedThread]);
const handleOpenDrawer = useCallback(() => {
setDrawerVisible(true);
}, []);
const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections");
}, [router]);
if (!environmentId || !threadId) {
return <LoadingScreen message="Opening thread…" />;
}
if (!selectedThread) {
const stillHydrating =
isLoadingSavedConnection ||
routeConnectionState === "connecting" ||
routeConnectionState === "reconnecting";
if (stillHydrating) {
return <LoadingScreen message="Opening thread…" />;
}
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
justifyContent: "center",
paddingHorizontal: 24,
paddingVertical: 32,
}}
className="bg-screen flex-1"
>
<EmptyState
title="Thread unavailable"
detail="This thread is not available in the current mobile snapshot."
/>
</ScrollView>
);
}
if (!selectedThreadDetail) {
return <LoadingScreen message="Opening thread…" />;
}
const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const serverConfig =
routeEnvironmentRuntime?.serverConfig ??
pipe(
Object.values(environmentStateById),
Arr.map((runtime) => runtime.serverConfig),
Arr.findFirst((value) => value !== null),
Option.getOrNull,
);
const headerSubtitle = [
selectedThreadProject?.title ?? null,
selectedEnvironmentConnection?.environmentLabel ?? null,
]
.filter(Boolean)
.join(" · ");
return (
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerBackTitle: "",
headerTitle: () => (
<Pressable
style={{ alignItems: "center", maxWidth: 200 }}
onLongPress={() => {
// TODO: trigger rename modal
}}
>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: 18,
fontWeight: "900",
color: foregroundColor,
letterSpacing: -0.4,
}}
>
{selectedThreadDetail.title}
</RNText>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: 12,
fontWeight: "700",
color: secondaryFg,
letterSpacing: 0.3,
}}
>
{headerSubtitle}
</RNText>
</Pressable>
),
}}
/>
<ThreadGitControls
currentBranch={selectedThreadDetail.branch}
gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel}
onPull={gitActions.onPullSelectedThreadBranch}
onRunAction={gitActions.onRunSelectedThreadGitAction}
/>
<GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThreadDetail}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null}
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={composer.activePendingApproval}
respondingApprovalId={commands.respondingApprovalId}
activePendingUserInput={composer.activePendingUserInput}
activePendingUserInputDrafts={composer.activePendingUserInputDrafts}
activePendingUserInputAnswers={composer.activePendingUserInputAnswers}
respondingUserInputId={commands.respondingUserInputId}
draftMessage={composer.draftMessage}
draftAttachments={composer.draftAttachments}
connectionStateLabel={routeConnectionState}
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
onRefresh={handleRefreshAll}
serverConfig={serverConfig}
onStopThread={commands.onStopThread}
onSendMessage={composer.onSendMessage}
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
onRespondToApproval={commands.onRespondToApproval}
onSelectUserInputOption={composer.onSelectUserInputOption}
onChangeUserInputCustomAnswer={composer.onChangeUserInputCustomAnswer}
onSubmitUserInput={commands.onSubmitUserInput}
/>
<ThreadNavigationDrawer
visible={drawerVisible}
projects={projects}
threads={threads}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
router.replace(buildThreadRoutePath(thread));
}}
onStartNewTask={() => router.push("/new")}
/>
</View>
</>
);
}
@@ -1,203 +0,0 @@
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useGitStatus } from "../../../state/use-git-status";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
import { SheetActionButton } from "./gitSheetComponents";
export function GitBranchesSheet() {
const router = useRouter();
const insets = useSafeAreaInsets();
const { selectedThread, selectedThreadProject } = useThreadSelection();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const borderColor = useThemeColor("--color-border");
const inputBorderColor = useThemeColor("--color-input-border");
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const subtleStrongColor = useThemeColor("--color-subtle-strong");
const gitStatus = useGitStatus({
environmentId: selectedThread?.environmentId ?? "",
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD";
const currentWorktreePath = selectedThread?.worktreePath ?? null;
const availableBranches = gitState.selectedThreadBranches;
const branchesLoading = gitState.selectedThreadBranchesLoading;
const busy = gitState.gitOperationLabel !== null;
const [newBranchName, setNewBranchName] = useState("");
const [worktreeBaseBranch, setWorktreeBaseBranch] = useState(
currentBranchLabel === "Detached HEAD" ? "main" : currentBranchLabel,
);
const [worktreeBranchName, setWorktreeBranchName] = useState("");
const disabledExistingBranches = new Set(
availableBranches
.filter(
(branch) => branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath,
)
.map((branch) => branch.name),
);
useEffect(() => {
void gitActions.refreshSelectedThreadBranches();
}, [gitActions]);
return (
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 16,
}}
>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New branch
</Text>
<TextInput
value={newBranchName}
onChangeText={setNewBranchName}
placeholder="feature/mobile-polish"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="plus"
label="Create & checkout"
tone="primary"
disabled={busy || newBranchName.trim().length === 0}
onPress={() => {
const branch = sanitizeFeatureBranchName(newBranchName.trim());
if (branch.length === 0) return;
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
setNewBranchName("");
router.dismiss();
});
}}
/>
</View>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New worktree
</Text>
<TextInput
value={worktreeBaseBranch}
onChangeText={setWorktreeBaseBranch}
placeholder="main"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<TextInput
value={worktreeBranchName}
onChangeText={setWorktreeBranchName}
placeholder="feature/mobile-thread"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="square.split.2x1"
label="Create worktree"
tone="primary"
disabled={
busy || worktreeBaseBranch.trim().length === 0 || worktreeBranchName.trim().length === 0
}
onPress={() => {
const baseBranch = worktreeBaseBranch.trim();
const newBranch = worktreeBranchName.trim();
if (baseBranch.length === 0 || newBranch.length === 0) return;
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
setWorktreeBranchName("");
router.dismiss();
});
}}
/>
</View>
<View className="gap-2">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
Existing branches
</Text>
{branchesLoading ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
Loading branches...
</Text>
) : null}
{!branchesLoading && availableBranches.length === 0 ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
No local branches found.
</Text>
) : null}
{availableBranches.map((branch) => {
const disabled = disabledExistingBranches.has(branch.name);
const subtitle = branch.worktreePath
? branch.worktreePath === currentWorktreePath
? "Checked out in this thread"
: "Checked out in another worktree"
: branch.isDefault
? "Default branch"
: "Local branch";
return (
<Pressable
key={branch.name}
className="gap-1 rounded-[18px] border px-4 py-3"
disabled={busy || disabled}
style={{
borderColor: branch.current ? subtleStrongColor : borderColor,
opacity: busy || disabled ? 0.45 : 1,
}}
onPress={() => {
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
router.dismiss();
});
}}
>
<View className="absolute inset-0 rounded-[18px] bg-card" />
<Text className="text-foreground text-[15px] font-t3-bold">{branch.name}</Text>
<Text className="text-foreground-secondary text-[12px] font-medium">{subtitle}</Text>
</Pressable>
);
})}
</View>
</ScrollView>
);
}
Loaded 100 of 576 files, more files were not shown because too many files have changed in this diff. Show more