Compare commits
114
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
159021e95e | ||
|
|
4b35ac856d | ||
|
|
efb25b1596 | ||
|
|
f6022f33d0 | ||
|
|
7d233d93ad | ||
|
|
5304f3e9d4 | ||
|
|
85389b9883 | ||
|
|
db1507e986 | ||
|
|
96bfa67b3d | ||
|
|
5ff3a03ada | ||
|
|
23d45d914e | ||
|
|
bad1143b02 | ||
|
|
92d4a2e996 | ||
|
|
2fab18e289 | ||
|
|
1b16ed663f | ||
|
|
83ad26c3a3 | ||
|
|
fd51561b4e | ||
|
|
9e201941aa | ||
|
|
2ab188f1c0 | ||
|
|
9513e62e24 | ||
|
|
97db94c9bf | ||
|
|
5015d7cf9f | ||
|
|
df19f6cfe3 | ||
|
|
6bc6cb6be4 | ||
|
|
1e59b4c400 | ||
|
|
33f9705926 | ||
|
|
da6253b3dd | ||
|
|
ac1264e2ca | ||
|
|
2eb099fdc8 | ||
|
|
b28f9bf0a1 | ||
|
|
d0b8d6306b | ||
|
|
9666b87516 | ||
|
|
e3a9c2518d | ||
|
|
18918d1c4d | ||
|
|
8d24b5131f | ||
|
|
770946d026 | ||
|
|
8601797233 | ||
|
|
b73232bdd3 | ||
|
|
f131228a59 | ||
|
|
e321667b10 | ||
|
|
849bac8946 | ||
|
|
6fd088af9f | ||
|
|
b54bfc9312 | ||
|
|
e1378a1f4d | ||
|
|
5a84614809 | ||
|
|
63e6faef62 | ||
|
|
d37a9b09b8 | ||
|
|
560d4a4560 | ||
|
|
52e5a75a87 | ||
|
|
c196f422ed | ||
|
|
f0b57ca231 | ||
|
|
2db08457f2 | ||
|
|
083fa4ab24 | ||
|
|
35172010b1 | ||
|
|
57b1052679 | ||
|
|
1e355a2a34 | ||
|
|
44621c345f | ||
|
|
220e573b14 | ||
|
|
6befe42eb0 | ||
|
|
b30a9bc414 | ||
|
|
ac4780f451 | ||
|
|
3da7f9c5c3 | ||
|
|
c842c6f5b9 | ||
|
|
6676f9c83b | ||
|
|
65b005f1e4 | ||
|
|
752acbf654 | ||
|
|
f5fce74169 | ||
|
|
9c7622dac3 | ||
|
|
c14bcca103 | ||
|
|
1fa315ea93 | ||
|
|
f9730979c1 | ||
|
|
59d0c922e9 | ||
|
|
2ea51bd31f | ||
|
|
e5c82d79a0 | ||
|
|
9afef94a61 | ||
|
|
a7b0366cbe | ||
|
|
428d9f9f67 | ||
|
|
1b120f352f | ||
|
|
0a7c662d39 | ||
|
|
b91a000a17 | ||
|
|
8de0aa24d9 | ||
|
|
cad2c93616 | ||
|
|
78f462c4e1 | ||
|
|
3b72d17cbc | ||
|
|
d440442db6 | ||
|
|
67ef189d8b | ||
|
|
fbcae59ef5 | ||
|
|
9821bca1ce | ||
|
|
3d74474f6c | ||
|
|
f0e2975180 | ||
|
|
d43210050b | ||
|
|
ef051bdb87 | ||
|
|
0ca9fb3fb5 | ||
|
|
cbd55d6374 | ||
|
|
96906805f1 | ||
|
|
73b2e8fdd4 | ||
|
|
5da45337f7 | ||
|
|
f21d5e444e | ||
|
|
9a1472d955 | ||
|
|
2abe66800c | ||
|
|
0d38866dcf | ||
|
|
f993fa1c5f | ||
|
|
83d769f02d | ||
|
|
c8ad4b8135 | ||
|
|
bd18d8d6d1 | ||
|
|
659986ce38 | ||
|
|
062b4618c2 | ||
|
|
deb901d638 | ||
|
|
02f4ce5667 | ||
|
|
285cf5947b | ||
|
|
1a003e383a | ||
|
|
963ebf5bd7 | ||
|
|
ba9c9ae81d | ||
|
|
076e9048dc |
No files matched your search
@@ -125,31 +125,29 @@ Do not start, stop, erase, or reconfigure an emulator owned by another task. Tra
|
||||
|
||||
## Pair each client once
|
||||
|
||||
Issue a fresh credential against the running backend's exact base directory:
|
||||
Use the bundled helper from the repository root. It issues a fresh credential against the running backend's exact base directory, opens the existing Add Environment route with the credential in an encoded query parameter, and asks that route to connect once:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--base-url <mobile-origin> \
|
||||
--ttl 15m \
|
||||
--label agent-mobile-<short-device-id>
|
||||
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
|
||||
ios <simulator-udid> <server-port> <base-dir>
|
||||
|
||||
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
|
||||
android <emulator-serial> <server-port> <base-dir>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
|
||||
Run only the command for the selected platform. The helper uses `http://127.0.0.1:<server-port>` for iOS and `http://10.0.2.2:<server-port>` for Android. Pass a fifth argument only when testing a non-development URL scheme.
|
||||
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
|
||||
The helper opens this registered route:
|
||||
|
||||
```bash
|
||||
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d 't3code-dev://connections/new' \
|
||||
com.t3tools.t3code.dev
|
||||
```text
|
||||
t3code-dev://connections/new?pairingUrl=<encoded-pairing-url>&autoConnect=1
|
||||
```
|
||||
|
||||
Run only the command for the selected platform.
|
||||
The Add Environment route owns the behavior: `pairingUrl` prefills its normal host and token inputs, while `autoConnect=1` submits once in development builds and returns to Home after success. Without `autoConnect`, the same route only prefills the form for manual inspection.
|
||||
|
||||
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
|
||||
Do not enter pairing hosts or tokens through simulator keyboard automation. Xcode's semantic typer sends HID-style key events through the simulator's active keyboard state, which can corrupt uppercase tokens and punctuation even when the host Mac uses a U.S. input source. The one-shot route is the deterministic pairing path. Use the visible form only as a fallback, and paste credentials rather than typing them character by character.
|
||||
|
||||
Verify the expected seeded projects appear before exercising the affected flow.
|
||||
|
||||
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
|
||||
|
||||
@@ -183,6 +181,8 @@ Keep local verification focused. Do not turn this workflow into a full repositor
|
||||
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
|
||||
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
|
||||
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
|
||||
- **The pairing form opens but does not connect:** confirm the deep link uses the existing `connections/new` route, includes `autoConnect=1`, and carries a freshly minted encoded `pairingUrl`.
|
||||
- **Pairing text changes case or punctuation:** do not retry semantic typing. Use `scripts/pair-client.sh`; the simulator keyboard layout and HID input path are not reliable for credentials.
|
||||
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
|
||||
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
|
||||
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 <ios|android> <device-id> <server-port> <base-dir> [url-scheme]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
[[ $# -ge 4 && $# -le 5 ]] || usage
|
||||
|
||||
platform="$1"
|
||||
device_id="$2"
|
||||
server_port="$3"
|
||||
base_dir="$4"
|
||||
url_scheme="${5:-t3code-dev}"
|
||||
|
||||
case "$platform" in
|
||||
ios)
|
||||
mobile_origin="http://127.0.0.1:${server_port}"
|
||||
;;
|
||||
android)
|
||||
mobile_origin="http://10.0.2.2:${server_port}"
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
|
||||
repo_root="$(git rev-parse --show-toplevel)"
|
||||
cd "$repo_root"
|
||||
|
||||
if ! pairing_output="$({
|
||||
T3CODE_PORT="$server_port" node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir "$base_dir" \
|
||||
--base-url "$mobile_origin" \
|
||||
--ttl 15m \
|
||||
--label "agent-mobile-${device_id:0:8}"
|
||||
} 2>&1)"; then
|
||||
echo "Could not mint a mobile pairing credential." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
pairing_url="$(printf '%s\n' "$pairing_output" | sed -n 's/^Pair URL: //p' | tail -n 1)"
|
||||
if [[ -z "$pairing_url" ]]; then
|
||||
echo "Could not parse the mobile pairing URL." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
deep_link="$(PAIRING_URL="$pairing_url" URL_SCHEME="$url_scheme" node - <<'NODE'
|
||||
const query = new URLSearchParams({
|
||||
pairingUrl: process.env.PAIRING_URL,
|
||||
autoConnect: "1",
|
||||
});
|
||||
process.stdout.write(`${process.env.URL_SCHEME}://connections/new?${query}`);
|
||||
NODE
|
||||
)"
|
||||
|
||||
case "$platform" in
|
||||
ios)
|
||||
xcrun simctl openurl "$device_id" "$deep_link"
|
||||
;;
|
||||
android)
|
||||
# adb shell re-joins its arguments and evaluates them through the device
|
||||
# shell, so the deep link's `?`/`&` must be quoted once more for that shell.
|
||||
adb -s "$device_id" shell \
|
||||
"am start -W -a android.intent.action.VIEW -d '$deep_link' com.t3tools.t3code.dev" \
|
||||
>/dev/null
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "Opened the existing Add Environment route with a fresh pairing credential."
|
||||
@@ -37,3 +37,5 @@ github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
github:SunkenInTime
|
||||
github:bil0000
|
||||
@@ -5,6 +5,25 @@ name: Mobile EAS Production
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
#
|
||||
# Every merge to main that touches the mobile app reconciles, per platform:
|
||||
# 1. Store builds: if the latest production build's version differs from
|
||||
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
|
||||
# track). Bumping `version` is therefore all it takes to
|
||||
# start the next release train — the first build of a version enters
|
||||
# external-TestFlight beta review immediately, and later builds of the
|
||||
# same version auto-approve until that version is released. After App
|
||||
# Store approval, Apple closes the release train and `version` must be
|
||||
# bumped before another iOS build can be submitted. Releasing to the App
|
||||
# Store stays a manual App Store Connect step.
|
||||
# 2. OTA: publish a production-channel update for each platform where at
|
||||
# least one finished production build matches the current native
|
||||
# fingerprint. Old-version binaries with a matching fingerprint receive
|
||||
# it too. When native drift means no binary could install the update,
|
||||
# it is skipped and flagged in the job summary instead of published
|
||||
# into the void.
|
||||
# workflow_dispatch remains as a manual override for both modes (e.g. to
|
||||
# retry an errored build or force an OTA).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -25,14 +44,38 @@ on:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
version:
|
||||
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
|
||||
required: false
|
||||
type: string
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-eas-production.yml
|
||||
|
||||
# Serialize runs so OTAs publish in merge order. GitHub keeps at most one
|
||||
# queued run per group, so a burst of merges collapses into one run of the
|
||||
# newest commit — intermediate commits don't need their own OTA.
|
||||
concurrency:
|
||||
group: mobile-eas-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
name: EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -52,11 +95,21 @@ jobs:
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- id: version_app_token
|
||||
name: Mint release app token for version override
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
|
||||
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
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.version_app_token.outputs.token || github.token }}
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
@@ -98,15 +151,74 @@ jobs:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
- name: Apply manual version override
|
||||
if: steps.version_app_token.outcome == 'success'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
|
||||
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
|
||||
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node --input-type=module -e '
|
||||
import fs from "node:fs";
|
||||
const path = "apps/mobile/app.config.ts";
|
||||
const source = fs.readFileSync(path, "utf8");
|
||||
const next = source.replace(
|
||||
/^( version: ")[^"]+(".*)$/m,
|
||||
`$1${process.env.RELEASE_VERSION}$2`,
|
||||
);
|
||||
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
|
||||
throw new Error("Could not update app version");
|
||||
}
|
||||
fs.writeFileSync(path, next);
|
||||
'
|
||||
vp fmt apps/mobile/app.config.ts
|
||||
|
||||
if git diff --quiet -- apps/mobile/app.config.ts; then
|
||||
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
git config user.name "${APP_SLUG}[bot]"
|
||||
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
|
||||
git add apps/mobile/app.config.ts
|
||||
git commit \
|
||||
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
|
||||
-m "Co-authored-by: codex <[email protected]>"
|
||||
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
|
||||
|
||||
- name: Summarize manual build version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
{
|
||||
echo "## Manual production build"
|
||||
echo
|
||||
echo "- App version: \`$version\`"
|
||||
echo "- Platform: \`${{ inputs.platform }}\`"
|
||||
echo
|
||||
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Build and submit (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
- name: Publish OTA update (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
@@ -117,3 +229,62 @@ jobs:
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
|
||||
# No --status filter on build:list: an in-queue/in-progress build must
|
||||
# count as existing, or every merge during the build window would cut a
|
||||
# duplicate. After an errored build, retry via workflow_dispatch
|
||||
# mode=build — pushes won't re-trigger it until the app version changes.
|
||||
- id: store_builds
|
||||
name: Ensure store builds exist for the current app version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
failed=0
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
for platform in ios android; do
|
||||
latest="$(eas build:list --platform "$platform" --build-profile production --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')"
|
||||
if [ "$latest" = "$version" ]; then
|
||||
echo "$platform: production build for $version already exists (or is in progress)"
|
||||
continue
|
||||
fi
|
||||
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
|
||||
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
|
||||
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
failed=1
|
||||
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
exit "$failed"
|
||||
|
||||
- name: Publish fingerprint-gated OTA
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))"
|
||||
for platform in ios android; do
|
||||
# eas-cli prints an environment-loaded notice to stdout before the
|
||||
# JSON even with --json, so discard everything before the document.
|
||||
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')"
|
||||
matching="$(eas build:list --platform "$platform" --build-profile production --status finished --fingerprint-hash "$hash" --limit 1 --json --non-interactive | jq 'length')"
|
||||
if [ "$matching" -gt 0 ]; then
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform "$platform" \
|
||||
--message "$message" \
|
||||
--non-interactive
|
||||
echo ":white_check_mark: $platform: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo ":warning: $platform: no finished production build matches fingerprint \`$hash\` — OTA skipped; JS changes reach $platform only once a matching build ships" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Propagate store build failure
|
||||
if: steps.store_builds.outcome == 'failure'
|
||||
run: exit 1
|
||||
@@ -0,0 +1,205 @@
|
||||
name: Mobile Fingerprint Check
|
||||
|
||||
# Detects whether a PR changes the native fingerprint — i.e. whether merging
|
||||
# it would leave main un-OTA-able until a new store build ships. Native-change
|
||||
# PRs get the "📱 Native Change" label so they can be held and merged as a
|
||||
# batch right before the next store submission, keeping main OTA-able for
|
||||
# everything else in between. (Once one native PR merges, every later merge
|
||||
# inherits the drifted fingerprint and loses OTA reach too — that is why the
|
||||
# signal has to fire before merge, not after.)
|
||||
#
|
||||
# The check is advisory: it always passes, the label is the signal. Both
|
||||
# fingerprints are computed in this one job (same OS, same corepack-pinned
|
||||
# pnpm), so the comparison is self-consistent; no EXPO_TOKEN needed.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-fingerprint-check.yml
|
||||
|
||||
concurrency:
|
||||
group: mobile-fingerprint-check-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
fingerprint:
|
||||
name: Native fingerprint diff
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
# Default pull_request checkout is the merge commit (PR applied on
|
||||
# top of base), so the "head" fingerprint is the state main would
|
||||
# actually be in after merging — stale branches compare cleanly.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Fingerprint merge result
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/fp/head" "$RUNNER_TEMP/fp/base"
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/head/$platform.json"
|
||||
done
|
||||
|
||||
- name: Fingerprint base
|
||||
run: |
|
||||
git checkout --quiet "${{ github.event.pull_request.base.sha }}"
|
||||
# Re-sync node_modules to the base commit's lockfile before
|
||||
# fingerprinting — a dep-changing PR must not fingerprint the base
|
||||
# against head's installed packages.
|
||||
pnpm install --filter=@t3tools/mobile...
|
||||
cd apps/mobile
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/base/$platform.json"
|
||||
done
|
||||
|
||||
- id: compare
|
||||
name: Compare fingerprints
|
||||
run: |
|
||||
changed=""
|
||||
{
|
||||
echo "## Native fingerprint diff"
|
||||
echo
|
||||
for platform in ios android; do
|
||||
head_hash="$(jq -r .hash "$RUNNER_TEMP/fp/head/$platform.json")"
|
||||
base_hash="$(jq -r .hash "$RUNNER_TEMP/fp/base/$platform.json")"
|
||||
if [ "$head_hash" = "$base_hash" ]; then
|
||||
echo "- ✅ **$platform**: unchanged (\`$head_hash\`) — OTA-compatible"
|
||||
continue
|
||||
fi
|
||||
changed="$changed $platform"
|
||||
echo "- 📱 **$platform**: \`$base_hash\` → \`$head_hash\` — merging requires a new native build before OTAs work again"
|
||||
jq -r -n \
|
||||
--slurpfile h "$RUNNER_TEMP/fp/head/$platform.json" \
|
||||
--slurpfile b "$RUNNER_TEMP/fp/base/$platform.json" '
|
||||
($b[0].sources | map({ (.filePath // .id): .hash }) | add // {}) as $bm
|
||||
| $h[0].sources[]
|
||||
| select($bm[(.filePath // .id)] != .hash)
|
||||
| " - \(.type): `\(.filePath // .id)`"'
|
||||
done
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "changed_platforms=${changed# }" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Sync native change label
|
||||
# Fork PRs get a read-only token under pull_request; the check stays
|
||||
# advisory there (summary only). This workflow must not move to
|
||||
# pull_request_target — it installs and runs PR code.
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
CHANGED_PLATFORMS: ${{ steps.compare.outputs.changed_platforms }}
|
||||
with:
|
||||
script: |
|
||||
const managedLabel = {
|
||||
name: "📱 Native Change",
|
||||
color: "d93f0b",
|
||||
description:
|
||||
"Changes the native fingerprint; merging blocks production OTAs until a new store build ships.",
|
||||
};
|
||||
const nativeChanged = (process.env.CHANGED_PLATFORMS ?? "").trim() !== "";
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== managedLabel.color ||
|
||||
(existing.description ?? "") !== managedLabel.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const hasLabel = currentLabels.some((label) => label.name === managedLabel.name);
|
||||
|
||||
if (nativeChanged && !hasLabel) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [managedLabel.name],
|
||||
});
|
||||
} else if (!nativeChanged && hasLabel) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.info(
|
||||
`PR #${issueNumber}: native fingerprint ${nativeChanged ? `changed (${process.env.CHANGED_PLATFORMS})` : "unchanged"}`,
|
||||
);
|
||||
@@ -746,7 +746,7 @@ jobs:
|
||||
needs: [preflight, build, publish_cli]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
name: Web Preview
|
||||
|
||||
# Label a PR `preview:web` to get a hosted-web preview deployment on Vercel for
|
||||
# that push and every subsequent push. The deployment is a plain (non-prod,
|
||||
# non-aliased) deploy into the existing hosted-web Vercel project, so the
|
||||
# latest/nightly channel aliases are never touched.
|
||||
#
|
||||
# The build intentionally omits the T3 Connect cloud config (Clerk keys, relay
|
||||
# URL): previews boot as the hosted-static app with manual pairing only. Pair a
|
||||
# server into a preview with `t3 pair --tailscale` (or any reachable HTTPS
|
||||
# backend) and open the pairing URL against the preview origin.
|
||||
#
|
||||
# The preview must be opened at the exact deployment URL from the PR comment.
|
||||
# Vite bakes that URL in as the hosted origin (via VERCEL_URL), and
|
||||
# `isHostedStaticApp` matches on origin, so branch-alias URLs will not
|
||||
# self-identify as the hosted app.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: web-preview-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy web preview
|
||||
# Same-repo PRs only: fork PRs do not receive the Vercel secrets, and this
|
||||
# workflow should skip rather than fail for them. On `labeled` events, only
|
||||
# the preview label itself triggers a deploy.
|
||||
if: >-
|
||||
github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
contains(github.event.pull_request.labels.*.name, 'preview:web') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'preview:web')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- id: deploy
|
||||
name: Deploy preview
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
|
||||
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
|
||||
|
||||
deployment_url="$(
|
||||
vp dlx [email protected] deploy \
|
||||
--archive=tgz \
|
||||
--yes \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
--scope "$vercel_scope"
|
||||
)"
|
||||
|
||||
echo "Deployed $deployment_url"
|
||||
echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Comment deployment URL
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment_url }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
with:
|
||||
script: |
|
||||
const marker = "<!-- web-preview-deploy -->";
|
||||
const body = [
|
||||
marker,
|
||||
"### Web preview",
|
||||
"",
|
||||
`${process.env.DEPLOYMENT_URL} (for ${process.env.HEAD_SHA.slice(0, 7)})`,
|
||||
"",
|
||||
"Open this exact URL — the hosted-app origin is baked in at build time.",
|
||||
"Pair a server into it with `t3 pair --tailscale`, or paste a host + pairing",
|
||||
"code under Settings → Connections.",
|
||||
].join("\n");
|
||||
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.pull_request.number,
|
||||
per_page: 100,
|
||||
});
|
||||
const existing = comments.find((comment) => comment.body?.includes(marker));
|
||||
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.pull_request.number,
|
||||
body,
|
||||
});
|
||||
}
|
||||
@@ -114,7 +114,6 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
|
||||
- Never make a PR unless the developer explicitly asks you to do so.
|
||||
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
|
||||
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
|
||||
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
|
||||
- UI changes need before/after images. Motion or timing needs a short video.
|
||||
- One concern per PR. If the description says "also", split it.
|
||||
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
|
||||
|
||||
@@ -68,6 +68,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
|
||||
- [Install and first run](./docs/user/install.md)
|
||||
- [Permission modes](./docs/user/permission-modes.md)
|
||||
- [Keyboard shortcuts](./docs/user/keybindings.md)
|
||||
- [Customize a project icon](./docs/user/project-settings.md)
|
||||
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
|
||||
- [Keeping app and server in sync](./docs/user/updating.md)
|
||||
- [Source control integrations](./docs/user/source-control.md)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.32",
|
||||
"version": "0.0.33",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -26,6 +26,7 @@ import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
|
||||
|
||||
@@ -286,6 +287,7 @@ const startup = Effect.gen(function* () {
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
@@ -165,6 +165,8 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
handleControlForSource: (_sourceId, message) =>
|
||||
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -72,6 +72,8 @@ function makePoolLayer(
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
}),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
|
||||
@@ -28,70 +28,6 @@ describe("ElectronDialog", () => {
|
||||
showErrorBoxMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("returns false without opening a confirm dialog for empty messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: " ",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.equal(showMessageBoxMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens a confirm dialog for the owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
const owner = { id: 1 } as BrowserWindow;
|
||||
showMessageBoxMock.mockResolvedValue({ response: 1 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.some(owner),
|
||||
});
|
||||
|
||||
assert.isTrue(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
owner,
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
showMessageBoxMock.mockResolvedValue({ response: 0 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves folder picker request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("folder picker failed");
|
||||
@@ -117,31 +53,6 @@ describe("ElectronDialog", () => {
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves confirmation request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("confirmation failed");
|
||||
const owner = { id: 9 } as BrowserWindow;
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.confirm({
|
||||
owner: Option.some(owner),
|
||||
message: " Confirm removal? ",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
|
||||
assert.strictEqual(error.ownerWindowId, 9);
|
||||
assert.strictEqual(error.promptLength, "Confirm removal?".length);
|
||||
assert.notProperty(error, "promptMessage");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 9");
|
||||
assert.notInclude(error.message, "Confirm removal?");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message box request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("message box failed");
|
||||
|
||||
@@ -6,8 +6,6 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
@@ -38,20 +36,6 @@ export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<Electr
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
promptLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
|
||||
"ElectronDialogShowMessageBoxError",
|
||||
{
|
||||
@@ -85,7 +69,6 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
@@ -103,11 +86,6 @@ export interface ElectronDialogPickFilesInput {
|
||||
readonly filters: readonly Electron.FileFilter[];
|
||||
}
|
||||
|
||||
export interface ElectronDialogConfirmInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export class ElectronDialog extends Context.Service<
|
||||
ElectronDialog,
|
||||
{
|
||||
@@ -117,9 +95,6 @@ export class ElectronDialog extends Context.Service<
|
||||
readonly pickFiles: (
|
||||
input: ElectronDialogPickFilesInput,
|
||||
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
@@ -188,39 +163,6 @@ export const make = ElectronDialog.of({
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
}),
|
||||
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
|
||||
const normalizedMessage = input.message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showMessageBox(options),
|
||||
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogConfirmError({
|
||||
ownerWindowId,
|
||||
promptLength: normalizedMessage.length,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
}),
|
||||
showMessageBox: (options) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.dialog.showMessageBox(options),
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
setUpdateChannel,
|
||||
} from "./methods/updates.ts";
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
@@ -81,7 +80,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(pickThemeFiles);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
|
||||
export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
|
||||
@@ -220,19 +220,6 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const confirm = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONFIRM_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
return yield* electronWindow.focusedMainOrFirst.pipe(
|
||||
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_THEME_CHANNEL,
|
||||
payload: DesktopThemeSchema,
|
||||
|
||||
@@ -98,7 +98,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) =>
|
||||
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
|
||||
|
||||
@@ -32,6 +32,7 @@ const clientSettings: ClientSettings = {
|
||||
planModeEnabled: false,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarAutoSettleOnMerge: true,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
|
||||
@@ -231,6 +231,7 @@ describe("DesktopShellEnvironment", () => {
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.local\\bin",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
|
||||
@@ -207,7 +207,7 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
|
||||
...trimNonEmpty(env.USERPROFILE).pipe(
|
||||
Option.match({
|
||||
onNone: () => [],
|
||||
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
}),
|
||||
),
|
||||
];
|
||||
@@ -379,10 +379,18 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
|
||||
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
|
||||
loadProfile: true,
|
||||
});
|
||||
// Concurrent, not sequential: these two probes are independent (only their
|
||||
// results are combined below) and each spawns its own PowerShell. Run in
|
||||
// series they sit at offset 0 of desktop.startup, before anything else, and
|
||||
// launch traces measured them at 2718ms then 2066ms — the entire 4.8s
|
||||
// startup span, of which desktop.bootstrap is ~30ms.
|
||||
const [noProfile, profile] = yield* Effect.all(
|
||||
[
|
||||
readWindowsEnvironment(["PATH"], { loadProfile: false }),
|
||||
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
const mergedPath = mergePaths("win32", [
|
||||
trimNonEmpty(profile.PATH),
|
||||
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
|
||||
|
||||
@@ -156,8 +156,11 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
decodeMessage(decoder.decode(bytes).trim()),
|
||||
);
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
const hello = messages[0];
|
||||
if (hello?.type !== "desktopTelemetryHello") {
|
||||
return assert.fail("Expected the first telemetry message to be the hello.");
|
||||
}
|
||||
assert.equal(hello.electronPid, process.pid);
|
||||
const initialSnapshot = messages[1];
|
||||
if (initialSnapshot?.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the second telemetry message to be a snapshot.");
|
||||
@@ -385,4 +388,80 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes requestDesktopUpdate control messages and replays update reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.succeed(false),
|
||||
getSystemIdleTime: Effect.succeed(0),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: () => Effect.void,
|
||||
onThermalStateChange: () => Effect.void,
|
||||
onSpeedLimitChange: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
|
||||
const requestFiber = yield* Stream.runHead(publisher.updateRequests).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControlForSource("test", {
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId: "req-9",
|
||||
});
|
||||
const received = yield* Fiber.join(requestFiber);
|
||||
assert.equal(Option.getOrThrow(received).requestId, "req-9");
|
||||
|
||||
const report = {
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
outcome: "up-to-date",
|
||||
state: {
|
||||
enabled: true,
|
||||
status: "up-to-date",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
},
|
||||
} as const;
|
||||
yield* publisher.publishUpdateReport(report);
|
||||
|
||||
// A subscriber that attaches after the publish (the backend spawned
|
||||
// by a relaunch) still sees the latest report replayed.
|
||||
const decoder = new TextDecoder();
|
||||
const decodeMessage = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopHostTelemetryMessage),
|
||||
);
|
||||
const replayed = yield* publisher.encoded.pipe(
|
||||
Stream.mapEffect((bytes) => decodeMessage(decoder.decode(bytes).trim())),
|
||||
Stream.filter((message) => message.type === "desktopUpdateStatus"),
|
||||
Stream.runHead,
|
||||
);
|
||||
const replayedReport = Option.getOrThrow(replayed);
|
||||
if (replayedReport.type !== "desktopUpdateStatus") {
|
||||
return assert.fail("Expected a desktop update status report.");
|
||||
}
|
||||
assert.equal(replayedReport.outcome, "up-to-date");
|
||||
assert.equal(replayedReport.state.currentVersion, "1.2.3");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryRequestDesktopUpdate,
|
||||
type DesktopUpdateStatusReport,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -65,6 +67,12 @@ export class DesktopTelemetryPublisher extends Context.Service<
|
||||
message: DesktopTelemetryControlMessage,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
|
||||
/** Sends the report to the attached backend and replays the latest one
|
||||
to backends that attach later (including the one spawned after a
|
||||
relaunch). */
|
||||
readonly publishUpdateReport: (report: DesktopUpdateStatusReport) => Effect.Effect<void>;
|
||||
/** Update requests received over the control channel. Single consumer. */
|
||||
readonly updateRequests: Stream.Stream<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
@@ -160,6 +168,9 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
|
||||
const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
|
||||
const updateRequestQueue = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
@@ -324,6 +335,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
active: Duration.millis(message.activeIntervalMs),
|
||||
idle: Duration.millis(message.idleIntervalMs),
|
||||
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
|
||||
case "requestDesktopUpdate":
|
||||
return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
|
||||
}
|
||||
};
|
||||
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
|
||||
@@ -357,15 +370,36 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
);
|
||||
}),
|
||||
);
|
||||
const updateReports = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(updateReportChanges);
|
||||
const initial = yield* Ref.get(latestUpdateReport);
|
||||
return Stream.concat(
|
||||
Option.match(initial, {
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
Stream.fromSubscription(subscription),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
Stream.merge(snapshots, updateReports),
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
|
||||
report,
|
||||
) =>
|
||||
Ref.set(latestUpdateReport, Option.some(report)).pipe(
|
||||
Effect.andThen(PubSub.publish(updateReportChanges, report)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
@@ -373,6 +407,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
handleControl,
|
||||
handleControlForSource,
|
||||
removeControlSource,
|
||||
publishUpdateReport,
|
||||
updateRequests: Stream.fromQueue(updateRequestQueue),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateStatusReport,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopRemoteUpdates from "./DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import { makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
// The remote flow hops between the test runtime's fibers and the updater's
|
||||
// runPromise-driven event handlers, so settling needs real microtask turns,
|
||||
// not just fiber yields.
|
||||
const settle = Effect.gen(function* () {
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
});
|
||||
|
||||
const request = (requestId: string): DesktopTelemetryRequestDesktopUpdate => ({
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId,
|
||||
});
|
||||
|
||||
function runRemoteUpdatesTest(
|
||||
harness: ReturnType<typeof makeHarness>,
|
||||
body: (context: {
|
||||
readonly reports: DesktopUpdateStatusReport[];
|
||||
readonly requests: Queue.Queue<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}) => Effect.Effect<void, never, DesktopUpdates.DesktopUpdates>,
|
||||
) {
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const requests = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
const reports: DesktopUpdateStatusReport[] = [];
|
||||
const publisher = DesktopTelemetryPublisher.DesktopTelemetryPublisher.of({
|
||||
latest: Effect.succeedNone,
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: (report) =>
|
||||
Effect.sync(() => {
|
||||
reports.push(report);
|
||||
}),
|
||||
updateRequests: Stream.fromQueue(requests),
|
||||
});
|
||||
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen.pipe(
|
||||
Effect.provideService(DesktopTelemetryPublisher.DesktopTelemetryPublisher, publisher),
|
||||
);
|
||||
yield* settle;
|
||||
yield* body({ reports, requests });
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}
|
||||
|
||||
function terminalReports(reports: DesktopUpdateStatusReport[]): DesktopUpdateStatusReport[] {
|
||||
return reports.filter((report) => report.outcome !== undefined);
|
||||
}
|
||||
|
||||
describe("DesktopRemoteUpdates", () => {
|
||||
it.effect("drives check, download, and install with no local confirmation", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-1"));
|
||||
yield* settle;
|
||||
assert.equal(harness.checkCount(), 1);
|
||||
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "installing");
|
||||
assert.equal(terminals[0]?.requestId, "req-1");
|
||||
assert.equal(harness.quitAndInstalls(), 1);
|
||||
|
||||
// The mirror stamped the in-run state changes with the request id.
|
||||
const statuses = reports
|
||||
.filter((report) => report.requestId === "req-1")
|
||||
.map((report) => report.state.status);
|
||||
assert.include(statuses, "available");
|
||||
assert.include(statuses, "downloaded");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports a failed outcome when quitAndInstall fails", () => {
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("spawn failed"),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-4"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
// Install failures reduce to status "downloaded" + errorContext
|
||||
// "install"; the run must still end with a failed report after the
|
||||
// premature "installing" one.
|
||||
const terminals = terminalReports(reports);
|
||||
assert.deepEqual(
|
||||
terminals.map((report) => report.outcome),
|
||||
["installing", "failed"],
|
||||
);
|
||||
assert.equal(terminals[1]?.state.errorContext, "install");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not misread a lingering install error as a failed retry", () => {
|
||||
let installAttempts = 0;
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.suspend(() => {
|
||||
installAttempts += 1;
|
||||
return installAttempts === 1
|
||||
? Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("first attempt failed"),
|
||||
}),
|
||||
)
|
||||
: Effect.void;
|
||||
}),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-5"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
// First run failed; state is "downloaded" with a lingering
|
||||
// errorContext "install". The retry succeeds and must not report
|
||||
// that leftover as a fresh failure.
|
||||
yield* Queue.offer(requests, request("req-6"));
|
||||
yield* settle;
|
||||
|
||||
const retryTerminals = terminalReports(reports).filter(
|
||||
(report) => report.requestId === "req-6",
|
||||
);
|
||||
assert.deepEqual(
|
||||
retryTerminals.map((report) => report.outcome),
|
||||
["installing"],
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 2);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports up-to-date without installing when there is no update", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-2"));
|
||||
yield* settle;
|
||||
harness.emit("update-not-available");
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "up-to-date");
|
||||
assert.equal(terminals[0]?.requestId, "req-2");
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails fast with the disabled reason when updates are off", () => {
|
||||
const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } });
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-3"));
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "failed");
|
||||
assert.equal(
|
||||
terminals[0]?.reason,
|
||||
"Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.",
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateRemoteOutcome,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import {
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-remote-updates");
|
||||
|
||||
/**
|
||||
* Server-triggered desktop updates. Forks two fibers into the surrounding
|
||||
* scope: one mirrors every updater state change to the attached backend (so
|
||||
* the server always knows the desktop's update state), one consumes
|
||||
* requestDesktopUpdate control messages and drives check -> download ->
|
||||
* quit-and-install with no local confirmation. The remote click that caused
|
||||
* the request is the consent.
|
||||
*/
|
||||
export const listen: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
DesktopUpdates.DesktopUpdates | DesktopTelemetryPublisher.DesktopTelemetryPublisher | Scope.Scope
|
||||
> = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const activeRequestIdRef = yield* Ref.make(Option.none<string>());
|
||||
|
||||
const publishReport = (
|
||||
state: DesktopUpdateState,
|
||||
terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string },
|
||||
): Effect.Effect<void> =>
|
||||
Ref.get(activeRequestIdRef).pipe(
|
||||
Effect.flatMap((requestId) =>
|
||||
publisher.publishUpdateReport({
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
...(Option.isSome(requestId) ? { requestId: requestId.value } : {}),
|
||||
...(terminal === undefined ? {} : { outcome: terminal.outcome }),
|
||||
...(terminal?.reason === undefined ? {} : { reason: terminal.reason }),
|
||||
state,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
yield* publishReport(latest);
|
||||
yield* Stream.runForEach(changes, (state) => publishReport(state));
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const handleRequest = (request: DesktopTelemetryRequestDesktopUpdate): Effect.Effect<void> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
|
||||
yield* logInfo("remote update requested", { requestId: request.requestId });
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
const disabledReason = Option.getOrNull(yield* updates.disabledReason);
|
||||
let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
// Returns true when the run reached a terminal outcome.
|
||||
const step = (state: DesktopUpdateState): Effect.Effect<boolean, never, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
|
||||
switch (next.action) {
|
||||
case "wait":
|
||||
return false;
|
||||
case "check":
|
||||
attempts = { ...attempts, checks: attempts.checks + 1 };
|
||||
yield* Effect.forkScoped(updates.check("remote-update"));
|
||||
return false;
|
||||
case "download":
|
||||
attempts = { ...attempts, downloads: attempts.downloads + 1 };
|
||||
yield* Effect.forkScoped(updates.download);
|
||||
return false;
|
||||
case "install": {
|
||||
// The terminal report must go out BEFORE installing:
|
||||
// install stops the backend server first, so anything
|
||||
// published after this point never reaches the requester.
|
||||
yield* publishReport(state, { outcome: "installing" });
|
||||
yield* logInfo("remote update installing", { requestId: request.requestId });
|
||||
const before = yield* updates.getState;
|
||||
const result = yield* updates.install;
|
||||
if (!result.accepted) {
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: "The desktop app could not start the install.",
|
||||
});
|
||||
} else if (result.state !== before) {
|
||||
// During an accepted install the only state writes are the
|
||||
// failure reducers, so a transition means this attempt
|
||||
// failed. Field checks cannot tell a fresh failure from a
|
||||
// lingering errorContext left by a previous attempt, which
|
||||
// success does not clear.
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: result.state.message ?? "The desktop app failed to install the update.",
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case "done":
|
||||
yield* publishReport(state, {
|
||||
outcome: next.outcome,
|
||||
...(next.reason === undefined ? {} : { reason: next.reason }),
|
||||
});
|
||||
yield* logInfo("remote update finished", {
|
||||
requestId: request.requestId,
|
||||
outcome: next.outcome,
|
||||
reason: next.reason ?? null,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (yield* step(latest)) return;
|
||||
yield* changes.pipe(
|
||||
Stream.mapEffect(step),
|
||||
Stream.takeUntil((done) => done),
|
||||
Stream.runDrain,
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.ensuring(Ref.set(activeRequestIdRef, Option.none())),
|
||||
Effect.catchCause((cause) =>
|
||||
logError("remote update request failed unexpectedly", {
|
||||
requestId: request.requestId,
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Sequential by construction: a second remote request queued mid-run is
|
||||
// handled after the current one, when the state machine resolves it fast.
|
||||
yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
|
||||
});
|
||||
@@ -1,6 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -11,201 +9,14 @@ import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
describe("DesktopUpdates", () => {
|
||||
it("preserves complete causes for update poller and event failures", () => {
|
||||
@@ -274,6 +85,29 @@ describe("DesktopUpdates", () => {
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("subscribe delivers the latest state plus subsequent changes", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
assert.equal(latest.status, "idle");
|
||||
|
||||
const nextState = yield* Stream.runHead(changes).pipe(Effect.forkChild);
|
||||
yield* flushCallbacks;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const observed = yield* Fiber.join(nextState);
|
||||
assert.equal(Option.getOrThrow(observed).status, "available");
|
||||
assert.equal(Option.getOrThrow(observed).availableVersion, "1.2.4");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("updates and broadcasts state from updater events", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
|
||||
@@ -14,9 +14,12 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
@@ -150,6 +153,15 @@ export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
/** Current state plus a stream of every later state change. */
|
||||
readonly subscribe: Effect.Effect<
|
||||
{
|
||||
readonly latest: DesktopUpdateState;
|
||||
readonly changes: Stream.Stream<DesktopUpdateState>;
|
||||
},
|
||||
never,
|
||||
Scope.Scope
|
||||
>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
@@ -268,12 +280,21 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
|
||||
// Makes ref writes + publishes atomic against subscribe, so a snapshot
|
||||
// never overlaps with the first change a subscriber receives.
|
||||
const stateMutex = yield* Semaphore.make(1);
|
||||
|
||||
const emitState = Ref.get(updateStateRef).pipe(
|
||||
Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
|
||||
);
|
||||
|
||||
const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(emitState));
|
||||
stateMutex
|
||||
.withPermits(1)(
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
|
||||
)
|
||||
.pipe(Effect.andThen(emitState));
|
||||
|
||||
const updateState = (
|
||||
f: (state: DesktopUpdateState) => DesktopUpdateState,
|
||||
@@ -705,6 +726,13 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return DesktopUpdates.of({
|
||||
getState: Ref.get(updateStateRef),
|
||||
subscribe: stateMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(stateChanges);
|
||||
const latest = yield* Ref.get(updateStateRef);
|
||||
return { latest, changes: Stream.fromSubscription(subscription) };
|
||||
}),
|
||||
),
|
||||
emitState,
|
||||
disabledReason: resolveDisabledReason,
|
||||
configure: Effect.gen(function* () {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
MAX_REMOTE_UPDATE_CHECKS,
|
||||
MAX_REMOTE_UPDATE_DOWNLOADS,
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const NO_ATTEMPTS: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
function makeState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {
|
||||
return {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("nextRemoteDesktopUpdateStep", () => {
|
||||
it("fails immediately when updates are disabled, preferring the known reason", () => {
|
||||
const state = makeState({ enabled: false, status: "disabled" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, "dev build"), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "dev build",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "Automatic updates are disabled on this machine.",
|
||||
});
|
||||
});
|
||||
|
||||
it("installs only from the downloaded status the updater will accept", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloaded", downloadedVersion: "1.2.4" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A previous install failure keeps status "downloaded", so a remote run
|
||||
// retries the install.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "downloaded",
|
||||
downloadedVersion: "1.2.4",
|
||||
errorContext: "install",
|
||||
message: "quitAndInstall failed",
|
||||
}),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A leftover downloadedVersion on an error state (background updater
|
||||
// error) must not report an install the updater refuses: fresh runs
|
||||
// re-check, and post-check it fails.
|
||||
const staleError = makeState({
|
||||
status: "error",
|
||||
downloadedVersion: "1.2.4",
|
||||
message: "background updater error",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, { checks: 1, downloads: 0 }, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "background updater error",
|
||||
});
|
||||
});
|
||||
|
||||
it("rides along while a check or download is already in flight", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "checking" }), NO_ATTEMPTS, null),
|
||||
{
|
||||
action: "wait",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloading", availableVersion: "1.2.4", downloadPercent: 40 }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "wait" },
|
||||
);
|
||||
});
|
||||
|
||||
it("downloads an available update until the attempt cap, then fails", () => {
|
||||
const available = makeState({ status: "available", availableVersion: "1.2.4" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(available, NO_ATTEMPTS, null), {
|
||||
action: "download",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
available,
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app failed to download the update.",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "available",
|
||||
availableVersion: "1.2.4",
|
||||
message: "network blipped",
|
||||
}),
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "network blipped" },
|
||||
);
|
||||
});
|
||||
|
||||
it("re-checks stale up-to-date and error states before trusting them", () => {
|
||||
// These states are retained from earlier/background checks; a remote
|
||||
// request must look again instead of replaying them.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), NO_ATTEMPTS, null),
|
||||
{ action: "check" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "check" },
|
||||
);
|
||||
});
|
||||
|
||||
it("reports up-to-date and error states as terminal after this run's check", () => {
|
||||
const checked = { checks: 1, downloads: 0 };
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), checked, null),
|
||||
{ action: "done", outcome: "up-to-date" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
checked,
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "feed unreachable" },
|
||||
);
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState({ status: "error" }), checked, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app update failed.",
|
||||
});
|
||||
});
|
||||
|
||||
it("checks from idle until the attempt cap, then fails", () => {
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState(), NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState(),
|
||||
{ checks: MAX_REMOTE_UPDATE_CHECKS, downloads: 0 },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { DesktopUpdateRemoteOutcome, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* What a server-triggered update run should do next, given the updater's
|
||||
* current state. "wait" means an action (possibly started locally) is in
|
||||
* flight and the run should ride along until the next state change.
|
||||
*/
|
||||
export type RemoteDesktopUpdateStep =
|
||||
| { readonly action: "check" }
|
||||
| { readonly action: "download" }
|
||||
| { readonly action: "install" }
|
||||
| { readonly action: "wait" }
|
||||
| {
|
||||
readonly action: "done";
|
||||
readonly outcome: DesktopUpdateRemoteOutcome;
|
||||
readonly reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many times this run already issued each action. The caps are what stop
|
||||
* a check -> up-to-date -> check loop and endless download retries; they are
|
||||
* counts rather than booleans because a state event raced by the local
|
||||
* 4-minute poller can re-show an already-handled status once.
|
||||
*/
|
||||
export interface RemoteDesktopUpdateAttempts {
|
||||
readonly checks: number;
|
||||
readonly downloads: number;
|
||||
}
|
||||
|
||||
export const MAX_REMOTE_UPDATE_CHECKS = 2;
|
||||
export const MAX_REMOTE_UPDATE_DOWNLOADS = 3;
|
||||
|
||||
export function nextRemoteDesktopUpdateStep(
|
||||
state: DesktopUpdateState,
|
||||
attempts: RemoteDesktopUpdateAttempts,
|
||||
disabledReason: string | null,
|
||||
): RemoteDesktopUpdateStep {
|
||||
if (!state.enabled || state.status === "disabled") {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: disabledReason ?? "Automatic updates are disabled on this machine.",
|
||||
};
|
||||
}
|
||||
// Only "downloaded" is installable: installDownloadedUpdate rejects any
|
||||
// other status. A leftover downloadedVersion on an "error" state (e.g. a
|
||||
// background updater error) must fall through to the error branch instead
|
||||
// of reporting an install that the updater will refuse.
|
||||
if (state.status === "downloaded") {
|
||||
return { action: "install" };
|
||||
}
|
||||
if (state.status === "downloading" || state.status === "checking") {
|
||||
return { action: "wait" };
|
||||
}
|
||||
if (state.status === "available") {
|
||||
if (attempts.downloads >= MAX_REMOTE_UPDATE_DOWNLOADS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app failed to download the update.",
|
||||
};
|
||||
}
|
||||
return { action: "download" };
|
||||
}
|
||||
// "up-to-date" and "error" are retained from earlier/background checks,
|
||||
// so before this run has issued its own check they are stale, not
|
||||
// terminal: the whole point of a remote request is to look again.
|
||||
if (state.status === "up-to-date") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return { action: "done", outcome: "up-to-date" };
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app update failed.",
|
||||
};
|
||||
}
|
||||
// status === "idle"
|
||||
if (attempts.checks >= MAX_REMOTE_UPDATE_CHECKS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
};
|
||||
}
|
||||
return { action: "check" };
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
/** Shared DesktopUpdates test harness: a fully stubbed updater layer whose
|
||||
electron-updater events are driven by hand via `emit`. Used by
|
||||
DesktopUpdates.test.ts and DesktopRemoteUpdates.test.ts. */
|
||||
|
||||
export const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
export interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
export function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let quitAndInstallCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () =>
|
||||
Effect.sync(() => {
|
||||
quitAndInstallCount += 1;
|
||||
}).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
quitAndInstalls: () => quitAndInstallCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -53,13 +53,13 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
pickFolder: () => Effect.succeed(Option.none()),
|
||||
pickFiles: () => Effect.succeed([]),
|
||||
confirm: () => Effect.succeed(false),
|
||||
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
|
||||
showErrorBox: () => Effect.void,
|
||||
} satisfies ElectronDialog.ElectronDialog["Service"]);
|
||||
|
||||
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
subscribe: Effect.die("unexpected subscribe"),
|
||||
emitState: Effect.void,
|
||||
disabledReason: Effect.succeed(Option.none()),
|
||||
configure: Effect.void,
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.2",
|
||||
version: "1.0.4",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
@@ -338,6 +338,7 @@ const config: ExpoConfig = {
|
||||
"./plugins/withAndroidModernPopupMenu.cjs",
|
||||
"./plugins/withAndroidModernAlertDialog.cjs",
|
||||
"./plugins/withAndroidPredictiveBackCompat.cjs",
|
||||
"./plugins/withAndroidTabletOrientation.cjs",
|
||||
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
|
||||
@@ -4,16 +4,13 @@ import type { MarkdownNode } from "react-native-nitro-markdown/headless";
|
||||
|
||||
import { CopyTextButton } from "./CopyTextButton";
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownListItemBlocks,
|
||||
nativeMarkdownTextRuns,
|
||||
} from "./nativeMarkdownText";
|
||||
import { nativeMarkdownDocumentRuns, nativeMarkdownListItemBlocks } from "./nativeMarkdownText";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
MarkdownCodeHighlighter,
|
||||
MarkdownHighlightedToken,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "./SelectableMarkdownText.types";
|
||||
|
||||
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
|
||||
@@ -48,12 +45,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
|
||||
|
||||
function SelectableNode(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -322,6 +320,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
|
||||
|
||||
function NativeTable(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -359,7 +358,7 @@ function NativeTable(props: {
|
||||
}}
|
||||
>
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownTextRuns(cell).map((run) =>
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
@@ -376,6 +375,7 @@ function NativeTable(props: {
|
||||
|
||||
function NativeMarkdownImage(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -384,6 +384,7 @@ function NativeMarkdownImage(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -445,6 +446,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
|
||||
|
||||
function NativeMixedParagraph(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -455,6 +457,7 @@ function NativeMixedParagraph(props: {
|
||||
<NativeMarkdownImage
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -462,6 +465,7 @@ function NativeMixedParagraph(props: {
|
||||
<SelectableNode
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -473,6 +477,7 @@ function NativeMixedParagraph(props: {
|
||||
|
||||
function NativeList(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -534,6 +539,7 @@ function NativeList(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, childIndex)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -551,6 +557,7 @@ function NativeList(props: {
|
||||
|
||||
export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -566,6 +573,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -587,6 +595,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeTable
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -595,6 +604,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeMarkdownImage
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -624,6 +634,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -637,6 +648,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeList
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -647,12 +659,14 @@ export function NativeMarkdownBlock(props: {
|
||||
return (props.node.children ?? []).some((child) => child.type === "image") ? (
|
||||
<NativeMixedParagraph
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -673,6 +687,7 @@ export function NativeMarkdownBlock(props: {
|
||||
>
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -690,6 +705,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -703,6 +719,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
|
||||
@@ -69,6 +69,7 @@ export function SelectableMarkdownText({
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
skills={skills}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
|
||||
@@ -70,15 +70,22 @@ const EMPTY_CONTEXT: RunContext = {
|
||||
|
||||
const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
|
||||
|
||||
function decodeCodePoint(codePoint: number, entity: string): string {
|
||||
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
|
||||
return entity;
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
|
||||
function decodeHtmlEntitiesOnce(value: string): string {
|
||||
return value.replace(
|
||||
/&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
|
||||
(entity, decimal: string | undefined, hexadecimal: string | undefined) => {
|
||||
if (decimal) {
|
||||
return String.fromCodePoint(Number.parseInt(decimal, 10));
|
||||
return decodeCodePoint(Number.parseInt(decimal, 10), entity);
|
||||
}
|
||||
if (hexadecimal) {
|
||||
return String.fromCodePoint(Number.parseInt(hexadecimal, 16));
|
||||
return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
|
||||
}
|
||||
switch (entity.toLowerCase()) {
|
||||
case "&":
|
||||
@@ -661,6 +668,7 @@ function appendDocumentBlock(
|
||||
function containsRichBlock(node: MarkdownNode): boolean {
|
||||
if (
|
||||
node.type === "code_block" ||
|
||||
node.type === "blockquote" ||
|
||||
node.type === "table" ||
|
||||
node.type === "image" ||
|
||||
node.type === "horizontal_rule" ||
|
||||
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.view.View
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
private val iconView = HeaderIconView(context)
|
||||
private val onTriggered by EventDispatcher()
|
||||
|
||||
init {
|
||||
isClickable = true
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
onTriggered(emptyMap<String, Any>())
|
||||
}
|
||||
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
|
||||
fun setLabel(label: String) {
|
||||
contentDescription = label
|
||||
}
|
||||
|
||||
fun setSystemImage(systemImage: String) {
|
||||
iconView.systemImage = systemImage
|
||||
}
|
||||
}
|
||||
|
||||
private class HeaderIconView(context: Context) : View(context) {
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.parseColor("#6B7280")
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeWidth = 3f * resources.displayMetrics.density
|
||||
style = Paint.Style.STROKE
|
||||
}
|
||||
|
||||
var systemImage: String = "gearshape"
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val size = minOf(width, height).toFloat()
|
||||
if (systemImage == "square.and.pencil") {
|
||||
drawNewTask(canvas, cx, cy, size)
|
||||
} else {
|
||||
drawSettings(canvas, cx, cy, size)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val radius = size * 0.12f
|
||||
canvas.drawCircle(cx, cy, radius, paint)
|
||||
for (index in 0 until 8) {
|
||||
val angle = Math.PI * index / 4.0
|
||||
val inner = size * 0.19f
|
||||
val outer = size * 0.27f
|
||||
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
|
||||
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
|
||||
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
|
||||
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
|
||||
canvas.drawLine(sx, sy, ex, ey, paint)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val left = cx - size * 0.2f
|
||||
val top = cy - size * 0.16f
|
||||
val right = cx + size * 0.14f
|
||||
val bottom = cy + size * 0.2f
|
||||
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
|
||||
canvas.drawLine(
|
||||
cx - size * 0.02f,
|
||||
cy + size * 0.13f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
canvas.drawLine(
|
||||
cx + size * 0.17f,
|
||||
cy - size * 0.2f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
}
|
||||
}
|
||||
-11
@@ -32,16 +32,5 @@ class T3NativeControlsModule : Module() {
|
||||
?.resolve("t3-showcase-ready")
|
||||
?.writeText(scene)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3HeaderButtonView: ExpoView {
|
||||
private static let size: CGFloat = 44
|
||||
private static let symbolSize: CGFloat = 18
|
||||
|
||||
private let button = UIButton(type: .system)
|
||||
private var systemImage = "circle"
|
||||
|
||||
let onTriggered = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
isAccessibilityElement = false
|
||||
button.frame = bounds
|
||||
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
|
||||
addSubview(button)
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
public override var intrinsicContentSize: CGSize {
|
||||
CGSize(width: Self.size, height: Self.size)
|
||||
}
|
||||
|
||||
public func setLabel(_ label: String) {
|
||||
button.accessibilityLabel = label
|
||||
}
|
||||
|
||||
public func setSystemImage(_ systemImage: String) {
|
||||
guard self.systemImage != systemImage else {
|
||||
return
|
||||
}
|
||||
self.systemImage = systemImage
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
private func applyConfiguration() {
|
||||
var configuration: UIButton.Configuration
|
||||
if #available(iOS 26.0, *) {
|
||||
configuration = .glass()
|
||||
configuration.cornerStyle = .capsule
|
||||
} else {
|
||||
configuration = .plain()
|
||||
}
|
||||
|
||||
configuration.baseForegroundColor = .label
|
||||
configuration.contentInsets = .zero
|
||||
configuration.image = UIImage(systemName: systemImage)
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
|
||||
pointSize: Self.symbolSize,
|
||||
weight: .regular
|
||||
)
|
||||
button.configuration = configuration
|
||||
}
|
||||
|
||||
@objc private func handlePress() {
|
||||
onTriggered()
|
||||
}
|
||||
}
|
||||
@@ -87,16 +87,5 @@ public final class T3NativeControlsModule: Module {
|
||||
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
|
||||
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/metro-runtime": "~56.0.15",
|
||||
"@expo/ui": "~56.0.18",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@legendapp/list": "catalog:",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
// The top-level `orientation: "portrait"` writes android:screenOrientation="portrait"
|
||||
// into the manifest, which locks every Android device — including tablets — to
|
||||
// portrait. iOS doesn't have this problem: iPads must support all orientations
|
||||
// because the app is multitasking-capable, so only iPhones end up portrait-only.
|
||||
// Mirror that split on Android: keep the manifest lock for phones and lift it at
|
||||
// runtime on tablets (smallest width >= 600dp, the standard tablet breakpoint),
|
||||
// since requestedOrientation set at runtime overrides the manifest value.
|
||||
// FULL_USER allows all four orientations while still respecting the user's
|
||||
// auto-rotate lock, matching iPad behavior. Foldables change
|
||||
// smallestScreenWidthDp on fold/unfold without recreating the activity
|
||||
// (smallestScreenSize is in the manifest's configChanges), so the policy is
|
||||
// re-evaluated in onConfigurationChanged: unfolding past the tablet breakpoint
|
||||
// unlocks rotation, and folding back restores the portrait lock.
|
||||
|
||||
const ORIENTATION_METHODS = `
|
||||
// Applied in onCreate and re-applied on fold/unfold; added by
|
||||
// withAndroidTabletOrientation.
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
applyTabletOrientation()
|
||||
}
|
||||
|
||||
private fun applyTabletOrientation() {
|
||||
requestedOrientation = if (resources.configuration.smallestScreenWidthDp >= 600) {
|
||||
ActivityInfo.SCREEN_ORIENTATION_FULL_USER
|
||||
} else {
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const ORIENTATION_ON_CREATE_CALL = `
|
||||
applyTabletOrientation()`;
|
||||
|
||||
function insertAfter(contents, anchor, insertion, description) {
|
||||
const index = contents.indexOf(anchor);
|
||||
if (index === -1) {
|
||||
throw new Error(
|
||||
`withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
|
||||
);
|
||||
}
|
||||
const end = index + anchor.length;
|
||||
return contents.slice(0, end) + insertion + contents.slice(end);
|
||||
}
|
||||
|
||||
module.exports = function withAndroidTabletOrientation(config) {
|
||||
return withMainActivity(config, (nextConfig) => {
|
||||
let contents = nextConfig.modResults.contents;
|
||||
if (nextConfig.modResults.language !== "kt") {
|
||||
throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin.");
|
||||
}
|
||||
if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) {
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"import android.os.Bundle",
|
||||
"\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
|
||||
"the android.os.Bundle import",
|
||||
);
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"class MainActivity : ReactActivity() {",
|
||||
ORIENTATION_METHODS,
|
||||
"the MainActivity class declaration",
|
||||
);
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"super.onCreate(null)",
|
||||
ORIENTATION_ON_CREATE_CALL,
|
||||
"the super.onCreate call",
|
||||
);
|
||||
|
||||
nextConfig.modResults.contents = contents;
|
||||
return nextConfig;
|
||||
});
|
||||
};
|
||||
+125
-42
@@ -11,14 +11,13 @@ import {
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
|
||||
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
|
||||
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
|
||||
@@ -40,6 +39,15 @@ import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
|
||||
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
|
||||
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
|
||||
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
|
||||
import {
|
||||
NewTaskBranchPickerRouteScreen,
|
||||
NewTaskEnvironmentPickerRouteScreen,
|
||||
} from "./features/threads/NewTaskContextPickerScreens";
|
||||
import {
|
||||
ExistingThreadSettingsRouteProvider,
|
||||
ExistingThreadSettingsRouteScreen,
|
||||
NewTaskThreadSettingsRouteScreen,
|
||||
} from "./features/threads/ThreadSettingsSheet";
|
||||
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
|
||||
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
|
||||
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
|
||||
@@ -48,6 +56,7 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
|
||||
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
@@ -62,17 +71,15 @@ import {
|
||||
} from "./features/sharing/incoming-share-presentation";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import {
|
||||
FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
NATIVE_SHEET_SURFACE_COLOR,
|
||||
NATIVE_SHEET_SURFACE_CONTENT_STYLE,
|
||||
} from "./native/sheet-surface";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
|
||||
// background stay STATIC config while still adapting to appearance changes.
|
||||
const SHEET_BACKGROUND_COLOR =
|
||||
Platform.OS === "ios"
|
||||
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
|
||||
: undefined;
|
||||
|
||||
type AppScreenOptions = NativeStackNavigationOptions & {
|
||||
readonly unstable_navigationItemStyle?: "editor";
|
||||
};
|
||||
@@ -91,8 +98,8 @@ const GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerShown: true,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? { backgroundColor: "transparent" }
|
||||
: SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
: NATIVE_SHEET_SURFACE_COLOR !== undefined
|
||||
? { backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
@@ -109,10 +116,10 @@ const SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
NATIVE_SHEET_SURFACE_COLOR !== undefined
|
||||
? // native-stack types this as `string`, but the native side accepts any
|
||||
// ColorValue including DynamicColorIOS.
|
||||
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
{ backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: false,
|
||||
@@ -125,6 +132,14 @@ const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
// A native glass header for a sheet screen whose primary child is a scroll
|
||||
// view. The centered sheet title stays stable while UIKit supplies scroll-edge
|
||||
// fading from that child.
|
||||
const SHEET_GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
headerBackVisible: false,
|
||||
@@ -133,7 +148,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
presentation: "fullScreenModal",
|
||||
};
|
||||
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
const SettingsContentStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
@@ -190,20 +205,37 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Client Storage",
|
||||
},
|
||||
}),
|
||||
SettingsUsage: createNativeStackScreen({
|
||||
screen: UsageRouteScreen,
|
||||
linking: "usage",
|
||||
options: {
|
||||
title: "Usage",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// The outer stack never owns visible chrome. Settings routes render inside a
|
||||
// nested stack whose native header remains mounted, while Clerk owns auth chrome.
|
||||
// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "SettingsContent",
|
||||
screenOptions: {
|
||||
headerShown: false,
|
||||
},
|
||||
screens: {
|
||||
SettingsContent: createNativeStackScreen({
|
||||
screen: SettingsContentStack,
|
||||
linking: "",
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
// Keep the old deep link working after the Connect GA launch.
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -221,9 +253,16 @@ const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
|
||||
const NewTaskSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "NewTask",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
// Sheets read better with the iOS-default centered title (no editor style).
|
||||
unstable_navigationItemStyle: undefined,
|
||||
...SHEET_GLASS_HEADER_OPTIONS,
|
||||
// The form-sheet host owns the one opaque adaptive surface. Child screens
|
||||
// and the navigation bar stay transparent over it, avoiding visible color
|
||||
// slabs as view controllers move horizontally.
|
||||
contentStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
|
||||
// UIKit's default push adds a dimming shadow and independently transitions
|
||||
// the navigation bar. Both read as mismatched sheet backgrounds here.
|
||||
// simple_push retains native push/pop gestures without either artifact.
|
||||
animation: Platform.OS === "ios" ? "simple_push" : undefined,
|
||||
animationDuration: Platform.OS === "ios" ? 350 : undefined,
|
||||
},
|
||||
screens: {
|
||||
NewTask: createNativeStackScreen({
|
||||
@@ -236,9 +275,39 @@ const NewTaskSheetStack = createNativeStackNavigator({
|
||||
NewTaskDraft: createNativeStackScreen({
|
||||
screen: NewTaskDraftRouteScreen,
|
||||
linking: "draft",
|
||||
// The draft composer has no scroll view for glass to sample; a solid
|
||||
// header also lays the content out below the bar (no manual inset).
|
||||
options: SHEET_SOLID_HEADER_OPTIONS,
|
||||
options: {
|
||||
headerBackVisible: false,
|
||||
title: "",
|
||||
},
|
||||
}),
|
||||
NewTaskEnvironment: createNativeStackScreen({
|
||||
screen: NewTaskEnvironmentPickerRouteScreen,
|
||||
linking: "draft/environment",
|
||||
options: {
|
||||
title: "Environment",
|
||||
},
|
||||
}),
|
||||
NewTaskBranch: createNativeStackScreen({
|
||||
screen: NewTaskBranchPickerRouteScreen,
|
||||
linking: "draft/branch",
|
||||
options: {
|
||||
title: "Branch",
|
||||
},
|
||||
}),
|
||||
ThreadSettings: createNativeStackScreen({
|
||||
screen: NewTaskThreadSettingsRouteScreen,
|
||||
linking: "draft/settings",
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [1],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
AddProject: createNativeStackScreen({
|
||||
screen: AddProjectSourceRoute,
|
||||
@@ -277,6 +346,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"SettingsLegal",
|
||||
"SettingsSheet",
|
||||
"ThreadReviewComment",
|
||||
"ThreadSettingsSheet",
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -339,11 +409,11 @@ function RootStackLayout(props: {
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<ExistingThreadSettingsRouteProvider>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
</ExistingThreadSettingsRouteProvider>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
@@ -425,7 +495,9 @@ export const RootStack = createNativeStackNavigator({
|
||||
options: {
|
||||
// Android cannot host the keyboard-driven comment composer inside a
|
||||
// formSheet; use a full-screen modal there instead.
|
||||
presentation: Platform.OS === "android" ? "fullScreenModal" : "formSheet",
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "fullScreenModal" as const }
|
||||
: FORM_SHEET_PRESENTATION_OPTIONS),
|
||||
sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.55, 0.92],
|
||||
sheetGrabberVisible: Platform.OS !== "android",
|
||||
},
|
||||
@@ -435,10 +507,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
linking: `${THREAD_LINKING_PREFIX}/files`,
|
||||
options: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR }
|
||||
: undefined,
|
||||
contentStyle: NATIVE_SHEET_SURFACE_CONTENT_STYLE,
|
||||
title: "Files",
|
||||
},
|
||||
}),
|
||||
@@ -447,11 +516,25 @@ export const RootStack = createNativeStackNavigator({
|
||||
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadSettingsSheet: createNativeStackScreen({
|
||||
screen: ExistingThreadSettingsRouteScreen,
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [1],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
GitOverview: createNativeStackScreen({
|
||||
screen: GitOverviewSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -460,7 +543,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitCommitSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -469,7 +552,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitBranchesSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -478,7 +561,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitConfirmSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.45, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -494,7 +577,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.7, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
@@ -517,7 +600,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.6, 0.95],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -532,7 +615,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const, headerShown: false }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
@@ -542,7 +625,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "connections/new",
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -562,7 +645,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
IconBellRinging,
|
||||
IconBolt,
|
||||
IconCamera,
|
||||
IconChartBar,
|
||||
IconCheck,
|
||||
IconChevronDown,
|
||||
IconCode,
|
||||
@@ -97,6 +98,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
"bolt.circle": IconBolt,
|
||||
"bolt.horizontal.circle": IconBolt,
|
||||
camera: IconCamera,
|
||||
"chart.bar.xaxis": IconChartBar,
|
||||
checkmark: IconCheck,
|
||||
"checkmark.circle": IconCircleCheck,
|
||||
clock: IconClock,
|
||||
|
||||
+65
-5
@@ -17,11 +17,73 @@ import { cn } from "../lib/cn";
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { SymbolView } from "./AppSymbol";
|
||||
|
||||
export const COMPOSER_TOOLBAR_CONTROL_HEIGHT = 44;
|
||||
export const COMPOSER_TOOLBAR_GAP = 8;
|
||||
export const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
|
||||
const COMPOSER_TOOLBAR_GAP = 8;
|
||||
const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
|
||||
const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4;
|
||||
|
||||
/**
|
||||
* Quiet inline composer control used inside cards and their context rows.
|
||||
* Unlike ComposerToolbarButton, this does not draw another pill inside the
|
||||
* composer surface, so model and workspace controls read as part of the card.
|
||||
*/
|
||||
export function ComposerInlineControl(props: {
|
||||
readonly accessibilityHint?: string;
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly disabled?: boolean;
|
||||
readonly emphasized?: boolean;
|
||||
readonly icon?: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly iconNode?: ReactNode;
|
||||
readonly label: string;
|
||||
readonly maxWidth?: number;
|
||||
readonly onPress?: () => void;
|
||||
readonly selected?: boolean;
|
||||
readonly static?: boolean;
|
||||
readonly chevronDirection?: "down" | "right";
|
||||
readonly showChevron?: boolean;
|
||||
}) {
|
||||
const iconColor = useThemeColor(
|
||||
props.emphasized || props.selected ? "--color-icon" : "--color-icon-muted",
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityHint={props.accessibilityHint}
|
||||
accessibilityRole={props.static ? undefined : "button"}
|
||||
accessibilityState={
|
||||
props.static ? undefined : { disabled: props.disabled, selected: props.selected }
|
||||
}
|
||||
className="h-11 flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"
|
||||
disabled={props.disabled || props.static}
|
||||
onPress={props.onPress}
|
||||
style={{ maxWidth: props.maxWidth ?? 190, opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
{props.iconNode ? (
|
||||
<View className="size-4 shrink-0 items-center justify-center">{props.iconNode}</View>
|
||||
) : props.icon ? (
|
||||
<SymbolView name={props.icon} size={16} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-sm font-t3-medium",
|
||||
props.emphasized || props.selected ? "text-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
{props.showChevron === false ? null : (
|
||||
<SymbolView
|
||||
name={props.chevronDirection === "right" ? "chevron.right" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerToolbarRow(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly paddingBottom?: number;
|
||||
@@ -247,5 +309,3 @@ export function ComposerToolbarButton(props: {
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export const ComposerToolbarTrigger = ComposerToolbarButton;
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type ComponentProps,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Platform, Pressable, useColorScheme, View } from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
@@ -21,10 +22,31 @@ export function ControlPill(props: {
|
||||
readonly label?: string;
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly onPress?: () => void;
|
||||
readonly activateOnPressIn?: boolean;
|
||||
readonly variant?: "circle" | "pill" | "primary" | "danger";
|
||||
readonly disabled?: boolean;
|
||||
readonly className?: string;
|
||||
}) {
|
||||
const variant = props.variant ?? "circle";
|
||||
const activatedOnPressInRef = useRef(false);
|
||||
|
||||
const handlePressIn = () => {
|
||||
activatedOnPressInRef.current = true;
|
||||
props.onPress?.();
|
||||
};
|
||||
const handlePressOut = () => {
|
||||
// Pressability invokes onPressOut immediately before onPress on release.
|
||||
// Defer the reset so onPress can identify the same physical gesture.
|
||||
setTimeout(() => {
|
||||
activatedOnPressInRef.current = false;
|
||||
}, 0);
|
||||
};
|
||||
const handlePress = () => {
|
||||
if (activatedOnPressInRef.current) {
|
||||
return;
|
||||
}
|
||||
props.onPress?.();
|
||||
};
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
@@ -54,6 +76,7 @@ export function ControlPill(props: {
|
||||
: variant === "danger"
|
||||
? "bg-danger"
|
||||
: "bg-subtle",
|
||||
props.className,
|
||||
);
|
||||
const labelClassName = cn(
|
||||
"text-center text-xs font-t3-bold",
|
||||
@@ -68,7 +91,9 @@ export function ControlPill(props: {
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
onPress={props.activateOnPressIn ? handlePress : props.onPress}
|
||||
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
|
||||
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
|
||||
disabled={props.disabled}
|
||||
className={containerClassName}
|
||||
>
|
||||
@@ -133,9 +158,25 @@ export function ControlPillMenu(
|
||||
}
|
||||
|
||||
const { className: _className, ...menuProps } = props;
|
||||
let children = menuProps.children;
|
||||
// In long-press mode the wrapped pressable still receives the touch (the
|
||||
// patched MenuView button is touch-transparent) and RN's Fabric touch
|
||||
// handler is never cancelled by the in-tree UIContextMenuInteraction, so a
|
||||
// bare onPress would fire on finger-up even after the menu opened — and
|
||||
// also on a long press released just under the menu threshold. A dispatched
|
||||
// onLongPress makes Pressability swallow the release, so holds past 350ms
|
||||
// (below the ~500ms context-menu threshold) can only open the menu, never
|
||||
// tap through.
|
||||
if (props.shouldOpenOnLongPress && isValidElement(children)) {
|
||||
const child = children as ReactElement<{ onLongPress?: () => void; delayLongPress?: number }>;
|
||||
children = cloneElement(child, {
|
||||
onLongPress: child.props.onLongPress ?? (() => undefined),
|
||||
delayLongPress: child.props.delayLongPress ?? 350,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<MenuView {...menuProps} themeVariant={isDarkMode ? "dark" : "light"}>
|
||||
{menuProps.children}
|
||||
{children}
|
||||
</MenuView>
|
||||
);
|
||||
}
|
||||
@@ -5,16 +5,19 @@ import {
|
||||
useColorScheme,
|
||||
View,
|
||||
type ColorValue,
|
||||
type StyleProp,
|
||||
type ViewProps,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
export interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
|
||||
interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
|
||||
readonly children: ReactNode;
|
||||
readonly glassEffectStyle?: "clear" | "regular" | "none";
|
||||
readonly tintColor?: ColorValue;
|
||||
readonly chrome?: "default" | "none";
|
||||
/** Styling used only when native Liquid Glass is unavailable. */
|
||||
readonly fallbackStyle?: StyleProp<ViewStyle>;
|
||||
}
|
||||
|
||||
export function GlassSurface({
|
||||
@@ -22,6 +25,7 @@ export function GlassSurface({
|
||||
glassEffectStyle = "regular",
|
||||
chrome = "default",
|
||||
tintColor,
|
||||
fallbackStyle,
|
||||
style,
|
||||
...props
|
||||
}: GlassSurfaceProps) {
|
||||
@@ -67,7 +71,7 @@ export function GlassSurface({
|
||||
}
|
||||
|
||||
return (
|
||||
<View {...props} style={[surfaceStyle, style]}>
|
||||
<View {...props} style={[surfaceStyle, fallbackStyle, style]}>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -24,13 +24,18 @@ export function ProjectFavicon(props: {
|
||||
readonly size?: number;
|
||||
readonly projectTitle: string;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly faviconPath?: string | null;
|
||||
}) {
|
||||
const size = props.size ?? 42;
|
||||
const faviconUrl = useAssetUrl(
|
||||
props.environmentId,
|
||||
props.workspaceRoot === null || props.workspaceRoot === undefined
|
||||
? null
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
: {
|
||||
_tag: "project-favicon",
|
||||
cwd: props.workspaceRoot,
|
||||
...(props.faviconPath ? { path: props.faviconPath } : {}),
|
||||
},
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
const cacheKey =
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useFocusEffect } from "@react-navigation/native";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { useArchivedThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
ArchivedThreadsScreen,
|
||||
@@ -18,7 +17,6 @@ import {
|
||||
} from "./useArchivedThreadSnapshots";
|
||||
|
||||
export function ArchivedThreadsRouteScreen() {
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
@@ -70,9 +68,8 @@ export function ArchivedThreadsRouteScreen() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
expand();
|
||||
refresh();
|
||||
}, [expand, refresh]),
|
||||
}, [refresh]),
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -368,6 +368,7 @@ function ProjectGroupLabel(props: {
|
||||
<View className="flex-row items-center gap-2.5 px-1 pb-2">
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
projectTitle={props.project.title}
|
||||
size={18}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import {
|
||||
createContext,
|
||||
type PropsWithChildren,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
interface ClerkSettingsSheetDetentValue {
|
||||
collapse: () => void;
|
||||
expand: () => void;
|
||||
isExpanded: boolean;
|
||||
}
|
||||
|
||||
const ClerkSettingsSheetDetentContext = createContext<ClerkSettingsSheetDetentValue | null>(null);
|
||||
|
||||
interface ClerkSettingsSheetDetentProviderProps extends PropsWithChildren {
|
||||
initiallyExpanded: boolean;
|
||||
}
|
||||
|
||||
export function ClerkSettingsSheetDetentProvider({
|
||||
children,
|
||||
initiallyExpanded,
|
||||
}: ClerkSettingsSheetDetentProviderProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(initiallyExpanded);
|
||||
const collapse = useCallback(() => setIsExpanded(false), []);
|
||||
const expand = useCallback(() => setIsExpanded(true), []);
|
||||
const value = useMemo(() => ({ collapse, expand, isExpanded }), [collapse, expand, isExpanded]);
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentContext value={value}>{children}</ClerkSettingsSheetDetentContext>
|
||||
);
|
||||
}
|
||||
|
||||
export function useClerkSettingsSheetDetent(): ClerkSettingsSheetDetentValue {
|
||||
const value = useContext(ClerkSettingsSheetDetentContext);
|
||||
if (!value) {
|
||||
throw new Error(
|
||||
"useClerkSettingsSheetDetent must be used inside ClerkSettingsSheetDetentProvider",
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
|
||||
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
|
||||
|
||||
// Sign-in happens inside the Settings sheet; give its detent/session-state
|
||||
// transitions a beat to settle before presenting another formSheet on top.
|
||||
// Sign-in happens inside the Settings sheet; give its session-state transition
|
||||
// a beat to settle before presenting another formSheet on top.
|
||||
const PRESENT_ONBOARDING_DELAY_MS = 600;
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import { CameraView, useCameraPermissions } from "expo-camera";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -11,12 +11,13 @@ import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ErrorBanner } from "../../components/ErrorBanner";
|
||||
import { ConnectionSheetButton } from "./ConnectionSheetButton";
|
||||
import { extractPairingUrlFromQrPayload } from "./pairing";
|
||||
import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { buildPairingUrl, parsePairingUrl } from "./pairing";
|
||||
|
||||
type ConnectionsNewRouteParams = {
|
||||
readonly mode?: string;
|
||||
readonly pairingUrl?: string;
|
||||
readonly autoConnect?: string;
|
||||
};
|
||||
|
||||
export function ConnectionsNewRouteScreen({
|
||||
@@ -30,6 +31,13 @@ export function ConnectionsNewRouteScreen({
|
||||
} = useRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const params = route.params ?? {};
|
||||
// Deep-link prefill exists for development automation only. A production
|
||||
// link must not arrive with attacker-chosen host and token already filled.
|
||||
const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
|
||||
const shouldAutoConnect =
|
||||
__DEV__ &&
|
||||
routePairingUrl.length > 0 &&
|
||||
(params.autoConnect === "1" || params.autoConnect === "true");
|
||||
const insets = useSafeAreaInsets();
|
||||
const [hostInput, setHostInput] = useState("");
|
||||
const [codeInput, setCodeInput] = useState("");
|
||||
@@ -37,6 +45,7 @@ export function ConnectionsNewRouteScreen({
|
||||
const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
|
||||
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
|
||||
const [scannerLocked, setScannerLocked] = useState(false);
|
||||
const attemptedAutoConnectRef = useRef<string | null>(null);
|
||||
|
||||
const headerIconColor = useThemeColor("--color-icon");
|
||||
|
||||
@@ -48,6 +57,16 @@ export function ConnectionsNewRouteScreen({
|
||||
setCodeInput(code);
|
||||
}, [connectionPairingUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (routePairingUrl.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { host, code } = parsePairingUrl(routePairingUrl);
|
||||
setHostInput(host);
|
||||
setCodeInput(code);
|
||||
}, [routePairingUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (pairingConnectionError) {
|
||||
setIsSubmitting(false);
|
||||
@@ -116,22 +135,38 @@ export function ConnectionsNewRouteScreen({
|
||||
[onChangeConnectionPairingUrl, scannerLocked],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
setIsSubmitting(true);
|
||||
|
||||
const pairingUrl = buildPairingUrl(hostInput, codeInput);
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
const result = await onConnectPress(pairingUrl);
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
if (navigation.canGoBack()) {
|
||||
navigation.goBack();
|
||||
} else {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
const connectAndClose = useCallback(
|
||||
async (pairingUrl: string, replaceWithHome: boolean) => {
|
||||
setIsSubmitting(true);
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
try {
|
||||
const result = await onConnectPress(pairingUrl);
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
if (replaceWithHome || !navigation.canGoBack()) {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
} else {
|
||||
navigation.goBack();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
} else {
|
||||
setIsSubmitting(false);
|
||||
},
|
||||
[navigation, onChangeConnectionPairingUrl, onConnectPress],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
await connectAndClose(buildPairingUrl(hostInput, codeInput), false);
|
||||
}, [codeInput, connectAndClose, hostInput]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
|
||||
return;
|
||||
}
|
||||
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, navigation]);
|
||||
|
||||
attemptedAutoConnectRef.current = routePairingUrl;
|
||||
void connectAndClose(routePairingUrl, true);
|
||||
}, [connectAndClose, routePairingUrl, shouldAutoConnect]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
|
||||
@@ -356,6 +356,7 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
onSearchTextChange: props.onSearchQueryChange,
|
||||
placeholder: "Search",
|
||||
searchTextChangeId: "home-search-text",
|
||||
showsSearchDismissButton: true,
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ export function HomeRouteScreen() {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -134,7 +135,10 @@ export function HomeRouteScreen() {
|
||||
<NativeStackScreenOptions
|
||||
options={getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: () =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
}),
|
||||
})}
|
||||
/>
|
||||
<HomeHeader
|
||||
@@ -148,9 +152,17 @@ export function HomeRouteScreen() {
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -161,7 +173,10 @@ export function HomeRouteScreen() {
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
onAddConnection={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
@@ -172,9 +187,15 @@ export function HomeRouteScreen() {
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
|
||||
@@ -115,6 +115,7 @@ interface HomeScreenProps {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -206,6 +207,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const autoSettleOnMerge =
|
||||
!AsyncResult.isSuccess(preferencesResult) ||
|
||||
preferencesResult.value.autoSettleOnMerge !== false;
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
@@ -482,8 +486,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
// the partition works directly off live shells — no snapshot merging or
|
||||
// optimistic holds.
|
||||
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
|
||||
// closed PR auto-settles its thread on the next partition (mirrors web).
|
||||
// PR states stream in per-row. The next partition applies the configured
|
||||
// merge rule and the always-on close rule, matching web.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
@@ -538,6 +542,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onUnpinThread],
|
||||
);
|
||||
const handleRegenerateThreadTitle = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onRegenerateThreadTitle(thread);
|
||||
},
|
||||
[props.onRegenerateThreadTitle],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -615,6 +625,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order (reorder-capable threads only) for the
|
||||
// Move up/down position flags. Computed from all shells, not the rendered
|
||||
// list, so search/scope filtering never disables or misdirects a move.
|
||||
@@ -649,6 +668,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
@@ -660,6 +680,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
@@ -811,6 +832,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -842,6 +865,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleRegenerateThreadTitle,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
@@ -863,6 +887,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Items,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
@@ -967,6 +992,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery={props.searchQuery}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onDeleteThread={props.onDeleteThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -988,6 +1015,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleRegenerateThreadTitle,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
@@ -998,6 +1026,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -48,6 +48,15 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsTitleRegeneration(
|
||||
environmentId: EnvironmentThreadShell["environmentId"],
|
||||
) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadTitleRegeneration === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -227,13 +236,18 @@ export function useThreadListActions(): {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
|
||||
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -405,6 +419,47 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[unpinMutation],
|
||||
);
|
||||
const regenerateThreadTitle = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (
|
||||
thread.titleRegeneration != null ||
|
||||
titleRegenerationInFlightThreadKeys.current.has(key)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
titleRegenerationInFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const result = await updateThreadMetadata({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, regenerateTitle: true },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread title could not be regenerated.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
titleRegenerationInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[updateThreadMetadata],
|
||||
);
|
||||
|
||||
// Move up / Move down for the pinned block. Computed against the CANONICAL
|
||||
// keyed pinned order (not the rendered list), so the move is valid even
|
||||
@@ -497,6 +552,7 @@ export function useThreadListActions(): {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -429,13 +429,19 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
);
|
||||
|
||||
const handleOpenSettings = useCallback(() => {
|
||||
navigation.navigate("SettingsSheet", { screen: "Settings" });
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
});
|
||||
}, [navigation]);
|
||||
|
||||
// Minted here (root stack navigation) so the sidebar pane stays free of
|
||||
// navigation hooks — on iOS it renders inside an independent nav tree.
|
||||
const handleOpenEnvironmentSettings = useCallback(() => {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
});
|
||||
}, [navigation]);
|
||||
|
||||
const handleNewThreadInProject = useCallback(
|
||||
|
||||
@@ -11,6 +11,9 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
*/
|
||||
export const NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED = NATIVE_LIQUID_GLASS_SUPPORTED;
|
||||
|
||||
/** Clearance for scroll content that must come to rest above the floating toolbar. */
|
||||
export const NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET = 56;
|
||||
|
||||
type NativeMailSearchToolbarInput = Omit<
|
||||
HeaderBarButtonMailSearchToolbarItem,
|
||||
"type" | "useFallbackSearchField"
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
inferProjectTitleFromPath,
|
||||
} from "@t3tools/client-runtime/state/projects";
|
||||
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
|
||||
@@ -402,13 +402,12 @@ function SourceControlRow(props: {
|
||||
icon={icon}
|
||||
isFirst={props.isFirst}
|
||||
onPress={() =>
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectRepository",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectRepository", {
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
source: props.source,
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
@@ -498,12 +497,11 @@ export function AddProjectSourceScreen() {
|
||||
}
|
||||
isFirst
|
||||
onPress={() =>
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectLocal",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectLocal", {
|
||||
environmentId: selectedEnvironment.environmentId,
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
|
||||
@@ -547,10 +545,18 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
if (existing) {
|
||||
Alert.alert("Project already exists", existing.title);
|
||||
navigation.dispatch(
|
||||
StackActions.replace("NewTaskDraft", {
|
||||
environmentId: existing.environmentId,
|
||||
projectId: existing.id,
|
||||
title: existing.title,
|
||||
CommonActions.reset({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: existing.environmentId,
|
||||
projectId: existing.id,
|
||||
title: existing.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
return;
|
||||
@@ -571,10 +577,18 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
return result;
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("NewTaskDraft", {
|
||||
environmentId: environment.environmentId,
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(workspaceRoot),
|
||||
CommonActions.reset({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: environment.environmentId,
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(workspaceRoot),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
@@ -612,15 +626,14 @@ export function AddProjectRepositoryScreen(props: {
|
||||
const provider = addProjectRemoteSourceProvider(source);
|
||||
if (!provider) {
|
||||
const remoteUrl = repositoryInput.trim();
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectDestination",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectDestination", {
|
||||
environmentId: environment.environmentId,
|
||||
source,
|
||||
remoteUrl,
|
||||
repositoryTitle: remoteUrl,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
@@ -636,15 +649,14 @@ export function AddProjectRepositoryScreen(props: {
|
||||
setError(errorMessage(Cause.squash(result.cause)));
|
||||
} else {
|
||||
const repository = result.value;
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectDestination",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectDestination", {
|
||||
environmentId: environment.environmentId,
|
||||
source,
|
||||
remoteUrl: repository.sshUrl,
|
||||
repositoryTitle: repository.nameWithOwner,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
setIsSubmitting(false);
|
||||
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { useCallback, useLayoutEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -10,9 +9,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
export function SettingsAuthRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
if (!hasCloudPublicConfig()) {
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
navigation.dispatch(StackActions.replace("SettingsContent"));
|
||||
}
|
||||
}, [navigation]);
|
||||
|
||||
@@ -22,20 +21,20 @@ export function SettingsAuthRouteScreen() {
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const navigation = useNavigation();
|
||||
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
|
||||
const handleHostBack = useCallback(
|
||||
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
|
||||
[navigation],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -98,7 +98,10 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
accessibilityLabel: "Add environment",
|
||||
icon: "plus",
|
||||
onPress: () =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
}),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
@@ -108,7 +111,10 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
}
|
||||
separateBackground
|
||||
tintColor={headerIconColor}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useAuth, useUser } from "@clerk/expo";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Updates from "expo-updates";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -30,7 +29,6 @@ import {
|
||||
subscribeAgentAwarenessRegistrationStatus,
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
@@ -40,6 +38,7 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import {
|
||||
type AppUpdateCheckState,
|
||||
isAppUpdateCheckAvailable,
|
||||
registerHiddenUpdateTap,
|
||||
runAppUpdateCheck,
|
||||
} from "../updates/app-updates";
|
||||
@@ -147,7 +146,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
|
||||
const insets = useSafeAreaInsets();
|
||||
const navigation = useNavigation();
|
||||
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
|
||||
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { user } = useUser();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
@@ -436,14 +434,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
const openAccount = useCallback(() => {
|
||||
if (!isLoaded) return;
|
||||
if (!isSignedIn) {
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
return;
|
||||
}
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
|
||||
}, [isLoaded, navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -530,9 +522,22 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const autoSettleOnMerge =
|
||||
!AsyncResult.isSuccess(preferencesResult) ||
|
||||
preferencesResult.value.autoSettleOnMerge !== false;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
<SettingsSwitchRow
|
||||
icon="arrow.triangle.branch"
|
||||
label="Auto-settle merged threads"
|
||||
value={autoSettleOnMerge}
|
||||
onValueChange={(value) => savePreferences({ autoSettleOnMerge: value })}
|
||||
/>
|
||||
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -544,7 +549,10 @@ function GeneralSettingsSection() {
|
||||
*/
|
||||
function LegacySettingsSection() {
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const preferences = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const planModeEnabled =
|
||||
AsyncResult.isSuccess(preferences) && preferences.value.planModeEnabled === true;
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
@@ -555,10 +563,16 @@ function LegacySettingsSection() {
|
||||
value={!threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
|
||||
/>
|
||||
<SettingsSwitchRow
|
||||
icon="hammer"
|
||||
label="Plan Mode"
|
||||
value={planModeEnabled}
|
||||
onValueChange={(value) => savePreferences({ planModeEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
Brings back the original grouped thread list. The default list is flat, in creation order:
|
||||
active work renders as cards; settled threads collapse to compact rows.
|
||||
Opt into retired interfaces kept for compatibility. Plan Mode restores the Build/Plan
|
||||
control; otherwise every task runs in Build mode.
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
@@ -576,6 +590,7 @@ function AppSettingsSection() {
|
||||
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
|
||||
const variantLabel = variant === "production" ? "" : capitalize(variant);
|
||||
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
|
||||
const updateCheckAvailable = isAppUpdateCheckAvailable();
|
||||
const busy =
|
||||
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
|
||||
|
||||
@@ -603,13 +618,13 @@ function AppSettingsSection() {
|
||||
}, []);
|
||||
|
||||
const handleVersionPress = useCallback(() => {
|
||||
if (!Updates.isEnabled || updateInFlight.current) return;
|
||||
if (!updateCheckAvailable || updateInFlight.current) return;
|
||||
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
|
||||
hiddenUpdateTapCount.current = tap.nextCount;
|
||||
if (tap.shouldCheck) {
|
||||
void checkForUpdate();
|
||||
}
|
||||
}, [checkForUpdate]);
|
||||
}, [checkForUpdate, updateCheckAvailable]);
|
||||
|
||||
const statusLabel =
|
||||
updateState === "checking"
|
||||
@@ -645,7 +660,7 @@ function AppSettingsSection() {
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
{Updates.isEnabled ? (
|
||||
{updateCheckAvailable ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Version ${versionLabel}`}
|
||||
accessibilityRole="text"
|
||||
|
||||
@@ -64,7 +64,8 @@ export function SettingsRow(props: {
|
||||
disabled={props.disabled}
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: target,
|
||||
screen: "SettingsContent",
|
||||
params: { screen: target },
|
||||
})
|
||||
}
|
||||
>
|
||||
|
||||
@@ -3,6 +3,7 @@ export type SettingsSheetTarget =
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
| "SettingsClientStorage";
|
||||
| "SettingsClientStorage"
|
||||
| "SettingsUsage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -1,6 +1,12 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Keyboard, View } from "react-native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import {
|
||||
CommonActions,
|
||||
type NavigationState,
|
||||
type PartialState,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
} from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
@@ -25,6 +31,8 @@ import { retryShowcaseOperation } from "./showcaseRetry";
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
const SHOWCASE_THREAD_ID = "remote-command-center";
|
||||
|
||||
type ShowcaseResetRoute = PartialState<NavigationState>["routes"][number];
|
||||
|
||||
function sceneFromPathname(pathname: string): ShowcaseScene | null {
|
||||
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
|
||||
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
|
||||
@@ -166,17 +174,21 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
navigation.dispatch(StackActions.popToTop());
|
||||
return;
|
||||
}
|
||||
const routes: Array<{
|
||||
name: string;
|
||||
params?: Record<string, unknown>;
|
||||
state?: { index: number; routes: Array<{ name: string }> };
|
||||
}> = [{ name: "Home" }];
|
||||
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
|
||||
if (requestedScene === "environments") {
|
||||
routes.push({
|
||||
name: "SettingsSheet",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "SettingsContent",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ComposerToolbarButton,
|
||||
ComposerToolbarRow,
|
||||
ComposerToolbarScroller,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
} from "../../components/ComposerToolbar";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger";
|
||||
import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -6,6 +5,7 @@ import { memo } from "react";
|
||||
import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
export type ComposerCommandItem =
|
||||
| {
|
||||
@@ -56,33 +56,14 @@ function PopoverSurface(props: {
|
||||
...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)",
|
||||
},
|
||||
]}
|
||||
<GlassSurface
|
||||
glassEffectStyle="clear"
|
||||
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
|
||||
style={baseStyle}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
</GlassSurface>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Switch,
|
||||
TextInput,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { vcsEnvironment } from "../../state/vcs";
|
||||
import {
|
||||
createNativeMailSearchToolbarItem,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
|
||||
} from "../layout/native-mail-search-toolbar";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
|
||||
|
||||
function SelectionRow(props: {
|
||||
readonly icon?: "arrow.triangle.branch" | "desktopcomputer";
|
||||
readonly onPress: () => void;
|
||||
readonly disabled?: boolean;
|
||||
readonly selected: boolean;
|
||||
readonly isLast?: boolean;
|
||||
readonly subtitle?: string;
|
||||
readonly title: string;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
const checkmarkColor = useThemeColor("--color-icon");
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}
|
||||
accessibilityRole="radio"
|
||||
accessibilityState={{ checked: props.selected }}
|
||||
className={cn(
|
||||
"min-h-14 flex-row items-center gap-3 bg-card px-4 py-3 active:bg-subtle",
|
||||
!props.isLast && "border-b border-border-subtle",
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
onPress={props.onPress}
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
{props.icon ? (
|
||||
<SymbolView name={props.icon} size={17} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
|
||||
{props.title}
|
||||
</Text>
|
||||
{props.subtitle ? (
|
||||
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
|
||||
{props.subtitle}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{props.selected ? (
|
||||
<SymbolView
|
||||
name="checkmark"
|
||||
size={16}
|
||||
tintColor={checkmarkColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function ToggleRow(props: {
|
||||
readonly title: string;
|
||||
readonly value: boolean;
|
||||
readonly onValueChange: (value: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="min-h-14 flex-row items-center gap-3 bg-card px-4 py-3">
|
||||
<Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
|
||||
{props.title}
|
||||
</Text>
|
||||
<Switch
|
||||
accessibilityLabel={props.title}
|
||||
onValueChange={props.onValueChange}
|
||||
value={props.value}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function BranchSelectionRow(props: {
|
||||
readonly badge: string | null;
|
||||
readonly branch: VcsRef;
|
||||
readonly disabled: boolean;
|
||||
readonly isFirst: boolean;
|
||||
readonly isLast: boolean;
|
||||
readonly onSelect: (branch: VcsRef) => void;
|
||||
readonly selected: boolean;
|
||||
}) {
|
||||
const onPress = useCallback(() => props.onSelect(props.branch), [props.branch, props.onSelect]);
|
||||
|
||||
return (
|
||||
<View
|
||||
className={cn(
|
||||
props.isFirst && "overflow-hidden rounded-t-2xl",
|
||||
props.isLast && "overflow-hidden rounded-b-2xl",
|
||||
)}
|
||||
>
|
||||
<SelectionRow
|
||||
icon="arrow.triangle.branch"
|
||||
disabled={props.disabled}
|
||||
isLast={props.isLast}
|
||||
onPress={onPress}
|
||||
selected={props.selected}
|
||||
subtitle={props.badge ? props.badge.toUpperCase() : undefined}
|
||||
title={props.branch.name}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function PickerSurface(props: { readonly children: ReactNode }) {
|
||||
return <View className="overflow-hidden rounded-2xl bg-card">{props.children}</View>;
|
||||
}
|
||||
|
||||
export function NewTaskEnvironmentPickerRouteScreen() {
|
||||
const flow = useNewTaskFlow();
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerShown: Platform.OS !== "android",
|
||||
title: "Environment",
|
||||
}}
|
||||
/>
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidScreenHeader title="Environment" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{
|
||||
paddingBottom: Math.max(insets.bottom, 16) + 16,
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<PickerSurface>
|
||||
{flow.environments.map((environment, index) => (
|
||||
<SelectionRow
|
||||
key={String(environment.environmentId)}
|
||||
icon="desktopcomputer"
|
||||
isLast={index === flow.environments.length - 1}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
flow.selectEnvironment(environment.environmentId);
|
||||
navigation.goBack();
|
||||
}}
|
||||
selected={flow.selectedEnvironmentId === environment.environmentId}
|
||||
title={environment.environmentLabel}
|
||||
/>
|
||||
))}
|
||||
</PickerSurface>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function NewTaskBranchPickerRouteScreen() {
|
||||
const flow = useNewTaskFlow();
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const placeholderColor = useThemeColor("--color-placeholder");
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const fontFamily = useFontFamily("regular");
|
||||
const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
|
||||
const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
|
||||
const selectingBranchNameRef = useRef<string | null>(null);
|
||||
const allowSelectionNavigationRef = useRef(false);
|
||||
const mountedRef = useRef(true);
|
||||
const screenTitle = flow.workspaceMode === "worktree" ? "Base branch" : "Branch";
|
||||
const usesNativeMailSearchToolbar = Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
|
||||
const selectedBranchName =
|
||||
flow.selectedBranchName ??
|
||||
flow.availableBranches.find((branch) => branch.current)?.name ??
|
||||
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
const branchListContentStyle = useMemo(
|
||||
() => ({
|
||||
paddingBottom: usesNativeMailSearchToolbar
|
||||
? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
|
||||
: Platform.OS === "ios"
|
||||
? 16
|
||||
: Math.max(insets.bottom, 16) + 16,
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 12,
|
||||
}),
|
||||
[insets.bottom, usesNativeMailSearchToolbar],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
flow.setBranchQuery("");
|
||||
};
|
||||
}, [flow.setBranchQuery]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
navigation.addListener("beforeRemove", (event) => {
|
||||
if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}),
|
||||
[navigation],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
async (branch: VcsRef) => {
|
||||
if (selectingBranchNameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
selectingBranchNameRef.current = branch.name;
|
||||
void Haptics.selectionAsync();
|
||||
|
||||
try {
|
||||
let selectedBranch = branch;
|
||||
const needsCheckout = shouldCheckoutNewTaskBranch({
|
||||
branchIsCurrent: branch.current,
|
||||
branchWorktreePath: branch.worktreePath,
|
||||
workspaceMode: flow.workspaceMode,
|
||||
});
|
||||
if (needsCheckout && flow.selectedProject) {
|
||||
setSwitchingBranchName(branch.name);
|
||||
const result = await switchRef({
|
||||
environmentId: flow.selectedProject.environmentId,
|
||||
input: {
|
||||
cwd: flow.selectedProject.workspaceRoot,
|
||||
refName: branch.name,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
Alert.alert(
|
||||
"Could not switch branch",
|
||||
error instanceof Error ? error.message : "The branch could not be checked out.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
selectedBranch = {
|
||||
...branch,
|
||||
current: true,
|
||||
isRemote: false,
|
||||
name: result.value.refName ?? branch.name,
|
||||
};
|
||||
}
|
||||
|
||||
// The checkout has already changed the repository. Persist the matching
|
||||
// draft selection even if the native sheet was dismissed while the
|
||||
// command was in flight; only visible-screen work is focus-gated below.
|
||||
flow.selectBranch(selectedBranch);
|
||||
if (!mountedRef.current || !navigation.isFocused()) {
|
||||
return;
|
||||
}
|
||||
flow.setBranchQuery("");
|
||||
allowSelectionNavigationRef.current = true;
|
||||
navigation.goBack();
|
||||
} finally {
|
||||
selectingBranchNameRef.current = null;
|
||||
allowSelectionNavigationRef.current = false;
|
||||
if (mountedRef.current) {
|
||||
setSwitchingBranchName(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
flow.selectBranch,
|
||||
flow.selectedProject,
|
||||
flow.setBranchQuery,
|
||||
flow.workspaceMode,
|
||||
navigation,
|
||||
switchRef,
|
||||
],
|
||||
);
|
||||
|
||||
const renderBranch = useCallback(
|
||||
({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
|
||||
<BranchSelectionRow
|
||||
badge={branchBadgeLabel({ branch: item, project: flow.selectedProject })}
|
||||
branch={item}
|
||||
disabled={switchingBranchName !== null}
|
||||
isFirst={index === 0}
|
||||
isLast={index === flow.filteredBranches.length - 1}
|
||||
onSelect={selectBranch}
|
||||
selected={selectedBranchName === item.name}
|
||||
/>
|
||||
),
|
||||
[
|
||||
flow.filteredBranches.length,
|
||||
flow.selectedProject,
|
||||
selectBranch,
|
||||
selectedBranchName,
|
||||
switchingBranchName,
|
||||
],
|
||||
);
|
||||
|
||||
const branchListHeader =
|
||||
flow.workspaceMode === "worktree" ? (
|
||||
<View className="mb-3 overflow-hidden rounded-2xl">
|
||||
<ToggleRow
|
||||
onValueChange={flow.setStartFromOrigin}
|
||||
title="Start from origin"
|
||||
value={flow.startFromOrigin}
|
||||
/>
|
||||
</View>
|
||||
) : null;
|
||||
|
||||
const branchContent =
|
||||
flow.filteredBranches.length === 0 ? (
|
||||
<ScrollView
|
||||
className="flex-1 bg-sheet"
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 12 }}
|
||||
scrollEnabled={false}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{branchListHeader}
|
||||
<View
|
||||
className="flex-1 items-center justify-center gap-3 px-4"
|
||||
style={{
|
||||
marginBottom: usesNativeMailSearchToolbar
|
||||
? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
|
||||
: 0,
|
||||
}}
|
||||
>
|
||||
{flow.branchesLoading ? <ActivityIndicator /> : null}
|
||||
<Text className="text-center text-sm text-foreground-muted">
|
||||
{flow.branchesLoading
|
||||
? "Loading branches…"
|
||||
: flow.branchesError
|
||||
? flow.branchesError
|
||||
: flow.branchQuery
|
||||
? "No matching branches"
|
||||
: "No branches available"}
|
||||
</Text>
|
||||
{!flow.branchesLoading && flow.branchesError ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
className="rounded-full bg-card px-4 py-2 active:opacity-70"
|
||||
onPress={flow.loadBranches}
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-foreground">Try again</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</ScrollView>
|
||||
) : (
|
||||
<LegendList
|
||||
alwaysBounceVertical={false}
|
||||
automaticallyAdjustsScrollIndicatorInsets
|
||||
automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
|
||||
className="flex-1 bg-sheet"
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={branchListContentStyle}
|
||||
data={flow.filteredBranches}
|
||||
keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyExtractor={(branch) =>
|
||||
`${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
|
||||
}
|
||||
ListHeaderComponent={branchListHeader}
|
||||
ListFooterComponent={
|
||||
flow.branchesFetchingNextPage ? (
|
||||
<View className="items-center py-4">
|
||||
<ActivityIndicator />
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
onEndReached={flow.hasMoreBranches ? flow.loadMoreBranches : undefined}
|
||||
onEndReachedThreshold={0.35}
|
||||
renderItem={renderBranch}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
);
|
||||
|
||||
if (Platform.OS === "android") {
|
||||
return (
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title={screenTitle} onBack={() => navigation.goBack()} />
|
||||
<View className="px-4 pb-2 pt-3">
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="h-11 rounded-xl bg-card px-4 text-base text-foreground"
|
||||
onChangeText={flow.setBranchQuery}
|
||||
placeholder="Find a branch"
|
||||
placeholderTextColor={placeholderColor}
|
||||
style={{ color: foregroundColor, fontFamily }}
|
||||
value={flow.branchQuery}
|
||||
/>
|
||||
</View>
|
||||
{branchContent}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerShown: true,
|
||||
title: screenTitle,
|
||||
unstable_headerToolbarItems: usesNativeMailSearchToolbar
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
onSearchTextChange: flow.setBranchQuery,
|
||||
placeholder: "Find a branch",
|
||||
searchTextChangeId: "new-task-branch-search-text",
|
||||
showsSearchDismissButton: true,
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
headerSearchBarOptions: usesNativeMailSearchToolbar
|
||||
? undefined
|
||||
: {
|
||||
allowToolbarIntegration: true,
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Find a branch",
|
||||
onChangeText: (event) => {
|
||||
flow.setBranchQuery(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
flow.setBranchQuery("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
{usesNativeMailSearchToolbar ? null : (
|
||||
<NativeHeaderToolbar placement="bottom">
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
{branchContent}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,21 @@
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import {
|
||||
StackActions,
|
||||
useFocusEffect,
|
||||
useNavigation,
|
||||
usePreventRemove,
|
||||
} from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Platform, Pressable, ScrollView, View, useColorScheme } from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
@@ -15,22 +23,24 @@ import {
|
||||
|
||||
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import {
|
||||
ComposerInlineControl,
|
||||
ComposerToolbarButton,
|
||||
ComposerToolbarRow,
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
} from "../../components/ComposerToolbar";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ComposerSurface } from "./ThreadComposer";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
import {
|
||||
useThreadSettingsSheetPresentation,
|
||||
type NavigationWithFinishTransitioning,
|
||||
} from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import {
|
||||
clearComposerDraftContent,
|
||||
@@ -45,21 +55,33 @@ import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { resolveDraftProjectSelection } from "./new-task-project-selection";
|
||||
import {
|
||||
resolveNewTaskBranchLabel,
|
||||
resolveNewTaskWorkspaceLabel,
|
||||
} from "./new-task-context-presentation";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
function formatWorkspaceLabel(input: {
|
||||
readonly workspaceMode: string;
|
||||
readonly currentBranchName: string | null;
|
||||
readonly selectedBranchName: string | null;
|
||||
}): string {
|
||||
const branchName = input.selectedBranchName ?? input.currentBranchName;
|
||||
if (input.workspaceMode === "worktree") {
|
||||
return branchName ? `New worktree · ${branchName}` : "New worktree";
|
||||
function NewTaskWorkspaceIcon(props: {
|
||||
readonly workspaceMode: "local" | "worktree";
|
||||
readonly worktreePath: string | null;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
if (props.workspaceMode === "local" && props.worktreePath === null) {
|
||||
return <SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />;
|
||||
}
|
||||
return branchName ? `Current · ${branchName}` : "Current checkout";
|
||||
|
||||
return (
|
||||
<View className="size-4">
|
||||
<SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />
|
||||
<View className="absolute -right-1 -bottom-1">
|
||||
<SymbolView name="arrow.triangle.branch" size={9} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function NewTaskDraftScreen(props: {
|
||||
@@ -86,7 +108,8 @@ export function NewTaskDraftScreen(props: {
|
||||
const insets = useSafeAreaInsets();
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const controlsBottomPadding = Math.max(insets.bottom, 10);
|
||||
const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
|
||||
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
@@ -104,6 +127,49 @@ export function NewTaskDraftScreen(props: {
|
||||
editorRef: promptInputRef,
|
||||
isEditorFocused: isComposerFocused,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (Platform.OS !== "ios") {
|
||||
return;
|
||||
}
|
||||
|
||||
navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });
|
||||
}, [isKeyboardVisible, navigation]);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (Platform.OS === "ios") {
|
||||
navigation.getParent()?.setOptions({ gestureEnabled: true });
|
||||
}
|
||||
};
|
||||
}, [navigation]);
|
||||
const settingsRoutePresentedRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = true;
|
||||
navigation.dispatch(StackActions.push("ThreadSettings"));
|
||||
}, [navigation, settingsSheetPresentation.isVisible]);
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = false;
|
||||
settingsSheetPresentation.onDismissed();
|
||||
}, [settingsSheetPresentation.onDismissed]),
|
||||
);
|
||||
useEffect(
|
||||
() =>
|
||||
// UIKit's completion callback for the sheet dismissal, surfaced by the
|
||||
// native-stack patch. This is when the queued keyboard restore runs.
|
||||
(navigation as unknown as NavigationWithFinishTransitioning).addListener(
|
||||
"finishTransitioning",
|
||||
settingsSheetPresentation.onStackTransitionsFinished,
|
||||
),
|
||||
[navigation, settingsSheetPresentation.onStackTransitionsFinished],
|
||||
);
|
||||
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
|
||||
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
|
||||
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
|
||||
@@ -223,9 +289,9 @@ export function NewTaskDraftScreen(props: {
|
||||
}, [props.pendingTaskId, cancelEditingPendingTask]);
|
||||
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const projectUnderlineColor = useThemeColor("--color-foreground-muted");
|
||||
const regularFontFamily = useFontFamily("regular");
|
||||
const bodyText = useScaledTextRole("body");
|
||||
const headlineText = useScaledTextRole("headline");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
|
||||
|
||||
@@ -311,7 +377,7 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
flow.loadBranches();
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -513,121 +579,6 @@ export function NewTaskDraftScreen(props: {
|
||||
shareImportAttempt,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
// Android starts with the collapsed composer pill (like an open thread)
|
||||
// and only expands/focuses when tapped.
|
||||
if (!selectedProject || Platform.OS === "android") {
|
||||
return;
|
||||
}
|
||||
|
||||
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
|
||||
const interaction = InteractionManager.runAfterInteractions(() => {
|
||||
focusFrame = requestAnimationFrame(() => {
|
||||
// The delayed focus can land after the settings sheet opened, which
|
||||
// would pop the keyboard underneath its modal.
|
||||
if (!settingsSheetPresentation.isActiveRef.current) {
|
||||
promptInputRef.current?.focus();
|
||||
} else {
|
||||
settingsSheetPresentation.restoreFocusAfterSave();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
interaction.cancel();
|
||||
if (focusFrame !== null) {
|
||||
cancelAnimationFrame(focusFrame);
|
||||
}
|
||||
};
|
||||
}, [
|
||||
selectedProject,
|
||||
settingsSheetPresentation.isActiveRef,
|
||||
settingsSheetPresentation.restoreFocusAfterSave,
|
||||
]);
|
||||
|
||||
const environmentMenuActions = useMemo(
|
||||
() =>
|
||||
flow.environments.map((environment) => ({
|
||||
id: `environment:${environment.environmentId}`,
|
||||
title: environment.environmentLabel,
|
||||
attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,
|
||||
state:
|
||||
flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
|
||||
})),
|
||||
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
|
||||
);
|
||||
|
||||
const providerOptionDescriptors = useMemo(
|
||||
() =>
|
||||
resolveProviderOptionDescriptors({
|
||||
capabilities: flow.selectedModelOption?.capabilities,
|
||||
selections: flow.selectedModel?.options,
|
||||
}),
|
||||
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
|
||||
);
|
||||
|
||||
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" ? "Current checkout" : "New worktree",
|
||||
subactions: (["local", "worktree"] as const).map((value) => ({
|
||||
id: `workspace:mode:${value}`,
|
||||
title: value === "local" ? "Current checkout" : "New worktree",
|
||||
state: flow.workspaceMode === value ? ("on" as const) : undefined,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "workspace:branch",
|
||||
title: "Branch",
|
||||
subtitle: flow.selectedBranchName ?? "Choose branch",
|
||||
subactions: branchActions,
|
||||
},
|
||||
...(flow.workspaceMode === "worktree"
|
||||
? [
|
||||
{
|
||||
id: "workspace:start-from-origin",
|
||||
title: "Start from origin",
|
||||
subtitle: "Base the worktree on the latest origin branch",
|
||||
image: "arrow.triangle.pull",
|
||||
state: flow.startFromOrigin ? ("on" as const) : undefined,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
}, [
|
||||
flow.availableBranches,
|
||||
flow.branchesLoading,
|
||||
flow.selectedBranchName,
|
||||
flow.selectedProject,
|
||||
flow.startFromOrigin,
|
||||
flow.workspaceMode,
|
||||
]);
|
||||
|
||||
const selectedEnvironmentLabel =
|
||||
flow.environments.find(
|
||||
(environment) => environment.environmentId === flow.selectedEnvironmentId,
|
||||
@@ -636,50 +587,17 @@ export function NewTaskDraftScreen(props: {
|
||||
flow.availableBranches.find((branch) => branch.current)?.name ??
|
||||
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: flow.selectedModelOption?.label ?? "Model",
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
const selectedBranchName = flow.selectedBranchName ?? currentBranchName;
|
||||
const selectedBranchLabel = resolveNewTaskBranchLabel({
|
||||
branchName: selectedBranchName,
|
||||
startFromOrigin: flow.startFromOrigin,
|
||||
workspaceMode: flow.workspaceMode,
|
||||
});
|
||||
const workspaceLabel = useMemo(
|
||||
() =>
|
||||
formatWorkspaceLabel({
|
||||
currentBranchName,
|
||||
selectedBranchName: flow.selectedBranchName,
|
||||
workspaceMode: flow.workspaceMode,
|
||||
}),
|
||||
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
|
||||
);
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
|
||||
return;
|
||||
}
|
||||
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
|
||||
}
|
||||
|
||||
function handleWorkspaceMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("workspace:mode:")) {
|
||||
flow.setWorkspaceMode(
|
||||
event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (event === "workspace:start-from-origin") {
|
||||
flow.setStartFromOrigin(!flow.startFromOrigin);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
const workspaceLabel = resolveNewTaskWorkspaceLabel({
|
||||
workspaceMode: flow.workspaceMode,
|
||||
worktreePath: flow.selectedWorktreePath,
|
||||
});
|
||||
const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
|
||||
|
||||
async function handlePickImages(): Promise<void> {
|
||||
if (isIncomingShareTransferPending) {
|
||||
@@ -729,7 +647,9 @@ export function NewTaskDraftScreen(props: {
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const interactionMode = flow.planModeEnabled
|
||||
? (draft.interactionMode ?? flow.interactionMode)
|
||||
: "default";
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
@@ -847,7 +767,7 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
if (!selectedProject) {
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
@@ -862,11 +782,6 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
const isAndroid = Platform.OS === "android";
|
||||
const isDarkMode = colorScheme === "dark";
|
||||
// Android expansion follows native editor focus so relayout cannot race
|
||||
// the touch gesture that opens the keyboard.
|
||||
// The settings sheet dismisses the keyboard, so its flag keeps the Android
|
||||
// draft composer expanded through the blur (mirrors ThreadComposer).
|
||||
const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;
|
||||
const canStart =
|
||||
Boolean(flow.selectedProject) &&
|
||||
Boolean(flow.selectedModel) &&
|
||||
@@ -878,220 +793,279 @@ export function NewTaskDraftScreen(props: {
|
||||
const promptEditor = (
|
||||
<ComposerEditor
|
||||
ref={promptInputRef}
|
||||
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
|
||||
// forces the iOS keyboard bring-up during the formSheet present
|
||||
// animation and stalls it. The runAfterInteractions effect above focuses
|
||||
// the editor once the transition settles instead.
|
||||
// The context-first screen intentionally opens with the keyboard closed.
|
||||
// Focusing is a user action, so presenting the form sheet has one motion.
|
||||
autoFocus={false}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
multiline
|
||||
scrollEnabled={isExpanded}
|
||||
scrollEnabled
|
||||
value={flow.prompt}
|
||||
skills={flow.selectedProviderSkills}
|
||||
onChangeText={flow.setPrompt}
|
||||
onFocus={() => setIsComposerFocused(true)}
|
||||
onBlur={() => setIsComposerFocused(false)}
|
||||
onPasteImages={(uris) => void handleNativePasteImages(uris)}
|
||||
placeholder={`Describe a coding task in ${selectedProject.title}`}
|
||||
// Same collapsed centering as ThreadComposer: native vertical gravity
|
||||
// in a pill-height box.
|
||||
singleLineCentered={!isExpanded}
|
||||
contentInsetVertical={isAndroid ? 0 : undefined}
|
||||
style={
|
||||
isAndroid
|
||||
? isExpanded
|
||||
? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }
|
||||
: { height: 36 }
|
||||
: { flex: 1, minHeight: 0 }
|
||||
}
|
||||
textStyle={
|
||||
isAndroid
|
||||
? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }
|
||||
: headlineText
|
||||
}
|
||||
placeholder="Ask anything…"
|
||||
singleLineCentered={false}
|
||||
contentInsetVertical={0}
|
||||
style={{
|
||||
minHeight: 72,
|
||||
maxHeight: 160,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
}}
|
||||
textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
|
||||
/>
|
||||
);
|
||||
|
||||
const toolbarPills = (
|
||||
<>
|
||||
<ComposerToolbarButton
|
||||
icon="plus"
|
||||
onPress={() => void handlePickImages()}
|
||||
const closeNewTask = () => {
|
||||
void KeyboardController.dismiss({ animated: true });
|
||||
const parentNavigation = navigation.getParent();
|
||||
if (parentNavigation) {
|
||||
parentNavigation.goBack();
|
||||
return;
|
||||
}
|
||||
navigation.goBack();
|
||||
};
|
||||
const chooseProject = () => {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
promptInputRef.current?.blur();
|
||||
void KeyboardController.dismiss({ animated: true });
|
||||
navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
|
||||
};
|
||||
const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
promptInputRef.current?.blur();
|
||||
void KeyboardController.dismiss({ animated: true });
|
||||
navigation.dispatch(StackActions.push(routeName));
|
||||
};
|
||||
|
||||
const hero = (
|
||||
<View className="items-center gap-6 px-6" testID="new-task-hero">
|
||||
<View className="w-full items-center gap-1.5">
|
||||
<Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
|
||||
What should we build
|
||||
</Text>
|
||||
<View className="max-w-full flex-row items-center justify-center">
|
||||
<Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
|
||||
<Pressable
|
||||
accessibilityHint="Opens the project picker"
|
||||
accessibilityLabel={`Change project from ${selectedProject.title}`}
|
||||
accessibilityRole="button"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
onPress={chooseProject}
|
||||
className="min-w-0 max-w-[250px] active:opacity-65"
|
||||
style={{
|
||||
borderBottomColor: projectUnderlineColor,
|
||||
borderBottomWidth: 1,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
className="text-2xl font-t3-medium tracking-tight text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{selectedProject.title}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
|
||||
chevronDirection="right"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="desktopcomputer"
|
||||
label={`on ${selectedEnvironmentLabel}`}
|
||||
maxWidth={260}
|
||||
onPress={
|
||||
flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined
|
||||
}
|
||||
showChevron={flow.environments.length > 1}
|
||||
static={flow.environments.length <= 1}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
const heroViewport = (
|
||||
<View className="flex-1" collapsable={false}>
|
||||
<ScrollView
|
||||
alwaysBounceVertical={isKeyboardVisible}
|
||||
className="flex-1"
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
contentContainerClassName="grow items-center pb-[236px] pt-12 ios:pt-[72px]"
|
||||
keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
testID="new-task-hero-scroll"
|
||||
>
|
||||
{hero}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
|
||||
const workspaceControls = (
|
||||
<View className="flex-row items-center gap-1 px-2">
|
||||
<ComposerInlineControl
|
||||
accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
|
||||
accessibilityLabel={workspaceLabel}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={
|
||||
<NewTaskWorkspaceIcon
|
||||
workspaceMode={flow.workspaceMode}
|
||||
worktreePath={flow.selectedWorktreePath}
|
||||
/>
|
||||
}
|
||||
label={workspaceLabel}
|
||||
maxWidth={flow.workspaceMode === "local" ? 220 : 148}
|
||||
onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
|
||||
showChevron={false}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
/>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
|
||||
chevronDirection="right"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
icon="arrow.triangle.branch"
|
||||
label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
|
||||
maxWidth={190}
|
||||
onPress={() => openContextPicker("NewTaskBranch")}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={environmentMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Environment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="desktopcomputer"
|
||||
label={selectedEnvironmentLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={workspaceMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Workspace"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
label={workspaceLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
</>
|
||||
</View>
|
||||
);
|
||||
|
||||
const settingsSheet = (
|
||||
<ThreadSettingsSheet
|
||||
visible={settingsSheetPresentation.isVisible}
|
||||
onClose={settingsSheetPresentation.close}
|
||||
onDismissed={settingsSheetPresentation.onDismissed}
|
||||
providerGroups={flow.providerGroups}
|
||||
selectedModel={flow.selectedModel}
|
||||
onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
|
||||
optionDescriptors={providerOptionDescriptors}
|
||||
onUpdateOptionSelections={flow.setSelectedModelOptions}
|
||||
runtimeMode={flow.runtimeMode}
|
||||
onUpdateRuntimeMode={flow.setRuntimeMode}
|
||||
/>
|
||||
);
|
||||
const composerDock = (
|
||||
<View className="bg-sheet px-4 pt-1" style={{ paddingBottom: controlsBottomPadding }}>
|
||||
<View className="pb-1">{workspaceControls}</View>
|
||||
|
||||
const startButton = (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={
|
||||
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
|
||||
}
|
||||
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
|
||||
onPress={() => void handleStart()}
|
||||
variant="primary"
|
||||
showChevron={false}
|
||||
disabled={!canStart}
|
||||
/>
|
||||
<ComposerSurface
|
||||
animateLayout={false}
|
||||
isDarkMode={isDarkMode}
|
||||
style={{
|
||||
borderRadius: 26,
|
||||
minHeight: 140,
|
||||
overflow: "hidden",
|
||||
paddingBottom: 6,
|
||||
paddingHorizontal: 14,
|
||||
paddingTop: 14,
|
||||
}}
|
||||
>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
imageBorderRadius={16}
|
||||
imageSize={72}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{promptEditor}
|
||||
|
||||
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={sheetFadeOpaque}
|
||||
fadeTransparent={sheetFadeTransparent}
|
||||
contentPaddingRight={8}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="plus"
|
||||
onPress={() => void handlePickImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel="Model and reasoning settings"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
emphasized
|
||||
iconNode={
|
||||
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={flow.selectedModelOption?.label ?? "Choose model"}
|
||||
maxWidth={152}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{flow.planModeEnabled ? (
|
||||
<ComposerInlineControl
|
||||
accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
|
||||
accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
emphasized
|
||||
icon={
|
||||
flow.interactionMode === "plan"
|
||||
? { ios: "list.bullet.clipboard", android: "auto_awesome" }
|
||||
: { ios: "hammer", android: "construction" }
|
||||
}
|
||||
label={flow.interactionMode === "plan" ? "Plan" : "Build"}
|
||||
onPress={() =>
|
||||
flow.setInteractionMode(flow.interactionMode === "plan" ? "default" : "plan")
|
||||
}
|
||||
showChevron={false}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerToolbarScroller>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={
|
||||
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
|
||||
}
|
||||
disabled={!canStart}
|
||||
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
|
||||
onPress={() => void handleStart()}
|
||||
showChevron={false}
|
||||
variant="primary"
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
</ComposerSurface>
|
||||
</View>
|
||||
);
|
||||
|
||||
if (isAndroid) {
|
||||
// The draft is a thread that doesn't exist yet, so it mirrors the thread
|
||||
// page: in-screen header, empty feed canvas above, and the same floating
|
||||
// composer chrome as ThreadComposer (collapsed pill → expanded card).
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
|
||||
<AndroidScreenHeader title="New task" onBack={closeNewTask} />
|
||||
{heroViewport}
|
||||
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="flex-1" />
|
||||
|
||||
<View
|
||||
className="px-4 pt-2"
|
||||
style={{
|
||||
paddingBottom: controlsBottomPadding,
|
||||
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%)",
|
||||
}}
|
||||
>
|
||||
<ComposerSurface
|
||||
isDarkMode={isDarkMode}
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
borderRadius: 20,
|
||||
overflow: "hidden",
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
}
|
||||
: {
|
||||
borderRadius: 999,
|
||||
overflow: "hidden",
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingLeft: 18,
|
||||
paddingRight: 5,
|
||||
paddingVertical: 5,
|
||||
}
|
||||
}
|
||||
>
|
||||
{isExpanded && flow.attachments.length > 0 ? (
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={
|
||||
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>
|
||||
{!isExpanded ? (
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canStart}
|
||||
onPress={() => void handleStart()}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{isExpanded ? (
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}
|
||||
fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}
|
||||
>
|
||||
{toolbarPills}
|
||||
</ComposerToolbarScroller>
|
||||
{startButton}
|
||||
</ComposerToolbarRow>
|
||||
) : null}
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
<KeyboardStickyView
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: keyboardOpenedOffset }}
|
||||
>
|
||||
{composerDock}
|
||||
</KeyboardStickyView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerBackVisible: false,
|
||||
headerShadowVisible: false,
|
||||
title: "",
|
||||
}}
|
||||
/>
|
||||
<NativeHeaderToolbar placement="left">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Cancel new task"
|
||||
label="Cancel"
|
||||
onPress={closeNewTask}
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>
|
||||
|
||||
<View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View className="px-4 pt-3">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
imageSize={88}
|
||||
imageBorderRadius={20}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={sheetFadeOpaque}
|
||||
fadeTransparent={sheetFadeTransparent}
|
||||
>
|
||||
{toolbarPills}
|
||||
</ComposerToolbarScroller>
|
||||
{startButton}
|
||||
</ComposerToolbarRow>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
{heroViewport}
|
||||
<KeyboardStickyView
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: keyboardOpenedOffset }}
|
||||
>
|
||||
{composerDock}
|
||||
</KeyboardStickyView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import {
|
||||
StackActions,
|
||||
useIsFocused,
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -14,10 +19,10 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { getProjectScopeSelectionTarget } from "./new-task-project-selection";
|
||||
|
||||
type NewTaskRouteParams = {
|
||||
readonly incomingShareId?: string | string[];
|
||||
@@ -80,7 +85,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
|
||||
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
|
||||
const projects = useProjects();
|
||||
const { projectScopes } = useNewTaskFlow();
|
||||
const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const navigation = useNavigation();
|
||||
const isFocused = useIsFocused();
|
||||
@@ -88,7 +93,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const { getShare, releaseShareReservation } = useIncomingShare();
|
||||
const routeShareId = Array.isArray(route.params?.incomingShareId)
|
||||
? route.params.incomingShareId[0]
|
||||
@@ -126,27 +130,22 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
return;
|
||||
}
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
const state = navigation.getState();
|
||||
const previousRoute = state?.routes[state.index - 1];
|
||||
if (previousRoute?.name === "NewTaskDraft") {
|
||||
setProject(project);
|
||||
navigation.goBack();
|
||||
return;
|
||||
}
|
||||
|
||||
navigation.dispatch(
|
||||
StackActions.push("NewTaskDraft", {
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
incomingShareId: incomingShare?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function toggleGroup(groupKey: string): void {
|
||||
setExpandedGroupKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(groupKey)) {
|
||||
next.delete(groupKey);
|
||||
} else {
|
||||
next.add(groupKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -169,15 +168,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
return;
|
||||
}
|
||||
resumedDestinationKeyRef.current = destinationKey;
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("NewTaskDraft", {
|
||||
environmentId: reservedDestinationProject.environmentId,
|
||||
projectId: reservedDestinationProject.id,
|
||||
title: reservedDestinationProject.title,
|
||||
incomingShareId: incomingShare.id,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
}, [incomingShare, isFocused, navigation, reservedDestinationProject]);
|
||||
|
||||
return (
|
||||
@@ -196,7 +194,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
{
|
||||
accessibilityLabel: "Add project",
|
||||
icon: "plus",
|
||||
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
|
||||
onPress: () => navigation.dispatch(StackActions.push("AddProject")),
|
||||
},
|
||||
]
|
||||
: []
|
||||
@@ -223,7 +221,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
{catalogState.hasReadyEnvironment ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
@@ -263,7 +261,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
) : (
|
||||
<Pressable
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
Add new project
|
||||
@@ -275,27 +273,21 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{projectScopes.map((scope, scopeIndex) => {
|
||||
const hasMultipleProjects = scope.projects.length > 1;
|
||||
const expanded = expandedGroupKeys.has(scope.key);
|
||||
const singleProject = hasMultipleProjects ? null : scope.projects[0];
|
||||
const selectionTarget = getProjectScopeSelectionTarget(scope, selectedEnvironmentId);
|
||||
return (
|
||||
<View
|
||||
key={scope.key}
|
||||
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
|
||||
>
|
||||
<Pressable
|
||||
disabled={singleProject !== null && reservedDestinationProject !== null}
|
||||
onPress={() => {
|
||||
if (singleProject) {
|
||||
void selectProject(singleProject);
|
||||
} else {
|
||||
toggleGroup(scope.key);
|
||||
}
|
||||
}}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(selectionTarget)}
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3.5"
|
||||
>
|
||||
<View className="h-7 w-7 items-center justify-center">
|
||||
<ProjectFavicon
|
||||
environmentId={scope.representative.environmentId}
|
||||
faviconPath={scope.representative.faviconPath}
|
||||
size={20}
|
||||
projectTitle={scope.title}
|
||||
workspaceRoot={scope.representative.workspaceRoot}
|
||||
@@ -310,51 +302,16 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
>
|
||||
{hasMultipleProjects
|
||||
? `${scope.projects.length} workspaces`
|
||||
: singleProject?.workspaceRoot}
|
||||
: selectionTarget.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
{hasMultipleProjects && expanded
|
||||
? scope.projects.map((project) => (
|
||||
<Pressable
|
||||
key={scopedProjectKey(project.environmentId, project.id)}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(project)}
|
||||
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
/>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-sm font-t3-bold text-foreground">
|
||||
{project.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{project.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
))
|
||||
: null}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,18 +1,64 @@
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInUp,
|
||||
FadeOutDown,
|
||||
LinearTransition,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
|
||||
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
isPendingUserInputOptionSelected,
|
||||
type PendingUserInput,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
/**
|
||||
* Constant while a request is pending (it reserves keyboard space), so the
|
||||
* keyboard transition is pure translation; changes only on rare discrete
|
||||
* corrections, which the layout transition smooths.
|
||||
*/
|
||||
readonly maxHeight: number;
|
||||
readonly collapsed: boolean;
|
||||
readonly onToggleCollapsed: () => void;
|
||||
/** Renders a stop control on the collapsed bar, which replaces the composer. */
|
||||
readonly onStopThread?: () => void;
|
||||
/**
|
||||
* 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
|
||||
* collapsed bar (inside a clipping window) on the UI thread; the host
|
||||
* animates it directly from the tap handler so the card and the feed
|
||||
* inset glide start the same frame.
|
||||
*/
|
||||
readonly cardProgress?: SharedValue<number>;
|
||||
/**
|
||||
* Receives how far the expanded card extends above the bar footprint
|
||||
* (written from onLayout with no re-render); the host adds it to the
|
||||
* thread feed's end inset so the end of the chat stays visible above the
|
||||
* card.
|
||||
*/
|
||||
readonly cardCoverage?: SharedValue<number>;
|
||||
/** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onInputFocusChange?: (focused: boolean) => void;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
@@ -23,74 +69,242 @@ export interface PendingUserInputCardProps {
|
||||
readonly onSubmit: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
|
||||
* card is an absolutely-positioned overlay rising above it. The overlay's
|
||||
* measured height (which drives the thread feed's bottom inset) therefore
|
||||
* never changes on collapse/expand, so the transcript stays perfectly still
|
||||
* while the card animates over it.
|
||||
*
|
||||
* Android cannot use the overlay: it does not hit-test touches outside a
|
||||
* parent's bounds, which made everything above the bar-sized wrapper
|
||||
* untouchable. There the expanded card renders in-flow instead (the wrapper
|
||||
* grows with it, and the host skips the coverage inset since the measured
|
||||
* overlay already includes the card).
|
||||
*/
|
||||
const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
|
||||
|
||||
const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
// The surface is opaque on purpose: the card floats over the thread feed
|
||||
// with no blur behind it, so a translucent background renders the questions
|
||||
// on top of whatever message happens to sit underneath.
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs 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-base leading-snug 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
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
const questionCount = props.pendingUserInput.questions.length;
|
||||
|
||||
const cardCoverage = props.cardCoverage;
|
||||
const barHeightRef = useRef(0);
|
||||
const cardHeightRef = useRef(0);
|
||||
// Measured card height, written straight from onLayout: the collapse slide
|
||||
// distance. Not animated — it only changes on discrete relayouts.
|
||||
const cardHeight = useSharedValue(0);
|
||||
const notifyCoverage = useCallback(() => {
|
||||
if (!cardCoverage) {
|
||||
return;
|
||||
}
|
||||
const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
|
||||
if (coverage === cardCoverage.value) {
|
||||
return;
|
||||
}
|
||||
if (cardCoverage.value === 0) {
|
||||
// First measurement lands while the list is doing its initial
|
||||
// end-pin (thread opened onto a pending request); animating it from
|
||||
// zero would move the end anchor out from under that scroll.
|
||||
cardCoverage.value = coverage;
|
||||
return;
|
||||
}
|
||||
// Animated so a coverage change at rest (discrete max-height
|
||||
// corrections) glides the feed instead of stepping it; toggle timing is
|
||||
// owned by the host's progress values.
|
||||
cardCoverage.value = withTiming(coverage, {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
});
|
||||
}, [cardCoverage]);
|
||||
const handleBarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
barHeightRef.current = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[notifyCoverage],
|
||||
);
|
||||
const handleCardLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
cardHeightRef.current = event.nativeEvent.layout.height;
|
||||
cardHeight.value = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[cardHeight, notifyCoverage],
|
||||
);
|
||||
const cardProgress = props.cardProgress;
|
||||
// No opacity: fading an opaque card over the live transcript reads as a
|
||||
// crossfade (card text, transcript, and bar all half-visible at once).
|
||||
// Instead the card stays opaque and slides its full height down past the
|
||||
// clipping window's bottom edge, so the transcript is only revealed where
|
||||
// the card has physically left.
|
||||
const cardAnimatedStyle = useAnimatedStyle(() => {
|
||||
const progress = cardProgress === undefined ? 1 : cardProgress.value;
|
||||
return {
|
||||
transform: [{ translateY: (1 - progress) * cardHeight.value }],
|
||||
};
|
||||
});
|
||||
|
||||
// On iOS the card stays MOUNTED while collapsed (hidden via the animated
|
||||
// style): expanding animates existing views on the UI thread the same
|
||||
// frame the host starts the progress timing, instead of paying a React
|
||||
// mount + layout before anything moves.
|
||||
const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
|
||||
const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
|
||||
// The bar renders UNDER the card (earlier in JSX), always opaque: while
|
||||
// expanded the opaque card covers it, and during the collapse slide the
|
||||
// card's top edge wipes past and reveals it — no opacity handoff, so no
|
||||
// crossfade frames.
|
||||
const bar = showBar ? (
|
||||
<View
|
||||
onLayout={handleBarLayout}
|
||||
pointerEvents={props.collapsed ? "auto" : "none"}
|
||||
accessibilityElementsHidden={!props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
|
||||
className="flex-row items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Expand user input, ${questionCount} question${
|
||||
questionCount === 1 ? "" : "s"
|
||||
}`}
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
|
||||
>
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-sans text-xs text-neutral-500 dark:text-neutral-400">
|
||||
{questionCount} question{questionCount === 1 ? "" : "s"}
|
||||
</Text>
|
||||
<View className="flex-1" />
|
||||
<SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
|
||||
</Pressable>
|
||||
{props.onStopThread ? (
|
||||
<ControlPill
|
||||
accessibilityLabel="Stop"
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
className="h-9 w-9"
|
||||
onPress={props.onStopThread}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
) : null;
|
||||
const card = renderCard ? (
|
||||
// The surface is opaque on purpose: the card floats over the thread
|
||||
// feed with no blur behind it, so a translucent background renders
|
||||
// the questions on top of whatever message happens to sit underneath.
|
||||
<Animated.View
|
||||
onLayout={handleCardLayout}
|
||||
pointerEvents={props.collapsed ? "none" : "auto"}
|
||||
accessibilityElementsHidden={props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
|
||||
entering={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
exiting={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
layout={CARD_LAYOUT_TRANSITION}
|
||||
className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
|
||||
style={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
|
||||
: { maxHeight: props.maxHeight }
|
||||
}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Collapse user input"
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="flex-row items-start gap-2"
|
||||
>
|
||||
<View className="flex-1 gap-2.5">
|
||||
<Text className="font-t3-bold text-2xs 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>
|
||||
</View>
|
||||
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
|
||||
<SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
|
||||
</View>
|
||||
</Pressable>
|
||||
<ScrollView
|
||||
bounces={false}
|
||||
className="min-h-0"
|
||||
contentContainerClassName="gap-2.5 pb-1"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
nestedScrollEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{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-base leading-snug 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 = isPendingUserInputOptionSelected(draft, option.label);
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
className={cn(
|
||||
"font-t3-bold text-sm",
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
? "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,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold text-sm",
|
||||
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)
|
||||
}
|
||||
onFocus={() => props.onInputFocusChange?.(true)}
|
||||
onBlur={() => props.onInputFocusChange?.(false)}
|
||||
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-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
</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-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
<Pressable
|
||||
className={cn(
|
||||
"items-center justify-center rounded-2xl px-4 py-3.5",
|
||||
@@ -103,6 +317,26 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
) : null;
|
||||
return (
|
||||
<View className="relative">
|
||||
{bar}
|
||||
{EXPANDED_CARD_IS_OVERLAY ? (
|
||||
// Clipping window for the collapse slide: same footprint as the
|
||||
// expanded card, bottom edge on the bar's bottom edge. The sliding
|
||||
// card exits through the bottom edge instead of drawing over the
|
||||
// composer area, wiping the bar (and the transcript) into view.
|
||||
<View
|
||||
pointerEvents={props.collapsed ? "none" : "box-none"}
|
||||
className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
|
||||
style={{ height: props.maxHeight }}
|
||||
>
|
||||
{card}
|
||||
</View>
|
||||
) : (
|
||||
card
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
@@ -14,6 +13,7 @@ import {
|
||||
serializeComposerFileLink,
|
||||
type ComposerTrigger,
|
||||
} from "@t3tools/shared/composerTrigger";
|
||||
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
@@ -40,17 +40,18 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
import {
|
||||
ComposerEditor,
|
||||
type ComposerEditorHandle,
|
||||
type ComposerEditorSelection,
|
||||
} from "../../components/ComposerEditor";
|
||||
import {
|
||||
ComposerInlineControl,
|
||||
ComposerToolbarButton,
|
||||
ComposerToolbarRow,
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
} from "../../components/ComposerToolbar";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
@@ -65,8 +66,14 @@ import {
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
import {
|
||||
type ExistingThreadSettingsRouteSession,
|
||||
useExistingThreadSettingsRoutePresentation,
|
||||
} from "./ThreadSettingsSheet";
|
||||
import {
|
||||
useThreadSettingsSheetPresentation,
|
||||
type NavigationWithFinishTransitioning,
|
||||
} from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
/**
|
||||
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
|
||||
@@ -78,7 +85,7 @@ export const COMPOSER_COLLAPSED_CHROME = 60;
|
||||
* 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 const COMPOSER_EXPANDED_CHROME = 156;
|
||||
|
||||
export interface ThreadComposerProps {
|
||||
readonly draftMessage: string;
|
||||
@@ -113,11 +120,13 @@ export interface ThreadComposerProps {
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onExpandedChange?: (expanded: boolean) => void;
|
||||
/** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onEditorFocusChange?: (focused: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pill / card container — renders as LiquidGlassView on supported
|
||||
* iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
|
||||
* The pill / card container — renders with Expo's native GlassView on supported
|
||||
* iOS 26+ devices and keeps the existing opaque fallback elsewhere.
|
||||
* Exported so NewTaskDraftScreen can render the same composer chrome.
|
||||
*/
|
||||
// One timing for every piece of the expanded↔compact morph so the surface,
|
||||
@@ -133,6 +142,8 @@ export function ComposerSurface(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly style: ViewStyle;
|
||||
readonly isDarkMode: boolean;
|
||||
/** Existing thread composers morph between pill and card layouts. */
|
||||
readonly animateLayout?: boolean;
|
||||
}) {
|
||||
// Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself
|
||||
// (needed to clip content to the pill shape) would clip the shadow on iOS.
|
||||
@@ -145,35 +156,26 @@ export function ComposerSurface(props: {
|
||||
elevation: 10,
|
||||
};
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<LiquidGlassView
|
||||
effect="regular"
|
||||
interactive
|
||||
colorScheme={props.isDarkMode ? "dark" : "light"}
|
||||
style={props.style}
|
||||
>
|
||||
{props.children}
|
||||
</LiquidGlassView>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<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)",
|
||||
},
|
||||
]}
|
||||
<Animated.View
|
||||
layout={props.animateLayout === false ? undefined : COMPOSER_LAYOUT_TRANSITION}
|
||||
style={shadowStyle}
|
||||
>
|
||||
<GlassSurface
|
||||
chrome="none"
|
||||
fallbackStyle={{
|
||||
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)",
|
||||
}}
|
||||
glassEffectStyle="regular"
|
||||
// The composer is a passive material containing interactive controls.
|
||||
// Expo GlassView defaults to non-interactive and both layouts share it.
|
||||
tintColor="transparent"
|
||||
style={props.style}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
</GlassSurface>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@@ -264,6 +266,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
});
|
||||
|
||||
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
|
||||
const navigation = useNavigation();
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const bodyText = useScaledTextRole("body");
|
||||
@@ -274,14 +277,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
editorRef: inputRef,
|
||||
isEditorFocused: isFocused,
|
||||
});
|
||||
const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
|
||||
const settingsRoutePresentedRef = useRef(false);
|
||||
const wasExpandedBeforePreviewRef = useRef(false);
|
||||
const inFlightThreadIdsRef = useRef(new Set<string>());
|
||||
const { onExpandedChange } = props;
|
||||
|
||||
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
|
||||
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
|
||||
// Opening and closing count as active so the composer stays expanded while
|
||||
// focus moves between its native editor and the settings modal.
|
||||
// Opening and presentation count as active so the composer stays expanded
|
||||
// while focus moves between its native editor and the settings picker.
|
||||
const isExpanded = isFocused || settingsSheetPresentation.isActive;
|
||||
const canSend = hasContent;
|
||||
|
||||
@@ -307,13 +312,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}
|
||||
}, [inputRef]);
|
||||
|
||||
const onEditorFocusChange = props.onEditorFocusChange;
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true);
|
||||
}, []);
|
||||
onEditorFocusChange?.(true);
|
||||
}, [onEditorFocusChange]);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsFocused(false);
|
||||
}, []);
|
||||
onEditorFocusChange?.(false);
|
||||
}, [onEditorFocusChange]);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
@@ -324,7 +332,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
: "Send";
|
||||
const currentModelSelection = props.selectedThread.modelSelection;
|
||||
const currentRuntimeMode = props.selectedThread.runtimeMode;
|
||||
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
|
||||
const connectionStatus = composerConnectionStatus({
|
||||
connectionError: props.connectionError,
|
||||
connectionState: props.connectionState,
|
||||
@@ -616,12 +623,71 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}),
|
||||
[currentModelOption?.capabilities, currentModelSelection.options],
|
||||
);
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
|
||||
() => ({
|
||||
ownerId: settingsOwnerId,
|
||||
providerGroups: threadProviderGroups,
|
||||
selectedModel: currentModelSelection,
|
||||
onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
onUpdateOptionSelections: (options) =>
|
||||
props.onUpdateModelSelection({ ...currentModelSelection, options }),
|
||||
runtimeMode: currentRuntimeMode,
|
||||
onUpdateRuntimeMode: props.onUpdateRuntimeMode,
|
||||
}),
|
||||
[
|
||||
currentModelSelection,
|
||||
currentRuntimeMode,
|
||||
props.onUpdateModelSelection,
|
||||
props.onUpdateRuntimeMode,
|
||||
providerOptionDescriptors,
|
||||
settingsOwnerId,
|
||||
threadProviderGroups,
|
||||
],
|
||||
);
|
||||
const openSettings = useCallback(() => {
|
||||
settingsRoutePresentation.present(settingsRouteSession);
|
||||
settingsSheetPresentation.open();
|
||||
}, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (settingsSheetPresentation.isActive) {
|
||||
settingsRoutePresentation.present(settingsRouteSession);
|
||||
}
|
||||
}, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = true;
|
||||
navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
|
||||
}, [navigation, settingsSheetPresentation.isVisible]);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = false;
|
||||
settingsSheetPresentation.onDismissed();
|
||||
settingsRoutePresentation.clear(settingsOwnerId);
|
||||
}, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
// UIKit's completion callback for the sheet dismissal, surfaced by the
|
||||
// native-stack patch. This is when the queued keyboard restore runs.
|
||||
(navigation as unknown as NavigationWithFinishTransitioning).addListener(
|
||||
"finishTransitioning",
|
||||
settingsSheetPresentation.onStackTransitionsFinished,
|
||||
),
|
||||
[navigation, settingsSheetPresentation.onStackTransitionsFinished],
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
@@ -674,10 +740,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
borderRadius: 20,
|
||||
borderRadius: 26,
|
||||
minHeight: 140,
|
||||
overflow: "hidden" as const,
|
||||
paddingBottom: 6,
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
paddingTop: 14,
|
||||
}
|
||||
: {
|
||||
borderRadius: 999,
|
||||
@@ -727,7 +795,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
minHeight: 80,
|
||||
minHeight: 72,
|
||||
maxHeight: 160,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
@@ -776,15 +844,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{isExpanded ? (
|
||||
// Toolbar row — matches draft page layout (expanded only)
|
||||
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
{isExpanded ? (
|
||||
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={toolbarFadeOpaque}
|
||||
fadeTransparent={toolbarFadeTransparent}
|
||||
contentPaddingRight={8}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
@@ -792,14 +857,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel="Model and reasoning settings"
|
||||
emphasized
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
maxWidth={152}
|
||||
onPress={openSettings}
|
||||
/>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
@@ -820,8 +886,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
showChevron={false}
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{/* Queue count */}
|
||||
{props.queueCount > 0 ? (
|
||||
@@ -834,21 +900,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
) : null}
|
||||
</Animated.View>
|
||||
|
||||
<ThreadSettingsSheet
|
||||
visible={settingsSheetPresentation.isVisible}
|
||||
onClose={settingsSheetPresentation.close}
|
||||
onDismissed={settingsSheetPresentation.onDismissed}
|
||||
providerGroups={threadProviderGroups}
|
||||
selectedModel={currentModelSelection}
|
||||
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
|
||||
optionDescriptors={providerOptionDescriptors}
|
||||
onUpdateOptionSelections={(options) =>
|
||||
props.onUpdateModelSelection({ ...currentModelSelection, options })
|
||||
}
|
||||
runtimeMode={currentRuntimeMode}
|
||||
onUpdateRuntimeMode={props.onUpdateRuntimeMode}
|
||||
/>
|
||||
|
||||
<ImageViewing
|
||||
images={previewImageUri ? [{ uri: previewImageUri }] : []}
|
||||
imageIndex={0}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
|
||||
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
@@ -13,14 +14,45 @@ import type {
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
AppState,
|
||||
Keyboard,
|
||||
Platform,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
type GestureResponderEvent,
|
||||
} from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInDown,
|
||||
FadeOut,
|
||||
useAnimatedReaction,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
@@ -34,6 +66,11 @@ import type {
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
import {
|
||||
derivePendingUserInputMaxHeight,
|
||||
ESTIMATED_KEYBOARD_HEIGHT,
|
||||
USER_INPUT_TOGGLE_DURATION_MS,
|
||||
} from "./pendingUserInputLayout";
|
||||
import {
|
||||
COMPOSER_COLLAPSED_CHROME,
|
||||
COMPOSER_EXPANDED_CHROME,
|
||||
@@ -54,7 +91,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
@@ -89,7 +126,7 @@ export interface ThreadDetailScreenProps {
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
@@ -171,8 +208,48 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
const USER_INPUT_TOGGLE_TIMING = {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
};
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const liveKeyboardHeight = useKeyboardState((state) => state.height);
|
||||
// Android can swallow the IME hide callbacks when the app is backgrounded
|
||||
// mid keyboard-hide (the reported repro: send — which blurs and starts the
|
||||
// hide — then Home within a second). The keyboard library's height AND
|
||||
// visibility then stay frozen open, so gating the sticky translation on
|
||||
// visibility alone still strands the composer after resume. Quarantine the
|
||||
// translation on every Android resume instead; any sign of a live keyboard
|
||||
// stream — an owned input gaining focus, or any visibility/height movement —
|
||||
// lifts it. A healthy resume sees no visual difference (the translation is
|
||||
// already zero while the keyboard is closed).
|
||||
const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
|
||||
useEffect(() => {
|
||||
if (Platform.OS !== "android") {
|
||||
return;
|
||||
}
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
setKeyboardStateSuspect(true);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setKeyboardStateSuspect(false);
|
||||
}, [isKeyboardVisible, liveKeyboardHeight]);
|
||||
const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
|
||||
if (focused) {
|
||||
setKeyboardStateSuspect(false);
|
||||
}
|
||||
}, []);
|
||||
const windowHeight = useWindowDimensions().height;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
@@ -183,7 +260,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
// Android keys the safe-area padding on keyboard visibility (#5988): the
|
||||
// back gesture closes the keyboard while the editor stays focused, and a
|
||||
// focus-keyed inset would leave the toolbar under the gesture bar. iOS must
|
||||
// NOT use visibility — it only flips on keyboardDidHide, after the hide
|
||||
// animation, so the composer would ride down flush to the screen edge and
|
||||
// then snap up into the inset. On iOS blur precedes the hide, so the
|
||||
// focus-keyed inset is already in place while the composer rides down.
|
||||
const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
|
||||
? 0
|
||||
: Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
// The raw sync status enters "synchronizing" on every full fetch, cached or
|
||||
// not. Whether messages are already on screen decides the pill label: no
|
||||
@@ -204,6 +291,41 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
// While a user-input request is pending, the questionnaire owns the
|
||||
// composer slot outright: expanded it is the full card, collapsed it is a
|
||||
// composer-style bar in the same place (with its own stop control). The
|
||||
// composer never mounts into the transition, which keeps the collapse and
|
||||
// keyboard animations coherent. Collapse state is keyed by request id so a
|
||||
// new request re-expands automatically.
|
||||
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
|
||||
useState<ApprovalRequestId | null>(null);
|
||||
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
|
||||
const userInputCollapsed =
|
||||
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
|
||||
// The card's height RESERVES keyboard space at all times instead of
|
||||
// tracking the keyboard: transforms (the sticky translation) apply
|
||||
// same-frame on the UI thread while layout props lag a Yoga pass behind,
|
||||
// so any height that follows the keyboard flashes the card over the nav
|
||||
// header on the way up. With a constant height the keyboard transition is
|
||||
// pure translation — frame-perfect by construction — and the resting card
|
||||
// stays compact over the transcript. Before the first open the reserve is
|
||||
// an estimate; once a real height is known the card corrects once,
|
||||
// discretely.
|
||||
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
|
||||
useEffect(() => {
|
||||
if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
|
||||
setLastKnownKeyboardHeight(liveKeyboardHeight);
|
||||
}
|
||||
}, [lastKnownKeyboardHeight, liveKeyboardHeight]);
|
||||
const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
|
||||
windowHeight,
|
||||
keyboardHeight:
|
||||
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
|
||||
navigationHeaderHeight,
|
||||
// The questionnaire owns the composer slot, so only the composer's
|
||||
// bottom inset still overlaps.
|
||||
composerOverlapHeight: composerBottomInset,
|
||||
});
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
@@ -220,7 +342,103 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
-nativeInsetOvercount,
|
||||
);
|
||||
// The expanded questionnaire is an absolute overlay on iOS, so it never
|
||||
// changes the measured overlay height (that constancy is what keeps the
|
||||
// feed from snapping on collapse/expand). The toggle choreography runs on
|
||||
// SHARED VALUES set directly in the tap handler — one JS hop, then the
|
||||
// card's rise/sink and the feed's end-inset glide animate in lockstep on
|
||||
// the UI thread, keyboard-style, instead of waiting on React mount +
|
||||
// onLayout + state round trips. Coverage (how far the card extends above
|
||||
// the bar) is measured straight into a shared value by the card's
|
||||
// onLayout, with no re-render.
|
||||
const userInputCardProgress = useSharedValue(1);
|
||||
const userInputInsetProgress = useSharedValue(1);
|
||||
const userInputCardCoverage = useSharedValue(0);
|
||||
// Android renders the expanded card in-flow (it cannot hit-test the iOS
|
||||
// overlay outside the bar's bounds), so its measured overlay height already
|
||||
// includes the card — the coverage extra is iOS-only.
|
||||
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
|
||||
const combinedContentInsetEndAdjustment = useSharedValue(
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
);
|
||||
useAnimatedReaction(
|
||||
() =>
|
||||
contentInsetEndAdjustment.value +
|
||||
(userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
|
||||
(value) => {
|
||||
combinedContentInsetEndAdjustment.value = value;
|
||||
},
|
||||
[userInputCoverageApplies],
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
endFollowEnabledRef.current = endFollowEnabled;
|
||||
const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// The list's own corrections for these inset changes drift on short
|
||||
// content (and the error compounds across toggles), so deterministically
|
||||
// re-pin the end once a toggle settles: a no-op when the resting position
|
||||
// is already right, corrective when it is not. Follow state is re-checked
|
||||
// inside the callback — the user may grab the list during the settle
|
||||
// window, and yanking them back would override a live gesture.
|
||||
const scheduleUserInputRepin = useCallback(
|
||||
(delayMs: number) => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
userInputRepinTimerRef.current = setTimeout(() => {
|
||||
userInputRepinTimerRef.current = null;
|
||||
if (!endFollowEnabledRef.current) {
|
||||
return;
|
||||
}
|
||||
void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, delayMs);
|
||||
},
|
||||
[freeze, scrollMessageToEnd],
|
||||
);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleToggleUserInputCollapsed = useCallback(() => {
|
||||
if (activeUserInputRequestId === null) {
|
||||
return;
|
||||
}
|
||||
if (userInputCollapsed) {
|
||||
// Expanding: card and feed glide start NOW, on the UI thread.
|
||||
userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
setCollapsedUserInputRequestId(null);
|
||||
scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
|
||||
} else {
|
||||
// Collapsing hides the custom-answer inputs; release the keyboard with
|
||||
// them instead of leaving it up over a dead responder.
|
||||
Keyboard.dismiss();
|
||||
userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
|
||||
// Instant: the sinking card still covers the strip being revealed, and
|
||||
// animating the inset downward is what drifted the short-content end
|
||||
// anchor.
|
||||
userInputInsetProgress.value = 0;
|
||||
setCollapsedUserInputRequestId(activeUserInputRequestId);
|
||||
scheduleUserInputRepin(60);
|
||||
}
|
||||
}, [
|
||||
activeUserInputRequestId,
|
||||
scheduleUserInputRepin,
|
||||
userInputCardProgress,
|
||||
userInputCollapsed,
|
||||
userInputInsetProgress,
|
||||
]);
|
||||
useEffect(() => {
|
||||
// A new request always arrives expanded.
|
||||
userInputCardProgress.value = 1;
|
||||
userInputInsetProgress.value = 1;
|
||||
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
@@ -241,6 +459,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
setEndFollowEnabled(true);
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
@@ -312,6 +531,16 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
composerEditorRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleScrollToEnd = useCallback(() => {
|
||||
void Haptics.selectionAsync();
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, [freeze, scrollMessageToEnd]);
|
||||
|
||||
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
feedTouchStartRef.current = {
|
||||
pageX: event.nativeEvent.pageX,
|
||||
@@ -365,13 +594,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
onEndFollowEnabledChange={setEndFollowEnabled}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
@@ -383,6 +613,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
<KeyboardStickyView
|
||||
// The animated keyboard height can remain stale after a dismissed
|
||||
// IME on both platforms. Visibility is the authoritative closed
|
||||
// state, so disable the translation rather than stranding the pill.
|
||||
enabled={isKeyboardVisible && !keyboardStateSuspect}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
@@ -390,10 +624,60 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
{showScrollToEndButton ? (
|
||||
<Animated.View
|
||||
pointerEvents="box-none"
|
||||
className="absolute -top-11 left-0 right-0 z-20 items-center"
|
||||
entering={FadeInDown.duration(160)}
|
||||
exiting={FadeOut.duration(100)}
|
||||
>
|
||||
{isLiquidGlassSupported ? (
|
||||
<LiquidGlassView
|
||||
colorScheme={isDarkMode ? "dark" : "light"}
|
||||
effect="regular"
|
||||
interactive
|
||||
// Interactive glass can render larger than the requested
|
||||
// box (minimum touch size), so center the pill instead of
|
||||
// relying on it filling the glass exactly.
|
||||
style={{
|
||||
alignItems: "center",
|
||||
borderRadius: 18,
|
||||
height: 36,
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
width: 36,
|
||||
}}
|
||||
>
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 bg-transparent"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
</LiquidGlassView>
|
||||
) : (
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
// The questionnaire replaces the composer, so it must pad
|
||||
// the home indicator the composer normally covers.
|
||||
style={
|
||||
activeUserInputRequestId !== null
|
||||
? { paddingBottom: composerBottomInset }
|
||||
: undefined
|
||||
}
|
||||
entering={FadeInDown.duration(220)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
@@ -407,6 +691,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
{props.activePendingUserInput ? (
|
||||
<PendingUserInputCard
|
||||
pendingUserInput={props.activePendingUserInput}
|
||||
maxHeight={pendingUserInputMaxHeight}
|
||||
collapsed={userInputCollapsed}
|
||||
onToggleCollapsed={handleToggleUserInputCollapsed}
|
||||
onStopThread={props.onStopThread}
|
||||
cardProgress={userInputCardProgress}
|
||||
cardCoverage={userInputCardCoverage}
|
||||
onInputFocusChange={handleOwnedInputFocusChange}
|
||||
drafts={props.activePendingUserInputDrafts}
|
||||
answers={props.activePendingUserInputAnswers}
|
||||
respondingUserInputId={props.respondingUserInputId}
|
||||
@@ -419,35 +710,40 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
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}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
{/* Hidden (not unmounted) while a user-input request owns the
|
||||
composer slot, so composer drafts and editor state survive. */}
|
||||
<View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
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}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
onEditorFocusChange={handleOwnedInputFocusChange}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
|
||||
@@ -48,7 +48,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
@@ -88,6 +90,10 @@ import {
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
resolveThreadFeedLiveFollow,
|
||||
type ThreadFeedLiveFollowEvent,
|
||||
} from "./thread-feed-live-follow";
|
||||
import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadWorkGroupToggle,
|
||||
@@ -98,6 +104,10 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
|
||||
includeOrderedLists: Platform.OS === "android",
|
||||
} as const;
|
||||
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -148,6 +158,7 @@ export interface ThreadFeedProps {
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
@@ -876,6 +887,12 @@ function renderFeedEntry(
|
||||
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
|
||||
const attachments = message.attachments ?? [];
|
||||
const hasReviewCommentContext = message.text.includes("<review_comment");
|
||||
// A bubble that sizes itself from its content cannot lay out a block whose
|
||||
// intrinsic width overflows `maxWidth`: Android positions the bubble's
|
||||
// children during the unclamped pass and never moves them once the width
|
||||
// is clamped, so the paragraphs around the block end up drawn on top of
|
||||
// each other. Pinning the width removes that pass.
|
||||
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
@@ -898,7 +915,11 @@ function renderFeedEntry(
|
||||
style={{
|
||||
backgroundColor: userBubbleColor,
|
||||
maxWidth: props.userBubbleMaxWidth,
|
||||
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
|
||||
...(hasReviewCommentContext
|
||||
? { width: props.reviewCommentBubbleWidth }
|
||||
: hasWideBlock
|
||||
? { width: props.userBubbleMaxWidth }
|
||||
: null),
|
||||
}}
|
||||
>
|
||||
{message.text.trim().length > 0 ? (
|
||||
@@ -1313,6 +1334,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
@@ -1331,13 +1353,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// momentum; only motion inside a session can break follow, so MVCP
|
||||
// compensations and programmatic scrolls never strand a follower.
|
||||
const userScrollSessionRef = useRef(false);
|
||||
const setEndFollow = useCallback((enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
}, []);
|
||||
const setEndFollow = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
props.onEndFollowEnabledChange?.(enabled);
|
||||
},
|
||||
[props.onEndFollowEnabledChange],
|
||||
);
|
||||
const transitionEndFollow = useCallback(
|
||||
(event: ThreadFeedLiveFollowEvent) => {
|
||||
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
|
||||
},
|
||||
[setEndFollow],
|
||||
);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1449,40 +1481,72 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
|
||||
// header height back or the material toggles a full header too late.
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
|
||||
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
|
||||
// before invoking this handler, so getState() is current. Returning to
|
||||
// the end re-arms follow no matter who scrolled (the user, or our own
|
||||
// scroll-to-end); moving away breaks it only during a user-initiated
|
||||
// scroll session, so MVCP compensations and programmatic repositioning
|
||||
// can never strand a follower.
|
||||
// LegendList recomputes its inset-aware end distance before invoking
|
||||
// this handler, so getState() is current. Only the actual end re-arms
|
||||
// follow: its broader maintain-scroll threshold is large enough for a
|
||||
// streaming chunk to pull a user back before their upward drag escapes.
|
||||
// A live user-scroll session still wins even if the first scroll event
|
||||
// remains inside LegendList's at-end tolerance.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
transitionEndFollow({
|
||||
type: "scroll",
|
||||
isAtEnd: listState.isAtEnd,
|
||||
userScrollSessionActive: userScrollSessionRef.current,
|
||||
});
|
||||
}
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
|
||||
);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
userScrollSessionRef.current = true;
|
||||
}, []);
|
||||
// The session must survive past finger-lift so momentum that carries the
|
||||
// user away from the end still breaks follow; a drag released with no
|
||||
// momentum ends its session at the release itself, otherwise at momentum
|
||||
// end. Leaving a session open would let a later animated maintain-scroll
|
||||
// read as user motion and break follow spuriously.
|
||||
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const velocity = event.nativeEvent.velocity?.y ?? 0;
|
||||
if (Math.abs(velocity) < 0.05) {
|
||||
userScrollSessionRef.current = false;
|
||||
const clearUserScrollSettle = useCallback(() => {
|
||||
if (userScrollSettleTimerRef.current !== null) {
|
||||
clearTimeout(userScrollSettleTimerRef.current);
|
||||
userScrollSettleTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = true;
|
||||
// Pause before the first scroll event. Otherwise a stream update can run
|
||||
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
|
||||
transitionEndFollow({ type: "user-scroll-begin" });
|
||||
}, [clearUserScrollSettle, transitionEndFollow]);
|
||||
const finishUserScroll = useCallback(
|
||||
(releaseIsAtEnd?: boolean) => {
|
||||
clearUserScrollSettle();
|
||||
const userScrollSessionActive = userScrollSessionRef.current;
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({
|
||||
type: "user-scroll-end",
|
||||
// With no momentum, preserve the finger-release position. Streaming
|
||||
// growth during the native momentum-detection window must not turn a
|
||||
// release at the live edge into an opt-out from follow.
|
||||
isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
|
||||
userScrollSessionActive,
|
||||
});
|
||||
},
|
||||
[clearUserScrollSettle, props.listRef, transitionEndFollow],
|
||||
);
|
||||
// Finger-lift velocity is not a reliable momentum signal: a gentle fling
|
||||
// can report zero and still decelerate. Give native momentum a short window
|
||||
// to announce itself; if it does, onMomentumScrollBegin cancels this fallback
|
||||
// and the session survives until the settled momentum-end position. This
|
||||
// mirrors the native-event handoff used by the home thread list's scroll gate.
|
||||
const handleScrollEndDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
|
||||
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
|
||||
}, [clearUserScrollSettle, finishUserScroll, props.listRef]);
|
||||
const handleMomentumScrollBegin = useCallback(() => {
|
||||
if (userScrollSessionRef.current) {
|
||||
clearUserScrollSettle();
|
||||
}
|
||||
}, [clearUserScrollSettle]);
|
||||
const handleMomentumScrollEnd = useCallback(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
finishUserScroll();
|
||||
}, [finishUserScroll]);
|
||||
|
||||
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
|
||||
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
@@ -1491,23 +1555,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
// Thread identity is env-scoped: two environments can hold the same
|
||||
// ThreadId, and keying resets (or the list mount) on the bare id would
|
||||
// carry stale scroll/follow state across an environment switch.
|
||||
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
|
||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||
// re-arm follow regardless of where the user had scrolled before.
|
||||
useEffect(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
transitionEndFollow({ type: "reset" });
|
||||
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
transitionEndFollow({ type: "reset" });
|
||||
}
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
@@ -1543,7 +1614,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// initial scroll-to-end computes with a zero end inset and rests one
|
||||
// composer-height short of the end. Layout effect: it must land before the
|
||||
// list's first positioning tick or the one-shot initial scroll misses it.
|
||||
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
useLayoutEffect(() => {
|
||||
const bottom = props.contentInsetEndAdjustment.value;
|
||||
if (bottom > 0) {
|
||||
@@ -1910,6 +1981,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollBegin={handleMomentumScrollBegin}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
@@ -29,6 +30,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadSearch } from "../../state/queries";
|
||||
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
@@ -211,8 +213,13 @@ function ThreadNavigationSidebarPane(
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const autoSettleOnMerge =
|
||||
!AsyncResult.isSuccess(preferencesResult) ||
|
||||
preferencesResult.value.autoSettleOnMerge !== false;
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -410,8 +417,8 @@ function ThreadNavigationSidebarPane(
|
||||
|
||||
// Thread List v2 (beta) support — same model as the compact Home list
|
||||
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
|
||||
// PR states stream in per-row; merged/closed PRs auto-settle their thread
|
||||
// on the next partition.
|
||||
// PR states stream in per-row. The next partition applies the configured
|
||||
// merge rule and the always-on close rule.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
@@ -505,6 +512,15 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order for Move up/down flags — computed from
|
||||
// all shells so search/scope filtering never disables a valid move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
@@ -536,6 +552,7 @@ function ThreadNavigationSidebarPane(
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
@@ -547,6 +564,7 @@ function ThreadNavigationSidebarPane(
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
@@ -950,6 +968,8 @@ function ThreadNavigationSidebarPane(
|
||||
onSelectThread={handleSelectThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onArchiveThread={archiveThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -1067,6 +1087,8 @@ function ThreadNavigationSidebarPane(
|
||||
fullSwipeWidth={props.width - 20}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -1103,6 +1125,7 @@ function ThreadNavigationSidebarPane(
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
regenerateThreadTitle,
|
||||
props.onNewThreadInProject,
|
||||
props.searchQuery,
|
||||
props.selectedThreadKey,
|
||||
@@ -1110,6 +1133,7 @@ function ThreadNavigationSidebarPane(
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { resolvePendingTaskInteractionMode } from "./legacy-plan-mode";
|
||||
|
||||
describe("resolvePendingTaskInteractionMode", () => {
|
||||
it("preserves a queued plan task while the preference is still loading", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: false,
|
||||
planModeEnabled: false,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: "plan",
|
||||
}),
|
||||
).toBe("plan");
|
||||
});
|
||||
|
||||
it("forces build mode once the disabled preference has loaded", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: true,
|
||||
planModeEnabled: false,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: "plan",
|
||||
}),
|
||||
).toBe("default");
|
||||
});
|
||||
|
||||
it("keeps a fresh draft in build mode while the preference is loading", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: false,
|
||||
planModeEnabled: false,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: undefined,
|
||||
}),
|
||||
).toBe("default");
|
||||
});
|
||||
|
||||
it("honors the draft's mode when the plan preference is enabled", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: true,
|
||||
planModeEnabled: true,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: undefined,
|
||||
}),
|
||||
).toBe("plan");
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: true,
|
||||
planModeEnabled: true,
|
||||
draftInteractionMode: undefined,
|
||||
queuedInteractionMode: "plan",
|
||||
}),
|
||||
).toBe("default");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
type ProviderInteractionMode,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export function resolveLegacyPlanModeEnabled(input: {
|
||||
readonly loaded: boolean;
|
||||
readonly preference: boolean | undefined;
|
||||
}): boolean {
|
||||
return input.loaded && input.preference === true;
|
||||
}
|
||||
|
||||
export function resolvePendingTaskInteractionMode(input: {
|
||||
readonly preferenceLoaded: boolean;
|
||||
readonly planModeEnabled: boolean;
|
||||
readonly draftInteractionMode: ProviderInteractionMode | undefined;
|
||||
readonly queuedInteractionMode: ProviderInteractionMode | undefined;
|
||||
}): ProviderInteractionMode {
|
||||
if (input.planModeEnabled) {
|
||||
return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
}
|
||||
if (!input.preferenceLoaded) {
|
||||
// Only an existing queued task may retain its previous mode while the
|
||||
// preference is unknown. A fresh draft still defaults to Build so a stale
|
||||
// persisted Plan selection cannot bypass a disabled preference at launch.
|
||||
return input.queuedInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
}
|
||||
return DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
resolveNewTaskBranchWorktreePath,
|
||||
resolveNewTaskBranchLabel,
|
||||
resolveNewTaskLocalWorkspaceSelection,
|
||||
} from "./new-task-context-presentation";
|
||||
|
||||
describe("resolveNewTaskLocalWorkspaceSelection", () => {
|
||||
it("waits for refs instead of carrying a worktree base into Current checkout", () => {
|
||||
expect(
|
||||
resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: [],
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
awaitsCurrentBranch: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("adopts the checkout's current branch once refs load", () => {
|
||||
expect(
|
||||
resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: [
|
||||
{ name: "feature/worktree-base", current: false, worktreePath: "/worktree" },
|
||||
{ name: "main", current: true, worktreePath: "/repo" },
|
||||
],
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
awaitsCurrentBranch: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries the worktree path when the current branch lives in another worktree", () => {
|
||||
expect(
|
||||
resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: [
|
||||
{ name: "feature/split", current: true, worktreePath: "/repo/.t3/worktrees/split" },
|
||||
{ name: "main", current: false, worktreePath: "/repo" },
|
||||
],
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "feature/split",
|
||||
worktreePath: "/repo/.t3/worktrees/split",
|
||||
awaitsCurrentBranch: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveNewTaskBranchWorktreePath", () => {
|
||||
it("moves Current checkout to the selected existing worktree", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "local",
|
||||
projectCwd: "/repo",
|
||||
branchWorktreePath: "/repo/.t3/worktrees/feature",
|
||||
}),
|
||||
).toBe("/repo/.t3/worktrees/feature");
|
||||
});
|
||||
|
||||
it("keeps the project checkout represented by a null override", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "local",
|
||||
projectCwd: "/repo",
|
||||
branchWorktreePath: "/repo",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("does not reuse an existing worktree while creating a new one", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "worktree",
|
||||
projectCwd: "/repo",
|
||||
branchWorktreePath: "/repo/.t3/worktrees/feature",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveNewTaskBranchLabel", () => {
|
||||
it("shows the checked-out branch without a base-ref prefix", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: "feature/mobile",
|
||||
startFromOrigin: true,
|
||||
workspaceMode: "local",
|
||||
}),
|
||||
).toBe("feature/mobile");
|
||||
});
|
||||
|
||||
it("labels a local worktree base with From", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: "main",
|
||||
startFromOrigin: false,
|
||||
workspaceMode: "worktree",
|
||||
}),
|
||||
).toBe("From main");
|
||||
});
|
||||
|
||||
it("labels a remote worktree base with From origin", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: "main",
|
||||
startFromOrigin: true,
|
||||
workspaceMode: "worktree",
|
||||
}),
|
||||
).toBe("From origin/main");
|
||||
});
|
||||
|
||||
it("prompts when no branch is available", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: null,
|
||||
startFromOrigin: true,
|
||||
workspaceMode: "worktree",
|
||||
}),
|
||||
).toBe("Choose branch");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
export function resolveNewTaskWorkspaceLabel(input: {
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
readonly worktreePath: string | null;
|
||||
}): "Current checkout" | "Current worktree" | "New worktree" {
|
||||
if (input.workspaceMode === "worktree") {
|
||||
return "New worktree";
|
||||
}
|
||||
return input.worktreePath ? "Current worktree" : "Current checkout";
|
||||
}
|
||||
|
||||
export function resolveNewTaskBranchWorktreePath(input: {
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
readonly projectCwd: string;
|
||||
readonly branchWorktreePath: string | null | undefined;
|
||||
}): string | null {
|
||||
if (
|
||||
input.workspaceMode === "worktree" ||
|
||||
!input.branchWorktreePath ||
|
||||
input.branchWorktreePath === input.projectCwd
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return input.branchWorktreePath;
|
||||
}
|
||||
|
||||
export function resolveNewTaskLocalWorkspaceSelection(input: {
|
||||
readonly branches: ReadonlyArray<{
|
||||
readonly name: string;
|
||||
readonly current: boolean;
|
||||
readonly worktreePath?: string | null;
|
||||
}>;
|
||||
readonly projectCwd: string;
|
||||
}): {
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly awaitsCurrentBranch: boolean;
|
||||
} {
|
||||
const currentBranch = input.branches.find((branch) => branch.current) ?? null;
|
||||
if (!currentBranch) {
|
||||
return {
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
awaitsCurrentBranch: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
branch: currentBranch.name,
|
||||
worktreePath: resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "local",
|
||||
projectCwd: input.projectCwd,
|
||||
branchWorktreePath: currentBranch.worktreePath,
|
||||
}),
|
||||
awaitsCurrentBranch: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveNewTaskBranchLabel(input: {
|
||||
readonly branchName: string | null;
|
||||
readonly startFromOrigin: boolean;
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
}): string {
|
||||
if (!input.branchName) {
|
||||
return "Choose branch";
|
||||
}
|
||||
|
||||
if (input.workspaceMode === "local") {
|
||||
return input.branchName;
|
||||
}
|
||||
|
||||
const baseRef = input.startFromOrigin ? `origin/${input.branchName}` : input.branchName;
|
||||
return `From ${baseRef}`;
|
||||
}
|
||||
|
||||
export function shouldCheckoutNewTaskBranch(input: {
|
||||
readonly branchIsCurrent: boolean;
|
||||
readonly branchWorktreePath: string | null | undefined;
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
}): boolean {
|
||||
return input.workspaceMode === "local" && !input.branchIsCurrent && !input.branchWorktreePath;
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import { useEnvironmentQuery } from "../../state/query";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
clearComposerDraft,
|
||||
copyComposerDraftContentIfEmpty,
|
||||
getComposerDraftSnapshot,
|
||||
isComposerDraftEmpty,
|
||||
removeComposerDraftAttachment,
|
||||
@@ -50,7 +51,7 @@ import {
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
|
||||
import {
|
||||
flattenQueuedThreadMessages,
|
||||
threadOutboxManager,
|
||||
@@ -74,10 +75,16 @@ import {
|
||||
type HomeProjectScope,
|
||||
} from "../home/homeThreadList";
|
||||
import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
|
||||
import { resolvePendingTaskInteractionMode } from "./legacy-plan-mode";
|
||||
import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
|
||||
import {
|
||||
resolveNewTaskBranchWorktreePath,
|
||||
resolveNewTaskLocalWorkspaceSelection,
|
||||
} from "./new-task-context-presentation";
|
||||
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
|
||||
const BRANCH_SEARCH_DEBOUNCE_MS = 150;
|
||||
|
||||
function pendingTaskDraftKey(messageId: string): string {
|
||||
return `pending-task:${messageId}`;
|
||||
@@ -96,14 +103,6 @@ function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {
|
||||
return message?.creation !== undefined ? message : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null {
|
||||
if (!branch.worktreePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return branch.worktreePath === project.workspaceRoot ? null : branch.worktreePath;
|
||||
}
|
||||
|
||||
export function branchBadgeLabel(input: {
|
||||
readonly branch: VcsRef;
|
||||
readonly project: EnvironmentProject | null;
|
||||
@@ -117,9 +116,6 @@ export function branchBadgeLabel(input: {
|
||||
if (input.branch.isDefault) {
|
||||
return "default";
|
||||
}
|
||||
if (input.branch.isRemote) {
|
||||
return "remote";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -139,9 +135,13 @@ type NewTaskFlowContextValue = {
|
||||
readonly submitting: boolean;
|
||||
readonly branchQuery: string;
|
||||
readonly branchesLoading: boolean;
|
||||
readonly branchesError: string | null;
|
||||
readonly branchesFetchingNextPage: boolean;
|
||||
readonly hasMoreBranches: boolean;
|
||||
readonly availableBranches: ReadonlyArray<VcsRef>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly planModeEnabled: boolean;
|
||||
readonly expandedProvider: string | null;
|
||||
readonly environments: ReadonlyArray<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -175,7 +175,8 @@ type NewTaskFlowContextValue = {
|
||||
readonly clearAttachments: () => void;
|
||||
readonly setSubmitting: (value: boolean) => void;
|
||||
readonly setBranchQuery: (value: string) => void;
|
||||
readonly loadBranches: () => Promise<void>;
|
||||
readonly loadBranches: () => void;
|
||||
readonly loadMoreBranches: () => void;
|
||||
readonly setRuntimeMode: (value: RuntimeMode) => void;
|
||||
readonly setInteractionMode: (value: ProviderInteractionMode) => void;
|
||||
readonly setSelectedModelOptions: (
|
||||
@@ -191,6 +192,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const threads = useThreadShells();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const groupingSettings = useMobileProjectGroupingSettings();
|
||||
const { enabled: planModeEnabled, loaded: planModePreferenceLoaded } = useLegacyPlanModeState();
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
@@ -219,6 +221,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
|
||||
const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
|
||||
// Mirrors `editingPendingTask` synchronously so the unmount flush cannot act
|
||||
// on a task whose editing session already ended this render.
|
||||
const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
|
||||
@@ -229,6 +232,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setExpandedProvider(null);
|
||||
pendingLocalBranchSyncDraftKeysRef.current.clear();
|
||||
const editing = editingPendingTaskRef.current;
|
||||
editingPendingTaskRef.current = null;
|
||||
setEditingPendingTask(null);
|
||||
@@ -395,7 +399,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
|
||||
true;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
const interactionMode = planModeEnabled
|
||||
? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)
|
||||
: DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
// Stored selections only count while their provider is usable on the
|
||||
// server; otherwise the server's default model wins instead of silently
|
||||
@@ -521,18 +527,24 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
}
|
||||
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
|
||||
}, [selectedProjectDraftKey]);
|
||||
const debouncedBranchQuery = useDebouncedValue(branchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
|
||||
const branchTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: selectedProject?.environmentId ?? null,
|
||||
// `|| null` also skips the stand-in project's empty workspaceRoot.
|
||||
cwd: selectedProject?.workspaceRoot || null,
|
||||
query: null,
|
||||
query: debouncedBranchQuery,
|
||||
}),
|
||||
[selectedProject?.environmentId, selectedProject?.workspaceRoot],
|
||||
[debouncedBranchQuery, selectedProject?.environmentId, selectedProject?.workspaceRoot],
|
||||
);
|
||||
const branchState = useBranches(branchTarget);
|
||||
const branchesLoading = branchState.isPending;
|
||||
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
|
||||
const branchState = usePaginatedBranches(branchTarget);
|
||||
const branchSearchIsDebouncing = branchQuery.trim() !== debouncedBranchQuery.trim();
|
||||
const branchesLoading =
|
||||
branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);
|
||||
const branchesFetchingNextPage = branchState.isFetchingNextPage;
|
||||
const hasMoreBranches =
|
||||
branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
|
||||
const allBranchRefs = branchState.refs;
|
||||
const availableBranches = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
@@ -554,11 +566,21 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
);
|
||||
}, [availableBranches, branchQuery]);
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
}, []);
|
||||
const setProject = useCallback(
|
||||
(project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
const nextDraftKey = `new-task:${nextProjectKey}`;
|
||||
if (
|
||||
selectedProjectDraftKey?.startsWith("new-task:") &&
|
||||
selectedProjectDraftKey !== nextDraftKey
|
||||
) {
|
||||
void copyComposerDraftContentIfEmpty(selectedProjectDraftKey, nextDraftKey);
|
||||
}
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const selectEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => {
|
||||
@@ -596,28 +618,86 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const localSelection = resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: availableBranches,
|
||||
projectCwd: selectedProject.workspaceRoot,
|
||||
});
|
||||
if (mode === "local" && localSelection.awaitsCurrentBranch) {
|
||||
pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
|
||||
} else {
|
||||
pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
branch: mode === "local" ? localSelection.branch : selectedBranchName,
|
||||
worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
[
|
||||
availableBranches,
|
||||
draftStartFromOrigin,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
selectedWorktreePath,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
workspaceMode !== "local" ||
|
||||
!selectedProject ||
|
||||
!selectedProjectDraftKey ||
|
||||
!pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const localSelection = resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: availableBranches,
|
||||
projectCwd: selectedProject.workspaceRoot,
|
||||
});
|
||||
if (localSelection.awaitsCurrentBranch) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: "local",
|
||||
branch: localSelection.branch,
|
||||
worktreePath: localSelection.worktreePath,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
}, [
|
||||
availableBranches,
|
||||
draftStartFromOrigin,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
worktreePath: resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode,
|
||||
projectCwd: selectedProject.workspaceRoot,
|
||||
branchWorktreePath: branch.worktreePath,
|
||||
}),
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
@@ -643,7 +723,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
const loadMoreBranches = branchState.loadNext;
|
||||
const loadBranches = useCallback(() => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
@@ -767,7 +848,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
attachments: draft.attachments,
|
||||
modelSelection: draftModelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: draft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
interactionMode: resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: planModePreferenceLoaded,
|
||||
planModeEnabled,
|
||||
draftInteractionMode: draft.interactionMode,
|
||||
queuedInteractionMode: editingPendingTask?.interactionMode,
|
||||
}),
|
||||
creation: {
|
||||
projectId: selectedProject.id,
|
||||
...(projectTitle !== undefined ? { projectTitle } : {}),
|
||||
@@ -792,6 +878,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
planModeEnabled,
|
||||
planModePreferenceLoaded,
|
||||
startFromOrigin,
|
||||
workspaceMode,
|
||||
],
|
||||
@@ -904,9 +992,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
submitting,
|
||||
branchQuery,
|
||||
branchesLoading,
|
||||
branchesError: branchState.error,
|
||||
branchesFetchingNextPage,
|
||||
hasMoreBranches,
|
||||
availableBranches,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
planModeEnabled,
|
||||
expandedProvider,
|
||||
environments,
|
||||
selectedProject,
|
||||
@@ -935,6 +1027,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSubmitting,
|
||||
setBranchQuery,
|
||||
loadBranches,
|
||||
loadMoreBranches,
|
||||
setRuntimeMode,
|
||||
setInteractionMode,
|
||||
setSelectedModelOptions,
|
||||
@@ -946,6 +1039,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
beginEditingPendingTask,
|
||||
branchQuery,
|
||||
branchesLoading,
|
||||
branchState.error,
|
||||
branchesFetchingNextPage,
|
||||
buildPendingTaskMessage,
|
||||
cancelEditingPendingTask,
|
||||
editingPendingTask,
|
||||
@@ -954,7 +1049,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
filteredBranches,
|
||||
finishEditingPendingTask,
|
||||
interactionMode,
|
||||
planModeEnabled,
|
||||
loadBranches,
|
||||
loadMoreBranches,
|
||||
projectScopes,
|
||||
modelOptions,
|
||||
prompt,
|
||||
@@ -963,6 +1060,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
reset,
|
||||
runtimeMode,
|
||||
selectedBranchName,
|
||||
hasMoreBranches,
|
||||
selectedEnvironmentId,
|
||||
selectedModel,
|
||||
selectedModelKey,
|
||||
|
||||
@@ -5,12 +5,13 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import type { HomeProjectScope } from "../home/homeThreadList";
|
||||
import {
|
||||
getOnlySelectableProject,
|
||||
getProjectScopeSelectionTarget,
|
||||
resolveDraftProjectSelection,
|
||||
} from "./new-task-project-selection";
|
||||
|
||||
function makeProject(id: string): EnvironmentProject {
|
||||
function makeProject(id: string, environmentId = "environment"): EnvironmentProject {
|
||||
return {
|
||||
environmentId: EnvironmentId.make("environment"),
|
||||
environmentId: EnvironmentId.make(environmentId),
|
||||
id: ProjectId.make(id),
|
||||
title: id,
|
||||
workspaceRoot: `/work/${id}`,
|
||||
@@ -41,9 +42,25 @@ describe("getOnlySelectableProject", () => {
|
||||
expect(getOnlySelectableProject([makeScope([project])])).toBe(project);
|
||||
});
|
||||
|
||||
it("does not auto-select a representative when one group has multiple clones", () => {
|
||||
it("selects the representative when one logical project has multiple workspaces", () => {
|
||||
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
|
||||
expect(getOnlySelectableProject([makeScope(projects)])).toBeNull();
|
||||
expect(getOnlySelectableProject([makeScope(projects)])).toBe(projects[0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProjectScopeSelectionTarget", () => {
|
||||
it("keeps the current environment when it hosts the selected logical project", () => {
|
||||
const projects = [makeProject("t3code-mac", "mac"), makeProject("t3code-server", "server")];
|
||||
expect(getProjectScopeSelectionTarget(makeScope(projects), EnvironmentId.make("server"))).toBe(
|
||||
projects[1],
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the representative when the current environment does not host the project", () => {
|
||||
const projects = [makeProject("t3code-mac", "mac"), makeProject("t3code-server", "server")];
|
||||
expect(getProjectScopeSelectionTarget(makeScope(projects), EnvironmentId.make("other"))).toBe(
|
||||
projects[0],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,10 +80,11 @@ describe("resolveDraftProjectSelection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the picker for multiple physical projects in one logical group", () => {
|
||||
it("selects one logical project even when it has multiple physical workspaces", () => {
|
||||
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
|
||||
expect(resolveDraftProjectSelection(null, projects, [makeScope(projects)])).toEqual({
|
||||
kind: "pick",
|
||||
kind: "select",
|
||||
project: projects[0],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import type { HomeProjectScope } from "../home/homeThreadList";
|
||||
|
||||
export type DraftProjectSelectionResolution =
|
||||
type DraftProjectSelectionResolution =
|
||||
| { readonly kind: "preserve" }
|
||||
| { readonly kind: "select"; readonly project: EnvironmentProject }
|
||||
| { readonly kind: "pick" };
|
||||
|
||||
export function getProjectScopeSelectionTarget(
|
||||
scope: HomeProjectScope,
|
||||
preferredEnvironmentId: EnvironmentId | null,
|
||||
): EnvironmentProject {
|
||||
return (
|
||||
scope.projects.find((project) => project.environmentId === preferredEnvironmentId) ??
|
||||
scope.representative
|
||||
);
|
||||
}
|
||||
|
||||
export function getOnlySelectableProject(
|
||||
projectScopes: ReadonlyArray<HomeProjectScope>,
|
||||
): EnvironmentProject | null {
|
||||
const onlyScope = projectScopes.length === 1 ? projectScopes[0] : null;
|
||||
return onlyScope?.projects.length === 1 ? (onlyScope.projects[0] ?? null) : null;
|
||||
return onlyScope?.representative ?? null;
|
||||
}
|
||||
|
||||
export function resolveDraftProjectSelection(
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { derivePendingUserInputMaxHeight } from "./pendingUserInputLayout";
|
||||
|
||||
describe("derivePendingUserInputMaxHeight", () => {
|
||||
it("caps a tall portrait viewport", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 932,
|
||||
keyboardHeight: 0,
|
||||
navigationHeaderHeight: 103,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(560);
|
||||
});
|
||||
|
||||
it("subtracts the keyboard while editing a custom answer", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 932,
|
||||
keyboardHeight: 336,
|
||||
navigationHeaderHeight: 103,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(387);
|
||||
});
|
||||
|
||||
it("keeps the fixed action area usable in a short keyboard-open viewport", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 375,
|
||||
keyboardHeight: 240,
|
||||
navigationHeaderHeight: 44,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(160);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
const PENDING_USER_INPUT_MAX_HEIGHT = 560;
|
||||
const PENDING_USER_INPUT_MIN_HEIGHT = 160;
|
||||
const PENDING_USER_INPUT_VERTICAL_GAP = 12;
|
||||
|
||||
/**
|
||||
* Reserve for a portrait iPhone keyboard with the QuickType bar until a real
|
||||
* height has been observed. Overestimating only costs card height; an
|
||||
* underestimate would let the card overshoot on the first keyboard open.
|
||||
*/
|
||||
export const ESTIMATED_KEYBOARD_HEIGHT = 336;
|
||||
|
||||
/**
|
||||
* One clock for the questionnaire expand/collapse choreography: the card's
|
||||
* enter/exit and the feed-inset glide must share it or they visibly drift.
|
||||
* Sized for the near-full-height slide (the card travels its own height),
|
||||
* in the same class as the iOS keyboard's ~250ms.
|
||||
*/
|
||||
export const USER_INPUT_TOGGLE_DURATION_MS = 220;
|
||||
|
||||
export function derivePendingUserInputMaxHeight(input: {
|
||||
readonly windowHeight: number;
|
||||
readonly keyboardHeight: number;
|
||||
readonly navigationHeaderHeight: number;
|
||||
readonly composerOverlapHeight: number;
|
||||
}): number {
|
||||
const availableHeight =
|
||||
input.windowHeight -
|
||||
Math.max(0, input.keyboardHeight) -
|
||||
Math.max(0, input.navigationHeaderHeight) -
|
||||
Math.max(0, input.composerOverlapHeight) -
|
||||
PENDING_USER_INPUT_VERTICAL_GAP;
|
||||
|
||||
return Math.min(
|
||||
PENDING_USER_INPUT_MAX_HEIGHT,
|
||||
Math.max(PENDING_USER_INPUT_MIN_HEIGHT, availableHeight),
|
||||
);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { View } from "react-native";
|
||||
|
||||
import { T3HeaderButton } from "../../native/T3HeaderButton.android";
|
||||
import type { SidebarHeaderActionsProps } from "./sidebar-header-actions";
|
||||
|
||||
export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
|
||||
return (
|
||||
<View className="h-11 flex-row gap-1">
|
||||
<T3HeaderButton
|
||||
accessibilityLabel="Open settings"
|
||||
icon="gearshape"
|
||||
onPress={props.onOpenSettings}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
|
||||
|
||||
describe("resolveThreadFeedLiveFollow", () => {
|
||||
it("pauses immediately when the user starts scrolling", () => {
|
||||
expect(resolveThreadFeedLiveFollow(true, { type: "user-scroll-begin" })).toBe(false);
|
||||
});
|
||||
|
||||
it("stays paused away from the actual end", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "scroll",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not mistake programmatic layout compensation for a user scroll", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(true, {
|
||||
type: "scroll",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not re-arm at the end while a user scroll session is active", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "scroll",
|
||||
isAtEnd: true,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("re-arms at the actual end only after the user scroll session ends", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: true,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores momentum-end events from programmatic scrolling", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(true, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("re-arms after an explicit reset", () => {
|
||||
expect(resolveThreadFeedLiveFollow(false, { type: "reset" })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
export type ThreadFeedLiveFollowEvent =
|
||||
| { readonly type: "reset" }
|
||||
| { readonly type: "user-scroll-begin" }
|
||||
| {
|
||||
readonly type: "user-scroll-end";
|
||||
readonly isAtEnd: boolean;
|
||||
readonly userScrollSessionActive: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "scroll";
|
||||
readonly isAtEnd: boolean;
|
||||
readonly userScrollSessionActive: boolean;
|
||||
};
|
||||
|
||||
export function resolveThreadFeedLiveFollow(
|
||||
current: boolean,
|
||||
event: ThreadFeedLiveFollowEvent,
|
||||
): boolean {
|
||||
switch (event.type) {
|
||||
case "reset":
|
||||
return true;
|
||||
case "user-scroll-begin":
|
||||
return false;
|
||||
case "user-scroll-end":
|
||||
return event.userScrollSessionActive ? event.isAtEnd : current;
|
||||
case "scroll":
|
||||
if (event.userScrollSessionActive) {
|
||||
return false;
|
||||
}
|
||||
if (event.isAtEnd) {
|
||||
return true;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
|
||||
import type { HomeGroupDisplayAction } from "../home/homeListItems";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import { resolveThreadStatus } from "./threadPresentation";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
|
||||
@@ -134,6 +135,7 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
open={!props.collapsed}
|
||||
size={compact ? 22 : 18}
|
||||
projectTitle={props.project.title}
|
||||
@@ -429,6 +431,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
@@ -450,7 +454,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
|
||||
props;
|
||||
const status = resolveThreadStatus(thread);
|
||||
const pr = useThreadPr(thread, props.projectCwd);
|
||||
const timestamp = relativeTime(
|
||||
@@ -470,6 +475,21 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
THREAD_ROW_MENU_ACTIONS[0]!,
|
||||
...buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
THREAD_ROW_MENU_ACTIONS[1]!,
|
||||
],
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const primaryAction = useMemo(
|
||||
() => ({
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
@@ -482,9 +502,10 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete],
|
||||
[handleArchive, handleDelete, handleRegenerateTitle],
|
||||
);
|
||||
|
||||
const statusPill = effectiveStatus ? (
|
||||
@@ -673,7 +694,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
// ControlPillMenu injects onLongPress into the row and anchors the
|
||||
// token-styled dropdown to it; taps and swipes are untouched.
|
||||
<ControlPillMenu
|
||||
actions={THREAD_ROW_MENU_ACTIONS}
|
||||
actions={menuActions}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
|
||||
@@ -27,6 +27,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import {
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
@@ -65,8 +66,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
// Menus keep lifecycle and title regeneration together. Archive keeps its
|
||||
// own surface (thread screen / settings) rather than crowding v2 rows.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
@@ -230,6 +231,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={pendingTask.message.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
size={15}
|
||||
projectTitle={projectTitle}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
@@ -340,6 +342,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly fullSwipeWidth?: number;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
@@ -354,6 +357,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly snoozeSupported: boolean;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: boolean;
|
||||
/** False on servers that predate thread title regeneration. */
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
/** False on servers that predate thread.pin.reorder. Gates the pinned
|
||||
Move up / Move down menu items. */
|
||||
readonly pinReorderSupported?: boolean;
|
||||
@@ -364,8 +369,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly canMovePinnedDown?: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
merged/closed work (mirrors web's onChangeRequestState). */
|
||||
/** Reports this row's live PR state for the partition's merge and close
|
||||
rules. Mirrors web's onChangeRequestState. */
|
||||
readonly onChangeRequestState?: (
|
||||
threadKey: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
@@ -383,6 +388,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onRegenerateThreadTitle,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
@@ -416,6 +422,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleSnooze = useCallback(
|
||||
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
|
||||
@@ -505,6 +515,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
props.pinningSupported,
|
||||
],
|
||||
);
|
||||
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
@@ -515,13 +533,31 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
() => [
|
||||
CARD_MENU_ACTIONS[0]!,
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
...CARD_MENU_ACTIONS.slice(1),
|
||||
],
|
||||
[pinMenuItem, titleRegenerationMenuItems],
|
||||
);
|
||||
const slimMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const snoozedMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const legacyMenuActions = useMemo<MenuAction[]>(
|
||||
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -533,6 +569,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
|
||||
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: nativeEvent.event,
|
||||
@@ -548,6 +585,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleRegenerateTitle,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
@@ -630,6 +668,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
@@ -818,6 +857,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<View className="opacity-40">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
@@ -887,11 +927,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
snoozedRow
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
? snoozedMenuActions
|
||||
: !props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
? legacyMenuActions
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
? slimMenuActions
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: cardMenuActions
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { selectableChoices } from "./thread-settings-options";
|
||||
|
||||
const effortDescriptor: Extract<ProviderOptionDescriptor, { type: "select" }> = {
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium", isDefault: true },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "ultrathink", label: "Ultrathink" },
|
||||
{ id: "ultracode", label: "Ultracode" },
|
||||
],
|
||||
currentValue: "high",
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
};
|
||||
|
||||
describe("selectableChoices", () => {
|
||||
it("hides prompt-injected and workflow-trigger choices, keeping declared order", () => {
|
||||
expect(selectableChoices(effortDescriptor).map((choice) => choice.id)).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
}> = [
|
||||
{
|
||||
mode: "approval-required",
|
||||
label: "Supervised",
|
||||
description: "Ask before commands and file changes.",
|
||||
},
|
||||
{
|
||||
mode: "auto-accept-edits",
|
||||
label: "Auto-accept edits",
|
||||
description: "Auto-approve edits, ask before other actions.",
|
||||
},
|
||||
{
|
||||
mode: "auto",
|
||||
label: "Auto",
|
||||
description: "Supported providers approve routine actions; others still ask.",
|
||||
},
|
||||
{
|
||||
mode: "full-access",
|
||||
label: "Full access",
|
||||
description: "Allow commands and edits without prompts.",
|
||||
},
|
||||
];
|
||||
|
||||
export function selectableChoices(
|
||||
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
|
||||
) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts";
|
||||
|
||||
import type { ModelOption } from "../../lib/modelOptions";
|
||||
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
import { modelMatchesCatalogQuery, pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
|
||||
function modelOption(
|
||||
model: string,
|
||||
@@ -28,6 +28,26 @@ function modelOption(
|
||||
}
|
||||
|
||||
describe("thread settings sheet state", () => {
|
||||
it("matches visible model and provider terms", () => {
|
||||
const model = modelOption("gpt-next");
|
||||
|
||||
expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "NEXT" })).toBe(true);
|
||||
expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "codex" })).toBe(true);
|
||||
expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "claude" })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("treats whitespace-only catalog searches as empty", () => {
|
||||
expect(
|
||||
modelMatchesCatalogQuery({
|
||||
model: modelOption("gpt-next"),
|
||||
providerLabel: "Codex",
|
||||
query: " ",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("clears staging when the applied model is pressed", () => {
|
||||
expect(
|
||||
pendingModelAfterPress({
|
||||
|
||||
@@ -1,5 +1,24 @@
|
||||
import type { ModelOption } from "../../lib/modelOptions";
|
||||
|
||||
/** Match the terms a user can actually see or recognize in the model picker. */
|
||||
export function modelMatchesCatalogQuery(input: {
|
||||
readonly model: ModelOption;
|
||||
readonly providerLabel: string;
|
||||
readonly query: string;
|
||||
}): boolean {
|
||||
const query = input.query.trim().toLocaleLowerCase();
|
||||
if (query.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return [
|
||||
input.model.label,
|
||||
input.model.subtitle,
|
||||
input.model.selection.model,
|
||||
input.providerLabel,
|
||||
].some((value) => value.toLocaleLowerCase().includes(query));
|
||||
}
|
||||
|
||||
/** Preserve staged provider options when the highlighted model is tapped again. */
|
||||
export function pendingModelAfterPress(input: {
|
||||
readonly current: ModelOption | null;
|
||||
@@ -11,3 +30,18 @@ export function pendingModelAfterPress(input: {
|
||||
}
|
||||
return input.current?.key === input.pressed.key ? input.current : input.pressed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Primary and selected providers start open; all other catalogs start closed.
|
||||
* A user's disclosure tap inverts that default until the picker is dismissed.
|
||||
*/
|
||||
export function providerSectionIsCollapsed(input: {
|
||||
readonly defaultExpanded: boolean;
|
||||
readonly hasExpansionOverride: boolean;
|
||||
readonly isNarrowed: boolean;
|
||||
}): boolean {
|
||||
if (input.isNarrowed) {
|
||||
return false;
|
||||
}
|
||||
return input.defaultExpanded ? input.hasExpansionOverride : !input.hasExpansionOverride;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
|
||||
describe("buildThreadTitleRegenerationMenuItems", () => {
|
||||
it("hides regeneration when the environment does not advertise support", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("offers regeneration for a supported environment", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows and disables the pending state", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerating…",
|
||||
image: "arrow.clockwise",
|
||||
attributes: { disabled: true },
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
|
||||
export function buildThreadTitleRegenerationMenuItems(input: {
|
||||
readonly supported: boolean;
|
||||
readonly isRegenerating: boolean;
|
||||
}): MenuAction[] {
|
||||
if (!input.supported) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -263,6 +263,21 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("keeps a merged thread active when auto-settle on merge is off", () => {
|
||||
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [merged],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
changeRequestStateByKey: new Map([[`${environmentId}:${merged.id}`, "merged"]]),
|
||||
autoSettleOnMerge: false,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["merged"]);
|
||||
expect(layout.settledCount).toBe(0);
|
||||
});
|
||||
|
||||
it("hides snoozed threads and counts them — visibility parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
|
||||
@@ -306,9 +306,8 @@ export function buildThreadListV2ListItems(input: {
|
||||
|
||||
/**
|
||||
* Partitions visible threads into the active card block (creation order) and
|
||||
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
|
||||
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
|
||||
* the default is fixed here rather than user-configurable.
|
||||
* the settled recency tail, matching the web v2 list. Mobile stores these
|
||||
* auto-settle preferences per device.
|
||||
*/
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
@@ -329,6 +328,7 @@ export function buildThreadListV2Items(input: {
|
||||
contract as settlementEnvironmentIds. */
|
||||
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
readonly autoSettleOnMerge?: boolean;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
@@ -349,6 +349,7 @@ export function buildThreadListV2Items(input: {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const autoSettleOnMerge = input.autoSettleOnMerge ?? true;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
@@ -405,7 +406,12 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
effectiveSettled(thread, {
|
||||
now,
|
||||
autoSettleAfterDays,
|
||||
autoSettleOnMerge,
|
||||
changeRequestState,
|
||||
})
|
||||
) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { resolveLegacyPlanModeEnabled } from "./legacy-plan-mode";
|
||||
|
||||
/**
|
||||
* Mobile preferences are device-local, matching the desktop client setting.
|
||||
* Keep the legacy composer mode hidden until the preference has loaded and is
|
||||
* explicitly enabled.
|
||||
*/
|
||||
export function useLegacyPlanModeEnabled(): boolean {
|
||||
return useLegacyPlanModeState().enabled;
|
||||
}
|
||||
|
||||
export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded: boolean } {
|
||||
const preferences = useAtomValue(mobilePreferencesAtom);
|
||||
const loaded = AsyncResult.isSuccess(preferences);
|
||||
return {
|
||||
enabled: resolveLegacyPlanModeEnabled({
|
||||
loaded,
|
||||
preference: loaded ? preferences.value.planModeEnabled : undefined,
|
||||
}),
|
||||
loaded,
|
||||
};
|
||||
}
|
||||
Loaded 100 of 508 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user