Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54d006d522 | ||
|
|
a3823306b7 | ||
|
|
a3e58c648b | ||
|
|
6031e5e53e | ||
|
|
48bb962515 | ||
|
|
ba79f14d2d | ||
|
|
66b6fb4cf0 | ||
|
|
d95c7667e4 |
No files matched your search
@@ -37,4 +37,3 @@ github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
github:SunkenInTime
|
||||
@@ -5,25 +5,6 @@ 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:
|
||||
@@ -44,38 +25,14 @@ 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 ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -95,21 +52,11 @@ 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)
|
||||
@@ -151,74 +98,15 @@ jobs:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- 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'
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && 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 (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
@@ -229,62 +117,3 @@ 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
|
||||
@@ -1,205 +0,0 @@
|
||||
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: 30
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -68,7 +68,6 @@ 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.33",
|
||||
"version": "0.0.32",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -28,6 +28,70 @@ 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");
|
||||
@@ -53,6 +117,31 @@ 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,6 +6,8 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
@@ -36,6 +38,20 @@ 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",
|
||||
{
|
||||
@@ -69,6 +85,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
@@ -86,6 +103,11 @@ 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,
|
||||
{
|
||||
@@ -95,6 +117,9 @@ 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>;
|
||||
@@ -163,6 +188,39 @@ 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,6 +31,7 @@ import {
|
||||
setUpdateChannel,
|
||||
} from "./methods/updates.ts";
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
@@ -80,6 +81,7 @@ 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,5 +1,6 @@
|
||||
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,6 +220,19 @@ 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,6 +98,7 @@ 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, {
|
||||
|
||||
@@ -231,7 +231,6 @@ 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}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
}),
|
||||
),
|
||||
];
|
||||
@@ -379,18 +379,10 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
// 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 noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
|
||||
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
|
||||
loadProfile: true,
|
||||
});
|
||||
const mergedPath = mergePaths("win32", [
|
||||
trimNonEmpty(profile.PATH),
|
||||
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
|
||||
|
||||
@@ -53,6 +53,7 @@ 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"]);
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.3",
|
||||
version: "1.0.2",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
@@ -338,7 +338,6 @@ const config: ExpoConfig = {
|
||||
"./plugins/withAndroidModernPopupMenu.cjs",
|
||||
"./plugins/withAndroidModernAlertDialog.cjs",
|
||||
"./plugins/withAndroidPredictiveBackCompat.cjs",
|
||||
"./plugins/withAndroidTabletOrientation.cjs",
|
||||
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
|
||||
@@ -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": "catalog:",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
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;
|
||||
});
|
||||
};
|
||||
+13
-28
@@ -18,6 +18,7 @@ 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";
|
||||
@@ -47,7 +48,6 @@ 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 {
|
||||
@@ -133,7 +133,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
presentation: "fullScreenModal",
|
||||
};
|
||||
|
||||
const SettingsContentStack = createNativeStackNavigator({
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
@@ -190,37 +190,20 @@ const SettingsContentStack = 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",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -356,9 +339,11 @@ function RootStackLayout(props: {
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
IconBellRinging,
|
||||
IconBolt,
|
||||
IconCamera,
|
||||
IconChartBar,
|
||||
IconCheck,
|
||||
IconChevronDown,
|
||||
IconCode,
|
||||
@@ -98,7 +97,6 @@ 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,
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type ComponentProps,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Platform, Pressable, useColorScheme, View } from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
@@ -22,31 +21,10 @@ 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");
|
||||
@@ -76,7 +54,6 @@ export function ControlPill(props: {
|
||||
: variant === "danger"
|
||||
? "bg-danger"
|
||||
: "bg-subtle",
|
||||
props.className,
|
||||
);
|
||||
const labelClassName = cn(
|
||||
"text-center text-xs font-t3-bold",
|
||||
@@ -91,9 +68,7 @@ export function ControlPill(props: {
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityRole="button"
|
||||
onPress={props.activateOnPressIn ? handlePress : props.onPress}
|
||||
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
|
||||
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
|
||||
onPress={props.onPress}
|
||||
disabled={props.disabled}
|
||||
className={containerClassName}
|
||||
>
|
||||
@@ -158,25 +133,9 @@ 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"}>
|
||||
{children}
|
||||
{menuProps.children}
|
||||
</MenuView>
|
||||
);
|
||||
}
|
||||
@@ -24,18 +24,13 @@ 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,
|
||||
...(props.faviconPath ? { path: props.faviconPath } : {}),
|
||||
},
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
const cacheKey =
|
||||
|
||||
@@ -5,6 +5,7 @@ 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,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
} from "./useArchivedThreadSnapshots";
|
||||
|
||||
export function ArchivedThreadsRouteScreen() {
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
@@ -68,8 +70,9 @@ export function ArchivedThreadsRouteScreen() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
expand();
|
||||
refresh();
|
||||
}, [refresh]),
|
||||
}, [expand, refresh]),
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -368,7 +368,6 @@ 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}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
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 session-state transition
|
||||
// a beat to settle before presenting another formSheet on top.
|
||||
// Sign-in happens inside the Settings sheet; give its detent/session-state
|
||||
// transitions a beat to settle before presenting another formSheet on top.
|
||||
const PRESENT_ONBOARDING_DELAY_MS = 600;
|
||||
|
||||
/**
|
||||
|
||||
@@ -45,7 +45,6 @@ export function HomeRouteScreen() {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -135,10 +134,7 @@ export function HomeRouteScreen() {
|
||||
<NativeStackScreenOptions
|
||||
options={getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: () =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
}),
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
|
||||
})}
|
||||
/>
|
||||
<HomeHeader
|
||||
@@ -152,17 +148,9 @@ export function HomeRouteScreen() {
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -173,10 +161,7 @@ export function HomeRouteScreen() {
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
onAddConnection={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
@@ -187,15 +172,9 @@ export function HomeRouteScreen() {
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
|
||||
@@ -115,7 +115,6 @@ 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;
|
||||
@@ -539,12 +538,6 @@ 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
|
||||
@@ -622,15 +615,6 @@ 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.
|
||||
@@ -827,8 +811,6 @@ 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)}
|
||||
@@ -860,7 +842,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleRegenerateThreadTitle,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
@@ -882,7 +863,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Items,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
@@ -987,8 +967,6 @@ 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}
|
||||
@@ -1010,7 +988,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleRegenerateThreadTitle,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
@@ -1021,7 +998,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -48,15 +48,6 @@ 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> = {
|
||||
@@ -236,18 +227,13 @@ 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) => {
|
||||
@@ -419,47 +405,6 @@ 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
|
||||
@@ -552,7 +497,6 @@ export function useThreadListActions(): {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -429,19 +429,13 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
);
|
||||
|
||||
const handleOpenSettings = useCallback(() => {
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
});
|
||||
navigation.navigate("SettingsSheet", { 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: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
});
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
|
||||
}, [navigation]);
|
||||
|
||||
const handleNewThreadInProject = useCallback(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useLayoutEffect } from "react";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -9,9 +10,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
export function SettingsAuthRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
useEffect(() => {
|
||||
if (!hasCloudPublicConfig()) {
|
||||
navigation.dispatch(StackActions.replace("SettingsContent"));
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
}
|
||||
}, [navigation]);
|
||||
|
||||
@@ -21,20 +22,20 @@ export function SettingsAuthRouteScreen() {
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const navigation = useNavigation();
|
||||
const handleHostBack = useCallback(
|
||||
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
|
||||
[navigation],
|
||||
);
|
||||
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
<>
|
||||
<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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -98,10 +98,7 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
accessibilityLabel: "Add environment",
|
||||
icon: "plus",
|
||||
onPress: () =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
}),
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
@@ -111,10 +108,7 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
}
|
||||
separateBackground
|
||||
tintColor={headerIconColor}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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";
|
||||
@@ -29,6 +30,7 @@ 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";
|
||||
@@ -38,7 +40,6 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import {
|
||||
type AppUpdateCheckState,
|
||||
isAppUpdateCheckAvailable,
|
||||
registerHiddenUpdateTap,
|
||||
runAppUpdateCheck,
|
||||
} from "../updates/app-updates";
|
||||
@@ -146,6 +147,7 @@ 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();
|
||||
@@ -434,8 +436,14 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
const openAccount = useCallback(() => {
|
||||
if (!isLoaded) return;
|
||||
if (!isSignedIn) {
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
return;
|
||||
}
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
}, [isLoaded, navigation]);
|
||||
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -525,7 +533,6 @@ function GeneralSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -569,7 +576,6 @@ 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";
|
||||
|
||||
@@ -597,13 +603,13 @@ function AppSettingsSection() {
|
||||
}, []);
|
||||
|
||||
const handleVersionPress = useCallback(() => {
|
||||
if (!updateCheckAvailable || updateInFlight.current) return;
|
||||
if (!Updates.isEnabled || updateInFlight.current) return;
|
||||
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
|
||||
hiddenUpdateTapCount.current = tap.nextCount;
|
||||
if (tap.shouldCheck) {
|
||||
void checkForUpdate();
|
||||
}
|
||||
}, [checkForUpdate, updateCheckAvailable]);
|
||||
}, [checkForUpdate]);
|
||||
|
||||
const statusLabel =
|
||||
updateState === "checking"
|
||||
@@ -639,7 +645,7 @@ function AppSettingsSection() {
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
{updateCheckAvailable ? (
|
||||
{Updates.isEnabled ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Version ${versionLabel}`}
|
||||
accessibilityRole="text"
|
||||
|
||||
@@ -64,8 +64,7 @@ export function SettingsRow(props: {
|
||||
disabled={props.disabled}
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: target },
|
||||
screen: target,
|
||||
})
|
||||
}
|
||||
>
|
||||
|
||||
@@ -3,7 +3,6 @@ export type SettingsSheetTarget =
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
| "SettingsClientStorage"
|
||||
| "SettingsUsage";
|
||||
| "SettingsClientStorage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -1,12 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Keyboard, View } from "react-native";
|
||||
import {
|
||||
CommonActions,
|
||||
type NavigationState,
|
||||
type PartialState,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
} from "@react-navigation/native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
@@ -31,8 +25,6 @@ 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")) {
|
||||
@@ -174,21 +166,17 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
navigation.dispatch(StackActions.popToTop());
|
||||
return;
|
||||
}
|
||||
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
|
||||
const routes: Array<{
|
||||
name: string;
|
||||
params?: Record<string, unknown>;
|
||||
state?: { index: number; routes: Array<{ name: string }> };
|
||||
}> = [{ name: "Home" }];
|
||||
if (requestedScene === "environments") {
|
||||
routes.push({
|
||||
name: "SettingsSheet",
|
||||
state: {
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "SettingsContent",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -2,11 +2,7 @@ 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,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
@@ -989,29 +985,14 @@ export function NewTaskDraftScreen(props: {
|
||||
// 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).
|
||||
//
|
||||
// Composer positioning mirrors ThreadDetailScreen's floating overlay
|
||||
// (KeyboardStickyView, absolute bottom overlay) rather than
|
||||
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
|
||||
// resolves the composer's on-screen frame via a native
|
||||
// viewPositionInWindow measurement, which this app's Android
|
||||
// edge-to-edge setup (KeyboardProvider's native content-view margin
|
||||
// handling neutralizes windowSoftInputMode="adjustResize" while active)
|
||||
// makes unreliable — the composer stayed under the keyboard instead of
|
||||
// translating above it. KeyboardStickyView sticks directly to the
|
||||
// animated keyboard height instead, sidestepping that measurement.
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
|
||||
|
||||
<View className="flex-1" />
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="flex-1" />
|
||||
|
||||
<KeyboardStickyView
|
||||
enabled={isKeyboardVisible}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View
|
||||
className="px-4 pt-2"
|
||||
style={{
|
||||
@@ -1075,7 +1056,7 @@ export function NewTaskDraftScreen(props: {
|
||||
</ComposerToolbarRow>
|
||||
) : null}
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -296,7 +296,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
<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}
|
||||
@@ -331,7 +330,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
faviconPath={project.faviconPath}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
|
||||
@@ -1,64 +1,18 @@
|
||||
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 type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
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 { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
isPendingUserInputOptionSelected,
|
||||
type PendingUserInput,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { PendingUserInput, 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 | ReadonlyArray<string>> | null;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
@@ -69,242 +23,74 @@ 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) {
|
||||
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}
|
||||
// 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
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
"font-t3-bold text-sm",
|
||||
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",
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
<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"
|
||||
/>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
<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>
|
||||
);
|
||||
})}
|
||||
<Pressable
|
||||
className={cn(
|
||||
"items-center justify-center rounded-2xl px-4 py-3.5",
|
||||
@@ -317,26 +103,6 @@ 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>
|
||||
);
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
serializeComposerFileLink,
|
||||
type ComposerTrigger,
|
||||
} from "@t3tools/shared/composerTrigger";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
@@ -52,7 +51,7 @@ import {
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
@@ -63,13 +62,9 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import {
|
||||
applyProviderOptionSelection,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import { buildThreadSettingsMenu } from "./thread-settings-menu";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
@@ -118,8 +113,6 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -314,16 +307,13 @@ 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";
|
||||
@@ -633,61 +623,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
|
||||
// iOS gets a native menu on the trigger pill: the everyday adjustments
|
||||
// apply without resigning the keyboard, while "All Settings…" (and the
|
||||
// Android trigger) still route through the sheet, which must dismiss it.
|
||||
const settingsMenu = useMemo(
|
||||
() =>
|
||||
Platform.OS === "ios"
|
||||
? buildThreadSettingsMenu({
|
||||
providerGroups: threadProviderGroups,
|
||||
selectedModel: currentModelSelection,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
})
|
||||
: null,
|
||||
[threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = props.onUpdateModelSelection;
|
||||
const onUpdateRuntimeMode = props.onUpdateRuntimeMode;
|
||||
const handleSettingsMenuAction = useCallback(
|
||||
(eventId: string) => {
|
||||
const event = settingsMenu?.events.get(eventId);
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
switch (event.type) {
|
||||
case "select-model":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection(event.option.selection);
|
||||
return;
|
||||
case "set-option": {
|
||||
const options = applyProviderOptionSelection(providerOptionDescriptors, {
|
||||
id: event.optionId,
|
||||
value: event.value,
|
||||
});
|
||||
if (options) {
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection({ ...currentModelSelection, options });
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "set-runtime":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateRuntimeMode(event.mode);
|
||||
return;
|
||||
}
|
||||
},
|
||||
[
|
||||
currentModelSelection,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
providerOptionDescriptors,
|
||||
settingsMenu,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="px-4"
|
||||
@@ -857,31 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
{settingsMenu ? (
|
||||
<ControlPillMenu
|
||||
actions={settingsMenu.actions}
|
||||
onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
) : (
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
)}
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
|
||||
@@ -2,7 +2,6 @@ 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,
|
||||
@@ -14,45 +13,14 @@ import type {
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Haptics from "expo-haptics";
|
||||
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 { 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 { 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";
|
||||
@@ -66,11 +34,6 @@ 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,
|
||||
@@ -91,7 +54,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
@@ -126,7 +89,7 @@ export interface ThreadDetailScreenProps {
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
@@ -208,48 +171,8 @@ 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);
|
||||
@@ -260,17 +183,7 @@ 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 [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 composerBottomInset = 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
|
||||
@@ -291,41 +204,6 @@ 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
|
||||
@@ -342,103 +220,7 @@ 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";
|
||||
@@ -459,7 +241,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
setEndFollowEnabled(true);
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
@@ -531,16 +312,6 @@ 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,
|
||||
@@ -594,14 +365,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
onEndFollowEnabledChange={setEndFollowEnabled}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
@@ -613,10 +383,6 @@ 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 }}
|
||||
>
|
||||
@@ -624,60 +390,10 @@ 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)}
|
||||
>
|
||||
@@ -691,13 +407,6 @@ 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}
|
||||
@@ -710,40 +419,35 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{/* 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>
|
||||
<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}
|
||||
/>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
|
||||
@@ -48,9 +48,7 @@ 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,
|
||||
@@ -90,10 +88,6 @@ import {
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
resolveThreadFeedLiveFollow,
|
||||
type ThreadFeedLiveFollowEvent,
|
||||
} from "./thread-feed-live-follow";
|
||||
import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadWorkGroupToggle,
|
||||
@@ -154,7 +148,6 @@ 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?: {
|
||||
@@ -883,12 +876,6 @@ 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);
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
@@ -911,11 +898,7 @@ function renderFeedEntry(
|
||||
style={{
|
||||
backgroundColor: userBubbleColor,
|
||||
maxWidth: props.userBubbleMaxWidth,
|
||||
...(hasReviewCommentContext
|
||||
? { width: props.reviewCommentBubbleWidth }
|
||||
: hasWideBlock
|
||||
? { width: props.userBubbleMaxWidth }
|
||||
: null),
|
||||
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
|
||||
}}
|
||||
>
|
||||
{message.text.trim().length > 0 ? (
|
||||
@@ -1330,7 +1313,6 @@ 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(() =>
|
||||
@@ -1349,23 +1331,13 @@ 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);
|
||||
props.onEndFollowEnabledChange?.(enabled);
|
||||
},
|
||||
[props.onEndFollowEnabledChange],
|
||||
);
|
||||
const transitionEndFollow = useCallback(
|
||||
(event: ThreadFeedLiveFollowEvent) => {
|
||||
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
|
||||
},
|
||||
[setEndFollow],
|
||||
);
|
||||
const setEndFollow = useCallback((enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
}, []);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1477,72 +1449,40 @@ 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);
|
||||
// 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.
|
||||
// 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.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
transitionEndFollow({
|
||||
type: "scroll",
|
||||
isAtEnd: listState.isAtEnd,
|
||||
userScrollSessionActive: userScrollSessionRef.current,
|
||||
});
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
);
|
||||
const clearUserScrollSettle = useCallback(() => {
|
||||
if (userScrollSettleTimerRef.current !== null) {
|
||||
clearTimeout(userScrollSettleTimerRef.current);
|
||||
userScrollSettleTimerRef.current = null;
|
||||
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 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(() => {
|
||||
finishUserScroll();
|
||||
}, [finishUserScroll]);
|
||||
|
||||
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
@@ -1551,30 +1491,23 @@ 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);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
}, [props.threadId, 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;
|
||||
transitionEndFollow({ type: "reset" });
|
||||
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({ type: "reset" });
|
||||
setEndFollow(true);
|
||||
}
|
||||
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
@@ -1610,7 +1543,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 = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
useLayoutEffect(() => {
|
||||
const bottom = props.contentInsetEndAdjustment.value;
|
||||
if (bottom > 0) {
|
||||
@@ -1977,7 +1910,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollBegin={handleMomentumScrollBegin}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
|
||||
@@ -211,7 +211,6 @@ function ThreadNavigationSidebarPane(
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -506,15 +505,6 @@ 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(() => {
|
||||
@@ -960,8 +950,6 @@ 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)}
|
||||
@@ -1079,8 +1067,6 @@ function ThreadNavigationSidebarPane(
|
||||
fullSwipeWidth={props.width - 20}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -1117,7 +1103,6 @@ function ThreadNavigationSidebarPane(
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
regenerateThreadTitle,
|
||||
props.onNewThreadInProject,
|
||||
props.searchQuery,
|
||||
props.selectedThreadKey,
|
||||
@@ -1125,7 +1110,6 @@ function ThreadNavigationSidebarPane(
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
|
||||
@@ -30,7 +30,6 @@ import { cn } from "../../lib/cn";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";
|
||||
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
@@ -41,6 +40,26 @@ import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet
|
||||
*/
|
||||
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
|
||||
|
||||
/**
|
||||
* 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"]);
|
||||
|
||||
const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
|
||||
* covering model, provider options, runtime mode, and plan mode in one label.
|
||||
@@ -60,6 +79,13 @@ export function threadSettingsSummaryLabel(input: {
|
||||
].join(" · ");
|
||||
}
|
||||
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
function ModelRow(props: {
|
||||
readonly option: ModelOption;
|
||||
readonly selected: boolean;
|
||||
|
||||
@@ -3,7 +3,6 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
ProjectReadFileResult,
|
||||
ProviderInteractionMode,
|
||||
ProviderOptionSelection,
|
||||
RuntimeMode,
|
||||
@@ -14,14 +13,8 @@ import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MessageId,
|
||||
T3_PROJECT_FILE_NAME,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
|
||||
import {
|
||||
isDefaultThreadEnvModeSettled,
|
||||
resolveDefaultThreadEnvMode,
|
||||
} from "@t3tools/shared/threadEnvMode";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
|
||||
@@ -37,8 +30,6 @@ import {
|
||||
} from "../../lib/modelOptions";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { projectEnvironment } from "../../state/projects";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
clearComposerDraft,
|
||||
@@ -354,35 +345,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
// Default mode until the user picks one explicitly — same resolution web
|
||||
// uses for new draft threads: per-project setting, then the repo's
|
||||
// checked-in t3.json, then the server's configured default.
|
||||
const t3ProjectFileQuery = useEnvironmentQuery(
|
||||
selectedProject !== null && selectedProject.workspaceRoot !== ""
|
||||
? projectEnvironment.readFile({
|
||||
environmentId: selectedProject.environmentId,
|
||||
input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
|
||||
const t3ProjectFileDefaultMode = useMemo(() => {
|
||||
if (t3ProjectFileData === null || t3ProjectFileData.truncated) return null;
|
||||
return parseT3ProjectFile(t3ProjectFileData.contents)?.defaultThreadEnvMode ?? null;
|
||||
}, [t3ProjectFileData]);
|
||||
const defaultWorkspaceMode: WorkspaceMode = resolveDefaultThreadEnvMode({
|
||||
projectSetting: selectedProject?.defaultThreadEnvMode,
|
||||
projectFile: t3ProjectFileDefaultMode,
|
||||
globalDefault: selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local",
|
||||
});
|
||||
// While unsettled the resolved default is provisional. Nothing may write
|
||||
// it into the draft during that window (the auto-branch effect does), or
|
||||
// the frozen interim value beats the t3.json default once it loads.
|
||||
const defaultWorkspaceModeSettled = isDefaultThreadEnvModeSettled({
|
||||
explicitMode: selectedProjectDraft.workspaceSelection?.mode,
|
||||
projectSetting: selectedProject?.defaultThreadEnvMode,
|
||||
projectFilePending: t3ProjectFileQuery.isPending,
|
||||
});
|
||||
// The server's configured default decides the mode until the user picks one
|
||||
// explicitly — same resolution web uses for new draft threads.
|
||||
const defaultWorkspaceMode: WorkspaceMode =
|
||||
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
@@ -652,11 +618,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
}, [refreshBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!defaultWorkspaceModeSettled ||
|
||||
workspaceMode !== "worktree" ||
|
||||
selectedBranchName !== null
|
||||
) {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
// The default may only exist as origin/<default> (isRemote), which
|
||||
@@ -668,14 +630,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [
|
||||
allBranchRefs,
|
||||
availableBranches,
|
||||
defaultWorkspaceModeSettled,
|
||||
selectBranch,
|
||||
selectedBranchName,
|
||||
workspaceMode,
|
||||
]);
|
||||
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
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,70 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
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,7 +22,6 @@ 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";
|
||||
|
||||
@@ -135,7 +134,6 @@ 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}
|
||||
@@ -431,8 +429,6 @@ 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<
|
||||
@@ -454,8 +450,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
|
||||
props;
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
|
||||
const status = resolveThreadStatus(thread);
|
||||
const pr = useThreadPr(thread, props.projectCwd);
|
||||
const timestamp = relativeTime(
|
||||
@@ -475,21 +470,6 @@ 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}`,
|
||||
@@ -502,10 +482,9 @@ 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, handleRegenerateTitle],
|
||||
[handleArchive, handleDelete],
|
||||
);
|
||||
|
||||
const statusPill = effectiveStatus ? (
|
||||
@@ -694,7 +673,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={menuActions}
|
||||
actions={THREAD_ROW_MENU_ACTIONS}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
|
||||
@@ -27,7 +27,6 @@ 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,
|
||||
@@ -66,8 +65,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus keep lifecycle and title regeneration together. Archive keeps its
|
||||
// own surface (thread screen / settings) rather than crowding v2 rows.
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
@@ -231,7 +230,6 @@ 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}
|
||||
@@ -342,7 +340,6 @@ 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;
|
||||
@@ -357,8 +354,6 @@ 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;
|
||||
@@ -388,7 +383,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onRegenerateThreadTitle,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
@@ -422,10 +416,6 @@ 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),
|
||||
@@ -515,14 +505,6 @@ 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" },
|
||||
@@ -533,31 +515,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
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],
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -569,7 +533,6 @@ 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,
|
||||
@@ -585,7 +548,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleRegenerateTitle,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
@@ -668,7 +630,6 @@ 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}
|
||||
@@ -857,7 +818,6 @@ 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}
|
||||
@@ -927,11 +887,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
snoozedRow
|
||||
? snoozedMenuActions
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
: !props.settlementSupported
|
||||
? legacyMenuActions
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? slimMenuActions
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: cardMenuActions
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";
|
||||
|
||||
function modelOption(
|
||||
model: string,
|
||||
overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},
|
||||
): ModelOption {
|
||||
const providerKey = overrides.providerKey ?? "codex";
|
||||
return {
|
||||
key: `${providerKey}:${model}`,
|
||||
label: model,
|
||||
subtitle: providerKey,
|
||||
providerKey,
|
||||
providerLabel: providerKey === "codex" ? "Codex" : "Claude",
|
||||
providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",
|
||||
isDefault: overrides.isDefault ?? false,
|
||||
isLegacy: overrides.isLegacy ?? false,
|
||||
capabilities: null,
|
||||
selection: {
|
||||
instanceId: ProviderInstanceId.make(providerKey),
|
||||
model,
|
||||
options: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function group(models: ReadonlyArray<ModelOption>): ProviderGroup {
|
||||
const first = models[0];
|
||||
if (!first) {
|
||||
throw new Error("group requires at least one model");
|
||||
}
|
||||
return {
|
||||
providerKey: first.providerKey,
|
||||
providerLabel: first.providerLabel,
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
const effortDescriptor: ProviderOptionDescriptor = {
|
||||
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"],
|
||||
};
|
||||
|
||||
const fastModeDescriptor: ProviderOptionDescriptor = {
|
||||
id: "fastMode",
|
||||
label: "Fast mode",
|
||||
type: "boolean",
|
||||
currentValue: false,
|
||||
};
|
||||
|
||||
function baseInput() {
|
||||
const models = [
|
||||
modelOption("gpt-current", { isDefault: true }),
|
||||
modelOption("gpt-next"),
|
||||
modelOption("gpt-old", { isLegacy: true }),
|
||||
];
|
||||
return {
|
||||
providerGroups: [group(models)],
|
||||
selectedModel: models[0]?.selection ?? null,
|
||||
optionDescriptors: [effortDescriptor, fastModeDescriptor],
|
||||
runtimeMode: "auto",
|
||||
} as const;
|
||||
}
|
||||
|
||||
function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {
|
||||
return id === undefined ? undefined : menu.events.get(id);
|
||||
}
|
||||
|
||||
describe("buildThreadSettingsMenu", () => {
|
||||
it("orders the top level as model, options, runtime", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.map((action) => action.title)).toEqual([
|
||||
"Model",
|
||||
"Reasoning",
|
||||
"Fast mode",
|
||||
"Runtime",
|
||||
]);
|
||||
});
|
||||
|
||||
it("summarizes the current choice on each submenu row", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");
|
||||
expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");
|
||||
expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");
|
||||
});
|
||||
|
||||
it("checkmarks the selected model and resolves selection events", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const current = modelItems.find((action) => action.title === "gpt-current");
|
||||
expect(current?.state).toBe("on");
|
||||
expect(current?.subtitle).toBe("Default");
|
||||
expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");
|
||||
|
||||
const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);
|
||||
expect(event?.type).toBe("select-model");
|
||||
expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");
|
||||
});
|
||||
|
||||
it("folds unselected legacy models behind a nested submenu", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"Legacy Models",
|
||||
]);
|
||||
expect(
|
||||
modelItems
|
||||
.find((action) => action.title === "Legacy Models")
|
||||
?.subactions?.map((action) => action.title),
|
||||
).toEqual(["gpt-old"]);
|
||||
});
|
||||
|
||||
it("keeps a selected legacy model in the main list", () => {
|
||||
const input = baseInput();
|
||||
const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...input,
|
||||
selectedModel: legacy?.selection ?? null,
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"gpt-old",
|
||||
]);
|
||||
expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");
|
||||
});
|
||||
|
||||
it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],
|
||||
});
|
||||
|
||||
const reasoning = menu.actions.find((action) => action.title === "Reasoning");
|
||||
expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);
|
||||
// The hidden value stays visible as the current summary; it just can't be
|
||||
// picked from the phone.
|
||||
expect(reasoning?.subtitle).toBe("Ultracode");
|
||||
expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves select-option and runtime events with checkmarked current values", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");
|
||||
expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "effort",
|
||||
value: "low",
|
||||
});
|
||||
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");
|
||||
expect(
|
||||
eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),
|
||||
).toEqual({ type: "set-runtime", mode: "full-access" });
|
||||
});
|
||||
|
||||
it("toggles boolean options with the inverted current value", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const fastMode = menu.actions.find((action) => action.title === "Fast mode");
|
||||
expect(fastMode?.state).toBe("off");
|
||||
expect(fastMode?.subactions).toBeUndefined();
|
||||
expect(eventFor(menu, fastMode?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: true,
|
||||
});
|
||||
|
||||
const enabled = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],
|
||||
});
|
||||
const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");
|
||||
expect(enabledRow?.state).toBe("on");
|
||||
expect(eventFor(enabled, enabledRow?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the menu presented only for top-level toggles", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
// Root-level boolean toggles refresh in place with clean chrome, so they
|
||||
// keep the menu presented.
|
||||
expect(
|
||||
menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,
|
||||
).toBe(true);
|
||||
|
||||
// Picks inside nested submenus close the menu: staying presented leaves
|
||||
// the submenu on screen with an expanded-submenu header, and the
|
||||
// bottom-anchored collapse back out drops by the levels' height delta.
|
||||
const expected = undefined;
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(
|
||||
(action) => action.subactions === undefined,
|
||||
);
|
||||
expect(nestedPicks.length).toBeGreaterThan(0);
|
||||
expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("sections models by provider only when multiple groups are offered", () => {
|
||||
const codexModels = [modelOption("gpt-current", { isDefault: true })];
|
||||
const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];
|
||||
const menu = buildThreadSettingsMenu({
|
||||
providerGroups: [group(codexModels), group(claudeModels)],
|
||||
selectedModel: codexModels[0]?.selection ?? null,
|
||||
optionDescriptors: [],
|
||||
runtimeMode: "auto",
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(
|
||||
modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),
|
||||
).toEqual([
|
||||
{ title: "Codex", inline: true },
|
||||
{ title: "Claude", inline: true },
|
||||
]);
|
||||
const claudeSection = modelItems.find((action) => action.title === "Claude");
|
||||
expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);
|
||||
});
|
||||
|
||||
const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {
|
||||
const types = new Set<ThreadSettingsMenuEvent["type"]>();
|
||||
for (const event of menu.events.values()) {
|
||||
types.add(event.type);
|
||||
}
|
||||
return types;
|
||||
};
|
||||
|
||||
it("registers an event for every leaf action id", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
const leafIds: string[] = [];
|
||||
const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {
|
||||
for (const item of items) {
|
||||
if (Array.isArray(item.subactions) && item.subactions.length > 0) {
|
||||
collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);
|
||||
} else if (item.id !== undefined) {
|
||||
leafIds.push(item.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
collect(menu.actions);
|
||||
|
||||
for (const id of leafIds) {
|
||||
expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();
|
||||
}
|
||||
expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));
|
||||
});
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
|
||||
import {
|
||||
getProviderOptionCurrentLabel,
|
||||
getProviderOptionCurrentValue,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
export type ThreadSettingsMenuEvent =
|
||||
| { readonly type: "select-model"; readonly option: ModelOption }
|
||||
| { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }
|
||||
| { readonly type: "set-runtime"; readonly mode: RuntimeMode };
|
||||
|
||||
export type ThreadSettingsMenu = {
|
||||
readonly actions: MenuAction[];
|
||||
/** Menu action id → the change it applies, for the onPressAction dispatch. */
|
||||
readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Native menu replacement for the thread settings sheet (model, select and
|
||||
* boolean provider options, runtime mode). The menu presents from the
|
||||
* composer pill without resigning the keyboard, so adjusting settings never
|
||||
* bounces focus. A thread is bound to one harness, so the menu covers the
|
||||
* sheet's full surface for existing threads; the sheet remains the Android
|
||||
* and new-task-draft surface.
|
||||
*
|
||||
* Selections apply immediately — the sheet's stage-then-Save flow only exists
|
||||
* because the sheet batches a model change with its option edits.
|
||||
*/
|
||||
export function buildThreadSettingsMenu(input: {
|
||||
readonly providerGroups: ReadonlyArray<ProviderGroup>;
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}): ThreadSettingsMenu {
|
||||
const events = new Map<string, ThreadSettingsMenuEvent>();
|
||||
const actions: MenuAction[] = [];
|
||||
|
||||
const isSelected = (option: ModelOption) =>
|
||||
option.selection.instanceId === input.selectedModel?.instanceId &&
|
||||
option.selection.model === input.selectedModel.model;
|
||||
|
||||
// Only top-level leaves (boolean toggles) keep the menu presented (iOS
|
||||
// 16+): the root refreshes in place with clean chrome. Picks inside nested
|
||||
// submenus close the menu — keeping the submenu presented renders an
|
||||
// expanded-submenu header with no way to pop back to the root, and the
|
||||
// bottom-anchored collapse back out travels the levels' height difference.
|
||||
const keepPresented = { keepsMenuPresented: true } as const;
|
||||
|
||||
const modelAction = (option: ModelOption, id: string): MenuAction => {
|
||||
events.set(id, { type: "select-model", option });
|
||||
return {
|
||||
id,
|
||||
title: option.label,
|
||||
...(option.isDefault ? { subtitle: "Default" } : {}),
|
||||
state: isSelected(option) ? "on" : "off",
|
||||
};
|
||||
};
|
||||
|
||||
const modelItems: MenuAction[] = [];
|
||||
const legacyItems: MenuAction[] = [];
|
||||
let selectedModelLabel: string | undefined;
|
||||
input.providerGroups.forEach((group, groupIndex) => {
|
||||
const groupItems: MenuAction[] = [];
|
||||
group.models.forEach((option, modelIndex) => {
|
||||
if (isSelected(option)) {
|
||||
selectedModelLabel = option.label;
|
||||
}
|
||||
const id = `model:${groupIndex}:${modelIndex}`;
|
||||
// A highlighted legacy model stays in the main list (mirroring the
|
||||
// sheet) so the checkmark isn't hidden behind the Legacy fold.
|
||||
if (option.isLegacy && !isSelected(option)) {
|
||||
legacyItems.push(modelAction(option, id));
|
||||
} else {
|
||||
groupItems.push(modelAction(option, id));
|
||||
}
|
||||
});
|
||||
if (groupItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
// A thread is bound to one harness, so provider sections only appear for
|
||||
// multi-group callers (the new-task draft, if it ever adopts the menu).
|
||||
if (input.providerGroups.length > 1) {
|
||||
modelItems.push({
|
||||
id: `model-group:${groupIndex}`,
|
||||
title: group.providerLabel,
|
||||
displayInline: true,
|
||||
subactions: groupItems,
|
||||
});
|
||||
} else {
|
||||
modelItems.push(...groupItems);
|
||||
}
|
||||
});
|
||||
if (legacyItems.length > 0) {
|
||||
modelItems.push({
|
||||
id: "legacy-models",
|
||||
title: "Legacy Models",
|
||||
subactions: legacyItems,
|
||||
});
|
||||
}
|
||||
if (modelItems.length > 0) {
|
||||
actions.push({
|
||||
id: "model",
|
||||
title: "Model",
|
||||
...(selectedModelLabel === undefined
|
||||
? input.selectedModel
|
||||
? { subtitle: input.selectedModel.model }
|
||||
: {}
|
||||
: { subtitle: selectedModelLabel }),
|
||||
subactions: modelItems,
|
||||
});
|
||||
}
|
||||
|
||||
for (const descriptor of input.optionDescriptors) {
|
||||
if (descriptor.type === "boolean") {
|
||||
const id = `option:${descriptor.id}`;
|
||||
events.set(id, {
|
||||
type: "set-option",
|
||||
optionId: descriptor.id,
|
||||
value: !(descriptor.currentValue ?? false),
|
||||
});
|
||||
actions.push({
|
||||
id,
|
||||
title: descriptor.label,
|
||||
state: descriptor.currentValue ? "on" : "off",
|
||||
attributes: keepPresented,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const currentValue = getProviderOptionCurrentValue(descriptor);
|
||||
const choices = selectableChoices(descriptor).map((choice): MenuAction => {
|
||||
const id = `option:${descriptor.id}:${choice.id}`;
|
||||
events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.id === currentValue ? "on" : "off",
|
||||
};
|
||||
});
|
||||
if (choices.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const currentLabel = getProviderOptionCurrentLabel(descriptor);
|
||||
actions.push({
|
||||
id: `option:${descriptor.id}`,
|
||||
title: descriptor.label,
|
||||
...(currentLabel === undefined ? {} : { subtitle: currentLabel }),
|
||||
subactions: choices,
|
||||
});
|
||||
}
|
||||
|
||||
const runtimeLabel = RUNTIME_MODE_CHOICES.find(
|
||||
(choice) => choice.mode === input.runtimeMode,
|
||||
)?.label;
|
||||
actions.push({
|
||||
id: "runtime",
|
||||
title: "Runtime",
|
||||
...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),
|
||||
subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {
|
||||
const id = `runtime:${choice.mode}`;
|
||||
events.set(id, { type: "set-runtime", mode: choice.mode });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.mode === input.runtimeMode ? "on" : "off",
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
return { actions, events };
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
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 } } : {}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -32,19 +32,6 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
|
||||
}
|
||||
|
||||
describe("runAppUpdateCheck", () => {
|
||||
it("does nothing while running from the Metro development server", async () => {
|
||||
vi.stubGlobal("__DEV__", true);
|
||||
const client = makeUpdateClient();
|
||||
|
||||
try {
|
||||
await runAppUpdateCheck({ client });
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
|
||||
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("downloads and restarts when a new update is available", async () => {
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
@@ -113,32 +100,6 @@ describe("runAppUpdateCheck", () => {
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it.each(["ERR_NOT_AVAILABLE_IN_DEV_CLIENT", "ERR_UPDATES_DISABLED"])(
|
||||
"treats Expo's %s failure as an unavailable update check",
|
||||
async (code) => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const error = Object.assign(new Error("Updates are unavailable"), { code });
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => {
|
||||
throw error;
|
||||
}),
|
||||
});
|
||||
const failures: string[] = [];
|
||||
const states: AppUpdateCheckState[] = [];
|
||||
|
||||
await runAppUpdateCheck({
|
||||
client,
|
||||
onFailure: (message) => failures.push(message),
|
||||
onStateChange: (state) => states.push(state),
|
||||
});
|
||||
|
||||
expect(reportError).not.toHaveBeenCalled();
|
||||
expect(failures).toEqual([]);
|
||||
expect(states).toEqual(["checking", "idle"]);
|
||||
reportError.mockRestore();
|
||||
},
|
||||
);
|
||||
|
||||
it("coalesces overlapping launch and manual checks", async () => {
|
||||
let resolveCheck!: (result: {
|
||||
readonly isAvailable: boolean;
|
||||
|
||||
@@ -48,17 +48,8 @@ interface Deferred {
|
||||
}
|
||||
|
||||
const HIDDEN_UPDATE_TAP_COUNT = 5;
|
||||
const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
|
||||
"ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
|
||||
"ERR_UPDATES_DISABLED",
|
||||
]);
|
||||
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
|
||||
|
||||
/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
|
||||
export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
|
||||
return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the manual update affordance discoverable only to someone deliberately
|
||||
* tapping the version row five times.
|
||||
@@ -82,7 +73,7 @@ export function registerHiddenUpdateTap(count: number): {
|
||||
|
||||
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
|
||||
const client = options.client ?? Updates;
|
||||
if (!isAppUpdateCheckAvailable(client)) return;
|
||||
if (!client.isEnabled) return;
|
||||
|
||||
if (appUpdateCheckInFlight) {
|
||||
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
|
||||
@@ -216,27 +207,19 @@ function reportUpdateFailure(
|
||||
fallback: string,
|
||||
onFailure: AppUpdateCheckOptions["onFailure"],
|
||||
): void {
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
if (isAppUpdateUnavailableError(error)) return;
|
||||
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
onFailure?.(error instanceof Error ? error.message : fallback);
|
||||
}
|
||||
|
||||
function isAppUpdateUnavailableError(error: unknown): boolean {
|
||||
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
||||
const code = error.code;
|
||||
return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
|
||||
}
|
||||
|
||||
export function createAppUpdateLaunchCheck(
|
||||
client: AppUpdateClient = Updates,
|
||||
): () => Promise<void> | undefined {
|
||||
let started = false;
|
||||
|
||||
return () => {
|
||||
if (started || !isAppUpdateCheckAvailable(client)) return undefined;
|
||||
if (started || !client.isEnabled) return undefined;
|
||||
started = true;
|
||||
return runAppUpdateCheck({ client });
|
||||
};
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { Chart, Host, type ChartDataPoint } from "@expo/ui/swift-ui";
|
||||
import { frame } from "@expo/ui/swift-ui/modifiers";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import type { DailyTotals } from "@t3tools/shared/usageMerge";
|
||||
|
||||
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
|
||||
import { useProviderColors } from "./usageProviders";
|
||||
|
||||
export interface UsageDailyChartProps {
|
||||
readonly days: readonly string[];
|
||||
readonly daily: readonly DailyTotals[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Native Swift Charts daily bars. Points sharing an x value stack, so emitting
|
||||
* one point per provider per day yields per-provider bands whose stack height
|
||||
* is the day's total; changes animate natively.
|
||||
*
|
||||
* Axes are hidden: 30-90 categorical day labels cannot fit on a phone, so the
|
||||
* screen renders its own edge labels under the chart instead.
|
||||
*/
|
||||
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
|
||||
const colors = useProviderColors();
|
||||
|
||||
const data = useMemo((): ChartDataPoint[] => {
|
||||
return buildChartDays(days, daily, metric).flatMap((day) =>
|
||||
day.values.map((entry) => ({
|
||||
x: day.day,
|
||||
y: entry.value,
|
||||
color: colors[entry.provider],
|
||||
})),
|
||||
);
|
||||
}, [days, daily, metric, colors]);
|
||||
|
||||
return (
|
||||
<Host style={{ height, width: "100%" }}>
|
||||
<Chart
|
||||
type="bar"
|
||||
data={data}
|
||||
animate
|
||||
showGrid={false}
|
||||
barStyle={{ cornerRadius: 2 }}
|
||||
modifiers={[frame({ height })]}
|
||||
/>
|
||||
</Host>
|
||||
);
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import type { DailyTotals } from "@t3tools/shared/usageMerge";
|
||||
|
||||
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
|
||||
import { useProviderColors } from "./usageProviders";
|
||||
|
||||
export interface UsageDailyChartProps {
|
||||
readonly days: readonly string[];
|
||||
readonly daily: readonly DailyTotals[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacked daily bars drawn with plain views. Android and any platform without
|
||||
* Swift Charts land here; iOS resolves `UsageDailyChart.ios.tsx` instead.
|
||||
*/
|
||||
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
|
||||
const colors = useProviderColors();
|
||||
const chartDays = useMemo(() => buildChartDays(days, daily, metric), [days, daily, metric]);
|
||||
const max = chartDays.reduce((peak, day) => Math.max(peak, day.total), 0);
|
||||
|
||||
return (
|
||||
<View style={{ height }} className="flex-row items-end gap-px">
|
||||
{/* column-reverse stacks the bottom-first provider values upward
|
||||
without reversing the array (Hermes lacks Array#toReversed). */}
|
||||
{chartDays.map((day) => (
|
||||
<View key={day.day} className="h-full flex-1 flex-col-reverse overflow-hidden rounded-sm">
|
||||
{day.values.map((entry) => (
|
||||
<View
|
||||
key={entry.provider}
|
||||
style={{
|
||||
height: max === 0 ? 0 : (entry.value / max) * height,
|
||||
backgroundColor: colors[entry.provider],
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import {
|
||||
enumerateDays,
|
||||
enumerateHourStarts,
|
||||
formatCount,
|
||||
formatDayShort,
|
||||
formatHourShort,
|
||||
formatPercent,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
makeWindow,
|
||||
} from "@t3tools/shared/usageFormat";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
|
||||
import { SettingsSection } from "../settings/components/SettingsSection";
|
||||
import { UsageDailyChart } from "./UsageDailyChart";
|
||||
import type { UsageChartMetric } from "./usageChartData";
|
||||
import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
|
||||
|
||||
const WINDOW_OPTIONS = [
|
||||
{ days: 1, label: "Past 24h" },
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
{ days: 90, label: "90 days" },
|
||||
] as const;
|
||||
|
||||
const CHART_HEIGHT = 180;
|
||||
|
||||
export function UsageRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const [windowSelection, setWindowSelection] = useState(() => ({
|
||||
days: 30,
|
||||
window: makeWindow(30),
|
||||
}));
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
const { days: windowDays, window } = windowSelection;
|
||||
const isPast24Hours = windowDays === 1;
|
||||
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
|
||||
|
||||
const days = useMemo(
|
||||
() => enumerateDays(window.sinceDay, window.untilDay),
|
||||
[window.sinceDay, window.untilDay],
|
||||
);
|
||||
const chartDays = useMemo(
|
||||
() =>
|
||||
isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
|
||||
? enumerateHourStarts(window.sinceTime, window.untilTime)
|
||||
: days,
|
||||
[days, isPast24Hours, window.sinceTime, window.untilTime],
|
||||
);
|
||||
const chartTotals = useMemo(
|
||||
(): readonly DailyTotals[] =>
|
||||
isPast24Hours
|
||||
? merged.hourly.map((hour) => ({
|
||||
day: hour.hourStart,
|
||||
costUsd: hour.costUsd,
|
||||
totalTokens: hour.totalTokens,
|
||||
byProvider: hour.byProvider,
|
||||
}))
|
||||
: merged.daily,
|
||||
[isPast24Hours, merged.daily, merged.hourly],
|
||||
);
|
||||
|
||||
// The pull spinner tracks re-scans of environments that have answered
|
||||
// before. The initial scan renders its own placeholder, and an unreachable
|
||||
// environment stays pending forever — neither may pin the spinner on.
|
||||
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
|
||||
const selectWindow = (days: number) => {
|
||||
setWindowSelection({
|
||||
days,
|
||||
window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
|
||||
});
|
||||
};
|
||||
const refreshWindow = () => {
|
||||
const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
|
||||
if (
|
||||
nextWindow.sinceDay === window.sinceDay &&
|
||||
nextWindow.untilDay === window.untilDay &&
|
||||
nextWindow.sinceTime === window.sinceTime &&
|
||||
nextWindow.untilTime === window.untilTime
|
||||
) {
|
||||
refresh();
|
||||
} else {
|
||||
setWindowSelection({ days: windowDays, window: nextWindow });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Usage" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentContainerClassName="gap-6 px-5 pt-4"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
|
||||
>
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
|
||||
selected={windowDays}
|
||||
onSelect={selectWindow}
|
||||
/>
|
||||
|
||||
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
|
||||
|
||||
{isPending ? (
|
||||
<Text className="py-16 text-center text-base text-foreground-muted">
|
||||
Scanning provider transcripts…
|
||||
</Text>
|
||||
) : environments.length === 0 ? (
|
||||
<Text className="py-16 text-center text-base text-foreground-muted">
|
||||
Connect an environment to see usage.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<ChartCard
|
||||
merged={merged}
|
||||
days={chartDays}
|
||||
daily={chartTotals}
|
||||
metric={metric}
|
||||
onMetricChange={setMetric}
|
||||
sinceDay={window.sinceDay}
|
||||
untilDay={window.untilDay}
|
||||
isPast24Hours={isPast24Hours}
|
||||
timeZone={window.timeZone}
|
||||
/>
|
||||
<ProviderSection merged={merged} metric={metric} />
|
||||
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
|
||||
<ModelsSection merged={merged} />
|
||||
</>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SegmentedControl<Value extends number | string>(props: {
|
||||
readonly options: readonly { readonly value: Value; readonly label: string }[];
|
||||
readonly selected: Value;
|
||||
readonly onSelect: (value: Value) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row overflow-hidden rounded-full border-continuous bg-card">
|
||||
{props.options.map((option) => {
|
||||
const active = option.value === props.selected;
|
||||
return (
|
||||
<Pressable
|
||||
key={String(option.value)}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: active }}
|
||||
onPress={() => props.onSelect(option.value)}
|
||||
className={
|
||||
active
|
||||
? "flex-1 items-center rounded-full bg-subtle-strong py-2"
|
||||
: "flex-1 items-center py-2"
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={
|
||||
active ? "text-sm font-t3-medium text-foreground" : "text-sm text-foreground-muted"
|
||||
}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Headline figure, the animated daily chart, and its legend, in one card. */
|
||||
function ChartCard(props: {
|
||||
readonly merged: MergedUsage;
|
||||
readonly days: readonly string[];
|
||||
readonly daily: readonly DailyTotals[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly onMetricChange: (metric: UsageChartMetric) => void;
|
||||
readonly sinceDay: string;
|
||||
readonly untilDay: string;
|
||||
readonly isPast24Hours: boolean;
|
||||
readonly timeZone: string;
|
||||
}) {
|
||||
const { merged, metric } = props;
|
||||
const colors = useProviderColors();
|
||||
const hasActivity = props.daily.some((period) => period.totalTokens > 0);
|
||||
|
||||
return (
|
||||
<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{metric === "cost" ? "Raw token cost" : "Processed tokens"}
|
||||
</Text>
|
||||
<Text className="text-4xl font-t3-bold tabular-nums text-foreground">
|
||||
{metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
|
||||
</Text>
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{metric === "cost"
|
||||
? "* if billed at full API rate"
|
||||
: `Across ${formatCount(merged.sessions)} sessions`}
|
||||
</Text>
|
||||
</View>
|
||||
<MetricToggle metric={metric} onChange={props.onMetricChange} />
|
||||
</View>
|
||||
|
||||
{hasActivity ? (
|
||||
<UsageDailyChart
|
||||
days={props.days}
|
||||
daily={props.daily}
|
||||
metric={metric}
|
||||
height={CHART_HEIGHT}
|
||||
/>
|
||||
) : (
|
||||
<View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
|
||||
<Text className="text-base text-foreground-muted">No activity in this window.</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View className="flex-row items-center justify-between">
|
||||
<Text className="text-xs text-foreground-tertiary">
|
||||
{props.isPast24Hours
|
||||
? formatHourShort(props.days[0] ?? "", props.timeZone)
|
||||
: formatDayShort(props.sinceDay)}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-4">
|
||||
{merged.providers.map((provider) => (
|
||||
<View key={provider.provider} className="flex-row items-center gap-1.5">
|
||||
<View
|
||||
className="size-2 rounded-full"
|
||||
style={{ backgroundColor: colors[provider.provider] }}
|
||||
/>
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{PROVIDER_LABEL[provider.provider]}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
<Text className="text-xs text-foreground-tertiary">
|
||||
{props.isPast24Hours
|
||||
? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
|
||||
: formatDayShort(props.untilDay)}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricToggle(props: {
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly onChange: (metric: UsageChartMetric) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row overflow-hidden rounded-full bg-subtle">
|
||||
{(["cost", "tokens"] as const).map((option) => {
|
||||
const active = option === props.metric;
|
||||
return (
|
||||
<Pressable
|
||||
key={option}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: active }}
|
||||
onPress={() => props.onChange(option)}
|
||||
className={active ? "rounded-full bg-subtle-strong px-3 py-1.5" : "px-3 py-1.5"}
|
||||
>
|
||||
<Text
|
||||
className={
|
||||
active
|
||||
? "text-xs font-t3-medium uppercase text-foreground"
|
||||
: "text-xs uppercase text-foreground-muted"
|
||||
}
|
||||
>
|
||||
{option}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderSection(props: {
|
||||
readonly merged: MergedUsage;
|
||||
readonly metric: UsageChartMetric;
|
||||
}) {
|
||||
const { merged, metric } = props;
|
||||
const colors = useProviderColors();
|
||||
if (merged.providers.length === 0) return null;
|
||||
|
||||
// Ranked by whatever the toggle is showing, so the rows always descend.
|
||||
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
|
||||
const ordered = [...merged.providers].sort((a, b) =>
|
||||
metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="Providers" card>
|
||||
{ordered.map((provider, index) => {
|
||||
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
|
||||
return (
|
||||
<View
|
||||
key={provider.provider}
|
||||
className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
|
||||
>
|
||||
<View className="flex-row items-baseline justify-between gap-3">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View
|
||||
className="size-2.5 rounded-full"
|
||||
style={{ backgroundColor: colors[provider.provider] }}
|
||||
/>
|
||||
<Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
|
||||
</View>
|
||||
<Text className="text-lg tabular-nums text-foreground">
|
||||
{metric === "cost"
|
||||
? formatUsd(provider.costUsd)
|
||||
: formatTokens(provider.totalTokens)}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
|
||||
<View
|
||||
className="h-full rounded-full"
|
||||
style={{ flex: share, backgroundColor: colors[provider.provider] }}
|
||||
/>
|
||||
<View style={{ flex: 1 - share }} />
|
||||
</View>
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{metric === "cost"
|
||||
? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
|
||||
: `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
|
||||
const { merged } = props;
|
||||
const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
|
||||
(period) => period.totalTokens > 0,
|
||||
).length;
|
||||
const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
|
||||
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
|
||||
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
|
||||
|
||||
return (
|
||||
<SettingsSection title="Totals" card>
|
||||
<View className="flex-row flex-wrap">
|
||||
<MetricCell
|
||||
label="Processed tokens"
|
||||
value={formatTokens(merged.totalTokens)}
|
||||
detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Cache savings"
|
||||
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
|
||||
detail={
|
||||
merged.costUsd > 0
|
||||
? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
|
||||
: "vs full input rates"
|
||||
}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Cached input"
|
||||
value={formatTokens(merged.cachedInputTokens)}
|
||||
detail={`${formatPercent(cachedShare)} of observed input`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Uncached input"
|
||||
value={formatTokens(merged.uncachedInputTokens)}
|
||||
detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Output"
|
||||
value={formatTokens(merged.outputTokens)}
|
||||
detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Unpriced"
|
||||
value={formatPercent(merged.costQuality.unpricedShare)}
|
||||
detail="of records, excluded from cost"
|
||||
/>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCell(props: {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly detail: string;
|
||||
}) {
|
||||
return (
|
||||
<View className="w-1/2 gap-0.5 p-4">
|
||||
<Text className="text-sm text-foreground-muted">{props.label}</Text>
|
||||
<Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ModelsSection(props: { readonly merged: MergedUsage }) {
|
||||
const { merged } = props;
|
||||
const colors = useProviderColors();
|
||||
if (merged.models.length === 0) return null;
|
||||
|
||||
return (
|
||||
<SettingsSection title="By model" card>
|
||||
{merged.models.map((model, index) => (
|
||||
<View
|
||||
key={`${model.provider}:${model.model}`}
|
||||
className={
|
||||
index === 0
|
||||
? "flex-row items-center gap-3 p-4"
|
||||
: "flex-row items-center gap-3 border-t border-border-subtle p-4"
|
||||
}
|
||||
>
|
||||
<View
|
||||
className="size-2.5 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: colors[model.provider] }}
|
||||
/>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-base text-foreground" numberOfLines={1}>
|
||||
{model.model}
|
||||
</Text>
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="text-base tabular-nums text-foreground">{formatUsd(model.costUsd)}</Text>
|
||||
</View>
|
||||
))}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Says plainly when the totals are incomplete: an environment still answering,
|
||||
* one that failed, or one whose transcripts another environment already
|
||||
* reported.
|
||||
*/
|
||||
function UsageCoverageNotice(props: {
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
readonly merged: MergedUsage;
|
||||
readonly isPartial: boolean;
|
||||
}) {
|
||||
const failed = props.environments.filter((environment) => environment.error !== null);
|
||||
const stale = props.environments.filter((environment) =>
|
||||
props.merged.staleEnvironments.includes(environment.environmentId),
|
||||
);
|
||||
const duplicateSources = props.merged.duplicateSources;
|
||||
if (
|
||||
failed.length === 0 &&
|
||||
stale.length === 0 &&
|
||||
duplicateSources.length === 0 &&
|
||||
!props.isPartial
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="gap-1 rounded-[16px] border-continuous bg-card px-4 py-3">
|
||||
{props.isPartial ? (
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
Some environments are still reporting. Totals are partial.
|
||||
</Text>
|
||||
) : null}
|
||||
{failed.map((environment) => (
|
||||
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
|
||||
{environment.label} could not report usage.
|
||||
</Text>
|
||||
))}
|
||||
{stale.map((environment) => (
|
||||
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
|
||||
{environment.label} runs an older server version and is excluded from totals.
|
||||
</Text>
|
||||
))}
|
||||
{duplicateSources.length > 0 ? (
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
Counted once across environments sharing a transcript directory:{" "}
|
||||
{duplicateSources.join(", ")}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* Shapes merged daily totals into the per-day provider stacks both chart
|
||||
* implementations (Swift Charts on iOS, plain views elsewhere) render.
|
||||
*
|
||||
* @module usageChartData
|
||||
*/
|
||||
import type { UsageProviderKind } from "@t3tools/contracts";
|
||||
import type { DailyTotals } from "@t3tools/shared/usageMerge";
|
||||
|
||||
import { PROVIDER_ORDER } from "./usageProviders";
|
||||
|
||||
export type UsageChartMetric = "cost" | "tokens";
|
||||
|
||||
export interface UsageChartDay {
|
||||
readonly day: string;
|
||||
/** In {@link PROVIDER_ORDER}, i.e. bottom of the stack first. */
|
||||
readonly values: readonly { readonly provider: UsageProviderKind; readonly value: number }[];
|
||||
readonly total: number;
|
||||
}
|
||||
|
||||
/** One entry per day in the window, zero-filled where nothing happened. */
|
||||
export function buildChartDays(
|
||||
days: readonly string[],
|
||||
daily: readonly DailyTotals[],
|
||||
metric: UsageChartMetric,
|
||||
): readonly UsageChartDay[] {
|
||||
const byDay = new Map(daily.map((totals) => [totals.day, totals]));
|
||||
return days.map((day) => {
|
||||
const totals = byDay.get(day);
|
||||
const values = PROVIDER_ORDER.map((provider) => {
|
||||
const entry = totals?.byProvider.get(provider);
|
||||
const value = entry === undefined ? 0 : metric === "cost" ? entry.costUsd : entry.totalTokens;
|
||||
return { provider, value };
|
||||
});
|
||||
return {
|
||||
day,
|
||||
values,
|
||||
total: values.reduce((sum, entry) => sum + entry.value, 0),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { UsageProviderKind } from "@t3tools/contracts";
|
||||
import { useColorScheme } from "react-native";
|
||||
|
||||
/**
|
||||
* Series and table order. The chart stacks providers from the bottom in this
|
||||
* order, so it also fixes which band sits on top of the bars.
|
||||
*/
|
||||
export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"];
|
||||
|
||||
export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {
|
||||
claude: "Claude Code",
|
||||
codex: "Codex",
|
||||
};
|
||||
|
||||
/**
|
||||
* Claude's brand orange holds in both themes; Codex is neutral and must flip
|
||||
* with the theme or its bars vanish against the matching background.
|
||||
*/
|
||||
export function useProviderColors(): Record<UsageProviderKind, string> {
|
||||
const scheme = useColorScheme();
|
||||
return {
|
||||
claude: "#d97757",
|
||||
codex: scheme === "dark" ? "#e6e6e6" : "#3c3c43",
|
||||
};
|
||||
}
|
||||
@@ -12,107 +12,12 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
isPendingUserInputOptionSelected,
|
||||
setPendingUserInputCustomAnswer,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
|
||||
const singleSelectQuestion = {
|
||||
id: "runtime",
|
||||
header: "Runtime",
|
||||
question: "Which runtime should be used?",
|
||||
options: [
|
||||
{ label: "Go", description: "One binary" },
|
||||
{ label: "Node.js", description: "Reuse TypeScript" },
|
||||
],
|
||||
multiSelect: false,
|
||||
} as const;
|
||||
|
||||
const multiSelectQuestion = {
|
||||
id: "scope",
|
||||
header: "Scope",
|
||||
question: "Which data should be collected?",
|
||||
options: [
|
||||
{ label: "Orders", description: "Receipts" },
|
||||
{ label: "Listings", description: "Inventory" },
|
||||
],
|
||||
multiSelect: true,
|
||||
} as const;
|
||||
|
||||
describe("pending user input answers", () => {
|
||||
it("replaces single-select options and toggles multi-select options", () => {
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(
|
||||
singleSelectQuestion,
|
||||
{ selectedOptionLabels: ["Go"] },
|
||||
"Node.js",
|
||||
),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
|
||||
|
||||
const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
|
||||
const ordersAndListings = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
orders,
|
||||
"Listings",
|
||||
);
|
||||
expect(ordersAndListings).toEqual({
|
||||
customAnswer: "",
|
||||
selectedOptionLabels: ["Orders", "Listings"],
|
||||
});
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
|
||||
|
||||
const paddedOrders = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
undefined,
|
||||
" Orders ",
|
||||
);
|
||||
expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
|
||||
).toEqual({ customAnswer: "" });
|
||||
});
|
||||
|
||||
it("builds array answers for multi-select questions", () => {
|
||||
expect(
|
||||
buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
|
||||
runtime: { selectedOptionLabels: ["Go"] },
|
||||
scope: { selectedOptionLabels: ["Orders", "Listings"] },
|
||||
}),
|
||||
).toEqual({
|
||||
runtime: "Go",
|
||||
scope: ["Orders", "Listings"],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears selected options while a custom answer is active", () => {
|
||||
expect(
|
||||
setPendingUserInputCustomAnswer(
|
||||
{ selectedOptionLabels: ["Orders", "Listings"] },
|
||||
"Orders first",
|
||||
),
|
||||
).toEqual({ customAnswer: "Orders first" });
|
||||
});
|
||||
|
||||
it("matches selected chips against normalized option labels", () => {
|
||||
expect(
|
||||
isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPendingUserInputOptionSelected(
|
||||
{ selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
|
||||
" Orders ",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface PendingUserInput {
|
||||
}
|
||||
|
||||
export interface PendingUserInputDraftAnswer {
|
||||
readonly selectedOptionLabels?: ReadonlyArray<string>;
|
||||
readonly selectedOptionLabel?: string;
|
||||
readonly customAnswer?: string;
|
||||
}
|
||||
|
||||
@@ -227,32 +227,14 @@ function normalizeDraftAnswer(value: string | undefined): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedOptionLabels(
|
||||
value: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Array.from(
|
||||
new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)),
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePendingUserInputAnswer(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
): string | ReadonlyArray<string> | null {
|
||||
): string | null {
|
||||
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
|
||||
if (customAnswer) {
|
||||
return customAnswer;
|
||||
}
|
||||
|
||||
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
if (question.multiSelect) {
|
||||
return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
|
||||
}
|
||||
return selectedOptionLabels[0] ?? null;
|
||||
return normalizeDraftAnswer(draft?.selectedOptionLabel);
|
||||
}
|
||||
|
||||
/** Codex children settle via task.updated (idle/failed/interrupted), never
|
||||
@@ -572,8 +554,6 @@ function toolDetailTextLooksLikeFailure(text: string): boolean {
|
||||
normalized.includes("command not found") ||
|
||||
(normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
|
||||
(normalized.includes("is not recognized") && normalized.includes("the term '")) ||
|
||||
normalized.includes("is not recognized as the name of a cmdlet") ||
|
||||
normalized.includes("a parameter cannot be found that matches parameter name") ||
|
||||
/<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
|
||||
/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
|
||||
/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
|
||||
@@ -1446,62 +1426,22 @@ export function setPendingUserInputCustomAnswer(
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
customAnswer: string,
|
||||
): PendingUserInputDraftAnswer {
|
||||
const selectedOptionLabels =
|
||||
customAnswer.trim().length > 0
|
||||
? undefined
|
||||
: normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
const selectedOptionLabel =
|
||||
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
|
||||
return {
|
||||
customAnswer,
|
||||
...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function isPendingUserInputOptionSelected(
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
optionLabel: string,
|
||||
): boolean {
|
||||
if (normalizeDraftAnswer(draft?.customAnswer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim());
|
||||
}
|
||||
|
||||
export function togglePendingUserInputOptionSelection(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
optionLabel: string,
|
||||
): PendingUserInputDraftAnswer {
|
||||
const normalizedOptionLabel = optionLabel.trim();
|
||||
|
||||
if (question.multiSelect) {
|
||||
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel)
|
||||
? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel)
|
||||
: [...selectedOptionLabels, normalizedOptionLabel];
|
||||
|
||||
return {
|
||||
customAnswer: "",
|
||||
...(nextSelectedOptionLabels.length > 0
|
||||
? { selectedOptionLabels: nextSelectedOptionLabels }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
customAnswer: "",
|
||||
selectedOptionLabels: [normalizedOptionLabel],
|
||||
...(selectedOptionLabel ? { selectedOptionLabel } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPendingUserInputAnswers(
|
||||
questions: ReadonlyArray<UserInputQuestion>,
|
||||
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
|
||||
): Record<string, string | ReadonlyArray<string>> | null {
|
||||
const answers: Record<string, string | ReadonlyArray<string>> = {};
|
||||
): Record<string, string> | null {
|
||||
const answers: Record<string, string> = {};
|
||||
|
||||
for (const question of questions) {
|
||||
const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
|
||||
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
|
||||
if (!answer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { hasWideMarkdownBlock } from "./wideMarkdownBlocks";
|
||||
|
||||
describe("hasWideMarkdownBlock", () => {
|
||||
it("ignores prose, inline code, and emphasis", () => {
|
||||
expect(hasWideMarkdownBlock("just a message")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("I found it in `secteurs_intervention` earlier")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("a | b in a sentence")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("an em dash — and a rule\n\n---\n")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects fenced code blocks", () => {
|
||||
expect(hasWideMarkdownBlock("before\n```\ncode\n```\nafter")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("before\n```ts\ncode\n```")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("before\n~~~\ncode\n~~~")).toBe(true);
|
||||
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
|
||||
});
|
||||
|
||||
it("detects GFM tables", () => {
|
||||
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* Detects markdown that the JS renderer draws as a standalone block View
|
||||
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
|
||||
*
|
||||
* Those blocks report an intrinsic width equal to their widest line, which is
|
||||
* effectively unbounded. A user bubble sizes itself from its content
|
||||
* (`maxWidth` with no `width`), so Android lays the bubble's children out
|
||||
* during the unclamped intrinsic pass — where the surrounding paragraphs
|
||||
* collapse to a single line — and never repositions them once the width is
|
||||
* clamped back to `maxWidth`. The result is siblings drawn on top of each
|
||||
* other inside an over-tall bubble. Pinning the bubble's width removes the
|
||||
* intrinsic pass entirely, which is the same reason review-comment bubbles
|
||||
* already carry an explicit width.
|
||||
*
|
||||
* Indented (four-space) code blocks are deliberately not detected: they are
|
||||
* vanishingly rare in chat input and the check would fire on ordinary nested
|
||||
* list continuations.
|
||||
*/
|
||||
|
||||
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
|
||||
|
||||
function isTableDelimiterRow(line: string): boolean {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.includes("|") || !trimmed.includes("-")) {
|
||||
return false;
|
||||
}
|
||||
return /^[|\-: \t]+$/.test(trimmed);
|
||||
}
|
||||
|
||||
export function hasWideMarkdownBlock(text: string): boolean {
|
||||
if (FENCED_CODE_BLOCK.test(text)) {
|
||||
return true;
|
||||
}
|
||||
if (!text.includes("|")) {
|
||||
return false;
|
||||
}
|
||||
return text.split("\n").some(isTableDelimiterRow);
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
/**
|
||||
* Multi-environment usage state.
|
||||
*
|
||||
* Every connected environment answers the same typed query; the client merges
|
||||
* the results. Raw transcripts never leave the machine that produced them.
|
||||
*
|
||||
* Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
|
||||
* rules themselves live in `@t3tools/shared/usageMerge`.
|
||||
*
|
||||
* @module state/usage
|
||||
*/
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
USAGE_CONTRACT_VERSION,
|
||||
type EnvironmentId,
|
||||
type UsageSummary,
|
||||
type UsageSummaryInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { environmentPresentations } from "./presentation";
|
||||
import { serverEnvironment } from "./server";
|
||||
|
||||
export interface EnvironmentUsageStatus {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly isPending: boolean;
|
||||
readonly error: string | null;
|
||||
readonly summary: UsageSummary | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads every environment's summary for one window.
|
||||
*
|
||||
* Keyed by the serialised window so switching ranges does not thrash the atom
|
||||
* cache, and so each environment's query is shared with any other reader of the
|
||||
* same window.
|
||||
*/
|
||||
const usageByWindowAtom = Atom.family((windowKey: string) =>
|
||||
Atom.make((get): readonly EnvironmentUsageStatus[] => {
|
||||
const input = JSON.parse(windowKey) as UsageSummaryInput;
|
||||
const presentations = get(environmentPresentations.presentationsAtom);
|
||||
|
||||
const statuses: EnvironmentUsageStatus[] = [];
|
||||
for (const [environmentId, presentation] of presentations) {
|
||||
const result = get(serverEnvironment.usageSummary({ environmentId, input }));
|
||||
statuses.push({
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
isPending: result.waiting,
|
||||
error: result._tag === "Failure" ? "This environment could not report usage." : null,
|
||||
summary: Option.getOrNull(AsyncResult.value(result)),
|
||||
});
|
||||
}
|
||||
return statuses;
|
||||
}).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
|
||||
);
|
||||
|
||||
export interface UsageView {
|
||||
readonly merged: MergedUsage;
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
/** True until at least one environment has answered. */
|
||||
readonly isPending: boolean;
|
||||
/**
|
||||
* True while environments that have not failed are still answering. Failed
|
||||
* environments are reported through their own error rows: totals will not
|
||||
* improve by waiting on them, so they must not read as "still reporting".
|
||||
*/
|
||||
readonly isPartial: boolean;
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
const windowKey = useMemo(
|
||||
() =>
|
||||
JSON.stringify({
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
}),
|
||||
[
|
||||
input.sinceDay,
|
||||
input.untilDay,
|
||||
input.timeZone,
|
||||
input.resolution,
|
||||
input.sinceTime,
|
||||
input.untilTime,
|
||||
],
|
||||
);
|
||||
const atom = usageByWindowAtom(windowKey);
|
||||
const environments = useAtomValue(atom);
|
||||
|
||||
// Refreshing only the derived atom would re-read the per-environment SWR
|
||||
// queries within their stale window and change nothing. Refresh each
|
||||
// environment's query so pull-to-refresh always rescans.
|
||||
const refresh = useCallback(() => {
|
||||
const input = JSON.parse(windowKey) as UsageSummaryInput;
|
||||
for (const environment of environments) {
|
||||
appAtomRegistry.refresh(
|
||||
serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
|
||||
);
|
||||
}
|
||||
}, [environments, windowKey]);
|
||||
|
||||
const merged = useMemo(() => {
|
||||
const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
|
||||
environment.summary === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
environmentId: environment.environmentId,
|
||||
label: environment.label,
|
||||
summary: environment.summary,
|
||||
},
|
||||
],
|
||||
);
|
||||
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
|
||||
}, [environments]);
|
||||
|
||||
const answeredCount = environments.filter((environment) => environment.summary !== null).length;
|
||||
const stillReporting = environments.filter(
|
||||
(environment) => environment.summary === null && environment.error === null,
|
||||
).length;
|
||||
|
||||
return {
|
||||
merged,
|
||||
environments,
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -1,11 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
@@ -16,7 +12,6 @@ import {
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -28,21 +23,15 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
|
||||
|
||||
function setUserInputDraftOption(
|
||||
requestKey: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
): void {
|
||||
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[question.id]: togglePendingUserInputOptionSelection(
|
||||
question,
|
||||
current[requestKey]?.[question.id],
|
||||
label,
|
||||
),
|
||||
[questionId]: {
|
||||
selectedOptionLabel: label,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -108,13 +97,13 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftOption(requestKey, question, label);
|
||||
setUserInputDraftOption(requestKey, questionId, label);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
@@ -37,6 +37,7 @@ import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapte
|
||||
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import * as AccountLimitsService from "../src/usage/AccountLimitsService.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import {
|
||||
@@ -318,6 +319,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(AccountLimitsService.layerTest),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.33",
|
||||
"version": "0.0.32",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../src/persistence/Migrations.ts";
|
||||
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
|
||||
import { runMigrateDevDb } from "./migrate-dev-db.ts";
|
||||
|
||||
const withDatabase = <A, E>(
|
||||
databasePath: string,
|
||||
effect: Effect.Effect<A, E, SqlClient.SqlClient>,
|
||||
) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
|
||||
|
||||
/** A migrated source db with one thread per lifecycle state. Only
|
||||
* `stopped-thread` qualifies for the clone. */
|
||||
const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* (
|
||||
baseDir: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const databasePath = path.join(stateDir, "state.sqlite");
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true });
|
||||
yield* withDatabase(
|
||||
databasePath,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* runMigrations();
|
||||
// The real shared db carries this column from a branch build without a
|
||||
// matching migration; reproduce that drift so the filter is exercised.
|
||||
yield* sql`ALTER TABLE projection_threads ADD COLUMN monitor_json TEXT`;
|
||||
|
||||
yield* sql`INSERT INTO projection_projects
|
||||
(project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at)
|
||||
VALUES
|
||||
('project-kept', 'Kept', '/tmp/kept', '[]', '2026-08-01', '2026-08-01', NULL),
|
||||
('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`;
|
||||
|
||||
const threads = [
|
||||
["stopped-thread", "project-kept", "stopped", null, null],
|
||||
["running-thread", "project-kept", "running", null, null],
|
||||
["settled-thread", "project-kept", "stopped", "2026-08-01", null],
|
||||
["monitored-thread", "project-kept", "stopped", null, '{"kind":"pr"}'],
|
||||
["deleted-project-thread", "project-deleted", "stopped", null, null],
|
||||
] as const;
|
||||
for (const [threadId, projectId, status, settledAt, monitorJson] of threads) {
|
||||
yield* sql`INSERT INTO projection_threads
|
||||
(thread_id, project_id, title, created_at, updated_at, settled_at, monitor_json)
|
||||
VALUES (${threadId}, ${projectId}, ${threadId}, '2026-08-01', '2026-08-01', ${settledAt}, ${monitorJson})`;
|
||||
yield* sql`INSERT INTO projection_thread_sessions (thread_id, status, updated_at)
|
||||
VALUES (${threadId}, ${status}, '2026-08-01')`;
|
||||
yield* sql`INSERT INTO orchestration_events
|
||||
(event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json)
|
||||
VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`;
|
||||
}
|
||||
yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
|
||||
VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
|
||||
}),
|
||||
);
|
||||
return databasePath;
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
|
||||
it.effect("keeps only stopped threads from live projects and clears auth state", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
|
||||
const result = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
);
|
||||
|
||||
assert.equal(result.databasePath, path.join(destDir, "userdata", "state.sqlite"));
|
||||
const kept = yield* withDatabase(
|
||||
result.databasePath,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const threads = yield* sql<{ thread_id: string }>`
|
||||
SELECT thread_id FROM projection_threads ORDER BY thread_id`;
|
||||
const events = yield* sql<{ stream_id: string }>`
|
||||
SELECT stream_id FROM orchestration_events`;
|
||||
const [auth] = yield* sql<{ count: number }>`
|
||||
SELECT COUNT(*) AS count FROM auth_sessions`;
|
||||
return { threads, events, authCount: auth?.count ?? 0 };
|
||||
}),
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
kept.threads.map((row) => row.thread_id),
|
||||
["stopped-thread"],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
kept.events.map((row) => row.stream_id),
|
||||
["stopped-thread"],
|
||||
);
|
||||
assert.equal(kept.authCount, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails loudly on a migration slot collision", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-dest-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
// Simulate another branch having claimed slot 1 first: the id is
|
||||
// recorded, so this checkout's migration 1 silently never runs.
|
||||
yield* withDatabase(
|
||||
source,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`UPDATE effect_sql_migrations
|
||||
SET name = 'SomebodyElsesMigration' WHERE migration_id = 1`;
|
||||
}),
|
||||
);
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbSlotCollisionError");
|
||||
if (error._tag === "MigrateDevDbSlotCollisionError") {
|
||||
assert.equal(error.slot, 1);
|
||||
assert.equal(error.appliedName, "SomebodyElsesMigration");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses while a dev server holds the destination", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
// This test process stands in for a live dev server.
|
||||
const stateDir = path.join(destDir, "userdata");
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(stateDir, "server-runtime.json"),
|
||||
`{"version":1,"pid":${process.pid}}`,
|
||||
);
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbServerRunningError");
|
||||
if (error._tag === "MigrateDevDbServerRunningError") {
|
||||
assert.equal(error.pid, process.pid);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses a source that resolves to a destination path", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
|
||||
// A leftover snapshot from a prior failed run, passed as --source: it
|
||||
// must not be deleted before it is read.
|
||||
const leftoverSnapshot = path.join(destDir, "userdata", "state.sqlite.migrate-dev-db-tmp");
|
||||
yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
|
||||
yield* fs.writeFileString(leftoverSnapshot, "not a real db");
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sharedDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
|
||||
assert.equal(yield* fs.exists(leftoverSnapshot), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to rebuild the shared home", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbSharedHomeError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,560 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Rebuild an isolated dev database from a pruned snapshot of the real
|
||||
* ~/.t3 database, then run this checkout's migrations against it.
|
||||
*
|
||||
* `vp run migrate-dev-db` from a worktree:
|
||||
* 1. Nukes `<worktree>/.t3/userdata/state.sqlite`.
|
||||
* 2. Snapshots the real db (read-only VACUUM INTO) and prunes it to the
|
||||
* most recently updated projects and, per project, the most recent
|
||||
* threads that have fully stopped. Working, settled, and monitored
|
||||
* threads are skipped so the dev server never adopts live work.
|
||||
* Auth sessions, pairing links, command receipts, and provider
|
||||
* runtime rows are dropped — pair a fresh browser against dev.
|
||||
* 3. Runs migrations on the result. Because the clone carries the real
|
||||
* `effect_sql_migrations` table, this proves a new migration applies
|
||||
* on top of the real applied set, and the slot check below catches
|
||||
* the silent failure where two branches claim the same
|
||||
* `Migrations/NNN_` id (the second one's CREATE TABLE is skipped).
|
||||
*
|
||||
* The event log (`orchestration_events`) is pruned per stream while
|
||||
* `sqlite_sequence` and `projection_state` carry over untouched, so new
|
||||
* events keep appending after the old high-water mark and projection
|
||||
* cursors never rewind.
|
||||
*/
|
||||
|
||||
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeOS from "node:os";
|
||||
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
|
||||
import { migrationManifest, runMigrations } from "../src/persistence/Migrations.ts";
|
||||
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
|
||||
|
||||
export class MigrateDevDbNotInWorktreeError extends Schema.TaggedErrorClass<MigrateDevDbNotInWorktreeError>()(
|
||||
"MigrateDevDbNotInWorktreeError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Not inside a linked git worktree. Pass --base-dir to target an isolated .t3 directory.";
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbSharedHomeError extends Schema.TaggedErrorClass<MigrateDevDbSharedHomeError>()(
|
||||
"MigrateDevDbSharedHomeError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Refusing to rebuild the shared ~/.t3 database. Use an isolated --base-dir.";
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbSourceMissingError extends Schema.TaggedErrorClass<MigrateDevDbSourceMissingError>()(
|
||||
"MigrateDevDbSourceMissingError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Source database does not exist at '${this.sourcePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbSourceIsDestinationError extends Schema.TaggedErrorClass<MigrateDevDbSourceIsDestinationError>()(
|
||||
"MigrateDevDbSourceIsDestinationError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Source database '${this.sourcePath}' resolves to a path this command rewrites. Pick a different --source or --base-dir.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbServerRunningError extends Schema.TaggedErrorClass<MigrateDevDbServerRunningError>()(
|
||||
"MigrateDevDbServerRunningError",
|
||||
{
|
||||
databasePath: Schema.String,
|
||||
pid: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Dev database at '${this.databasePath}' is open by a running server (pid ${this.pid} per server-runtime.json). Stop that server first; if that pid is not actually a T3 server (stale descriptor, reused pid), delete the server-runtime.json next to the database and retry.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbDestinationBusyError extends Schema.TaggedErrorClass<MigrateDevDbDestinationBusyError>()(
|
||||
"MigrateDevDbDestinationBusyError",
|
||||
{
|
||||
databasePath: Schema.String,
|
||||
reason: Schema.Literals(["write-locked", "wal-held"]),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const detail =
|
||||
this.reason === "write-locked"
|
||||
? "the database is write-locked"
|
||||
: "another connection is holding its WAL";
|
||||
return `Dev database at '${this.databasePath}' looks in use (${detail}). Stop the dev server first; if none is running, delete the -wal/-shm files next to it.`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Two branches claimed the same Migrations/NNN_ slot: the id was already
|
||||
* recorded under a different name, so this checkout's migration was
|
||||
* silently skipped and its schema changes never applied.
|
||||
*/
|
||||
export class MigrateDevDbSlotCollisionError extends Schema.TaggedErrorClass<MigrateDevDbSlotCollisionError>()(
|
||||
"MigrateDevDbSlotCollisionError",
|
||||
{
|
||||
slot: Schema.Number,
|
||||
codeName: Schema.String,
|
||||
appliedName: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Migration slot collision at ${this.slot}: this checkout registers '${this.codeName}' but the database already applied '${this.appliedName}' in that slot. Renumber the new migration to a free slot.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbPhaseError extends Schema.TaggedErrorClass<MigrateDevDbPhaseError>()(
|
||||
"MigrateDevDbPhaseError",
|
||||
{
|
||||
phase: Schema.Literals(["snapshot", "prune", "compact", "migrate", "verify"]),
|
||||
databasePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `migrate-dev-db failed during ${this.phase} on '${this.databasePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RunMigrateDevDbInput {
|
||||
/** Isolated .t3 directory. Defaults to `<worktree>/.t3` of the cwd. */
|
||||
readonly baseDir?: string | undefined;
|
||||
/** Source database. Defaults to `~/.t3/userdata/state.sqlite`. */
|
||||
readonly source?: string | undefined;
|
||||
readonly projects: number;
|
||||
readonly threadsPerProject: number;
|
||||
}
|
||||
|
||||
export interface RunMigrateDevDbOptions {
|
||||
/** Overridable for tests; the directory writes must never target. */
|
||||
readonly sharedHome?: string | undefined;
|
||||
}
|
||||
|
||||
interface KeptProject {
|
||||
readonly title: string;
|
||||
readonly threads: number;
|
||||
}
|
||||
|
||||
const removeDatabaseFiles = Effect.fn("removeDatabaseFiles")(function* (databasePath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const suffix of ["", "-wal", "-shm"]) {
|
||||
yield* fs.remove(`${databasePath}${suffix}`).pipe(Effect.orElseSucceed(() => undefined));
|
||||
}
|
||||
});
|
||||
|
||||
/** The slice of server-runtime.json this script cares about. */
|
||||
const ServerRuntimeState = Schema.fromJsonString(Schema.Struct({ pid: Schema.Number }));
|
||||
const decodeServerRuntimeState = Schema.decodeEffect(ServerRuntimeState);
|
||||
|
||||
const isProcessAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
// EPERM means the process exists but belongs to someone else.
|
||||
return (error as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
};
|
||||
|
||||
/** Liveness probe for a running dev server. The server writes its pid to
|
||||
* server-runtime.json next to the database, which also catches an idle
|
||||
* server holding an open-but-inactive connection. The SQL probes below back
|
||||
* that up: BEGIN IMMEDIATE fails while a writer is active, and
|
||||
* wal_checkpoint(TRUNCATE) reports busy while another connection holds the
|
||||
* WAL. A leftover -shm alone is not a signal — read-only connections cannot
|
||||
* clean it up on close. */
|
||||
const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const runtimeStatePath = path.join(path.dirname(databasePath), "server-runtime.json");
|
||||
const runtimeState = yield* fs.readFileString(runtimeStatePath).pipe(
|
||||
Effect.flatMap(decodeServerRuntimeState),
|
||||
// A missing or malformed descriptor is not a liveness signal.
|
||||
Effect.option,
|
||||
);
|
||||
if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
|
||||
return yield* new MigrateDevDbServerRunningError({
|
||||
databasePath,
|
||||
pid: runtimeState.value.pid,
|
||||
});
|
||||
}
|
||||
|
||||
if (!(yield* fs.exists(databasePath))) {
|
||||
return;
|
||||
}
|
||||
const checkpoint = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql.unsafe("PRAGMA busy_timeout = 0").unprepared;
|
||||
yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;
|
||||
yield* sql.unsafe("ROLLBACK").unprepared;
|
||||
return yield* sql.unsafe<{ busy: number }>("PRAGMA wal_checkpoint(TRUNCATE)").unprepared;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new MigrateDevDbDestinationBusyError({
|
||||
databasePath,
|
||||
reason: "write-locked",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (checkpoint[0] !== undefined && Number(checkpoint[0].busy) !== 0) {
|
||||
return yield* new MigrateDevDbDestinationBusyError({
|
||||
databasePath,
|
||||
reason: "wal-held",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// The shared db can carry monitor_json from a branch build even though no
|
||||
// migration in this checkout creates it, so filter it only when present.
|
||||
const threadColumns = yield* sql<{ name: string }>`
|
||||
SELECT name FROM pragma_table_info('projection_threads')`;
|
||||
const monitorFilter = threadColumns.some((column) => column.name === "monitor_json")
|
||||
? "AND t.monitor_json IS NULL"
|
||||
: "";
|
||||
|
||||
// "Stopped" is the persisted subset of the UI's thread status: the session
|
||||
// reached status 'stopped' and nothing marks the thread settled or
|
||||
// monitored. The in-memory working/monitoring liveness never persists, so
|
||||
// filtering the session status is sufficient.
|
||||
yield* sql.unsafe(`CREATE TEMP TABLE stopped_threads AS
|
||||
SELECT t.thread_id, t.project_id, t.updated_at
|
||||
FROM projection_threads t
|
||||
JOIN projection_thread_sessions s ON s.thread_id = t.thread_id
|
||||
WHERE t.deleted_at IS NULL
|
||||
AND t.archived_at IS NULL
|
||||
AND t.settled_at IS NULL
|
||||
AND (t.settled_override IS NULL OR t.settled_override <> 'settled')
|
||||
${monitorFilter}
|
||||
AND s.status = 'stopped'`).unprepared;
|
||||
|
||||
// Projects with clonable threads outrank empty-but-recent ones: the point
|
||||
// of the exercise is thread data, not the project list.
|
||||
yield* sql`CREATE TEMP TABLE kept_projects AS
|
||||
SELECT p.project_id
|
||||
FROM projection_projects p
|
||||
LEFT JOIN (
|
||||
SELECT project_id, MAX(updated_at) AS last_stopped_at
|
||||
FROM stopped_threads
|
||||
GROUP BY project_id
|
||||
) q ON q.project_id = p.project_id
|
||||
WHERE p.deleted_at IS NULL
|
||||
ORDER BY (q.last_stopped_at IS NULL) ASC,
|
||||
COALESCE(q.last_stopped_at, p.updated_at) DESC
|
||||
LIMIT ${input.projects}`;
|
||||
|
||||
yield* sql`CREATE TEMP TABLE kept_threads AS
|
||||
SELECT thread_id FROM (
|
||||
SELECT
|
||||
st.thread_id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY st.project_id
|
||||
ORDER BY st.updated_at DESC
|
||||
) AS recency_rank
|
||||
FROM stopped_threads st
|
||||
JOIN kept_projects kp ON kp.project_id = st.project_id
|
||||
)
|
||||
WHERE recency_rank <= ${input.threadsPerProject}`;
|
||||
|
||||
yield* sql.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
yield* sql`DELETE FROM projection_projects
|
||||
WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
|
||||
yield* sql`DELETE FROM projection_threads
|
||||
WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
|
||||
for (const table of [
|
||||
"projection_thread_messages",
|
||||
"projection_thread_activities",
|
||||
"projection_thread_sessions",
|
||||
"projection_turns",
|
||||
"projection_pending_approvals",
|
||||
"projection_thread_proposed_plans",
|
||||
"checkpoint_diff_blobs",
|
||||
]) {
|
||||
yield* sql.unsafe(
|
||||
`DELETE FROM ${table} WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
|
||||
).unprepared;
|
||||
}
|
||||
yield* sql`DELETE FROM orchestration_events
|
||||
WHERE (aggregate_kind = 'thread'
|
||||
AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
|
||||
OR (aggregate_kind = 'project'
|
||||
AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
|
||||
yield* sql`DELETE FROM orchestration_command_receipts`;
|
||||
yield* sql`DELETE FROM provider_session_runtime`;
|
||||
yield* sql`DELETE FROM auth_sessions`;
|
||||
yield* sql`DELETE FROM auth_pairing_links`;
|
||||
}),
|
||||
);
|
||||
|
||||
const keptProjects = yield* sql<{ title: string; threads: number }>`
|
||||
SELECT
|
||||
p.title,
|
||||
(SELECT COUNT(*) FROM projection_threads t WHERE t.project_id = p.project_id) AS threads
|
||||
FROM projection_projects p
|
||||
ORDER BY p.updated_at DESC`;
|
||||
const [events] = yield* sql<{ count: number }>`
|
||||
SELECT COUNT(*) AS count FROM orchestration_events`;
|
||||
|
||||
return {
|
||||
projects: keptProjects as ReadonlyArray<KeptProject>,
|
||||
eventCount: events?.count ?? 0,
|
||||
};
|
||||
});
|
||||
|
||||
/** Compare this checkout's migration registry against what the cloned
|
||||
* database recorded: same slot under a different name means the migration
|
||||
* was skipped, not applied. */
|
||||
const verifyMigrationSlots = Effect.fn("verifyMigrationSlots")(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const applied = yield* sql<{ migration_id: number; name: string }>`
|
||||
SELECT migration_id, name FROM effect_sql_migrations`;
|
||||
const appliedById = new Map(applied.map((row) => [Number(row.migration_id), row.name]));
|
||||
for (const [slot, codeName] of migrationManifest) {
|
||||
const appliedName = appliedById.get(slot);
|
||||
if (appliedName !== undefined && appliedName !== codeName) {
|
||||
return yield* new MigrateDevDbSlotCollisionError({ slot, codeName, appliedName });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
|
||||
input: RunMigrateDevDbInput,
|
||||
options: RunMigrateDevDbOptions = {},
|
||||
) {
|
||||
// SQLite treats a negative LIMIT as "no limit", which would clone
|
||||
// everything. The CLI flags validate this too; this covers direct callers.
|
||||
if (input.projects < 1 || input.threadsPerProject < 0) {
|
||||
return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
|
||||
}
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
|
||||
const sourcePath = path.resolve(
|
||||
input.source ?? path.join(sharedHome, "userdata", "state.sqlite"),
|
||||
);
|
||||
|
||||
const baseDir =
|
||||
input.baseDir !== undefined
|
||||
? path.resolve(input.baseDir)
|
||||
: yield* resolveWorktreeT3Home(process.cwd());
|
||||
if (baseDir === undefined) {
|
||||
return yield* new MigrateDevDbNotInWorktreeError();
|
||||
}
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const databasePath = path.join(stateDir, "state.sqlite");
|
||||
const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new MigrateDevDbSourceMissingError({ sourcePath });
|
||||
}
|
||||
const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
|
||||
fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
|
||||
fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
|
||||
]);
|
||||
if (canonicalBaseDir === canonicalSharedHome) {
|
||||
return yield* new MigrateDevDbSharedHomeError();
|
||||
}
|
||||
// The destination db and snapshot both get deleted below; a --source that
|
||||
// resolves to either (e.g. a leftover snapshot file) would be destroyed
|
||||
// before it is ever read.
|
||||
const canonicalSourcePath = yield* fs
|
||||
.realPath(sourcePath)
|
||||
.pipe(Effect.orElseSucceed(() => sourcePath));
|
||||
for (const destination of [databasePath, snapshotPath]) {
|
||||
const canonicalDestination = yield* fs
|
||||
.realPath(destination)
|
||||
.pipe(Effect.orElseSucceed(() => destination));
|
||||
if (canonicalSourcePath === canonicalDestination) {
|
||||
return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
|
||||
}
|
||||
}
|
||||
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true });
|
||||
yield* ensureNotInUse(databasePath);
|
||||
|
||||
const wrapPhase =
|
||||
(phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
yield* removeDatabaseFiles(snapshotPath);
|
||||
// The snapshot is a full-size copy of the source; make sure it is removed
|
||||
// even when a phase fails partway through.
|
||||
const { executedMigrations, pruned } = yield* Effect.gen(function* () {
|
||||
yield* Console.log(`Snapshotting ${sourcePath} (read-only)...`);
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`VACUUM INTO ${snapshotPath}`;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: sourcePath, readonly: true })),
|
||||
wrapPhase("snapshot", sourcePath),
|
||||
);
|
||||
|
||||
// Migrate before pruning: a source older than this checkout would
|
||||
// otherwise crash the prune queries on columns that don't exist yet.
|
||||
// Running against the full snapshot also exercises new migrations on the
|
||||
// same data volume the real database would face.
|
||||
yield* Console.log("Running migrations on the snapshot...");
|
||||
const executed = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
// Mirror server boot (persistence/Layers/Sqlite.ts).
|
||||
yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
|
||||
return yield* runMigrations();
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
wrapPhase("migrate", snapshotPath),
|
||||
);
|
||||
|
||||
// Verify while the snapshot is still the only thing touched: a slot
|
||||
// collision must abort before the old worktree db gets replaced with a
|
||||
// schema whose colliding migration was silently skipped.
|
||||
yield* verifyMigrationSlots().pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
Effect.catchTags({
|
||||
SqlError: (cause) =>
|
||||
Effect.fail(
|
||||
new MigrateDevDbPhaseError({ phase: "verify", databasePath: snapshotPath, cause }),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Console.log(
|
||||
`Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
|
||||
);
|
||||
const result = yield* pruneSnapshot(input).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
wrapPhase("prune", snapshotPath),
|
||||
);
|
||||
|
||||
yield* Console.log(`Compacting into ${databasePath}...`);
|
||||
// Re-check right before the swap: a dev server started while the
|
||||
// snapshot was migrating and pruning must not lose its database.
|
||||
yield* ensureNotInUse(databasePath);
|
||||
yield* removeDatabaseFiles(databasePath);
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`VACUUM INTO ${databasePath}`;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
wrapPhase("compact", databasePath),
|
||||
);
|
||||
return { executedMigrations: executed, pruned: result };
|
||||
}).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
|
||||
yield* fs.chmod(databasePath, 0o600);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
// WAL does not survive VACUUM INTO; set it so first `vp run dev` finds
|
||||
// the database exactly as server boot would have left it.
|
||||
yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
|
||||
wrapPhase("compact", databasePath),
|
||||
);
|
||||
|
||||
const size = (yield* fs.stat(databasePath)).size;
|
||||
return {
|
||||
databasePath,
|
||||
sizeBytes: Number(size),
|
||||
projects: pruned.projects,
|
||||
eventCount: pruned.eventCount,
|
||||
executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
|
||||
};
|
||||
});
|
||||
|
||||
const formatSize = (bytes: number): string =>
|
||||
bytes >= 1024 * 1024
|
||||
? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
: `${(bytes / 1024).toFixed(0)} KB`;
|
||||
|
||||
export const migrateDevDbCommand = Command.make(
|
||||
"migrate-dev-db",
|
||||
{
|
||||
projects: Flag.integer("projects").pipe(
|
||||
Flag.withDefault(5),
|
||||
Flag.withDescription("How many recently updated projects to keep."),
|
||||
),
|
||||
threadsPerProject: Flag.integer("threads-per-project").pipe(
|
||||
Flag.withDefault(10),
|
||||
Flag.withDescription("How many recent stopped threads to keep per project."),
|
||||
),
|
||||
baseDir: Flag.string("base-dir").pipe(
|
||||
Flag.optional,
|
||||
Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
|
||||
),
|
||||
source: Flag.string("source").pipe(
|
||||
Flag.optional,
|
||||
Flag.withDescription("Source database. Defaults to ~/.t3/userdata/state.sqlite."),
|
||||
),
|
||||
},
|
||||
({ projects, threadsPerProject, baseDir, source }) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* runMigrateDevDb({
|
||||
projects,
|
||||
threadsPerProject,
|
||||
baseDir: Option.getOrUndefined(baseDir),
|
||||
source: Option.getOrUndefined(source),
|
||||
});
|
||||
yield* Console.log("");
|
||||
yield* Console.log(
|
||||
`Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
|
||||
);
|
||||
for (const project of result.projects) {
|
||||
yield* Console.log(` ${project.title}: ${project.threads} threads`);
|
||||
}
|
||||
yield* Console.log(` ${result.eventCount} orchestration events kept`);
|
||||
yield* Console.log(
|
||||
result.executedMigrations.length === 0
|
||||
? " Migrations: already current (no new migrations in this checkout)"
|
||||
: ` Migrations applied: ${result.executedMigrations.join(", ")}`,
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Command.withDescription(
|
||||
"Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
|
||||
),
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
|
||||
Effect.provide(NodeServices.layer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -225,7 +225,6 @@ describe("AssetAccess", () => {
|
||||
const faviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(faviconResult.sourcePath).toBe("favicon.svg");
|
||||
expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
expect(
|
||||
yield* issueAssetUrl({
|
||||
@@ -254,7 +253,6 @@ describe("AssetAccess", () => {
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
|
||||
expect(fallbackResult.sourcePath).toBeUndefined();
|
||||
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
|
||||
expect(
|
||||
@@ -266,86 +264,6 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues project favicon capabilities for a saved override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-override-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
projectFaviconPath: "brand/custom.svg",
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("brand/custom.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("ignores a client favicon path hint", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-hint-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
|
||||
projectFaviconPath: "brand/saved.svg",
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("brand/saved.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("keeps automatic favicon resolution separate from a saved override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-automatic-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("favicon.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects a resolved project favicon with a non-image extension", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-type-",
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
projectFaviconPath: "secret.txt",
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("buckets project favicon expiry after content hashing", () =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
@@ -169,7 +169,6 @@ const resolveCanonicalWorkspaceFileForRequest = (input: {
|
||||
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
|
||||
readonly resource: AssetResource;
|
||||
readonly workspaceRoot?: string;
|
||||
readonly projectFaviconPath?: string;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -177,7 +176,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
let claims: AssetClaims;
|
||||
let fileName: string;
|
||||
let sourcePath: string | undefined;
|
||||
|
||||
switch (input.resource._tag) {
|
||||
case "workspace-file": {
|
||||
@@ -289,22 +287,16 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
),
|
||||
);
|
||||
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const faviconPath = yield* faviconResolver
|
||||
.resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
if (relativePath && !isWorkspaceImagePreviewPath(relativePath)) {
|
||||
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
|
||||
}
|
||||
sourcePath = relativePath ?? undefined;
|
||||
const canonicalFaviconPath = relativePath
|
||||
? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
@@ -387,7 +379,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
return {
|
||||
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
|
||||
expiresAt,
|
||||
...(sourcePath !== undefined ? { sourcePath } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -37,17 +37,6 @@ describe("RPC authorization scopes", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);
|
||||
});
|
||||
|
||||
it("reads the reviewer menu under the same scope as the pull request it belongs to", () => {
|
||||
// The candidate list is a read like the detail beside it, and asking somebody for a review is
|
||||
// a write like every other pull request operation.
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsReviewerCandidates)).toBe(
|
||||
requiredScopeForRpcMethod(WS_METHODS.pullRequestsDetail),
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsRequestReviewers)).toBe(
|
||||
requiredScopeForRpcMethod(WS_METHODS.pullRequestsComment),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects unknown RPC method names", () => {
|
||||
for (const method of ["server.notRegistered", "toString", "constructor"]) {
|
||||
expect(() => requiredScopeForRpcMethod(method)).toThrow(
|
||||
|
||||
@@ -46,29 +46,13 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverGetAccountLimits]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,
|
||||
[WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
|
||||
[WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsRunAction]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsComment]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsSubmitReview]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsReplyToThread]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsSetThreadResolution]: AuthOrchestrationOperateScope,
|
||||
// Read scope like the reads it un-caches: refreshing is part of reading, and a read-only
|
||||
// client pressing refresh must not be told it may not look again.
|
||||
[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
|
||||
// The candidate list is a read like the detail beside it; asking somebody for a review is a
|
||||
// write like every other one.
|
||||
[WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsRequestReviewers]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type RelayClientInstallProgressStage,
|
||||
} from "@t3tools/contracts";
|
||||
import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -695,11 +694,8 @@ export const connectCommand = Command.make("connect", {
|
||||
// fail the command, just tell the user what happened and move on.
|
||||
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
|
||||
if (background) {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
yield* Console.log(
|
||||
platform === "darwin"
|
||||
? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."
|
||||
: "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
|
||||
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -29,9 +29,9 @@ it("gives a direct repair command for a stale service", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("explains where the service is supported", () => {
|
||||
it("explains service availability without systemd", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
|
||||
"Supported on: Linux with systemd, macOS with launchd",
|
||||
"Supported on: Linux with systemd",
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -49,7 +48,7 @@ export function formatServiceStatus(
|
||||
cliVersion: string,
|
||||
): string {
|
||||
if (!status.supported) {
|
||||
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
|
||||
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
|
||||
}
|
||||
if (!status.installed) {
|
||||
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
|
||||
@@ -153,18 +152,12 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
// A LaunchAgent starts at login and dies at logout; there is no
|
||||
// enable-linger equivalent on macOS. Do not promise more than that.
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code service needs an update or repair. Update it now?"
|
||||
: platform === "darwin"
|
||||
? "Run T3 Code in the background whenever you log in to this Mac? " +
|
||||
"It stays reachable through T3 Connect while you are logged in."
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -4,10 +4,8 @@ import {
|
||||
HostProcessArguments,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
HostProcessUserId,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -37,63 +35,6 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
|
||||
expect(unit).not.toContain("versions/1.2.3");
|
||||
});
|
||||
|
||||
it("survives the kernel OOM-killing a greedy agent child", () => {
|
||||
const unit = BootService.renderBootServiceUnit({
|
||||
nodePath: "/usr/bin/node",
|
||||
launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
|
||||
baseDir: "/home/theo/.t3",
|
||||
logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
|
||||
unitPath: "/home/theo/.config/systemd/user/t3code.service",
|
||||
});
|
||||
|
||||
expect(unit).toContain("OOMPolicy=continue");
|
||||
});
|
||||
|
||||
const macPlan = {
|
||||
nodePath: "/opt/homebrew/bin/node",
|
||||
launcherPath: "/Users/theo/.t3/runtime/service-launcher.mjs",
|
||||
baseDir: "/Users/theo/.t3",
|
||||
logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
|
||||
unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
|
||||
};
|
||||
|
||||
it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {
|
||||
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
|
||||
|
||||
expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");
|
||||
expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");
|
||||
expect(plist).not.toContain("versions/1.2.3");
|
||||
});
|
||||
|
||||
it("restarts the launch agent on the systemd cadence", () => {
|
||||
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
|
||||
|
||||
expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
|
||||
expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
|
||||
expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
|
||||
expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
|
||||
});
|
||||
|
||||
it("appends both stdio streams to the boot service log", () => {
|
||||
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
|
||||
|
||||
expect(plist).toContain(
|
||||
"<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
|
||||
);
|
||||
expect(plist).toContain(
|
||||
"<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
|
||||
);
|
||||
});
|
||||
|
||||
it("escapes XML in host paths", () => {
|
||||
const plist = BootService.renderBootServicePlist(
|
||||
{ ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
|
||||
{ homeDir: "/Users/theo" },
|
||||
);
|
||||
|
||||
expect(plist).toContain("<string>/Users/theo/T3 & <Co></string>");
|
||||
});
|
||||
|
||||
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
platform: NodeJS.Platform = "linux",
|
||||
usePinnedLauncher = false,
|
||||
@@ -115,14 +56,12 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
|
||||
|
||||
const commands: string[] = [];
|
||||
const timeouts = new Map<string, unknown>();
|
||||
const control: { failCommand: string | undefined } = { failCommand: undefined };
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
const command = `${input.command} ${input.args.join(" ")}`;
|
||||
commands.push(command);
|
||||
timeouts.set(command, input.timeout);
|
||||
return {
|
||||
stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
|
||||
stderr: "",
|
||||
@@ -130,8 +69,6 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -148,20 +85,19 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(HostProcessPlatform, platform),
|
||||
Layer.succeed(HostProcessUserId, 501),
|
||||
Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
|
||||
Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
|
||||
),
|
||||
),
|
||||
);
|
||||
return { service, fs, statePath, commands, timeouts, control };
|
||||
return { service, fs, statePath, commands, control };
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("boot service install", (it) => {
|
||||
it.effect("installs, reports current state, and uninstalls", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
|
||||
const { service, fs, statePath, commands } = yield* makeHarness();
|
||||
const plan = yield* service.install;
|
||||
|
||||
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
|
||||
@@ -187,11 +123,6 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
|
||||
expect(yield* service.uninstall).toBe(true);
|
||||
expect((yield* service.status).installed).toBe(false);
|
||||
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
|
||||
// The stop can block up to systemd's 90s TimeoutStopSec; the runner's
|
||||
// 60s default would cancel it mid-shutdown.
|
||||
expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
|
||||
Duration.seconds(120),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -250,95 +181,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails closed on Windows", () =>
|
||||
it.effect("fails closed off Linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service } = yield* makeHarness("win32");
|
||||
const { service } = yield* makeHarness("darwin");
|
||||
expect((yield* service.status).supported).toBe(false);
|
||||
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs, reports current state, and uninstalls on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
|
||||
const plan = yield* service.install;
|
||||
|
||||
expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
|
||||
protocol: SERVICE_LAUNCHER_PROTOCOL,
|
||||
activeVersion: "1.2.3",
|
||||
});
|
||||
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
|
||||
expect((yield* service.status).current).toBe(true);
|
||||
expect(yield* service.uninstall).toBe(true);
|
||||
expect((yield* service.status).installed).toBe(false);
|
||||
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
|
||||
expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
|
||||
// A bootout can block up to the plist's 90s ExitTimeOut; the runner's
|
||||
// 60s default would cancel it and let bootstrap race a loaded job.
|
||||
expect(timeouts.get("launchctl bootout gui/501/com.t3tools.t3code.service")).toEqual(
|
||||
Duration.seconds(120),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restarts the launch agent when repair fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, commands, control } = yield* makeHarness("darwin");
|
||||
yield* service.install;
|
||||
const plistPath = (yield* service.status).unitPath;
|
||||
commands.length = 0;
|
||||
control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
|
||||
|
||||
const error = yield* service.install.pipe(Effect.flip);
|
||||
expect(error._tag).toBe("BootServiceCommandError");
|
||||
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
|
||||
"launchctl bootout gui/501/com.t3tools.t3code.service",
|
||||
"launchctl enable gui/501/com.t3tools.t3code.service",
|
||||
`launchctl bootstrap gui/501 ${plistPath}`,
|
||||
`launchctl bootstrap gui/501 ${plistPath}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores a bootout for an agent that is not loaded", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, control } = yield* makeHarness("darwin");
|
||||
yield* service.install;
|
||||
control.failCommand = "launchctl bootout gui/501/com.t3tools.t3code.service";
|
||||
|
||||
yield* service.install;
|
||||
expect((yield* service.status).current).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restarts without overwriting a pending remote update on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, fs, statePath, commands } = yield* makeHarness("darwin");
|
||||
yield* service.install;
|
||||
const plistPath = (yield* service.status).unitPath;
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
|
||||
const pendingState = JSON.stringify({
|
||||
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
|
||||
activeVersion: "1.2.3",
|
||||
update: {
|
||||
id: "remote-update",
|
||||
fromVersion: "1.2.3",
|
||||
targetVersion: "1.2.4",
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
yield* fs.writeFileString(statePath, pendingState);
|
||||
commands.length = 0;
|
||||
|
||||
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
|
||||
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
|
||||
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
|
||||
"launchctl bootout gui/501/com.t3tools.t3code.service",
|
||||
`launchctl bootstrap gui/501 ${plistPath}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
HostProcessUserId,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -31,10 +27,6 @@ import {
|
||||
|
||||
const BOOT_SERVICE_NAME = "t3code";
|
||||
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
|
||||
// `.service` suffix keeps the label distinct from the desktop app's bundle id
|
||||
// (com.t3tools.t3code), so launchd and TCC records never collide.
|
||||
export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
|
||||
export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
|
||||
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
|
||||
|
||||
/** systemd expands `%` specifiers, including in unquoted append-log paths. */
|
||||
@@ -75,11 +67,6 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
// Let the launcher mark an explicit stop before it signals the server.
|
||||
// systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
|
||||
"KillMode=mixed",
|
||||
// Agent tool calls run as children of the server, so they share this cgroup.
|
||||
// With the systemd default of OOMPolicy=stop, the kernel killing one greedy
|
||||
// child stops the whole unit: the server, every live agent, and the user's
|
||||
// connection. Keep running and let Restart=always cover the main process.
|
||||
"OOMPolicy=continue",
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
|
||||
@@ -91,276 +78,12 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Plist values are emitted as XML text nodes; only these three need escaping. */
|
||||
export function escapeXmlText(value: string): string {
|
||||
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
||||
}
|
||||
|
||||
/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
|
||||
export function renderBootServicePlist(
|
||||
plan: BootServicePlan,
|
||||
options: { readonly homeDir: string },
|
||||
): string {
|
||||
// KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
|
||||
// has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
|
||||
// ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
|
||||
// completes within the launcher's 5s child grace, but a stop that queues
|
||||
// behind an in-flight update transition can take much longer; launchd's
|
||||
// system-defined default (5s on current macOS) would SIGKILL the launcher
|
||||
// (and, with it, the process group) mid-handoff.
|
||||
// ProcessType Interactive opts out of background-job resource throttling.
|
||||
// AbandonProcessGroup stays at its default (false): launchd reaps leftover
|
||||
// process-group members only when the launcher itself exits — the analog of
|
||||
// KillMode=mixed's final cgroup kill — and not when the launcher restarts its
|
||||
// child, so agent children survive server updates.
|
||||
return [
|
||||
`<?xml version="1.0" encoding="UTF-8"?>`,
|
||||
`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
|
||||
`<plist version="1.0">`,
|
||||
`<dict>`,
|
||||
` <key>Label</key>`,
|
||||
` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
|
||||
` <key>ProgramArguments</key>`,
|
||||
` <array>`,
|
||||
` <string>${escapeXmlText(plan.nodePath)}</string>`,
|
||||
` <string>${escapeXmlText(plan.launcherPath)}</string>`,
|
||||
` </array>`,
|
||||
` <key>EnvironmentVariables</key>`,
|
||||
` <dict>`,
|
||||
` <key>T3CODE_HOME</key>`,
|
||||
` <string>${escapeXmlText(plan.baseDir)}</string>`,
|
||||
` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
|
||||
` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
|
||||
` </dict>`,
|
||||
` <key>WorkingDirectory</key>`,
|
||||
` <string>${escapeXmlText(options.homeDir)}</string>`,
|
||||
` <key>RunAtLoad</key>`,
|
||||
` <true/>`,
|
||||
` <key>KeepAlive</key>`,
|
||||
` <true/>`,
|
||||
` <key>ThrottleInterval</key>`,
|
||||
` <integer>5</integer>`,
|
||||
` <key>ExitTimeOut</key>`,
|
||||
` <integer>90</integer>`,
|
||||
` <key>ProcessType</key>`,
|
||||
` <string>Interactive</string>`,
|
||||
` <key>StandardOutPath</key>`,
|
||||
` <string>${escapeXmlText(plan.logPath)}</string>`,
|
||||
` <key>StandardErrorPath</key>`,
|
||||
` <string>${escapeXmlText(plan.logPath)}</string>`,
|
||||
`</dict>`,
|
||||
`</plist>`,
|
||||
``,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export interface BootServiceStep {
|
||||
readonly step: string;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
/**
|
||||
* Non-zero exit is logged and ignored. Reserved for steps whose common
|
||||
* failures (not loaded, already enabled) leave a state a later strict step
|
||||
* either tolerates or fails loudly on.
|
||||
*/
|
||||
readonly optional?: boolean;
|
||||
/** Override the ProcessRunner default (60s) for steps that block longer. */
|
||||
readonly timeout?: Duration.Input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop commands block until the service manager gives up: 90s by default for
|
||||
* systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
|
||||
* must stay above both, or the runner cancels the stop mid-shutdown and the
|
||||
* next step races a still-loaded service.
|
||||
*/
|
||||
const STOP_STEP_TIMEOUT = Duration.seconds(120);
|
||||
|
||||
/**
|
||||
* Platform service-manager integration as data: paths, a pure renderer, and
|
||||
* the command steps each flow runs. install/uninstall/status consume this and
|
||||
* never branch on platform.
|
||||
*/
|
||||
export interface BootServiceManager {
|
||||
readonly kind: "systemd" | "launchd";
|
||||
readonly unitPath: string;
|
||||
readonly render: (plan: BootServicePlan) => string;
|
||||
/** Before rewriting files, when a unit is already installed. */
|
||||
readonly stop: ReadonlyArray<BootServiceStep>;
|
||||
/** After files are written. The last entry starts the service. */
|
||||
readonly activate: ReadonlyArray<BootServiceStep>;
|
||||
/** Best-effort recovery after a failed repair of an installed service. */
|
||||
readonly restart: ReadonlyArray<BootServiceStep>;
|
||||
/** Uninstall, before the unit file is removed. */
|
||||
readonly deactivate: ReadonlyArray<BootServiceStep>;
|
||||
/** Uninstall, after the unit file is removed. */
|
||||
readonly finalize: ReadonlyArray<BootServiceStep>;
|
||||
}
|
||||
|
||||
export function systemdManager(input: {
|
||||
readonly path: Path.Path;
|
||||
readonly homeDir: string;
|
||||
}): BootServiceManager {
|
||||
const unitPath = input.path.join(
|
||||
input.homeDir,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
return {
|
||||
kind: "systemd",
|
||||
unitPath,
|
||||
render: renderBootServiceUnit,
|
||||
stop: [
|
||||
{
|
||||
step: "stopping the installed service",
|
||||
command: "systemctl",
|
||||
args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
|
||||
timeout: STOP_STEP_TIMEOUT,
|
||||
},
|
||||
],
|
||||
activate: [
|
||||
{
|
||||
step: "reloading systemd user units",
|
||||
command: "systemctl",
|
||||
args: ["--user", "daemon-reload"],
|
||||
},
|
||||
{
|
||||
step: "enabling the service",
|
||||
command: "systemctl",
|
||||
args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
|
||||
},
|
||||
{ step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
|
||||
// Start last. No administrative state write occurs after this succeeds.
|
||||
{
|
||||
step: "starting the service",
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
},
|
||||
],
|
||||
restart: [
|
||||
{
|
||||
step: "restarting the service after a failed update",
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
},
|
||||
],
|
||||
deactivate: [
|
||||
{
|
||||
step: "stopping the service",
|
||||
command: "systemctl",
|
||||
args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
|
||||
timeout: STOP_STEP_TIMEOUT,
|
||||
},
|
||||
],
|
||||
finalize: [
|
||||
{
|
||||
step: "reloading systemd user units",
|
||||
command: "systemctl",
|
||||
args: ["--user", "daemon-reload"],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function launchdManager(input: {
|
||||
readonly path: Path.Path;
|
||||
readonly homeDir: string;
|
||||
readonly uid: number;
|
||||
}): BootServiceManager {
|
||||
const unitPath = input.path.join(
|
||||
input.homeDir,
|
||||
"Library",
|
||||
"LaunchAgents",
|
||||
BOOT_SERVICE_PLIST_FILE,
|
||||
);
|
||||
const domainTarget = `gui/${input.uid}`;
|
||||
const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
|
||||
// bootout/enable are optional: they fail on not-loaded states that are fine
|
||||
// to proceed from. The strict `bootstrap` runs last and is also the start:
|
||||
// loading a RunAtLoad/KeepAlive plist starts the job, so a separate
|
||||
// kickstart would kill and restart a server it just booted. A lingering job
|
||||
// that survived bootout, or a gui domain with nobody logged in at the
|
||||
// screen (SSH install), makes bootstrap fail the flow loudly rather than
|
||||
// silently keeping a stale server.
|
||||
return {
|
||||
kind: "launchd",
|
||||
unitPath,
|
||||
render: (plan) => renderBootServicePlist(plan, { homeDir: input.homeDir }),
|
||||
stop: [
|
||||
{
|
||||
step: "stopping the installed launch agent",
|
||||
command: "launchctl",
|
||||
args: ["bootout", serviceTarget],
|
||||
optional: true,
|
||||
timeout: STOP_STEP_TIMEOUT,
|
||||
},
|
||||
],
|
||||
activate: [
|
||||
// A persisted `launchctl disable` override refuses bootstrap; clear it.
|
||||
{
|
||||
step: "enabling the launch agent",
|
||||
command: "launchctl",
|
||||
args: ["enable", serviceTarget],
|
||||
optional: true,
|
||||
},
|
||||
// Start last. No administrative state write occurs after this succeeds.
|
||||
{
|
||||
step: "starting the service",
|
||||
command: "launchctl",
|
||||
args: ["bootstrap", domainTarget, unitPath],
|
||||
},
|
||||
],
|
||||
restart: [
|
||||
{
|
||||
step: "restarting the service after a failed update",
|
||||
command: "launchctl",
|
||||
args: ["bootstrap", domainTarget, unitPath],
|
||||
},
|
||||
],
|
||||
// No `launchctl disable` here: a persisted override would sabotage a
|
||||
// later reinstall. Removing the plist is what stops the next login load.
|
||||
// A bootout that fails for a reason other than "not loaded" leaves the
|
||||
// job running until logout; the failure is in the boot-service log.
|
||||
deactivate: [
|
||||
{
|
||||
step: "stopping the service",
|
||||
command: "launchctl",
|
||||
args: ["bootout", serviceTarget],
|
||||
optional: true,
|
||||
timeout: STOP_STEP_TIMEOUT,
|
||||
},
|
||||
],
|
||||
finalize: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Undefined means this host cannot run the background service. */
|
||||
export function selectBootServiceManager(input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly homeDir: string;
|
||||
readonly uid: number | undefined;
|
||||
readonly path: Path.Path;
|
||||
}): BootServiceManager | undefined {
|
||||
if (input.homeDir === "") {
|
||||
return undefined;
|
||||
}
|
||||
if (input.platform === "linux") {
|
||||
return systemdManager({ path: input.path, homeDir: input.homeDir });
|
||||
}
|
||||
if (input.platform === "darwin" && input.uid !== undefined) {
|
||||
return launchdManager({ path: input.path, homeDir: input.homeDir, uid: input.uid });
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
|
||||
"BootServiceUnsupportedError",
|
||||
{ platform: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
|
||||
return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,15 +158,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
}) {
|
||||
const hostExecPath = yield* HostProcessExecutablePath;
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const uid = yield* HostProcessUserId;
|
||||
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const host = input.host ?? { execPath: hostExecPath };
|
||||
|
||||
const detectedManager = selectBootServiceManager({ platform, homeDir, uid, path });
|
||||
const unitPath = detectedManager?.unitPath ?? "";
|
||||
const unitDir = path.join(homeDir, ".config", "systemd", "user");
|
||||
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
|
||||
const logPath = path.join(input.logsDir, "boot-service.log");
|
||||
const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
|
||||
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
|
||||
@@ -471,11 +193,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
unitPath,
|
||||
};
|
||||
|
||||
const requireManager = Effect.suspend(() =>
|
||||
detectedManager === undefined
|
||||
? new BootServiceUnsupportedError({ platform })
|
||||
: Effect.succeed(detectedManager),
|
||||
);
|
||||
const requireSystemdLinux = Effect.gen(function* () {
|
||||
if (platform !== "linux" || homeDir === "") {
|
||||
return yield* new BootServiceUnsupportedError({ platform });
|
||||
}
|
||||
});
|
||||
|
||||
const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
|
||||
step: string,
|
||||
@@ -508,25 +230,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
);
|
||||
});
|
||||
|
||||
const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
|
||||
Effect.forEach(
|
||||
steps,
|
||||
(entry) => {
|
||||
const run = runStep(
|
||||
entry.step,
|
||||
entry.command,
|
||||
entry.args,
|
||||
entry.timeout === undefined ? undefined : { timeout: entry.timeout },
|
||||
);
|
||||
// runStep's tapError already appends the failure to the log, so an
|
||||
// ignored optional step still leaves a trace.
|
||||
return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
|
||||
},
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
const install: BootService["Service"]["install"] = Effect.gen(function* () {
|
||||
const manager = yield* requireManager;
|
||||
yield* requireSystemdLinux;
|
||||
yield* fs
|
||||
.makeDirectory(input.logsDir, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
|
||||
@@ -588,7 +293,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
.exists(unitPath)
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
|
||||
if (installed) {
|
||||
yield* runSteps(manager.stop);
|
||||
yield* runStep("stopping the installed service", "systemctl", [
|
||||
"--user",
|
||||
"stop",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
]);
|
||||
}
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -602,7 +311,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
}
|
||||
}
|
||||
yield* fs
|
||||
.makeDirectory(path.dirname(unitPath), { recursive: true })
|
||||
.makeDirectory(unitDir, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
|
||||
yield* writeDurably(launcherPath, launcherSource);
|
||||
yield* writeDurably(
|
||||
@@ -617,35 +326,58 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
yield* writeDurably(unitPath, manager.render(plan));
|
||||
yield* writeDurably(unitPath, renderBootServiceUnit(plan));
|
||||
|
||||
yield* runSteps(manager.activate);
|
||||
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
|
||||
yield* runStep("enabling the service", "systemctl", [
|
||||
"--user",
|
||||
"enable",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
]);
|
||||
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
|
||||
// Start last. No administrative state write occurs after this succeeds.
|
||||
yield* runStep("starting the service", "systemctl", [
|
||||
"--user",
|
||||
"restart",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.tapError(() =>
|
||||
installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
|
||||
installed
|
||||
? runStep("restarting the service after a failed update", "systemctl", [
|
||||
"--user",
|
||||
"restart",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
]).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
return plan;
|
||||
}).pipe(Effect.withSpan("cloud.boot_service.install"));
|
||||
|
||||
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
|
||||
const manager = yield* requireManager;
|
||||
yield* requireSystemdLinux;
|
||||
if (
|
||||
!(yield* fs
|
||||
.exists(unitPath)
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
|
||||
)
|
||||
return false;
|
||||
yield* runSteps(manager.deactivate);
|
||||
yield* runStep("stopping the service", "systemctl", [
|
||||
"--user",
|
||||
"disable",
|
||||
"--now",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
]);
|
||||
yield* fs
|
||||
.remove(unitPath)
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
|
||||
yield* runSteps(manager.finalize);
|
||||
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
|
||||
return true;
|
||||
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
|
||||
|
||||
const status: BootService["Service"]["status"] = Effect.gen(function* () {
|
||||
if (detectedManager === undefined) {
|
||||
if (platform !== "linux" || homeDir === "") {
|
||||
return { supported: false, installed: false, current: false, unitPath, logPath };
|
||||
}
|
||||
if (!(yield* fs.exists(unitPath))) {
|
||||
@@ -664,7 +396,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
supported: true,
|
||||
installed: true,
|
||||
current:
|
||||
unit === detectedManager.render(plan) &&
|
||||
unit === renderBootServiceUnit(plan) &&
|
||||
launcherExists &&
|
||||
runtimeEntryExists &&
|
||||
Option.isSome(runtimeSentinel) &&
|
||||
|
||||
@@ -649,8 +649,7 @@ export const pendingServiceUpdateExists = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
// A pending update alone is not proof a replacement server is coming: an
|
||||
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,
|
||||
// `launchctl bootout`) during
|
||||
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
|
||||
// the pending window also tears this server down. The launcher marks that case
|
||||
// just before it signals the child, so pending + no marker is the handoff.
|
||||
const pendingUpdateHandoffExists = Effect.gen(function* () {
|
||||
|
||||
@@ -31,8 +31,6 @@ const successfulRunner = (fs: FileSystem.FileSystem, path: Path.Path) =>
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -10,8 +10,8 @@ import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
/**
|
||||
* A pinned runtime is an exact `t3@<version>` npm-installed into
|
||||
* <baseDir>/runtime/versions/<version>. The boot service points its unit or
|
||||
* launch agent here, and server self-update installs the target version here before
|
||||
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
|
||||
* unit here, and server self-update installs the target version here before
|
||||
* switching over, never `npx t3`, whose cache is ephemeral and whose
|
||||
* registry fetch at boot would make startup depend on the network.
|
||||
*/
|
||||
|
||||
@@ -45,8 +45,6 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}
|
||||
order.push("preflight");
|
||||
@@ -66,8 +64,6 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -69,7 +69,6 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
||||
expect(first.environmentId).toBe(second.environmentId);
|
||||
expect(second.capabilities.repositoryIdentity).toBe(true);
|
||||
expect(second.capabilities.connectionProbe).toBe(true);
|
||||
expect(second.capabilities.pullRequests).toBe(true);
|
||||
expect(second.capabilities.threadTitleRegeneration).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -143,7 +143,6 @@ export const make = Effect.gen(function* () {
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
pullRequests: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
threadPinning: true,
|
||||
|
||||
@@ -81,8 +81,6 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -122,8 +120,6 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -227,8 +223,6 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -270,8 +264,6 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -3341,7 +3341,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("launches setup when creating a new PR worktree", () =>
|
||||
it.effect("launches setup only when creating a new PR worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -3614,547 +3614,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.branch).toBe("feature/pr-existing-worktree");
|
||||
// Nothing to fetch from, so the checkout keeps the commit it had and setup stays out of a
|
||||
// worktree another thread may be sitting in.
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes a reused PR worktree onto the updated pull request head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-stale"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "stale.txt"), "stale\n");
|
||||
yield* runGit(repoDir, ["add", "stale.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Reused stale PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-reused-stale"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-reused-stale-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-stale"]);
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "author-push", "origin/feature/pr-reused-stale"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "authored.txt"), "authored\n");
|
||||
yield* runGit(repoDir, ["add", "authored.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "New PR head commit"]);
|
||||
yield* runGit(repoDir, ["push", "origin", "author-push:feature/pr-reused-stale"]);
|
||||
const updatedHead = (yield* runGit(repoDir, ["rev-parse", "author-push"])).stdout.trim();
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 84,
|
||||
title: "Reused stale PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/84",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-reused-stale",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "84",
|
||||
mode: "worktree",
|
||||
});
|
||||
|
||||
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.branch).toBe("feature/pr-reused-stale");
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(updatedHead);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("runs the setup script when a reused PR worktree moves onto the new head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-setup"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "reused-setup.txt"), "reused setup\n");
|
||||
yield* runGit(repoDir, ["add", "reused-setup.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Reused setup PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-reused-setup"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-reused-setup-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-setup"]);
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "setup-author-push", "feature/pr-reused-setup"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "reused-setup.txt"), "reused setup again\n");
|
||||
yield* runGit(repoDir, ["add", "reused-setup.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "New reused setup head"]);
|
||||
yield* runGit(repoDir, ["push", "origin", "setup-author-push:feature/pr-reused-setup"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 85,
|
||||
title: "Reused setup PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/85",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-reused-setup",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "85",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-reused-setup"),
|
||||
});
|
||||
|
||||
expect(setupCalls).toHaveLength(1);
|
||||
expect(setupCalls[0]).toEqual({
|
||||
threadId: "thread-pr-reused-setup",
|
||||
projectCwd: repoDir,
|
||||
worktreePath: result.worktreePath as string,
|
||||
});
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("leaves the setup script alone when a reused PR worktree is already on the head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-current"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "reused-current.txt"), "reused current\n");
|
||||
yield* runGit(repoDir, ["add", "reused-current.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Reused current PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-reused-current"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-reused-current-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-current"]);
|
||||
const currentHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 95,
|
||||
title: "Reused current PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/95",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-reused-current",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "95",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-reused-current"),
|
||||
});
|
||||
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(currentHead);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resets a clean reused PR worktree onto a force-pushed pull request head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-force-pushed"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "force-pushed.txt"), "first\n");
|
||||
yield* runGit(repoDir, ["add", "force-pushed.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Force-pushed PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-force-pushed"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-force-pushed-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-force-pushed"]);
|
||||
const staleHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "author-rewrite", "feature/pr-force-pushed"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "force-pushed.txt"), "rewritten\n");
|
||||
yield* runGit(repoDir, ["add", "force-pushed.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten PR head"]);
|
||||
yield* runGit(repoDir, [
|
||||
"push",
|
||||
"--force",
|
||||
"origin",
|
||||
"author-rewrite:feature/pr-force-pushed",
|
||||
]);
|
||||
const rewrittenHead = (yield* runGit(repoDir, ["rev-parse", "author-rewrite"])).stdout.trim();
|
||||
// Pushing from this clone also advanced its remote-tracking ref. A head rewritten by the
|
||||
// author leaves that ref behind, which is the state a reused worktree is really opened in.
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"refs/remotes/origin/feature/pr-force-pushed",
|
||||
staleHead,
|
||||
]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 86,
|
||||
title: "Force-pushed PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/86",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-force-pushed",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "86",
|
||||
mode: "worktree",
|
||||
});
|
||||
|
||||
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(
|
||||
rewrittenHead,
|
||||
);
|
||||
expect(NodeFS.readFileSync(NodePath.join(worktreePath, "force-pushed.txt"), "utf8")).toBe(
|
||||
"rewritten\n",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a reused PR worktree that carries its own commit off the rewritten head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-commit"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "local-commit.txt"), "first\n");
|
||||
yield* runGit(repoDir, ["add", "local-commit.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Local commit PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-commit"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-local-commit-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-local-commit"]);
|
||||
const upstreamHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "local-commit-rewrite", "feature/pr-local-commit"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "local-commit.txt"), "rewritten\n");
|
||||
yield* runGit(repoDir, ["add", "local-commit.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten local commit head"]);
|
||||
yield* runGit(repoDir, [
|
||||
"push",
|
||||
"--force",
|
||||
"origin",
|
||||
"local-commit-rewrite:feature/pr-local-commit",
|
||||
]);
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"refs/remotes/origin/feature/pr-local-commit",
|
||||
upstreamHead,
|
||||
]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
// The work that must survive: a commit made in the worktree, on top of the stale head.
|
||||
NodeFS.writeFileSync(NodePath.join(worktreePath, "thread-work.txt"), "thread work\n");
|
||||
yield* runGit(worktreePath, ["add", "thread-work.txt"]);
|
||||
yield* runGit(worktreePath, ["commit", "-m", "Work done in the reused worktree"]);
|
||||
const worktreeHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 87,
|
||||
title: "Local commit PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/87",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-local-commit",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "87",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-local-commit"),
|
||||
});
|
||||
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(worktreeHead);
|
||||
expect(NodeFS.existsSync(NodePath.join(worktreePath, "thread-work.txt"))).toBe(true);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a dirty reused PR worktree off the rewritten pull request head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-dirty-worktree"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "dirty.txt"), "first\n");
|
||||
yield* runGit(repoDir, ["add", "dirty.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Dirty worktree PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-dirty-worktree"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-dirty-worktree-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-dirty-worktree"]);
|
||||
const staleHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "dirty-rewrite", "feature/pr-dirty-worktree"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "dirty.txt"), "rewritten\n");
|
||||
yield* runGit(repoDir, ["add", "dirty.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten dirty head"]);
|
||||
yield* runGit(repoDir, [
|
||||
"push",
|
||||
"--force",
|
||||
"origin",
|
||||
"dirty-rewrite:feature/pr-dirty-worktree",
|
||||
]);
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"refs/remotes/origin/feature/pr-dirty-worktree",
|
||||
staleHead,
|
||||
]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
NodeFS.writeFileSync(NodePath.join(worktreePath, "dirty.txt"), "uncommitted edit\n");
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 89,
|
||||
title: "Dirty worktree PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/89",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-dirty-worktree",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "89",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-dirty-worktree"),
|
||||
});
|
||||
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(staleHead);
|
||||
expect(NodeFS.readFileSync(NodePath.join(worktreePath, "dirty.txt"), "utf8")).toBe(
|
||||
"uncommitted edit\n",
|
||||
);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes a reused PR worktree that has no upstream from the pull request ref", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-ref-only"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "ref-only.txt"), "ref only\n");
|
||||
yield* runGit(repoDir, ["add", "ref-only.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Pull ref only PR branch"]);
|
||||
// The head lives at refs/pull/90/head and nowhere else, so nothing can be tracked.
|
||||
yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/90/head"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "feature/pr-ref-only"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 90,
|
||||
title: "Pull ref only PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/90",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-ref-only",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const created = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "90",
|
||||
mode: "worktree",
|
||||
});
|
||||
const worktreePath = created.worktreePath as string;
|
||||
expect(
|
||||
(yield* runGit(worktreePath, ["rev-parse", "--abbrev-ref", "@{upstream}"], true)).exitCode,
|
||||
).not.toBe(0);
|
||||
|
||||
yield* runGit(repoDir, ["fetch", "origin", "refs/pull/90/head"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "ref-only-author", "FETCH_HEAD"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "ref-only.txt"), "ref only again\n");
|
||||
yield* runGit(repoDir, ["add", "ref-only.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "New pull ref head"]);
|
||||
yield* runGit(repoDir, ["push", "origin", "ref-only-author:refs/pull/90/head"]);
|
||||
const updatedHead = (yield* runGit(repoDir, ["rev-parse", "ref-only-author"])).stdout.trim();
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "90",
|
||||
mode: "worktree",
|
||||
});
|
||||
|
||||
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(updatedHead);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("never moves an unrelated local branch that shares the fork head branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const originDir = yield* createBareRemote();
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "fork-main-collision"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "contributor.txt"), "contributor\n");
|
||||
yield* runGit(repoDir, ["add", "contributor.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Contributor commit on the fork main"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-collision:main"]);
|
||||
// The user's own main, checked out in its own worktree and behind the fork's main: a
|
||||
// fast-forward would land the contributor's commits in it.
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/root-work", "main"]);
|
||||
const mainWorktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`local-main-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", mainWorktreePath, "main"]);
|
||||
const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 94,
|
||||
title: "Fork main collision PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/94",
|
||||
baseRefName: "main",
|
||||
headRefName: "main",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
},
|
||||
repositoryCloneUrls: {
|
||||
"octocat/codething-mvp": {
|
||||
url: forkDir,
|
||||
sshUrl: forkDir,
|
||||
},
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "94",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-fork-main-collision"),
|
||||
});
|
||||
|
||||
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);
|
||||
expect((yield* runGit(mainWorktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(
|
||||
localMainBefore,
|
||||
);
|
||||
expect(NodeFS.existsSync(NodePath.join(mainWorktreePath, "contributor.txt"))).toBe(false);
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1849,7 +1849,6 @@ export const make = Effect.gen(function* () {
|
||||
pullRequest,
|
||||
branch: details.branch ?? pullRequest.headBranch,
|
||||
worktreePath: null,
|
||||
isOnPullRequestHead: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1874,102 +1873,6 @@ export const make = Effect.gen(function* () {
|
||||
const localPullRequestBranch =
|
||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||
|
||||
// Git refuses to move a branch that is checked out in a worktree, so the
|
||||
// reuse paths cannot go through materializePullRequestHeadBranch and instead
|
||||
// advance the checkout from inside the worktree. A worktree that cannot be
|
||||
// moved (no reachable head, local commits, dirty tree) is still handed
|
||||
// back, because stranding the thread is worse than reporting the staleness.
|
||||
const reuseExistingWorktree = Effect.fn("reuseExistingWorktree")(function* (
|
||||
worktreePath: string,
|
||||
checkedOutBranch: string,
|
||||
) {
|
||||
if (checkedOutBranch !== localPullRequestBranch) {
|
||||
// findLocalHeadBranch also accepts a branch that merely shares the head's bare name —
|
||||
// a fork PR opened from "main" matches the user's own local main. That checkout is
|
||||
// somebody else's work, so it keeps its tracking config and nothing else.
|
||||
yield* ensureExistingWorktreeUpstream(worktreePath);
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath,
|
||||
isOnPullRequestHead: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Read before ensureExistingWorktreeUpstream: it force-updates the remote-tracking ref,
|
||||
// and once that has jumped to a rewritten head there is no way left to tell a checkout
|
||||
// that holds nothing of its own from one carrying local commits.
|
||||
const upstreamCommitBeforeFetch = yield* gitCore
|
||||
.resolveCommit({ cwd: worktreePath, revision: "@{upstream}" })
|
||||
.pipe(
|
||||
Effect.map((resolved) => resolved.commitSha),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
yield* ensureExistingWorktreeUpstream(worktreePath);
|
||||
|
||||
const refreshed = yield* gitCore
|
||||
// The pull request's own ref, because it is the only thing that certainly names its
|
||||
// head. The branch's upstream does not: configuring it is best-effort, so a branch cut
|
||||
// from `origin/main` whose head branch has since been deleted still resolves — and
|
||||
// following it would move the checkout onto main and call that the pull request.
|
||||
.fetchPullRequestHeadCommit({ cwd: worktreePath, prNumber: pullRequest.number })
|
||||
.pipe(
|
||||
// A host that publishes no `refs/pull/<n>/head` leaves the remote-tracking branch,
|
||||
// taken only where it is the head branch's own rather than whatever the checkout
|
||||
// happened to be cut from.
|
||||
Effect.catch(() =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(worktreePath);
|
||||
if (
|
||||
details.upstreamRef === null ||
|
||||
!details.upstreamRef.endsWith(`/${pullRequest.headBranch}`)
|
||||
) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "preparePullRequestThread",
|
||||
cwd: worktreePath,
|
||||
detail: "The pull request head could not be resolved for this checkout.",
|
||||
});
|
||||
}
|
||||
return yield* gitCore.resolveCommit({
|
||||
cwd: worktreePath,
|
||||
revision: details.upstreamRef,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((target) =>
|
||||
gitCore.refreshCheckedOutBranch({
|
||||
cwd: worktreePath,
|
||||
targetCommit: target.commitSha,
|
||||
resetWhenHeadCommit: upstreamCommitBeforeFetch,
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
"GitManager.preparePullRequestThread reused worktree refresh failed",
|
||||
{
|
||||
worktreePath,
|
||||
localBranch: localPullRequestBranch,
|
||||
cause: error,
|
||||
},
|
||||
).pipe(Effect.as({ moved: false, onTarget: false })),
|
||||
),
|
||||
);
|
||||
|
||||
// Only when the checkout actually moved: another thread may be running in this worktree,
|
||||
// and re-running the setup script under it buys nothing when the code did not change.
|
||||
if (refreshed.moved) {
|
||||
yield* maybeRunSetupScript(worktreePath);
|
||||
}
|
||||
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath,
|
||||
isOnPullRequestHead: refreshed.onTarget,
|
||||
};
|
||||
});
|
||||
|
||||
const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
|
||||
const result = yield* gitCore.listRefs({ cwd, refresh: true });
|
||||
const localBranch = result.refs.find(
|
||||
@@ -2004,10 +1907,12 @@ export const make = Effect.gen(function* () {
|
||||
existingBranchBeforeFetch?.worktreePath &&
|
||||
existingBranchBeforeFetchPath !== rootWorktreePath
|
||||
) {
|
||||
return yield* reuseExistingWorktree(
|
||||
existingBranchBeforeFetch.worktreePath,
|
||||
existingBranchBeforeFetch.name,
|
||||
);
|
||||
yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath);
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath: existingBranchBeforeFetch.worktreePath,
|
||||
};
|
||||
}
|
||||
if (existingBranchBeforeFetchPath === rootWorktreePath) {
|
||||
return yield* new GitManagerError({
|
||||
@@ -2032,10 +1937,12 @@ export const make = Effect.gen(function* () {
|
||||
existingBranchAfterFetch?.worktreePath &&
|
||||
existingBranchAfterFetchPath !== rootWorktreePath
|
||||
) {
|
||||
return yield* reuseExistingWorktree(
|
||||
existingBranchAfterFetch.worktreePath,
|
||||
existingBranchAfterFetch.name,
|
||||
);
|
||||
yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath);
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath: existingBranchAfterFetch.worktreePath,
|
||||
};
|
||||
}
|
||||
if (existingBranchAfterFetchPath === rootWorktreePath) {
|
||||
return yield* new GitManagerError({
|
||||
@@ -2058,7 +1965,6 @@ export const make = Effect.gen(function* () {
|
||||
pullRequest,
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath: worktree.worktree.path,
|
||||
isOnPullRequestHead: true,
|
||||
};
|
||||
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { assetResponseHeaders, isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
|
||||
describe("http dev routing", () => {
|
||||
it("treats localhost and loopback addresses as local", () => {
|
||||
@@ -26,22 +26,3 @@ describe("http dev routing", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assetResponseHeaders", () => {
|
||||
it("sandboxes SVG assets", () => {
|
||||
expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
|
||||
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
|
||||
"Content-Security-Policy",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not apply document policy to raster images", () => {
|
||||
expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
});
|
||||
});
|
||||
+4
-13
@@ -43,18 +43,6 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
|
||||
|
||||
export function assetResponseHeaders(filePath: string): Record<string, string> {
|
||||
return {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...(filePath.toLowerCase().endsWith(".svg")
|
||||
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
|
||||
global: true,
|
||||
});
|
||||
@@ -219,7 +207,10 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
}
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: assetResponseHeaders(asset.path),
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
|
||||
@@ -2764,18 +2764,15 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5",
|
||||
},
|
||||
faviconPath: "brand/icon.svg",
|
||||
});
|
||||
|
||||
const projectRows = yield* sql<{
|
||||
readonly scriptsJson: string;
|
||||
readonly defaultModelSelection: string;
|
||||
readonly faviconPath: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
scripts_json AS "scriptsJson",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
favicon_path AS "faviconPath"
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-scripts'
|
||||
`;
|
||||
@@ -2784,7 +2781,6 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
scriptsJson:
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
|
||||
faviconPath: "brand/icon.svg",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
|
||||
@@ -495,8 +495,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
title: event.payload.title,
|
||||
workspaceRoot: event.payload.workspaceRoot,
|
||||
defaultModelSelection: event.payload.defaultModelSelection,
|
||||
defaultThreadEnvMode: null,
|
||||
faviconPath: event.payload.faviconPath ?? null,
|
||||
scripts: event.payload.scripts,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -520,12 +518,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...(event.payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: event.payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(event.payload.defaultThreadEnvMode !== undefined
|
||||
? { defaultThreadEnvMode: event.payload.defaultThreadEnvMode }
|
||||
: {}),
|
||||
...(event.payload.faviconPath !== undefined
|
||||
? { faviconPath: event.payload.faviconPath }
|
||||
: {}),
|
||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
|
||||
@@ -275,7 +275,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
faviconPath: null,
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
@@ -285,7 +284,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
defaultThreadEnvMode: null,
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:01.000Z",
|
||||
deletedAt: null,
|
||||
@@ -395,7 +393,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
faviconPath: null,
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
@@ -405,7 +402,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
defaultThreadEnvMode: null,
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:01.000Z",
|
||||
},
|
||||
|
||||
@@ -316,8 +316,6 @@ function mapProjectShellRow(
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
defaultThreadEnvMode: row.defaultThreadEnvMode,
|
||||
faviconPath: row.faviconPath ?? null,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -393,8 +391,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -848,8 +844,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -872,8 +866,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -1550,8 +1542,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
defaultThreadEnvMode: row.defaultThreadEnvMode,
|
||||
faviconPath: row.faviconPath ?? null,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -1681,8 +1671,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
defaultThreadEnvMode: row.defaultThreadEnvMode,
|
||||
faviconPath: row.faviconPath ?? null,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -2174,8 +2162,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
workspaceRoot: option.value.workspaceRoot,
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: option.value.defaultModelSelection,
|
||||
defaultThreadEnvMode: option.value.defaultThreadEnvMode,
|
||||
faviconPath: option.value.faviconPath ?? null,
|
||||
scripts: option.value.scripts,
|
||||
createdAt: option.value.createdAt,
|
||||
updatedAt: option.value.updatedAt,
|
||||
|
||||
@@ -53,6 +53,7 @@ import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeInge
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import * as AccountLimitsService from "../../usage/AccountLimitsService.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
|
||||
@@ -246,6 +247,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provideMerge(ThreadPlanProgress.layer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(AccountLimitsService.layerTest),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
} from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { forkParked } from "../../serverActivation.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { AccountLimitsService } from "../../usage/AccountLimitsService.ts";
|
||||
|
||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
|
||||
@@ -875,6 +876,7 @@ const make = Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const accountLimits = yield* AccountLimitsService;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
|
||||
@@ -1474,6 +1476,17 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
// Rate-limit payloads feed the server-wide limits cache, not a thread
|
||||
// projection, so they are folded in before the thread lookup: a
|
||||
// snapshot must not be lost because its thread is already gone.
|
||||
if (event.type === "account.rate-limits.updated") {
|
||||
yield* accountLimits.ingest({
|
||||
provider: event.provider,
|
||||
payload: event.payload.rateLimits,
|
||||
createdAt: event.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadShell(event.threadId);
|
||||
if (!thread) return;
|
||||
|
||||
|
||||
@@ -94,47 +94,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("propagates a project favicon path in project.meta.update", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const readModel = yield* projectEvent(createEmptyReadModel(now), {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create-favicon"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-favicon"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create-favicon"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create-favicon"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-favicon"),
|
||||
title: "Favicon",
|
||||
workspaceRoot: "/tmp/favicon",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("cmd-project-update-favicon"),
|
||||
projectId: asProjectId("project-favicon"),
|
||||
faviconPath: "brand/icon.svg",
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
const event = Array.isArray(result) ? result[0] : result;
|
||||
expect(event.type).toBe("project.meta-updated");
|
||||
expect((event.payload as { faviconPath?: string }).faviconPath).toBe("brand/icon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects project.create for an active workspace root that already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
Loaded 100 of 409 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user