diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 988e223d219f5..2f9faba635e34 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -25,6 +25,7 @@ github:D3OXY github:dbalders github:eggfriedrice24 github:extoci +github:f-trycua github:flamboh github:FllipEis github:gbarros-dev diff --git a/.github/scripts/stage-preview-bundle.py b/.github/scripts/stage-preview-bundle.py new file mode 100644 index 0000000000000..0b3a53285916b --- /dev/null +++ b/.github/scripts/stage-preview-bundle.py @@ -0,0 +1,76 @@ +"""Stage an untrusted preview ZIP without letting it replace packaging code.""" + +import shutil +import stat +import sys +import zipfile +from pathlib import Path + +ROOTS = ("server/dist", "desktop/dist-electron") +REQUIRED_FILES = { + "server/dist/bin.mjs", + "server/dist/client/index.html", + "desktop/dist-electron/main.cjs", +} +# The current bundle is about 32 MiB compressed. Bound extraction on the +# trusted runner even when the PR replaces the uploader entirely. +MAX_ARCHIVE_BYTES = 512 * 1024 * 1024 +MAX_EXPANDED_BYTES = 2 * 1024 * 1024 * 1024 +MAX_ENTRIES = 50_000 + + +def stage_bundle(archive: Path, destination: Path): + if archive.stat().st_size > MAX_ARCHIVE_BYTES: + raise ValueError("Preview archive is too large") + with zipfile.ZipFile(archive) as bundle: + entries = bundle.infolist() + if len(entries) > MAX_ENTRIES: + raise ValueError("Preview archive has too many entries") + if sum(entry.file_size for entry in entries) > MAX_EXPANDED_BYTES: + raise ValueError("Expanded preview bundle is too large") + seen = set() + files = set() + for entry in entries: + name = entry.filename.removesuffix("/") + parts = name.split("/") + # Reject ambiguous paths before normalization, including names + # that would alias on the macOS signing runner. + if ( + entry.orig_filename != entry.filename + or any(part in ("", ".", "..") for part in parts) + or any(char in name for char in "\\:") + or not name.isascii() + or any(ord(char) < 32 or ord(char) == 127 for char in name) + ): + raise ValueError(f"Unsafe preview path: {entry.filename!r}") + allowed = any(name.startswith(root + "/") for root in ROOTS) + if entry.is_dir(): + allowed |= any(root == name or root.startswith(name + "/") for root in ROOTS) + if not allowed: + raise ValueError(f"Unexpected preview path: {name!r}") + kind = stat.S_IFMT(entry.external_attr >> 16) + if kind not in (0, stat.S_IFDIR if entry.is_dir() else stat.S_IFREG): + raise ValueError(f"Non-regular preview entry: {name!r}") + if name.casefold() in seen: + raise ValueError(f"Duplicate preview path: {name!r}") + seen.add(name.casefold()) + if not entry.is_dir(): + files.add(name) + if not REQUIRED_FILES <= files: + raise ValueError("Preview bundle is missing required entry points") + # Validate all names before writing anything. This is a fresh directory + # outside the checkout; neither pre-existing links nor trusted files + # can be followed or overwritten. ZIP permissions are never restored. + destination.mkdir(parents=True, exist_ok=False) + for entry in entries: + target = destination / entry.filename + if entry.is_dir(): + target.mkdir(parents=True, exist_ok=True) + else: + target.parent.mkdir(parents=True, exist_ok=True) + with bundle.open(entry) as source, target.open("xb") as output: + shutil.copyfileobj(source, output) + + +if __name__ == "__main__": + stage_bundle(Path(sys.argv[1]), Path(sys.argv[2])) diff --git a/.github/scripts/stage-preview-bundle.test.py b/.github/scripts/stage-preview-bundle.test.py new file mode 100644 index 0000000000000..5957279c88850 --- /dev/null +++ b/.github/scripts/stage-preview-bundle.test.py @@ -0,0 +1,97 @@ +import importlib.util +import stat +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location( + "stage_preview_bundle", Path(__file__).with_name("stage-preview-bundle.py") +) +staging = importlib.util.module_from_spec(spec) +spec.loader.exec_module(staging) + + +class StagePreviewBundleTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.archive = self.root / "bundle.zip" + self.destination = self.root / "staged" + + def bundle(self, extra=(), missing=None): + with zipfile.ZipFile(self.archive, "w") as bundle: + for name in sorted(staging.REQUIRED_FILES - {missing}): + bundle.writestr(name, b"bundle data, never executed") + for name, content in extra: + bundle.writestr(name, content) + + def stage(self): + staging.stage_bundle(self.archive, self.destination) + + def test_preserves_valid_bundle_layout_and_bytes(self): + self.bundle([("server/", b""), ("server/dist/", b""), + ("desktop/dist-electron/chunks/helper.cjs", b"chunk")]) + self.stage() + for name in staging.REQUIRED_FILES: + self.assertEqual((self.destination / name).read_bytes(), b"bundle data, never executed") + self.assertEqual((self.destination / "desktop/dist-electron/chunks/helper.cjs").read_bytes(), b"chunk") + + def test_rejects_builder_overwrite_and_unsafe_paths_before_writing(self): + for name in [ + "desktop/node_modules/electron-builder/cli.js", + "desktop/package.json", + "server/dist/../../desktop/package.json", + "../package.json", + "/server/dist/absolute", + "server/dist/./alias", + "server/dist//alias", + "server/dist/back\\slash", + "server/dist/file:stream", + "server/dist/BIN.MJS", + ]: + with self.subTest(name=name): + self.bundle([(name, b"untrusted")]) + with self.assertRaises(ValueError): + self.stage() + self.assertFalse(self.destination.exists()) + + def test_rejects_links_and_special_files(self): + for mode in [stat.S_IFLNK, stat.S_IFIFO, stat.S_IFCHR]: + with self.subTest(mode=mode): + entry = zipfile.ZipInfo("server/dist/link") + entry.create_system = 3 + entry.external_attr = (mode | 0o777) << 16 + self.bundle([(entry, b"../../../desktop/node_modules")]) + with self.assertRaises(ValueError): + self.stage() + self.assertFalse(self.destination.exists()) + + def test_requires_entry_points(self): + self.bundle(missing="desktop/dist-electron/main.cjs") + with self.assertRaises(ValueError): + self.stage() + self.assertFalse(self.destination.exists()) + + def test_bounds_archive_size_expanded_size_and_entry_count(self): + for limit in ["MAX_ARCHIVE_BYTES", "MAX_EXPANDED_BYTES", "MAX_ENTRIES"]: + with self.subTest(limit=limit), patch.object(staging, limit, 1): + self.bundle() + with self.assertRaises(ValueError): + self.stage() + self.assertFalse(self.destination.exists()) + + def test_refuses_existing_destination(self): + self.bundle() + self.destination.mkdir() + sentinel = self.destination / "trusted" + sentinel.write_text("untouched") + with self.assertRaises(FileExistsError): + self.stage() + self.assertEqual(sentinel.read_text(), "untouched") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b40b3a7cb1e1..f3c062cf9c15a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,8 +5,6 @@ on: push: branches: - main - # Keep v2 checked while its pull request has conflicts with main. - - t3code/codex-turn-mapping permissions: contents: read @@ -115,6 +113,9 @@ jobs: sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config + - name: Test preview artifact validation + run: python3 -B .github/scripts/stage-preview-bundle.test.py + - name: Test nightly release checks run: node --test .github/scripts/check-nightly-release.test.cjs diff --git a/.github/workflows/desktop-macos-preview-publish.yml b/.github/workflows/desktop-macos-preview-publish.yml new file mode 100644 index 0000000000000..4d141e327c1f7 --- /dev/null +++ b/.github/workflows/desktop-macos-preview-publish.yml @@ -0,0 +1,575 @@ +name: Desktop macOS Preview Publish + +# Trusted half of the macOS preview. Runs from main with secrets and a write +# token, so it must never execute PR code: the PR's JS bundle is only data that +# gets packaged into the app. Everything that runs here (packaging, signing, +# notarization, publishing) is main's code. +# +# Gate, in order: the completed build run belongs to an open PR that still +# carries the preview:mac label and whose head is the built commit, and the PR +# author is trusted by the vouch list. A maintainer applying the label alone is +# not enough, since the bundle gets signed with the Developer ID certificate. +# +# The label is consumed here once the gate passes, so it only ever covers the +# one commit a maintainer applied it to. A later push builds nothing until the +# label is applied again. + +on: + workflow_run: + workflows: [Desktop macOS Preview] + types: [completed] + # The way out: closing the PR deletes its download, and removing the label + # before it is consumed cancels the preview. pull_request_target gives this a + # write token for fork PRs; it never checks out PR code. + pull_request_target: + types: [closed, unlabeled] + +permissions: + contents: read + +jobs: + resolve: + name: Verify preview eligibility + if: >- + github.event_name == 'workflow_run' && + github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion == 'success' + # The build workflow completes for every PR push (its label gate is on the + # job), so this runs often and usually finds nothing. Keep it cheap. + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: read + # write only to consume the label; nothing here runs PR code. + pull-requests: write + outputs: + eligible: ${{ steps.gate.outputs.eligible }} + pr_number: ${{ steps.pr.outputs.pr_number }} + head_sha: ${{ steps.pr.outputs.head_sha }} + version: ${{ steps.version.outputs.version }} + clerk_publishable_key: ${{ steps.version.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ steps.version.outputs.clerk_jwt_template }} + clerk_cli_oauth_client_id: ${{ steps.version.outputs.clerk_cli_oauth_client_id }} + relay_url: ${{ steps.version.outputs.relay_url }} + steps: + - id: pr + name: Resolve the pull request behind the build + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + with: + script: | + const run = context.payload.workflow_run; + const { owner, repo } = context.repo; + + // The build workflow also completes (with every job skipped) for + // label events that are not the preview label. Only a run that + // produced a bundle is worth resolving. + const artifacts = await github.paginate(github.rest.actions.listWorkflowRunArtifacts, { + owner, + repo, + run_id: run.id, + per_page: 100, + }); + const bundles = artifacts.filter((artifact) => artifact.name === "js-bundle" && !artifact.expired); + if (bundles.length !== 1) { + core.info(`Expected one js-bundle artifact; found ${bundles.length}. Skipping.`); + core.setOutput("eligible", "false"); + return; + } + + // workflow_run.pull_requests is empty for fork PRs, so resolve the + // PR from the built commit instead and require exactly one open PR + // from the same head repository and branch. The build baked its + // PR number into the version, so two candidates would mean the + // asset name could belong to either. + const associated = await github.paginate( + github.rest.repos.listPullRequestsAssociatedWithCommit, + { owner, repo, commit_sha: run.head_sha, per_page: 100 }, + ); + const matching = associated.filter( + (candidate) => + candidate.state === "open" && + candidate.head.sha === run.head_sha && + candidate.head.ref === run.head_branch && + candidate.head.repo?.full_name === run.head_repository?.full_name, + ); + if (matching.length !== 1) { + core.info(`Expected one open PR for ${run.head_sha}; found ${matching.length}. Skipping.`); + core.setOutput("eligible", "false"); + return; + } + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: matching[0].number, + }); + + if (pull.state !== "open") { + core.info(`PR #${pull.number} is not open. Skipping.`); + core.setOutput("eligible", "false"); + return; + } + if (pull.head.sha !== run.head_sha) { + core.info(`PR #${pull.number} moved to ${pull.head.sha} after ${run.head_sha} was built. Skipping.`); + core.setOutput("eligible", "false"); + return; + } + if (!pull.labels.some((label) => label.name === "preview:mac")) { + core.info(`PR #${pull.number} no longer carries the preview:mac label. Skipping.`); + core.setOutput("eligible", "false"); + return; + } + + core.setOutput("artifact_id", String(bundles[0].id)); + core.setOutput("eligible", "true"); + core.setOutput("pr_number", String(pull.number)); + core.setOutput("head_sha", pull.head.sha); + core.setOutput("author", pull.user.login); + + # Reads VOUCHED.td from the default branch through the API, so a PR + # cannot vouch for itself. + - id: vouch + name: Check PR author trust + if: steps.pr.outputs.eligible == 'true' + uses: mitchellh/vouch/action/check-user@d66fa29a64600490892131ad87597c30c91fcac4 # v1 + with: + user: ${{ steps.pr.outputs.author }} + allow-fail: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # The label authorized exactly this build, so take it now, before the + # long signing job. Removing it with GITHUB_TOKEN does not fire the + # unlabeled cleanup below (workflow-token events never start runs), so + # the download this run publishes survives. If a maintainer removed the + # label first, that removal wins: the 404 makes this run ineligible. + - id: consume + name: Consume the preview label + if: steps.pr.outputs.eligible == 'true' + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + env: + PR_NUMBER: ${{ steps.pr.outputs.pr_number }} + with: + script: | + try { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: Number(process.env.PR_NUMBER), + name: "preview:mac", + }); + core.setOutput("consumed", "true"); + } catch (error) { + if (error.status !== 404) throw error; + core.info("The preview:mac label was removed before this build could consume it. Skipping."); + core.setOutput("consumed", "false"); + } + + - id: gate + name: Decide eligibility + shell: bash + env: + PR_ELIGIBLE: ${{ steps.pr.outputs.eligible }} + LABEL_CONSUMED: ${{ steps.consume.outputs.consumed }} + VOUCH_STATUS: ${{ steps.vouch.outputs.status }} + AUTHOR: ${{ steps.pr.outputs.author }} + run: | + set -euo pipefail + if [[ "$PR_ELIGIBLE" != "true" || "$LABEL_CONSUMED" != "true" ]]; then + echo "eligible=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + case "$VOUCH_STATUS" in + bot|collaborator|vouched) + echo "Author $AUTHOR is trusted ($VOUCH_STATUS)." + echo "eligible=true" >> "$GITHUB_OUTPUT" + ;; + *) + echo "Author $AUTHOR is not vouched ($VOUCH_STATUS). Add them to .github/VOUCHED.td to allow signed previews." + echo "eligible=false" >> "$GITHUB_OUTPUT" + ;; + esac + + # Same inputs as the build workflow, read from the built commit through + # the contents API as data: the desktop manifest's base version plus the + # build run's number reproduces the version baked into the bundle, and + # .env.example holds the public T3 Connect identifiers the bundle was + # compiled with, which the signed app's passkey entitlement must match. + # Both are validated before they reach a file name or an entitlement. + - id: version + name: Resolve preview version and public configuration + if: steps.gate.outputs.eligible == 'true' + shell: bash + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ steps.pr.outputs.pr_number }} + HEAD_SHA: ${{ steps.pr.outputs.head_sha }} + BUILD_RUN_NUMBER: ${{ github.event.workflow_run.run_number }} + run: | + set -euo pipefail + head_file() { + gh api "repos/${GITHUB_REPOSITORY}/contents/$1?ref=${HEAD_SHA}" --jq '.content' | base64 --decode + } + + base_version="$(head_file apps/desktop/package.json | node -p "JSON.parse(require('fs').readFileSync(0, 'utf8')).version")" + # The committed desktop version is always a plain X.Y.Z; every + # prerelease identifier is added by a release run. Anything else + # would also let a foreign -pr.N. marker into the asset name, which + # is what publish and cleanup key on. + if [[ ! "$base_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Unexpected desktop version '$base_version' at $HEAD_SHA; expected X.Y.Z." >&2 + exit 1 + fi + echo "version=${base_version}-pr.${PR_NUMBER}.${BUILD_RUN_NUMBER}" >> "$GITHUB_OUTPUT" + + head_file .env.example > "$RUNNER_TEMP/head.env.example" + for key in clerk_publishable_key:T3CODE_CLERK_PUBLISHABLE_KEY clerk_jwt_template:T3CODE_CLERK_JWT_TEMPLATE clerk_cli_oauth_client_id:T3CODE_CLERK_CLI_OAUTH_CLIENT_ID relay_url:T3CODE_RELAY_URL; do + output="${key%%:*}" + name="${key##*:}" + value="$(sed -n "s/^${name}=//p" "$RUNNER_TEMP/head.env.example" | head -n 1)" + if [[ ! "$value" =~ ^[A-Za-z0-9._:/-]+$ ]]; then + echo "$name is missing or malformed in .env.example at $HEAD_SHA." >&2 + exit 1 + fi + echo "${output}=${value}" >> "$GITHUB_OUTPUT" + done + + # Only the default-branch revision that owns this workflow supplies the + # validator. Never check out the PR in a workflow_run job. + - name: Checkout trusted artifact validator + if: steps.gate.outputs.eligible == 'true' + shell: bash + env: + CHECKOUT_REF: ${{ github.sha }} + GIT_TERMINAL_PROMPT: "0" + # Anonymous fetch avoids checkout's credential cleanup, which fails on + # orphaned gitlinks in .repos even when that directory is excluded. + run: | + set -euo pipefail + git init . + git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" + git sparse-checkout set .github/scripts + git checkout --detach FETCH_HEAD + + # Fetch the archive as bytes. Extracting it over the checkout, even with + # download-artifact, could replace code that runs with signing secrets. + - name: Download and validate PR JS bundle + if: steps.gate.outputs.eligible == 'true' + shell: bash + env: + GH_TOKEN: ${{ github.token }} + ARTIFACT_ID: ${{ steps.pr.outputs.artifact_id }} + run: | + set -euo pipefail + gh api "repos/${GITHUB_REPOSITORY}/actions/artifacts/${ARTIFACT_ID}/zip" > "$RUNNER_TEMP/js-bundle.zip" + python3 .github/scripts/stage-preview-bundle.py "$RUNNER_TEMP/js-bundle.zip" "$RUNNER_TEMP/js-bundle" + + # Only validated bundle files cross into the signing job's artifact. + - name: Stage JS bundle for packaging + if: steps.gate.outputs.eligible == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: js-bundle + path: ${{ runner.temp }}/js-bundle + if-no-files-found: error + # Re-running this workflow re-uploads under the same run. + overwrite: true + retention-days: 1 + + build: + name: Package and sign macOS arm64 preview + needs: resolve + if: needs.resolve.outputs.eligible == 'true' + concurrency: + group: desktop-macos-preview-${{ needs.resolve.outputs.pr_number }}-build + cancel-in-progress: true + uses: ./.github/workflows/release-desktop.yml + secrets: + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }} + with: + version: ${{ needs.resolve.outputs.version }} + ref: ${{ github.sha }} + release_channel: preview + relay_client_tracing: false + clerk_publishable_key: ${{ needs.resolve.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ needs.resolve.outputs.clerk_jwt_template }} + clerk_cli_oauth_client_id: ${{ needs.resolve.outputs.clerk_cli_oauth_client_id }} + relay_url: ${{ needs.resolve.outputs.relay_url }} + label: macOS arm64 preview + runner: blacksmith-12vcpu-macos-26 + platform: mac + target: dmg + arch: arm64 + rust_target: aarch64-apple-darwin + resource_key: darwin-arm64 + cli_archive: false + + # Release assets download without a GitHub account, unlike workflow + # artifacts. All preview DMGs live on one rolling prerelease tagged + # "desktop-preview" (release.yml only matches v*.*.* tags), so publishing a + # build never notifies release watchers. + publish: + name: Publish anonymous download + needs: [resolve, build] + if: needs.resolve.outputs.eligible == 'true' && needs.build.result == 'success' + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 10 + # Its own group, so a publish never cancels a newer commit's signing job + # (they would share the build group) and is never cancelled mid-upload. + # preview_eligible's head check keeps a superseded publish from landing. + concurrency: + group: desktop-macos-preview-${{ needs.resolve.outputs.pr_number }}-publish + cancel-in-progress: false + permissions: + contents: write + pull-requests: write + steps: + - name: Download macOS artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: desktop-mac-arm64 + path: release + + - id: upload + name: Upload DMG to the rolling preview release + shell: bash + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ needs.resolve.outputs.pr_number }} + HEAD_SHA: ${{ needs.resolve.outputs.head_sha }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + set -euo pipefail + + tag="desktop-preview" + + # True while the PR is open and still points at the commit this + # build came from. The label was consumed in resolve, so it is not + # part of this check. A push does not cancel an already-running + # signing job, so this is what keeps a superseded commit's DMG off + # the release. + preview_eligible() { + [[ "$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" \ + --json state,headRefOid \ + --jq '.state + " " + .headRefOid')" == "OPEN $HEAD_SHA" ]] + } + + # The build ran for many minutes. If the PR closed or moved on + # meanwhile, cleanup already ran in its own concurrency group or a + # newer build owns the asset, so publishing now would resurrect a + # deleted download or clobber a newer one. + if ! preview_eligible; then + echo "PR closed or head moved while building. Skipping publish." + exit 0 + fi + + shopt -s nullglob + dmg_files=(release/*.dmg) + if (( ${#dmg_files[@]} != 1 )); then + printf 'Expected one DMG, found %s.\n' "${#dmg_files[@]}" >&2 + exit 1 + fi + dmg_path="${dmg_files[0]}" + + # Requiring this PR's marker keeps a build from clobbering or + # deleting another PR's asset, since those names carry a different + # -pr.N. marker. + if [[ "$(basename "$dmg_path")" != *"-pr.${PR_NUMBER}."* ]]; then + echo "DMG name '$(basename "$dmg_path")' does not carry this PR's -pr.${PR_NUMBER}. marker. Refusing to publish." >&2 + exit 1 + fi + + if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + # "|| true" tolerates a concurrent publish job creating the + # release between the check and the create. + gh release create "$tag" \ + --repo "$GITHUB_REPOSITORY" \ + --target "$DEFAULT_BRANCH" \ + --prerelease \ + --title "Desktop preview builds" \ + --notes "Rolling desktop builds from pull requests with a preview label. Each download is removed when its pull request closes or loses the label. Install stable builds from the latest release instead." \ + || true + fi + + # Keep one DMG per PR: drop this PR's older builds first. The + # trailing dot keeps -pr.12. from matching -pr.123. builds. + gh release view "$tag" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' \ + | { grep -F -- "-pr.${PR_NUMBER}." || true; } \ + | while read -r asset; do + gh release delete-asset "$tag" "$asset" --repo "$GITHUB_REPOSITORY" --yes \ + || echo "Asset $asset was already removed by a concurrent run." + done + + gh release upload "$tag" "$dmg_path" --repo "$GITHUB_REPOSITORY" --clobber + + # Re-check after uploading. A cleanup run that started during the + # upload listed assets before ours existed, so it cannot delete it. + # Whichever writer acts last sees the final PR state; if the preview + # became ineligible, delete what we just uploaded. + if ! preview_eligible; then + gh release delete-asset "$tag" "$(basename "$dmg_path")" --repo "$GITHUB_REPOSITORY" --yes \ + || echo "Asset was already removed by a concurrent run." + echo "PR closed or head moved during upload. Removed the download." + exit 0 + fi + + echo "dmg_name=$(basename "$dmg_path")" >> "$GITHUB_OUTPUT" + echo "download_url=https://github.com/${GITHUB_REPOSITORY}/releases/download/${tag}/$(basename "$dmg_path")" >> "$GITHUB_OUTPUT" + + - name: Comment download link + if: steps.upload.outputs.download_url != '' + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + env: + PR_NUMBER: ${{ needs.resolve.outputs.pr_number }} + DOWNLOAD_URL: ${{ steps.upload.outputs.download_url }} + HEAD_SHA: ${{ needs.resolve.outputs.head_sha }} + PREVIEW_VERSION: ${{ needs.resolve.outputs.version }} + with: + script: | + const prNumber = Number(process.env.PR_NUMBER); + const { data: pullRequest } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber, + }); + if (pullRequest.head.sha !== process.env.HEAD_SHA || pullRequest.state !== "open") { + core.info("Skipping the outdated macOS preview comment."); + return; + } + + const marker = ""; + const body = [ + marker, + "### macOS preview", + "", + `[Download Apple Silicon DMG](${process.env.DOWNLOAD_URL})`, + "", + `Version: ${process.env.PREVIEW_VERSION}`, + `Commit: ${process.env.HEAD_SHA.slice(0, 7)}`, + "", + "Signed and notarized, with T3 Connect enabled. The app bundle (server, web client, Electron main) is built from this PR; packaging, native helpers, and desktop dependencies come from `main`.", + "", + "No GitHub sign-in is needed. The download stays available until this PR closes. The `preview:mac` label was consumed by this build; a maintainer applies it again to build a newer commit.", + ].join("\n"); + + const comments = await github.paginate(github.rest.issues.listComments, { + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + per_page: 100, + }); + const existing = comments.find( + (comment) => comment.user?.login === "github-actions[bot]" && 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: prNumber, + body, + }); + } + + cleanup: + name: Remove preview download + # A published preview no longer carries the label (resolve consumed it), + # so every close must look for assets; the -pr.N. filter below makes + # that a cheap no-op for PRs that never had one. A manual unlabel before + # the build consumed it withdraws the request and drops any older + # download too. + if: >- + github.event_name == 'pull_request_target' && + (github.event.action == 'closed' || + (github.event.action == 'unlabeled' && github.event.label.name == 'preview:mac')) + # Runs on every PR close and usually finds nothing. Keep it cheap. + runs-on: ubuntu-24.04 + timeout-minutes: 10 + # Cleanup runs must complete: a close event right after an unlabel queues + # behind the running cleanup instead of canceling it mid-delete. + concurrency: + group: desktop-macos-preview-${{ github.event.pull_request.number }}-cleanup + cancel-in-progress: false + permissions: + contents: write + pull-requests: write + steps: + - id: delete + name: Delete this PR's preview assets + shell: bash + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + set -euo pipefail + + tag="desktop-preview" + + # A stale cleanup must not delete a download that became valid + # again. If the PR is open and labeled once more, the next publish + # owns this PR's assets and replaces them itself. + if [[ "$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" \ + --json state,labels \ + --jq '.state + " " + (.labels | map(.name) | contains(["preview:mac"]) | tostring)')" == "OPEN true" ]]; then + echo "PR is open and labeled again. Skipping cleanup." + echo "removed=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + echo "removed=true" >> "$GITHUB_OUTPUT" + + if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "No preview release exists. Nothing to clean up." + exit 0 + fi + + gh release view "$tag" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' \ + | { grep -F -- "-pr.${PR_NUMBER}." || true; } \ + | while read -r asset; do + gh release delete-asset "$tag" "$asset" --repo "$GITHUB_REPOSITORY" --yes \ + || echo "Asset $asset was already removed by a concurrent run." + done + + - name: Mark the preview comment as removed + if: steps.delete.outputs.removed == 'true' + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + with: + script: | + const marker = ""; + const comments = await github.paginate(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.user?.login === "github-actions[bot]" && comment.body?.includes(marker), + ); + if (!existing) { + return; + } + + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existing.id, + body: [ + marker, + "### macOS preview", + "", + "The preview download was removed because this PR closed or the preview label was removed.", + ].join("\n"), + }); diff --git a/.github/workflows/desktop-macos-preview.yml b/.github/workflows/desktop-macos-preview.yml index 7875aec6f36b0..43b6c8220aaf3 100644 --- a/.github/workflows/desktop-macos-preview.yml +++ b/.github/workflows/desktop-macos-preview.yml @@ -1,74 +1,67 @@ name: Desktop macOS Preview +# Untrusted half of the macOS preview. This runs PR code (including fork PRs) +# with a read-only token and no secrets, and only produces the JS bundle. The +# trusted half, desktop-macos-preview-publish.yml, runs on workflow_run from +# main, verifies the PR author is vouched, then packages, signs, notarizes, and +# publishes the bundle without ever executing it. +# +# The label is a one-shot request for the commit it was applied to, not a +# standing subscription: the trusted half removes it once this run completes, +# and later pushes do not build until a maintainer applies it again. Each +# signed preview is therefore an explicit per-commit decision. +# +# Closing the PR is handled by the publish workflow too, since deleting the +# download needs a write token. + on: pull_request: - types: [labeled, unlabeled, synchronize, reopened, closed] + types: [labeled] permissions: contents: read -# Build events and cleanup events use separate groups: a push must cancel a -# stale in-flight build, but must never cancel a cleanup run mid-delete. The -# publish job re-checks PR state before uploading to cover the reverse race. concurrency: - group: desktop-macos-preview-${{ github.event.pull_request.number }}-${{ contains(fromJSON('["closed", "unlabeled"]'), github.event.action) && 'cleanup' || 'build' }} - # Cleanup runs must complete (a close event right after an unlabel queues - # behind the running cleanup instead of canceling it mid-delete), and events - # that skip the build job, such as adding an unrelated label, must not - # cancel an in-flight build either. - cancel-in-progress: ${{ !contains(fromJSON('["closed", "unlabeled"]'), github.event.action) && (github.event.action != 'labeled' || github.event.label.name == 'preview:mac') }} + group: desktop-macos-preview-${{ github.event.pull_request.number }} + # Adding an unrelated label skips the job and must not cancel a build. + cancel-in-progress: ${{ github.event.label.name == 'preview:mac' }} jobs: - # Builds run PR code, so this job keeps a read-only token. Publishing to the - # release happens in the publish job below, which never checks out PR code. build: - name: Build macOS Apple Silicon preview - if: >- - github.event.action != 'closed' && - github.event.action != 'unlabeled' && - github.event.pull_request.head.repo.full_name == github.repository && - contains(github.event.pull_request.labels.*.name, 'preview:mac') && - (github.event.action != 'labeled' || github.event.label.name == 'preview:mac') - runs-on: blacksmith-12vcpu-macos-26 + name: Build preview JS bundle + if: github.event.label.name == 'preview:mac' + runs-on: blacksmith-32vcpu-ubuntu-2404 timeout-minutes: 30 - outputs: - dmg_name: ${{ steps.build.outputs.dmg_name }} - version: ${{ steps.version.outputs.version }} steps: + # This repository is public, so Git needs no credentials. checkout's + # credential cleanup runs submodule foreach even with submodules disabled, + # which fails on the orphaned gitlinks in our vendored .repos tree. - name: Checkout - uses: actions/checkout@v6 - with: - ref: ${{ github.event.pull_request.head.sha }} - sparse-checkout: | - /* - !/.repos/ - sparse-checkout-cone-mode: false + shell: bash + env: + CHECKOUT_REF: ${{ github.event.pull_request.head.sha }} + GIT_TERMINAL_PROMPT: "0" + run: | + set -euo pipefail + git init . + git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" + git sparse-checkout set --no-cone '/*' '!/.repos/' + git checkout --detach FETCH_HEAD - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 with: node-version-file: package.json cache: true run-install: false - - name: Install desktop dependencies - run: vp install --filter=@t3tools/desktop... --filter=t3... --filter=@t3tools/scripts... - - - name: Cache resource monitor - id: resource_monitor_cache - uses: actions/cache@v6 - with: - path: native/resource-monitor/target/aarch64-apple-darwin/release/t3-resource-monitor - key: resource-monitor-aarch64-apple-darwin-${{ hashFiles('native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }} - - - name: Setup Rust - if: steps.resource_monitor_cache.outputs.cache-hit != 'true' - uses: dtolnay/rust-toolchain@stable - with: - targets: aarch64-apple-darwin + - name: Install bundle dependencies + run: vp install --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... - - id: version - name: Set preview version and public configuration + # The publish workflow derives the same version from this run's number, + # so the version baked into the bundle matches the packaged app. + - name: Set preview version and public configuration shell: bash env: PR_NUMBER: ${{ github.event.pull_request.number }} @@ -76,286 +69,26 @@ jobs: set -euo pipefail base_version="$(node -p "require('./apps/desktop/package.json').version")" - preview_version="${base_version}-pr.${PR_NUMBER}.${GITHUB_RUN_NUMBER}" - node scripts/update-release-package-versions.ts "$preview_version" + node scripts/update-release-package-versions.ts "${base_version}-pr.${PR_NUMBER}.${GITHUB_RUN_NUMBER}" + # Public T3 Connect identifiers (Clerk publishable key, relay URL). cp .env.example .env - echo "version=$preview_version" >> "$GITHUB_OUTPUT" - - - id: build - name: Build unsigned macOS DMG - shell: bash - env: - T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: ${{ steps.resource_monitor_cache.outputs.cache-hit == 'true' }} - PREVIEW_VERSION: ${{ steps.version.outputs.version }} - run: | - set -euo pipefail + - uses: ./.github/actions/setup-apt-mirrors - vp run dist:desktop:artifact \ - --platform mac \ - --target dmg \ - --arch arm64 \ - --build-version "$PREVIEW_VERSION" \ - --verbose + - name: Install browser secret helper build libraries + run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config - shopt -s nullglob - dmg_files=(release/*.dmg) - if (( ${#dmg_files[@]} != 1 )); then - printf 'Expected one DMG, found %s.\n' "${#dmg_files[@]}" >&2 - exit 1 - fi - printf 'dmg_name=%s\n' "$(basename "${dmg_files[0]}")" >> "$GITHUB_OUTPUT" + - name: Build JS bundle + run: vp run build:desktop - # archive: false uploads the file as its own artifact named after the - # file, so the publish job downloads by *.dmg pattern, not by name. - - name: Upload macOS DMG - uses: actions/upload-artifact@v7 + # Same layout as release.yml's js-bundle so release-desktop.yml can + # package it unchanged. + - name: Upload JS bundle + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: - path: release/*.dmg + name: js-bundle + path: | + apps/server/dist + apps/desktop/dist-electron if-no-files-found: error - archive: false - overwrite: true - retention-days: 7 - - # Release assets download without a GitHub account, unlike workflow - # artifacts. All preview DMGs live on one rolling prerelease tagged - # "desktop-preview" (release.yml only matches v*.*.* tags), so publishing a - # build never notifies release watchers. This job holds the write token and - # only handles the artifact the build job produced; it never runs PR code. - publish: - name: Publish anonymous download - needs: build - runs-on: blacksmith-8vcpu-ubuntu-2404 - timeout-minutes: 10 - permissions: - contents: write - pull-requests: write - steps: - - name: Download macOS DMG - uses: actions/download-artifact@v8 - with: - pattern: "*.dmg" - merge-multiple: true - path: release - - - id: upload - name: Upload DMG to the rolling preview release - shell: bash - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ github.event.pull_request.number }} - DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} - run: | - set -euo pipefail - - tag="desktop-preview" - - # True while the PR is open and still carries the preview label. - preview_eligible() { - [[ "$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" \ - --json state,labels \ - --jq '.state + " " + (.labels | map(.name) | contains(["preview:mac"]) | tostring)')" == "OPEN true" ]] - } - - # The build ran for many minutes. If the PR closed or lost the label - # meanwhile, cleanup already ran in its own concurrency group, so - # publishing now would resurrect a deleted download. - if ! preview_eligible; then - echo "PR closed or preview label removed while building. Skipping publish." - exit 0 - fi - - dmg_path="$(find release -type f -name '*.dmg' -print -quit)" - if [[ -z "$dmg_path" ]]; then - echo "No DMG found in the downloaded artifact." >&2 - exit 1 - fi - - # The filename comes out of the build, which runs PR code. Requiring - # this PR's marker keeps a build from clobbering or deleting another - # PR's asset, since those names carry a different -pr.N. marker. - if [[ "$(basename "$dmg_path")" != *"-pr.${PR_NUMBER}."* ]]; then - echo "DMG name '$(basename "$dmg_path")' does not carry this PR's -pr.${PR_NUMBER}. marker. Refusing to publish." >&2 - exit 1 - fi - - if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then - # "|| true" tolerates a concurrent publish job creating the - # release between the check and the create. - gh release create "$tag" \ - --repo "$GITHUB_REPOSITORY" \ - --target "$DEFAULT_BRANCH" \ - --prerelease \ - --title "Desktop preview builds" \ - --notes "Rolling unsigned desktop builds from pull requests with a preview label. Each download is removed when its pull request closes or loses the label. Install stable builds from the latest release instead." \ - || true - fi - - # Keep one DMG per PR: drop this PR's older builds first. The - # trailing dot keeps -pr.12. from matching -pr.123. builds. - gh release view "$tag" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' \ - | { grep -F -- "-pr.${PR_NUMBER}." || true; } \ - | while read -r asset; do - gh release delete-asset "$tag" "$asset" --repo "$GITHUB_REPOSITORY" --yes \ - || echo "Asset $asset was already removed by a concurrent run." - done - - gh release upload "$tag" "$dmg_path" --repo "$GITHUB_REPOSITORY" --clobber - - # Re-check after uploading. A cleanup run that started during the - # upload listed assets before ours existed, so it cannot delete it. - # Whichever writer acts last sees the final PR state; if the preview - # became ineligible, delete what we just uploaded. - if ! preview_eligible; then - gh release delete-asset "$tag" "$(basename "$dmg_path")" --repo "$GITHUB_REPOSITORY" --yes \ - || echo "Asset was already removed by a concurrent run." - echo "PR closed or preview label removed during upload. Removed the download." - exit 0 - fi - - echo "download_url=https://github.com/${GITHUB_REPOSITORY}/releases/download/${tag}/$(basename "$dmg_path")" >> "$GITHUB_OUTPUT" - - - name: Comment download link - if: steps.upload.outputs.download_url != '' - uses: actions/github-script@v8 - env: - DOWNLOAD_URL: ${{ steps.upload.outputs.download_url }} - DMG_NAME: ${{ needs.build.outputs.dmg_name }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PREVIEW_VERSION: ${{ needs.build.outputs.version }} - with: - script: | - const { data: pullRequest } = await github.rest.pulls.get({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: context.payload.pull_request.number, - }); - if ( - pullRequest.head.sha !== process.env.HEAD_SHA || - pullRequest.state !== "open" || - !pullRequest.labels.some((label) => label.name === "preview:mac") - ) { - core.info("Skipping the outdated macOS preview comment."); - return; - } - - const marker = ""; - const body = [ - marker, - "### macOS preview", - "", - `[Download Apple Silicon DMG](${process.env.DOWNLOAD_URL})`, - "", - `Version: ${process.env.PREVIEW_VERSION}`, - `Commit: ${process.env.HEAD_SHA.slice(0, 7)}`, - "", - "Unsigned build. Clear quarantine before opening:", - "```sh", - `xattr -d com.apple.quarantine ~/Downloads/${process.env.DMG_NAME}`, - "```", - "", - "No GitHub sign-in is needed. The download stays available until this PR closes or the preview label is removed.", - ].join("\n"); - - const comments = await github.paginate(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, - }); - } - - # The way out: closing the PR or removing the label deletes its DMG from the - # rolling release and updates the PR comment to say so. - cleanup: - name: Remove preview download - if: >- - github.event.pull_request.head.repo.full_name == github.repository && - ((github.event.action == 'closed' && contains(github.event.pull_request.labels.*.name, 'preview:mac')) || - (github.event.action == 'unlabeled' && github.event.label.name == 'preview:mac')) - runs-on: blacksmith-8vcpu-ubuntu-2404 - timeout-minutes: 10 - permissions: - contents: write - pull-requests: write - steps: - - id: delete - name: Delete this PR's preview assets - shell: bash - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - set -euo pipefail - - tag="desktop-preview" - - # A stale cleanup must not delete a download that became valid - # again. If the PR is open and labeled once more, the next publish - # owns this PR's assets and replaces them itself. - if [[ "$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" \ - --json state,labels \ - --jq '.state + " " + (.labels | map(.name) | contains(["preview:mac"]) | tostring)')" == "OPEN true" ]]; then - echo "PR is open and labeled again. Skipping cleanup." - echo "removed=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - echo "removed=true" >> "$GITHUB_OUTPUT" - - if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then - echo "No preview release exists. Nothing to clean up." - exit 0 - fi - - gh release view "$tag" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' \ - | { grep -F -- "-pr.${PR_NUMBER}." || true; } \ - | while read -r asset; do - gh release delete-asset "$tag" "$asset" --repo "$GITHUB_REPOSITORY" --yes \ - || echo "Asset $asset was already removed by a concurrent run." - done - - - name: Mark the preview comment as removed - if: steps.delete.outputs.removed == 'true' - uses: actions/github-script@v8 - with: - script: | - const marker = ""; - const comments = await github.paginate(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) { - return; - } - - await github.rest.issues.updateComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: existing.id, - body: [ - marker, - "### macOS preview", - "", - "The preview download was removed because this PR closed or the preview label was removed.", - ].join("\n"), - }); + retention-days: 1 diff --git a/.github/workflows/fold-desktop-release.yml b/.github/workflows/fold-desktop-release.yml index 51f704d045dc0..619dca3da826d 100644 --- a/.github/workflows/fold-desktop-release.yml +++ b/.github/workflows/fold-desktop-release.yml @@ -115,13 +115,25 @@ jobs: run: node scripts/publish-fold-desktop.ts release-assets "$RELEASE_TAG" "$FOLD_VERSION" "$PUBLISH_MODE" wsl: if: github.repository == 'BreakTheBeta/T3codefold' && (inputs.platform == 'all' || inputs.platform == 'win') - uses: ./.github/workflows/fold-cli-archive.yml - with: - runner: ubuntu-24.04 - platform: linux - arch: x64 - version: ${{ inputs.version }} - artifact_name: fold-wsl-runtime + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + run-install: true + - name: Build WSL terminal binding + shell: bash + run: | + pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['./apps/server'] }))")" + pty_dir="$(dirname "$pty_pkg")" + (cd "$pty_dir" && npx --yes node-gyp rebuild) + mkdir -p wsl-prebuild + cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node + - uses: actions/upload-artifact@v7 + with: + name: fold-wsl-pty + path: wsl-prebuild/pty.node windows: if: ${{ !cancelled() && needs.wsl.result == 'success' && (needs.server.result == 'success' || (inputs.desktop_only && needs.server.result == 'skipped')) }} needs: [wsl, server] @@ -145,8 +157,8 @@ jobs: rustup override set 1.95.0 - uses: actions/download-artifact@v8 with: - name: fold-wsl-runtime - path: wsl-runtime + name: fold-wsl-pty + path: wsl-prebuild - name: Install Spectre-mitigated MSVC libs shell: pwsh run: | @@ -168,7 +180,7 @@ jobs: env: FOLD_VERSION: ${{ inputs.version }} run: | - node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64 --build-version "$env:FOLD_VERSION" --output-dir release-assets --wsl-runtime (Get-ChildItem wsl-runtime/t3-*-linux-x64.tar.gz | Select-Object -First 1).FullName --verbose + node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64 --build-version "$env:FOLD_VERSION" --output-dir release-assets --wsl-prebuild wsl-prebuild/pty.node --verbose if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - uses: actions/upload-artifact@v7 with: diff --git a/.github/workflows/fold-server-release.yml b/.github/workflows/fold-server-release.yml index 8aa16fd6067bd..1392428597102 100644 --- a/.github/workflows/fold-server-release.yml +++ b/.github/workflows/fold-server-release.yml @@ -25,26 +25,7 @@ concurrency: group: fold-server-release cancel-in-progress: false jobs: - archives: - if: github.repository == 'BreakTheBeta/T3codefold' - strategy: - fail-fast: false - matrix: - include: - - { runner: ubuntu-24.04, platform: linux, arch: x64, key: linux-x64 } - - { runner: ubuntu-24.04-arm, platform: linux, arch: arm64, key: linux-arm64 } - - { runner: macos-15, platform: mac, arch: arm64, key: darwin-arm64 } - - { runner: windows-2025, platform: win, arch: x64, key: win32-x64 } - - { runner: windows-11-arm, platform: win, arch: arm64, key: win32-arm64 } - uses: ./.github/workflows/fold-cli-archive.yml - with: - runner: ${{ matrix.runner }} - platform: ${{ matrix.platform }} - arch: ${{ matrix.arch }} - version: ${{ inputs.version }} - artifact_name: fold-cli-${{ matrix.key }} release: - needs: archives if: github.repository == 'BreakTheBeta/T3codefold' runs-on: ubuntu-24.04 steps: @@ -89,11 +70,10 @@ jobs: if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then published_commit="$(gh release view "$tag" --repo "$GITHUB_REPOSITORY" --json targetCommitish --jq .targetCommitish)" test "$published_commit" = "$GITHUB_SHA" || { echo "Version already belongs to another commit" >&2; exit 1; } - gh release download "$tag" --repo "$GITHUB_REPOSITORY" --dir published - (cd published && sha256sum -c SHA256SUMS) + gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern "t3-$version.tgz" --dir published cp "published/t3-$version.tgz" "release-assets/t3-$version.tgz" else - gh release create "$tag" release-assets/* --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "Fold server $version" --notes "Fold server and web client. Install a self-contained CLI archive, or use the npm-compatible tarball for older launchers." --prerelease + gh release create "$tag" "release-assets/t3-$version.tgz" --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "Fold server $version" --notes "Fold server and web client. Install using the attached npm-compatible tarball." --prerelease fi cp "release-assets/t3-$version.tgz" release-assets/t3.tgz channel_tag="fold-server-$CHANNEL" diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 5d790e49a061f..c374a8692db6c 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -8,6 +8,33 @@ name: Release desktop build on: workflow_call: + secrets: + CSC_LINK: + required: false + CSC_KEY_PASSWORD: + required: false + APPLE_API_KEY: + required: false + APPLE_API_KEY_ID: + required: false + APPLE_API_ISSUER: + required: false + MACOS_PROVISIONING_PROFILE: + required: false + AZURE_TENANT_ID: + required: false + AZURE_CLIENT_ID: + required: false + AZURE_CLIENT_SECRET: + required: false + AZURE_TRUSTED_SIGNING_ENDPOINT: + required: false + AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: + required: false + AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: + required: false + AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: + required: false inputs: label: required: true @@ -46,6 +73,12 @@ on: release_channel: required: true type: string + # Whether a `relay-client-tracing-config` artifact from the production + # relay state is expected. PR previews carry no tracing config. + relay_client_tracing: + required: false + default: true + type: boolean clerk_publishable_key: required: true type: string @@ -73,17 +106,24 @@ jobs: T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ inputs.clerk_cli_oauth_client_id }} T3CODE_RELAY_URL: ${{ inputs.relay_url }} steps: + # This repository is public, so Git needs no credentials. checkout's + # credential cleanup runs submodule foreach even with submodules disabled, + # which fails on the orphaned gitlinks in our vendored .repos tree. - name: Checkout - uses: actions/checkout@v6 - with: - ref: ${{ inputs.ref }} - sparse-checkout: | - /* - !/.repos/ - sparse-checkout-cone-mode: false + shell: bash + env: + CHECKOUT_REF: ${{ inputs.ref }} + GIT_TERMINAL_PROMPT: "0" + run: | + set -euo pipefail + git init . + git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" + git sparse-checkout set --no-cone '/*' '!/.repos/' + git checkout --detach FETCH_HEAD - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 with: node-version-file: package.json cache: ${{ inputs.platform != 'win' }} @@ -97,7 +137,7 @@ jobs: - name: Cache Windows packages if: inputs.platform == 'win' - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: path: ${{ steps.package_cache_path.outputs.path }} key: windows-release-packages-v1-${{ inputs.arch }}-${{ hashFiles('pnpm-lock.yaml') }} @@ -106,7 +146,7 @@ jobs: # artifact leaves the cache empty, so installation runs the checks again. - name: Download dependency verification continue-on-error: true - uses: actions/download-artifact@v8 + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: name: release-dependency-verification path: ${{ runner.temp }}/pnpm-metadata @@ -118,7 +158,7 @@ jobs: - name: Cache resource monitor id: resource_monitor_cache - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: path: native/resource-monitor/target/${{ inputs.rust_target }}/release/t3-resource-monitor${{ inputs.platform == 'win' && '.exe' || '' }} key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }} @@ -126,7 +166,7 @@ jobs: - name: Cache Linux capture helpers if: inputs.platform == 'linux' id: capture_helper_cache - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: path: | native/kde-snap-shot/target/${{ inputs.rust_target }}/release/t3-kde-snap-shot @@ -135,17 +175,20 @@ jobs: - name: Setup Rust if: steps.resource_monitor_cache.outputs.cache-hit != 'true' || (inputs.platform == 'linux' && steps.capture_helper_cache.outputs.cache-hit != 'true') - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable with: + toolchain: stable targets: ${{ inputs.rust_target }} - name: Download relay client tracing config - uses: actions/download-artifact@v8 + if: inputs.relay_client_tracing + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: name: relay-client-tracing-config path: ${{ runner.temp }}/relay-client-tracing - name: Load relay client tracing config + if: inputs.relay_client_tracing shell: bash run: | config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env" @@ -160,7 +203,7 @@ jobs: # ancestor of its paths), so extracting into `apps` restores # apps/server/dist and apps/desktop/dist-electron at their build paths. - name: Download JS bundle - uses: actions/download-artifact@v8 + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: name: js-bundle path: apps @@ -169,7 +212,7 @@ jobs: # Windows desktop embeds the same-arch archive the release attaches. - name: Download Linux CLI archive for WSL if: inputs.platform == 'win' - uses: actions/download-artifact@v8 + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: name: cli-linux-${{ inputs.arch }} path: wsl-runtime @@ -450,7 +493,7 @@ jobs: - name: Upload CLI archive if: inputs.cli_archive - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: cli-${{ inputs.platform }}-${{ inputs.arch }} path: release-cli/* @@ -514,14 +557,14 @@ jobs: cp "$source_path" "$target_dir/$binary_name" - name: Upload build artifacts - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: desktop-${{ inputs.platform }}-${{ inputs.arch }} path: release-publish/* if-no-files-found: error - name: Upload resource monitor - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: resource-monitor-${{ inputs.resource_key }} path: resource-monitor-publish/${{ inputs.resource_key }}/* diff --git a/.gitignore b/.gitignore index 8482c5a290e13..38bac103f1f41 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,7 @@ squashfs-root/ .vercel .gstack/ .plans/ +/audits/ dist-electron/ .electron-runtime/ .showcase/ diff --git a/.macroscope/check-run-agents/effect-service-conventions.md b/.macroscope/check-run-agents/effect-service-conventions.md index 8ed88559cfd8c..e38c0b040af04 100644 --- a/.macroscope/check-run-agents/effect-service-conventions.md +++ b/.macroscope/check-run-agents/effect-service-conventions.md @@ -12,14 +12,11 @@ include: - "infra/**/*.ts" exclude: - "**/*.test.ts" -labels: - - vouch:trusted - - macroscope-review requires: - Check maxBudgetPerRun: 5 maxBudgetPerPR: 25 -conclusion: failure +conclusion: neutral showToolCalls: true --- diff --git a/.macroscope/check-run-agents/ui-consistency.md b/.macroscope/check-run-agents/ui-consistency.md index 87285d7b08819..b90c81ab0a499 100644 --- a/.macroscope/check-run-agents/ui-consistency.md +++ b/.macroscope/check-run-agents/ui-consistency.md @@ -11,14 +11,11 @@ include: - "apps/web/src/**/*.css" exclude: - "apps/web/src/**/*.test.tsx" -labels: - - vouch:trusted - - macroscope-review requires: - Check maxBudgetPerRun: 2 maxBudgetPerPR: 10 -conclusion: failure +conclusion: neutral --- # UI consistency review diff --git a/README.md b/README.md index 25a6f71f81482..bb99396260d9e 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,18 @@ T3 Code Fold extends [T3 Code](https://github.com/pingdotgg/t3code) with a folda ## Extra features -Compared with upstream `main` at [08463e2c40](https://github.com/pingdotgg/t3code/commit/08463e2c40), reviewed **9 September 2026**. These tables describe the code on Fold's `main`; an older published installer may not include every change. +| Difference | What Fold adds / how to use it | Upstream comparison and retirement condition | +| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Live GPT/Codex voice** | Talk with Codex from web, desktop, or mobile. Includes voice selection, transcripts, separate microphone/speaker mute, microphone selection, keyboard controls, calls that survive navigation, optional bounded file/diff/question context, and spoken end/task switching. Switching reconnects audio; screen capture is not included. See [voice setup](docs/user/providers-codex.md#talk-to-codex-fold-beta). | Compare upstream realtime controls, thread ownership, context sharing, idle-session resumption, and all client surfaces before retiring these changes. Voice choices follow the host CLI; experimental APIs can change. | +| **Background Android calls and system audio** | Keep talking with the screen locked, end calls from the ongoing notification, recover from brief network interruptions, and use speakerphone or Bluetooth call-capable headsets/glasses through Core-Telecom. Meta Ray-Ban audio still needs physical-device verification. | Retire the Android additions only when upstream voice covers background lifetime, system call controls, microphone routing, and recovery. | +| **Project colours and icons on mobile** | Mobile displays automatic project colours, custom icons, and emoji selected on desktop when connected to the same host. | Upstream already has desktop/web project styling; Fold shares its icon model with mobile. Replace when upstream mobile renders the same settings consistently. | +| **Foldable workspace and resizable panes** | Keep chat beside Files, Terminal, or Git on an unfolded Android phone. Drag the divider to give either pane more room, down to a compact sliver. | Builds on upstream's adaptive layout. Compare fold/unfold resizing, pane limits, and persistent chat visibility before dropping Fold's layout changes. | +| **Fold-aware navigation** | Selected tool states, reversible sidebar controls, and Android Back behavior work with the split workspace. | Compare upstream navigation with both panes open, including opening, closing, and returning from tools. | +| **Selectable Android output and clickable links** | Select and copy across Markdown paragraphs, lists, and tables; open links directly from responses. | Extends the Android Markdown rendering path. Retire when upstream supports selection across mixed content and link activation together. | +| **Android completion notifications** | Enable notifications in mobile Settings to hear when work finishes while the app remains connected in the background. | Upstream's iOS notification support is shared foundation, not a Fold feature. Compare Android background delivery and thread navigation; this is not disconnected push delivery. | +| **Optional Cite selection bubble** | In web or desktop, turn off **Settings → General → Show Cite on text selection** to stop the Cite bubble appearing when selecting assistant text. Enabled by default; saved per client. | The Cite feature itself is upstream. Fold adds its opt-out. Replace when upstream provides an equivalent preference, preserving saved choices. | +| **Isolated Android preview and GitHub updates** | The preview installs alongside the Play Store app and uses Fold's own update source. Compatible JavaScript updates are published through GitHub; runtime fingerprints keep native revisions separate. See the [mobile build configuration](apps/mobile/app.config.ts) and [update publisher](scripts/publish-mobile-github-ota.ts). | Keep fork identity and update isolation while distributing Fold builds. Reuse upstream update mechanisms only if they preserve that separation. | +| **Fold Windows desktop releases** | A dedicated [release workflow](.github/workflows/fold-desktop-release.yml) builds Windows installers with WSL terminal support, installs native build prerequisites, and keeps packaging diagnostics out of release downloads. | Fork release destinations remain intentional. Drop individual build workarounds when equivalent upstream packaging is verified. | ### Agents, voice, and compatibility @@ -66,7 +77,7 @@ Fold also includes [upstream's orchestration work](https://github.com/pingdotgg/ Upgrading an older server also migrates its conversation transcripts into the new runtime. Read [older-thread migration](docs/user/thread-migration.md) for what carries over and how sessions resume. -Upstream already supplies the core clients, remote connections, provider support, voice dictation, source-control tools, and much of the project styling. The September 9 sync also includes desktop window capture, question-answer attachments, Android wallpaper colors and optional Material You layout, minimap turn navigation, and pull-request merge defaults. These are shared upstream features, not Fold-only additions. The tables above describe Fold's additions or extensions to that foundation. Recheck them after upstream merges overlapping functionality; Pebble's separate watch app and its legacy compatibility branch are not features of this main branch. +Upstream already supplies the core clients, remote connections, provider support, voice dictation, source-control tools, and much of the project styling. The tables above describe Fold's additions or extensions to that foundation. Recheck them after upstream merges overlapping functionality; Pebble's separate watch app and its legacy compatibility branch are not features of this main branch. ## Foldable demo diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs index eedfff9744f8a..48f66ab76b560 100644 --- a/apps/desktop/scripts/electron-launcher.mjs +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -116,6 +116,8 @@ export function makeDevelopmentEnvironmentScript(environment) { ["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH], ["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL], ["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS], + ["T3CODE_OTLP_HEADERS", environment.T3CODE_OTLP_HEADERS], + ["T3CODE_OTLP_PROTOCOL", environment.T3CODE_OTLP_PROTOCOL], ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID], ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0); return [ diff --git a/apps/desktop/scripts/electron-launcher.test.mjs b/apps/desktop/scripts/electron-launcher.test.mjs index 50f5e5f0ac846..84d08cd9b6b89 100644 --- a/apps/desktop/scripts/electron-launcher.test.mjs +++ b/apps/desktop/scripts/electron-launcher.test.mjs @@ -21,12 +21,17 @@ describe("electron development launcher", () => { VITE_DEV_SERVER_URL: "http://127.0.0.1:8526", T3CODE_PORT: "16566", T3CODE_HOME: "/tmp/t3", + T3CODE_OTLP_PROTOCOL: "http/protobuf", }); assert.include( environmentScript, "if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi", ); + assert.include( + environmentScript, + "if [ -z \"${T3CODE_OTLP_PROTOCOL:-}\" ]; then export T3CODE_OTLP_PROTOCOL='http/protobuf'; fi", + ); assert.notInclude(environmentScript, "\nexport VITE_DEV_SERVER_URL="); }); diff --git a/apps/desktop/scripts/main-process-bundle.test.mjs b/apps/desktop/scripts/main-process-bundle.test.mjs new file mode 100644 index 0000000000000..28d8e37d7a9e7 --- /dev/null +++ b/apps/desktop/scripts/main-process-bundle.test.mjs @@ -0,0 +1,110 @@ +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeVM from "node:vm"; +import { build } from "vite-plus/pack"; +import { assert, it } from "vite-plus/test"; + +import desktopConfig from "../vite.config.ts"; + +it("keeps lazy Linux imports and worker bundles from executing desktop startup twice", async () => { + const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-desktop-bundle-")); + try { + const workerEntries = [ + "src/electron/WindowsForegroundFocusWorker.ts", + "src/snapShot/GlobalShiftShortcutWorker.ts", + "src/snapShot/RegionSnapShotWorker.ts", + "src/snapShot/SnapShotAccessibilityWorker.ts", + ]; + await Promise.all([ + NodeFSP.mkdir(NodePath.join(directory, "src/electron"), { recursive: true }), + NodeFSP.mkdir(NodePath.join(directory, "src/snapShot"), { recursive: true }), + ]); + await Promise.all([ + NodeFSP.writeFile( + NodePath.join(directory, "src/main.ts"), + `import { shared } from "./shared.ts"; +process.emit("startup", shared.value); +void import("./linux.ts").then(({ result }) => process.emit("ready", result));`, + ), + NodeFSP.writeFile( + NodePath.join(directory, "src/shared.ts"), + "export const shared = { value: 42 };", + ), + NodeFSP.writeFile( + NodePath.join(directory, "src/linux.ts"), + 'import { shared } from "./shared.ts"; export const result = shared.value + 1;', + ), + ...workerEntries.map((entry) => + NodeFSP.writeFile( + NodePath.join(directory, entry), + 'import { shared } from "../shared.ts"; process.emit("worker", shared.value);', + ), + ), + ]); + assert.ok(Array.isArray(desktopConfig.pack)); + const fixtureEntries = new Set(["src/main.ts", ...workerEntries]); + for (const packConfig of desktopConfig.pack) { + if (!Array.isArray(packConfig.entry)) continue; + if (!packConfig.entry.some((entry) => fixtureEntries.has(entry))) continue; + await build({ + ...packConfig, + config: false, + cwd: directory, + tsconfig: false, + sourcemap: false, + onSuccess: undefined, + logLevel: "silent", + }); + } + + const outputDirectory = NodePath.join(directory, "dist-electron"); + const filenames = (await NodeFSP.readdir(outputDirectory, { recursive: true })).filter( + (filename) => filename.endsWith(".cjs"), + ); + const sources = new Map( + await Promise.all( + filenames.map(async (filename) => { + const path = NodePath.join(outputDirectory, filename); + return [path, await NodeFSP.readFile(path, "utf8")]; + }), + ), + ); + const modules = new Map(); + const startups = []; + const workers = []; + const ready = Promise.withResolvers(); + const load = (filename, cacheModule = true) => { + const cached = modules.get(filename); + if (cached) return cached.exports; + const module = { exports: {} }; + if (cacheModule) modules.set(filename, module); + const source = sources.get(filename); + assert.ok(source, `Missing bundle: ${filename}`); + NodeVM.runInNewContext(source, { + exports: module.exports, + module, + require: (specifier) => load(NodePath.resolve(NodePath.dirname(filename), specifier)), + process: { + emit: (event, value) => { + if (event === "startup") startups.push(value); + if (event === "worker") workers.push(value); + if (event === "ready") ready.resolve(value); + }, + }, + }); + return module.exports; + }; + + load(NodePath.join(outputDirectory, "main.cjs"), false); + assert.equal(await ready.promise, 43); + assert.deepEqual(startups, [42]); + for (const entry of workerEntries) { + load(NodePath.join(outputDirectory, entry.replace(/^src\//, "").replace(/\.ts$/, ".cjs"))); + } + assert.deepEqual(workers, [42, 42, 42, 42]); + assert.deepEqual(startups, [42]); + } finally { + await NodeFSP.rm(directory, { recursive: true, force: true }); + } +}); diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts index d157a4c6ba441..924b8ce6e72b6 100644 --- a/apps/desktop/src/app/DesktopConfig.ts +++ b/apps/desktop/src/app/DesktopConfig.ts @@ -1,3 +1,4 @@ +import { OtlpHeadersFromString, OtlpProtocol } from "@t3tools/shared/observability"; import * as Config from "effect/Config"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Option from "effect/Option"; @@ -48,6 +49,10 @@ export const DesktopConfig = Config.all({ otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe( Config.withDefault(10_000), ), + otlpHeaders: Config.schema(OtlpHeadersFromString, "T3CODE_OTLP_HEADERS").pipe(Config.option), + otlpProtocol: Config.schema(OtlpProtocol, "T3CODE_OTLP_PROTOCOL").pipe( + Config.withDefault("http/json"), + ), appImagePath: trimmedString("APPIMAGE"), disableAutoUpdate: optionalBoolean("T3CODE_DISABLE_AUTO_UPDATE"), mockUpdates: optionalBoolean("T3CODE_DESKTOP_MOCK_UPDATES"), diff --git a/apps/desktop/src/app/DesktopEnvironment.test.ts b/apps/desktop/src/app/DesktopEnvironment.test.ts index 3bf9196a89343..5ded307da1289 100644 --- a/apps/desktop/src/app/DesktopEnvironment.test.ts +++ b/apps/desktop/src/app/DesktopEnvironment.test.ts @@ -52,6 +52,8 @@ describe("DesktopEnvironment", () => { T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH: " /remote/server.mjs ", T3CODE_OTLP_TRACES_URL: " http://127.0.0.1:4318/v1/traces ", T3CODE_OTLP_EXPORT_INTERVAL_MS: "2500", + T3CODE_OTLP_HEADERS: "authorization=Basic%20abc%3D%3D,x-tenant=t3", + T3CODE_OTLP_PROTOCOL: "http/protobuf", }, ); @@ -85,6 +87,14 @@ describe("DesktopEnvironment", () => { assert.deepEqual(environment.commitHashOverride, Option.some("0123456789abcdef")); assert.deepEqual(environment.otlpTracesUrl, Option.some("http://127.0.0.1:4318/v1/traces")); assert.equal(environment.otlpExportIntervalMs, 2500); + assert.deepEqual( + environment.otlpHeaders, + Option.some({ + authorization: "Basic abc==", + "x-tenant": "t3", + }), + ); + assert.equal(environment.otlpProtocol, "http/protobuf"); }), ); @@ -104,6 +114,7 @@ describe("DesktopEnvironment", () => { assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json"); assert.equal(environment.userDataDirName, "t3code"); assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha)"); + assert.equal(environment.otlpProtocol, "http/json"); }), ); diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index e604cb767f3fc..e7a489d5e89d9 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -16,6 +16,7 @@ import * as DesktopConfig from "./DesktopConfig.ts"; import { resolveLinuxDesktopEntryName } from "./DesktopEarlyElectronStartup.ts"; import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts"; import { isNightlyDesktopVersion } from "../updates/updateChannels.ts"; +import type { OtlpProtocol } from "@t3tools/shared/observability"; export interface MakeDesktopEnvironmentInput { readonly dirname: string; @@ -72,6 +73,8 @@ export class DesktopEnvironment extends Context.Service< readonly commitHashOverride: Option.Option; readonly otlpTracesUrl: Option.Option; readonly otlpExportIntervalMs: number; + readonly otlpHeaders: Option.Option>; + readonly otlpProtocol: OtlpProtocol; readonly branding: DesktopAppBranding; readonly displayName: string; readonly appUserModelId: string; @@ -225,6 +228,8 @@ const make = Effect.fn("desktop.environment.make")(function* ( commitHashOverride: config.commitHashOverride, otlpTracesUrl: config.otlpTracesUrl, otlpExportIntervalMs: config.otlpExportIntervalMs, + otlpHeaders: config.otlpHeaders, + otlpProtocol: config.otlpProtocol, branding, displayName, appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () => diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts index d2ff0b4e2ad59..19ed351dffb7f 100644 --- a/apps/desktop/src/app/DesktopObservability.ts +++ b/apps/desktop/src/app/DesktopObservability.ts @@ -1,5 +1,9 @@ import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts"; -import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability"; +import { + makeLocalFileTracer, + makeTraceSink, + otlpSerializationLayer, +} from "@t3tools/shared/observability"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -17,7 +21,7 @@ import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as SynchronizedRef from "effect/SynchronizedRef"; import * as Tracer from "effect/Tracer"; -import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; +import { OtlpExporter, OtlpTracer } from "effect/unstable/observability"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; @@ -584,6 +588,7 @@ const tracerLayer = Layer.unwrap( : yield* OtlpTracer.make({ url: otlpTracesUrl.value, exportInterval: `${environment.otlpExportIntervalMs} millis`, + headers: Option.getOrUndefined(environment.otlpHeaders), resource: { serviceName: "desktop", attributes: { @@ -591,7 +596,7 @@ const tracerLayer = Layer.unwrap( "service.mode": environment.isDevelopment ? "development" : "packaged", }, }, - }); + }).pipe(Effect.provide(otlpSerializationLayer(environment.otlpProtocol))); const tracer = yield* makeLocalFileTracer({ filePath: tracePath, maxBytes: DESKTOP_LOG_FILE_MAX_BYTES, @@ -603,7 +608,7 @@ const tracerLayer = Layer.unwrap( return Layer.succeed(Tracer.Tracer, tracer); }), -).pipe(Layer.provide(OtlpExporter.layerFlusher), Layer.provideMerge(OtlpSerialization.layerJson)); +).pipe(Layer.provide(OtlpExporter.layerFlusher)); export const layer = Layer.mergeAll( backendOutputLogFactoryLayer, diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 642a1bc82f421..595582a162803 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -399,10 +399,10 @@ describe("DesktopBackendConfiguration", () => { observedProbeRoots.push(root); return { ok: true, resolvedPath }; }, - // The staged runtime carries its own Node, so the preflight must not - // go looking for one in the distro. + // The staged runtime carries its own Node and node-pty, so it must + // not require the mounted server tree's native dependency check. ensureNodePty: () => { - throw new Error("the staged runtime must not probe for Node"); + throw new Error("the staged runtime must not probe for node-pty"); }, }), }, @@ -853,10 +853,14 @@ describe("DesktopBackendConfiguration", () => { const previousWslEnv = process.env.WSLENV; const previousOpenAiKey = process.env.OPENAI_API_KEY; const previousAnthropicKey = process.env.ANTHROPIC_API_KEY; + const previousOtlpHeaders = process.env.T3CODE_OTLP_HEADERS; + const previousOtlpProtocol = process.env.T3CODE_OTLP_PROTOCOL; try { process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u"; process.env.OPENAI_API_KEY = "openai-key"; process.env.ANTHROPIC_API_KEY = "anthropic-key"; + process.env.T3CODE_OTLP_HEADERS = 'authorization="Bearer%20my-token"'; + process.env.T3CODE_OTLP_PROTOCOL = "http/protobuf"; yield* Effect.gen(function* () { const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; @@ -876,13 +880,14 @@ describe("DesktopBackendConfiguration", () => { assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/"); assert.equal(config.env.OPENAI_API_KEY, "openai-key"); assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key"); + assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf"); // The existing WSLENV is preserved byte-for-byte (note the empty // "::" segment survives — WSL ignores it, so we don't normalize // it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is // already declared, so it isn't forwarded twice. assert.equal( config.env.WSLENV, - "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY", + "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL", ); }).pipe( Effect.provide( @@ -905,6 +910,8 @@ describe("DesktopBackendConfiguration", () => { restoreEnv("WSLENV", previousWslEnv); restoreEnv("OPENAI_API_KEY", previousOpenAiKey); restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey); + restoreEnv("T3CODE_OTLP_HEADERS", previousOtlpHeaders); + restoreEnv("T3CODE_OTLP_PROTOCOL", previousOtlpProtocol); } }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 3486daebf79e2..a36902304809d 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -87,11 +87,16 @@ const DESKTOP_BACKEND_ENV_NAMES = [ "T3CODE_TAILSCALE_SERVE_PORT", ] as const; -// Sensitive env vars that the WSL backend needs but Windows process.env won't -// forward across the wsl.exe boundary without WSLENV. The dev-server URL is -// handled separately via a `--dev-url` CLI flag because WSLENV translation of +// Env vars that the WSL backend needs but Windows process.env won't forward +// across the wsl.exe boundary without WSLENV. The dev-server URL is handled +// separately via a `--dev-url` CLI flag because WSLENV translation of // URL-shaped values (colons / slashes) is unreliable. -const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const; +const WSL_FORWARDED_ENV_NAMES = [ + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "T3CODE_OTLP_HEADERS", + "T3CODE_OTLP_PROTOCOL", +] as const; const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; @@ -384,8 +389,8 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f if (input.runtimeArchive !== null) { const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); if (runtime.ok) { - // The staged runtime is self-contained, so the only question is whether - // it runs here; there is no Node to find or node-pty to load. + // The staged runtime supplies its own Node and node-pty. Provider PATH + // discovery must not require either dependency for runtime readiness. const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot); if (stagedProbe.ok) { yield* wslServerTree.cleanupLegacy; diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index dedac75a280f3..66c91981b6675 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -3922,94 +3922,6 @@ describe("PreviewManager", () => { ), ); - effectIt.effect( - "hands keyboard focus back to the previous renderer after an automation click", - () => - withManager((manager) => - Effect.gen(function* () { - let humanInput: ((_event: unknown, signal: unknown) => void) | undefined; - const sendCommand = vi.fn(async (method: string, params?: Record) => { - if (method === "Runtime.evaluate") { - return { result: { value: { width: 800, height: 600 } } }; - } - if (method === "Input.dispatchMouseEvent" && params?.type === "mousePressed") { - humanInput?.({}, { kind: "pointer", x: params.x, y: params.y, button: 0 }); - } - return undefined; - }); - const restoreFocus = vi.fn(); - getFocusedWebContents.mockReturnValue({ - id: 7, - isDestroyed: () => false, - focus: restoreFocus, - } as never); - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoading: () => false, - isDevToolsOpened: () => false, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - off: vi.fn(), - ipc: { - on: vi.fn((channel: string, listener: typeof humanInput) => { - if (channel === "preview:human-input") humanInput = listener; - }), - off: vi.fn(), - }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand, - on: vi.fn(), - off: vi.fn(), - }, - } as never); - - yield* manager.createTab("tab_1"); - yield* manager.registerWebview("tab_1", 42); - const click = yield* manager - .automationClick("tab_1", { x: 120, y: 80 }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* TestClock.adjust(200); - yield* Fiber.join(click); - - expect(restoreFocus).toHaveBeenCalledTimes(1); - expect(restoreFocus.mock.invocationCallOrder[0]).toBeGreaterThan( - sendCommand.mock.invocationCallOrder.at(-1) ?? 0, - ); - - const offscreen = yield* manager - .automationClick("tab_1", { x: 5000, y: 80 }) - .pipe(Effect.exit, Effect.forkChild({ startImmediately: true })); - yield* TestClock.adjust(200); - expect((yield* Fiber.join(offscreen))._tag).toBe("Failure"); - expect(restoreFocus).toHaveBeenCalledTimes(2); - - // Focus that moved to a third renderer while the click ran is left alone. - getFocusedWebContents - .mockReturnValueOnce({ id: 7, isDestroyed: () => false, focus: restoreFocus } as never) - .mockReturnValue({ id: 9, isDestroyed: () => false, focus: vi.fn() } as never); - const moved = yield* manager - .automationClick("tab_1", { x: 120, y: 80 }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* TestClock.adjust(200); - yield* Fiber.join(moved); - expect(restoreFocus).toHaveBeenCalledTimes(2); - }), - ), - ); - effectIt.effect("types in background webviews and enables native key input", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 697c81752e2cf..7cf73af91e92e 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -3731,55 +3731,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); - // Dispatching input moves keyboard focus into the guest renderer as a side - // effect. Hand it back to whatever had it before, so the user's next keystroke - // does not land in the previewed page, which may not even be visible. - const restoreFocusedWebContents = Effect.fn("PreviewManager.restoreFocusedWebContents")( - function* ( - operation: string, - tabId: string, - wc: Electron.WebContents, - previouslyFocused: Electron.WebContents | null, - ) { - if (!previouslyFocused || previouslyFocused.id === wc.id || previouslyFocused.isDestroyed()) { - return; - } - // A newer selection the user made while the action ran wins over the restore. - const focusedNow = yield* attempt({ operation, tabId, webContentsId: wc.id }, () => - webContents.getFocusedWebContents(), - ).pipe(Effect.orElseSucceed(() => null)); - if (focusedNow && focusedNow.id !== wc.id && focusedNow.id !== previouslyFocused.id) { - return; - } - yield* attempt({ operation, tabId, webContentsId: previouslyFocused.id }, () => - previouslyFocused.focus(), - ).pipe(Effect.ignore); - }, - ); - const performAutomationClick = Effect.fn("PreviewManager.performAutomationClick")(function* ( - tabId: string, - wc: Electron.WebContents, - input: PreviewAutomationClickInput, - send: SendCommand, - ) { - const previouslyFocused = yield* attempt( - { operation: "automationClick.getFocusedWebContents", tabId, webContentsId: wc.id }, - () => webContents.getFocusedWebContents(), - ); - yield* dispatchAutomationClick(tabId, input, send).pipe( - Effect.ensuring( - restoreFocusedWebContents( - "automationClick.restoreFocusedWebContents", - tabId, - wc, - previouslyFocused, - ), - ), - ); - }); - - const dispatchAutomationClick = Effect.fn("PreviewManager.dispatchAutomationClick")(function* ( tabId: string, input: PreviewAutomationClickInput, send: SendCommand, @@ -3842,7 +3794,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { const wc = yield* requireWebContents(tabId); yield* withControlSession(tabId, wc, "click", (send) => - performAutomationClick(tabId, wc, input, send), + performAutomationClick(tabId, input, send), ); }); diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index c1d17597f5602..d45a1015e0299 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -18,8 +18,6 @@ import * as DesktopClientSettings from "./DesktopClientSettings.ts"; const clientSettings: ClientSettings = { ...DEFAULT_CLIENT_SETTINGS, - citeSelectionEnabled: true, - notificationMode: "notifications-and-sound", inAppNotificationsEnabled: true, appearanceContrast: 100, diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index c51d57e8cdd0d..26ca9b984565a 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -713,6 +713,7 @@ export const make = Effect.gen(function* () { const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes( info.releaseNotes, info.version, + state.channel, ); yield* setState( reduceDesktopUpdateStateOnUpdateAvailable( diff --git a/apps/desktop/src/updates/releaseNotes.test.ts b/apps/desktop/src/updates/releaseNotes.test.ts index 3ba2444dc185f..57d185c0975e9 100644 --- a/apps/desktop/src/updates/releaseNotes.test.ts +++ b/apps/desktop/src/updates/releaseNotes.test.ts @@ -21,6 +21,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { "**Full Changelog**: https://github.com/pingdotgg/t3code/compare/old...new", ].join("\n"), "0.0.36-nightly.20260828.1213", + "nightly", ); expect(result).toEqual({ @@ -50,6 +51,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { "

New Contributors

  • @human made their first contribution
" + "

Full Changelog

", "1.2.3", + "latest", ); expect(result).toEqual({ @@ -69,6 +71,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { }, ], "1.2.4", + "latest", ); expect(result.releaseNotes).toEqual([ @@ -85,6 +88,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { { version: "1.2.1", note: "- Older release" }, ], "1.2.3", + "latest", ); expect(result).toEqual({ @@ -96,6 +100,42 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { }); }); + it("drops releases from other trains before grouping on nightly", () => { + // electron-updater's full changelog is "every version above the running + // one", and preview sorts above nightly, so the preview cuts come first. + const releaseNotes = [ + { version: "0.0.41-preview.20260914.1683", note: "- Maintainer test build" }, + { version: "0.0.41-preview.20260913.1669", note: "- Maintainer test build" }, + { version: "0.0.41-nightly.20260914.1707", note: "- Nightly change 2" }, + { version: "0.0.41-nightly.20260914.1700", note: "- Nightly change 1" }, + ]; + + const result = normalizeDesktopUpdateReleaseNotes( + releaseNotes, + "0.0.41-nightly.20260914.1707", + "nightly", + ); + + expect(result.releaseNotes.map(({ version }) => version)).toEqual([ + "0.0.41-nightly.20260914.1707", + "0.0.41-nightly.20260914.1700", + ]); + expect(result.omittedReleaseCount).toBe(0); + }); + + it("keeps only stable releases on the latest channel", () => { + const result = normalizeDesktopUpdateReleaseNotes( + [ + { version: "0.0.42", note: "- Stable change" }, + { version: "0.0.42-nightly.20260915.1710", note: "- Nightly change" }, + ], + "0.0.42", + "latest", + ); + + expect(result.releaseNotes.map(({ version }) => version)).toEqual(["0.0.42"]); + }); + it("counts valid groups before applying the six-release limit", () => { const releaseNotes = [ { version: "1.3.9", note: "- Change 9" }, @@ -108,7 +148,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { { version: "1.3.2", note: "- Change 2" }, ]; - const result = normalizeDesktopUpdateReleaseNotes(releaseNotes, "1.3.9"); + const result = normalizeDesktopUpdateReleaseNotes(releaseNotes, "1.3.9", "latest"); expect(result.releaseNotes.map(({ version }) => version)).toEqual([ "1.3.9", @@ -122,7 +162,11 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { }); it("decodes valid HTML entities", () => { - const result = normalizeDesktopUpdateReleaseNotes("- Fix & polish 😀", "1.0.0"); + const result = normalizeDesktopUpdateReleaseNotes( + "- Fix & polish 😀", + "1.0.0", + "latest", + ); expect(result).toEqual({ releaseNotes: [{ version: "1.0.0", items: ["Fix & polish 😀"], totalItems: 1 }], omittedReleaseCount: 0, @@ -140,6 +184,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { null, ], "1.2.3", + "latest", ); expect(result).toEqual({ @@ -149,14 +194,18 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { }); it("returns an empty result for an invalid payload", () => { - expect(normalizeDesktopUpdateReleaseNotes({ note: "- Invalid" }, "1.0.0")).toEqual({ + expect(normalizeDesktopUpdateReleaseNotes({ note: "- Invalid" }, "1.0.0", "latest")).toEqual({ releaseNotes: [], omittedReleaseCount: 0, }); }); it("does not throw on out-of-range numeric entities and keeps the literal", () => { - const result = normalizeDesktopUpdateReleaseNotes("- Broken entity �", "1.0.0"); + const result = normalizeDesktopUpdateReleaseNotes( + "- Broken entity �", + "1.0.0", + "latest", + ); expect(result).toEqual({ releaseNotes: [{ version: "1.0.0", items: ["Broken entity �"], totalItems: 1 }], omittedReleaseCount: 0, diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts index 3b2f32e646a1f..3cab5f15e4516 100644 --- a/apps/desktop/src/updates/releaseNotes.ts +++ b/apps/desktop/src/updates/releaseNotes.ts @@ -1,4 +1,6 @@ -import type { DesktopUpdateReleaseNote } from "@t3tools/contracts"; +import type { DesktopUpdateChannel, DesktopUpdateReleaseNote } from "@t3tools/contracts"; + +import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts"; interface ElectronReleaseNoteInfo { readonly version: string; @@ -122,16 +124,27 @@ interface NormalizedDesktopUpdateReleaseNotes { readonly omittedReleaseCount: number; } +/** + * Turns electron-updater's release notes into the groups the popover shows. + * With `fullChangelog` on (nightly), electron-updater collects every GitHub + * release whose version is semver-greater than the running one, whatever + * train it belongs to; a maintainers' `-preview.` cut sorts above every + * `-nightly.` of the same base version and would lead the list. Only + * releases on the channel being followed are kept, the same test the + * updater applies to the offered version itself. + */ export function normalizeDesktopUpdateReleaseNotes( releaseNotes: unknown, fallbackVersion: string, + channel: DesktopUpdateChannel, ): NormalizedDesktopUpdateReleaseNotes { - const rawNotes = + const rawNotes = ( typeof releaseNotes === "string" ? [{ version: fallbackVersion, note: releaseNotes }] : Array.isArray(releaseNotes) ? releaseNotes.filter(isElectronReleaseNoteInfo) - : []; + : [] + ).filter((entry) => resolveDefaultDesktopUpdateChannel(entry.version) === channel); const normalizedNotes = rawNotes.flatMap((entry) => { const { items, totalItems } = extractReleaseNoteItems(entry.note); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 366bdfce9946c..e28a9c6c78005 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -15,6 +15,7 @@ import { buildWslRuntimeInstallScript, buildWslRuntimeInvalidateScript, buildWslRuntimePruneScript, + buildWslRuntimeProbeScript, DesktopWslDistroListError, formatMissingToolsReason, parseNodePath, @@ -446,6 +447,75 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed }; }; + const probeFixture = (fixture: ReturnType) => + runShell( + [ + `export HOME=${sh(`${fixture.work}/home`)}`, + 'export NVM_DIR="$HOME/.nvm" FNM_DIR="$HOME/.fnm" VOLTA_HOME="$HOME/.volta"', + // Isolate login profiles and hide the host's Node/version managers. + // The resolver must discover the fixture's installation itself. + "bash() { (", + " command() {", + ' case "$*" in', + ' "-v node"|"-v mise"|"-v fnm"|"-v nodenv") return 1 ;;', + ' *) builtin command "$@" ;;', + " esac", + " }", + ' eval "$2"', + "); }", + buildWslRuntimeProbeScript(fixture.runtimeRoot), + ].join("\n"), + ); + + it("discovers version-managed Node for providers with a standalone runtime", () => { + const fixture = createFixture(); + expect(fixture.install().status).toBe(0); + const nodeBin = `${fixture.work}/home/.nvm/versions/node/v24.15.0/bin`; + const setup = runShell( + [ + "set -eu", + `mkdir -p ${sh(nodeBin)}`, + `printf '%s' ${sh('#!/bin/sh\nprintf "linux-node-provider\\n"\n')} > ${sh(`${nodeBin}/node`)}`, + `chmod +x ${sh(`${nodeBin}/node`)}`, + ].join("\n"), + ); + expect(setup.status, setup.stderr).toBe(0); + + const probe = probeFixture(fixture); + + expect(probe.status, probe.stderr).toBe(0); + const resolvedPath = parseResolvedPath(probe.stdout); + expect(resolvedPath?.split(":")).toContain(nodeBin); + const provider = runShell(`export PATH=${sh(resolvedPath ?? "")}\nnode provider.js`); + expect(provider.status, provider.stderr).toBe(0); + expect(provider.stdout).toBe("linux-node-provider\n"); + }); + + it("keeps standalone runtime readiness independent of Node availability", () => { + const fixture = createFixture(); + expect(fixture.install().status).toBe(0); + + const probe = probeFixture(fixture); + + expect(probe.status, probe.stderr).toBe(0); + expect(parseResolvedPath(probe.stdout)).not.toBeNull(); + }); + + it("keeps the inherited PATH when bash is unavailable", () => { + const fixture = createFixture(); + expect(fixture.install().status).toBe(0); + const probe = runShell( + [ + "bash() { return 127; }", + 'export PATH="/fixture/bin:/usr/bin:/bin"', + buildWslRuntimeProbeScript(fixture.runtimeRoot), + ].join("\n"), + ); + + expect(probe.status, probe.stderr).toBe(0); + expect(parseResolvedPath(probe.stdout)).toBe("/fixture/bin:/usr/bin:/bin"); + }); + it("reuses a warm cache without touching the archive", () => { const fixture = createFixture(); expect(fixture.install().status).toBe(0); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index ebd4f853da608..95b217c622b1c 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -122,8 +122,8 @@ export class DesktopWslEnvironment extends Context.Service< // Marks a staged runtime as unusable so the next launch reinstalls it. readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect; // Proves a staged self-contained runtime can run (`/t3 --version`) - // and captures the user's login-shell PATH for the launch. Needs no Node - // in the distro; the mounted server tree still goes through ensureNodePty. + // and resolves the user's PATH, including version-managed Node for provider + // CLIs. Node is optional; the mounted tree still requires ensureNodePty. readonly probeRuntime: ( distro: string | null, linuxAppRoot: string, @@ -545,13 +545,12 @@ require("node-pty"); NODE`; // Readiness proof for a staged self-contained runtime: the executable runs and -// reports its version, and the login shell's PATH is captured for the launch. -// This runs under plain `sh` (no Node resolver preamble, since the runtime -// needs no Node), so the login shell is entered explicitly for the PATH -// capture; a distro without bash falls back to the PATH sh was started with. -const RUNTIME_PROBE_SCRIPT = (linuxAppRoot: string) => +// reports its version. Provider CLIs may still need version-managed Node, so +// resolve it before capturing PATH without requiring it for runtime readiness. +// A distro without bash falls back to the PATH sh was started with. +export const buildWslRuntimeProbeScript = (linuxAppRoot: string) => [ - `bash -lc ${shellQuote(RESOLVED_PATH_LINE)} 2>/dev/null || ${RESOLVED_PATH_LINE}`, + `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`, `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`, ].join("\n"); @@ -676,9 +675,14 @@ const probeWslRuntimeImpl = ( linuxAppRoot: string, ): Effect.Effect => Effect.gen(function* () { - const probe = yield* runWslShell(distro, RUNTIME_PROBE_SCRIPT(linuxAppRoot), PROBE_TIMEOUT, { - resolveNode: false, - }); + const probe = yield* runWslShell( + distro, + buildWslRuntimeProbeScript(linuxAppRoot), + PROBE_TIMEOUT, + { + resolveNode: false, + }, + ); const transportFailureReason = formatWslShellTransportFailureReason( probe.transportFailure, "the staged runtime", diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index f3ec31ed34d9d..c451a89b57672 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -48,6 +48,23 @@ export default defineConfig({ }, }, pack: [ + { + format: "cjs", + outDir: "dist-electron", + dts: false, + sourcemap: true, + outExtensions: () => ({ js: ".cjs" }), + define: publicConfigDefine, + outputOptions: { codeSplitting: false }, + entry: ["src/main.ts"], + clean: true, + deps: { + alwaysBundle: (id) => !id.startsWith("node:") && !isMainProcessExternal(id), + neverBundle: isMainProcessExternal, + onlyBundle: false, + }, + ...(shouldLaunchElectronAfterPack ? { onSuccess: "node scripts/dev-electron.mjs" } : {}), + }, { format: "cjs", outDir: "dist-electron", @@ -56,19 +73,17 @@ export default defineConfig({ outExtensions: () => ({ js: ".cjs" }), define: publicConfigDefine, entry: [ - "src/main.ts", "src/electron/WindowsForegroundFocusWorker.ts", "src/snapShot/GlobalShiftShortcutWorker.ts", "src/snapShot/RegionSnapShotWorker.ts", "src/snapShot/SnapShotAccessibilityWorker.ts", ], - clean: true, + clean: false, deps: { alwaysBundle: (id) => !id.startsWith("node:") && !isMainProcessExternal(id), neverBundle: isMainProcessExternal, onlyBundle: false, }, - ...(shouldLaunchElectronAfterPack ? { onSuccess: "node scripts/dev-electron.mjs" } : {}), }, { format: "cjs", diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index c4596df8dd860..c21e70a18ba03 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -222,7 +222,10 @@ const config: ExpoConfig = { // fingerprinted so OTAs only reach binaries with matching native projects. policy: runtimeVersionPolicy, }, - orientation: "portrait", + // Foldables, tablets, DeX, and Android multi-window can resize or rotate + // the app while it is running. Keep the window unrestricted so the + // adaptive workspace can respond to the actual available dimensions. + orientation: "default", icon: variant.assets.appIcon, userInterfaceStyle: "automatic", updates: { diff --git a/apps/mobile/global.css b/apps/mobile/global.css index 2f686e3a1fa94..7a401fd7289d8 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -233,6 +233,31 @@ } } +/* ─── Clerk native profile ──────────────────────────────────────────── */ +/* Fixed palette for custom pages inside Clerk's native user profile. Mirrors + clerk-theme.json, which themes the SDK's own screens, so ours match them. + Kept out of the runtime palette above on purpose: custom themes must not + restyle Clerk's chrome. Keep in sync with clerk-theme.json. */ +@layer theme { + :root { + @variant light { + --color-clerk-page: #f2f2f7; + --color-clerk-foreground: #262626; + --color-clerk-foreground-muted: #737373; + --color-clerk-border: rgba(229, 229, 234, 0.06); + --color-clerk-danger: #dc2626; + } + + @variant dark { + --color-clerk-page: #0e0e0e; + --color-clerk-foreground: #f5f5f5; + --color-clerk-foreground-muted: #a3a3a3; + --color-clerk-border: rgba(42, 42, 42, 0.06); + --color-clerk-danger: #fca5a5; + } + } +} + /* ─── Typography ────────────────────────────────────────────────────── */ @theme { /* Keep these native family names aligned with app.config.ts. */ diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentActivityPresentation.kt b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentActivityPresentation.kt new file mode 100644 index 0000000000000..feca1133d9a3e --- /dev/null +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentActivityPresentation.kt @@ -0,0 +1,201 @@ +package expo.modules.t3agentnotifications + +import android.content.Context +import android.graphics.Typeface +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.text.style.ForegroundColorSpan +import android.text.style.StyleSpan +import androidx.core.app.NotificationCompat +import androidx.core.content.ContextCompat + +internal data class ActivityRow(val status: String, val title: String, val project: String) + +/** + * One entry per relay phase. The status label matches the relay's row wording and the + * tint matches the web sidebar pills and the iOS Live Activity so a thread reads the + * same on every surface. The icon is always the T3 mark; the chip verb carries the state. + */ +internal enum class ActivityPhase( + val status: String, + val heading: String, + val chip: String, + val action: String, + val color: Int +) { + STARTING("Connecting", "Starting", "Working", "Open", R.color.agent_activity_working), + RUNNING("Working", "Working", "Working", "Open", R.color.agent_activity_working), + APPROVAL( + "Approval", + "Approval needed", + "Approve", + "Approve", + R.color.agent_activity_attention + ), + INPUT( + "Input", + "Question for you", + "Answer", + "Answer", + R.color.agent_activity_input + ), + STALE( + "Waiting", + "Waiting for an update", + "Waiting", + "Open", + R.color.agent_activity_waiting + ), + COMPLETED( + "Done", + "Finished", + "Done", + "Open", + R.color.agent_activity_done + ), + FAILED( + "Failed", + "Failed", + "Failed", + "Open", + R.color.agent_activity_failed + ); + + val needsUser get() = this == APPROVAL || this == INPUT + val finished get() = this == COMPLETED || this == FAILED + + companion object { + fun forStatus(status: String) = entries.firstOrNull { it.status == status } + } +} + +/** The relay orders rows and their deep link together; never reorder them in the client. */ +internal fun activityRows(data: Map) = (0..4).mapNotNull { + val parts = data["activity_line_$it"]?.split('\t', limit = 3) ?: return@mapNotNull null + if (parts.size != 3 || parts[1].isBlank()) { + null + } else { + ActivityRow(parts[0].take(40), parts[1].take(120), parts[2].take(120)) + } +} + +internal fun activityPhase(data: Map, rows: List): ActivityPhase? = + when (data["activity_phase"]?.takeIf { it.isNotBlank() }) { + "starting" -> ActivityPhase.STARTING + "running" -> ActivityPhase.RUNNING + "waiting_for_approval" -> ActivityPhase.APPROVAL + "waiting_for_input" -> ActivityPhase.INPUT + "stale" -> ActivityPhase.STALE + "completed" -> ActivityPhase.COMPLETED + "failed" -> ActivityPhase.FAILED + else -> rows.firstOrNull()?.let { ActivityPhase.forStatus(it.status) } + } + +/** + * Header carries the state, the title says what needs you (or which thread, when + * there is only one), and the body lists every thread with its status in front. + * System UI renders all of it, so the same builder serves the shade, the lock + * screen and the status bar chip. + */ +internal class ActivityPresentation(data: Map, private val active: Boolean) { + private val rows = activityRows(data) + private val hero = rows.firstOrNull() + val phase = activityPhase(data, rows) + private val activeCount = data["activity_active_count"]?.toIntOrNull()?.coerceAtLeast(0) + ?: rows.count { ActivityPhase.forStatus(it.status)?.finished != true } + private val attentionCount = data["activity_attention_count"]?.toIntOrNull()?.coerceAtLeast(0) + ?: rows.count { ActivityPhase.forStatus(it.status)?.needsUser == true } + private val failedCount = rows.count { it.status == ActivityPhase.FAILED.status } + val threadCount = + activeCount + rows.count { ActivityPhase.forStatus(it.status)?.finished == true } + private val singleProject = rows.map { it.project }.distinct().size == 1 + private val legacyBody = (0..4).mapNotNull { data["activity_line_$it"]?.take(300) } + .takeIf { it.isNotEmpty() }?.joinToString("\n") + ?: data["activity_body"].orEmpty().take(240) + + val summary = when { + hero == null -> data["activity_title"]?.takeIf { it.isNotBlank() }?.take(120) + ?: "Agent activity" + rows.size == 1 -> hero.title + attentionCount == 1 -> "1 needs you" + attentionCount > 1 -> "$attentionCount need you" + activeCount > 0 && failedCount > 0 -> "$failedCount failed" + activeCount > 0 -> "$activeCount working" + failedCount > 0 -> "Finished, $failedCount failed" + else -> "All finished" + } + + val chip = when { + !active -> null + phase == null -> data["activity_chip"]?.takeIf { it.isNotBlank() }?.take(7) ?: "Active" + phase == ActivityPhase.RUNNING && activeCount > 1 -> + "${if (activeCount > 9) "9+" else activeCount} live" + else -> phase.chip + } + + val action = if (active) phase?.action ?: "Open" else null + + fun applyTo(builder: NotificationCompat.Builder, context: Context) { + val tint = phase?.let { ContextCompat.getColor(context, it.color) } + builder.setSmallIcon(R.drawable.agent_activity_mark) + if (tint != null) builder.setColor(tint) + // Tint the summary only when it names an outcome or a request; a plain + // "3 working" stays neutral so the accent keeps meaning something. + val tintedSummary = tint != null && rows.size > 1 && phase != ActivityPhase.RUNNING && + phase != ActivityPhase.STARTING + builder.setContentTitle(if (tintedSummary) tinted(summary, tint!!) else summary) + if (rows.size > 1) { + builder.setSubText( + listOfNotNull( + hero!!.project.takeIf { singleProject && it.isNotBlank() }, + if (activeCount > 0) "$activeCount active" else "$threadCount threads" + ).joinToString(" · ") + ) + } + val body = body(context) + // The collapsed card gets the priority row; the expanded card gets them all. + val lineBreak = body.indexOf('\n') + val firstLine = if (lineBreak >= 0) body.subSequence(0, lineBreak) else body + builder.setContentText(firstLine).setStyle(NotificationCompat.BigTextStyle().bigText(body)) + // Thread update timestamps can change while an approval remains pending. + // Leave the timer hidden until the payload has a stable phase-entry timestamp. + builder.setShowWhen(false).setUsesChronometer(false) + } + + private fun body(context: Context): CharSequence = when { + hero == null -> legacyBody + // The title already names the thread; the body only needs its status and project. + rows.size == 1 -> statusLine(context, hero.copy(title = hero.project), "") + else -> SpannableStringBuilder().apply { + rows.forEachIndexed { index, row -> + if (index > 0) append("\n") + append(statusLine(context, row, row.project.takeUnless { singleProject }.orEmpty())) + } + } + } + + private fun statusLine(context: Context, row: ActivityRow, trailing: String): CharSequence = + SpannableStringBuilder().apply { + val status = ActivityPhase.forStatus(row.status) + val color = ContextCompat.getColor(context, status?.color ?: R.color.agent_activity_waiting) + append(tinted(row.status, color, bold = true)) + append(" ").append(row.title) + // Promoted cards drop text color, so the separator has to do the work of the dimming. + if (trailing.isNotBlank()) { + val start = length + append(" · ").append(trailing) + setSpan( + ForegroundColorSpan(ContextCompat.getColor(context, R.color.agent_activity_waiting)), + start, + length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) + } + } + + private fun tinted(text: String, color: Int, bold: Boolean = false) = + SpannableStringBuilder(text).apply { + setSpan(ForegroundColorSpan(color), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + if (bold) setSpan(StyleSpan(Typeface.BOLD), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + } +} diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt index d1b81661151c5..35086bbd75f9a 100644 --- a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt @@ -11,8 +11,6 @@ import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Build -import android.text.TextPaint -import android.text.TextUtils import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.Lifecycle @@ -197,34 +195,32 @@ object AgentNotifications { active: Boolean, remainingMs: Long ) { - val body = data["activity_body"].orEmpty().take(240) val dismissIntent = PendingIntent.getBroadcast( context, ACTIVITY_ID, Intent(context, AgentActivityDismissReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) - val lines = (0..4).mapNotNull { - data["activity_line_$it"]?.let { line -> activityLine(context, line) } - } - // BigTextStyle remains eligible for Android Live Update promotion. - val style = NotificationCompat.BigTextStyle().bigText( - if (lines.isEmpty()) body else lines.joinToString("\n") - ) - val notification = base(context, ACTIVITY_CHANNEL) - .setContentTitle(data["activity_title"].orEmpty().take(120)) - .setContentText(body) - .setStyle(style) + val presentation = ActivityPresentation(data, active) + val openThread = contentIntent(context, scheme, data["activity_path"], ACTIVITY_ID) + val builder = base(context, ACTIVITY_CHANNEL) .setOngoing(active).setOnlyAlertOnce(true).setSilent(true) .setTimeoutAfter(remainingMs) // Live Updates must remain uncolorized to qualify for promotion. .setColorized(false) .setRequestPromotedOngoing(active) - .setContentIntent(contentIntent(context, scheme, data["activity_path"], ACTIVITY_ID)) + .setShortCriticalText(presentation.chip) + .setContentIntent(openThread) .setDeleteIntent(dismissIntent) - .addAction(0, "Dismiss", dismissIntent) - .build() - manager(context).notify(ACTIVITY_TAG, ACTIVITY_ID, notification) + presentation.applyTo(builder, context) + // A finished card is no longer ongoing, so it swipes away and a tap opens + // the thread; buttons would only repeat that. + val action = presentation.action + if (action != null) { + if (openThread != null) builder.addAction(0, action, openThread) + builder.addAction(0, "Dismiss", dismissIntent) + } + manager(context).notify(ACTIVITY_TAG, ACTIVITY_ID, builder.build()) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // Notification timeouts were added in API 26. One inexact alarm also // expires cards on Android 7, including when the app process has exited. @@ -253,32 +249,6 @@ object AgentNotifications { } } - private fun activityLine(context: Context, value: String): String { - val parts = value.split('\t', limit = 3) - if (parts.size != 3) return value.take(300) - val metrics = context.resources.displayMetrics - val paint = TextPaint().apply { textSize = 14 * metrics.scaledDensity } - val prefix = "${parts[0]}: " - val separator = " · " - // Reserve the system notification's icon and margins. Fit the two titles - // independently so large fonts/long names never hide the project or status. - // The shade uses a narrow column even when a headless service sees a - // foldable's wider display metrics. Keep rows inside that column too. - val width = (metrics.widthPixels - 152 * metrics.density) - .coerceIn(120 * metrics.density, 280 * metrics.density) - val available = (width - paint.measureText(prefix + separator)).coerceAtLeast(0f) - val projectWidth = paint.measureText(parts[2]).coerceAtMost(available * 0.4f) - val titleWidth = paint.measureText(parts[1]).coerceAtMost(available - projectWidth) - val title = TextUtils.ellipsize(parts[1], paint, titleWidth, TextUtils.TruncateAt.END) - val project = TextUtils.ellipsize( - parts[2], - paint, - available - titleWidth, - TextUtils.TruncateAt.END - ) - return "$prefix$title$separator$project" - } - private fun manager(context: Context) = context.getSystemService(NotificationManager::class.java) private fun channels(context: Context) { diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt index d394db56115ff..246db274a195d 100644 --- a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt @@ -1,5 +1,9 @@ package expo.modules.t3agentnotifications +import android.content.ActivityNotFoundException +import android.content.Intent +import android.os.Build +import android.provider.Settings import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition @@ -21,5 +25,23 @@ class T3AgentNotificationsModule : Module() { Function("clear") { appContext.reactContext?.let { AgentNotifications.clear(it) } } + + Function("openLiveUpdateSettings") { + val context = appContext.reactContext + if (context == null || Build.VERSION.SDK_INT < 36) { + false + } else { + try { + context.startActivity( + Intent(Settings.ACTION_APP_NOTIFICATION_PROMOTION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + true + } catch (_: ActivityNotFoundException) { + false + } + } + } } } diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/res/drawable/agent_activity_mark.xml b/apps/mobile/modules/t3-agent-notifications/android/src/main/res/drawable/agent_activity_mark.xml new file mode 100644 index 0000000000000..7aa01bac42c1a --- /dev/null +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/res/drawable/agent_activity_mark.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/res/values-night/agent_activity_colors.xml b/apps/mobile/modules/t3-agent-notifications/android/src/main/res/values-night/agent_activity_colors.xml new file mode 100644 index 0000000000000..e08b159d9f047 --- /dev/null +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/res/values-night/agent_activity_colors.xml @@ -0,0 +1,9 @@ + + + #7DD3FC + #FCD34D + #A5B4FC + #94A3B8 + #6EE7B7 + #FCA5A5 + diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/res/values/agent_activity_colors.xml b/apps/mobile/modules/t3-agent-notifications/android/src/main/res/values/agent_activity_colors.xml new file mode 100644 index 0000000000000..262bbfc23fb72 --- /dev/null +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/res/values/agent_activity_colors.xml @@ -0,0 +1,9 @@ + + + #0284C7 + #D97706 + #4F46E5 + #64748B + #059669 + #DC2626 + diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt b/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt index 734fbbc2f3b27..3e9b3b24c1938 100644 --- a/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt +++ b/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt @@ -294,26 +294,183 @@ class AgentNotificationsTest { } @Test - fun longRowsKeepStatusAndBothTitlesWithinTheNotificationWidth() { + fun severalThreadsListEveryRowWithItsStatusAndActionsFollowThePriorityThread() { lifecycle.currentState = Lifecycle.State.RESUMED - val raw = "Approval\t${"Long thread name ".repeat(10)}\t${"Project name ".repeat(10)}" + val title = "A long thread title that should wrap rather than disappear" + val data = update("attention", true) + mapOf( + "activity_line_0" to "Approval $title Project", + "activity_line_1" to "Working Another thread Other project", + "activity_phase" to "waiting_for_approval", + "activity_active_count" to "8", + "activity_attention_count" to "1", + ) + AgentNotifications.receive(context, data) + val card = manager.activeNotifications.single().notification + assertEquals("1 needs you", card.extras.getCharSequence(Notification.EXTRA_TITLE).toString()) + assertEquals("8 active", card.extras.getString(Notification.EXTRA_SUB_TEXT)) + assertEquals( + "Approval $title · Project\nWorking Another thread · Other project", + card.extras.getCharSequence(Notification.EXTRA_BIG_TEXT).toString() + ) + assertEquals( + "Approval $title · Project", + card.extras.getCharSequence(Notification.EXTRA_TEXT).toString() + ) + assertEquals(listOf("Approve", "Dismiss"), card.actions.map { it.title.toString() }) + assertEquals( + "t3code-dev://threads/environment/thread", + shadowOf(card.actions[0].actionIntent).savedIntent.dataString + ) + assertEquals("Approve", card.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) + AgentNotifications.receive( context, - update("long-work", true) + (0..4).associate { "activity_line_$it" to raw } - ) - val lines = manager.activeNotifications.single().notification.extras.getString( - Notification.EXTRA_BIG_TEXT - )!!.split('\n') - assertEquals(5, lines.size) - for (line in lines) { - assertTrue(line.startsWith("Approval: ")) - assertTrue(line.contains(" · ")) - assertTrue(line.length < raw.length) - assertFalse(line.contains('\t')) - assertTrue(line.substringAfter(" · ").isNotBlank()) + data + mapOf( + "activity_phase" to "waiting_for_input", + "activity_attention_count" to "2", + "activity_path" to "/threads/another-environment/another-thread", + ) + ) + val next = manager.activeNotifications.single().notification + assertEquals("2 need you", next.extras.getCharSequence(Notification.EXTRA_TITLE).toString()) + assertEquals("Answer", next.actions[0].title.toString()) + assertEquals( + "t3code-dev://threads/another-environment/another-thread", + shadowOf(next.actions[0].actionIntent).savedIntent.dataString + ) + assertEquals("Answer", next.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) + } + + @Test + fun waitingCardsIgnoreMutableThreadTimestampsEvenAfterRename() { + lifecycle.currentState = Lifecycle.State.RESUMED + val now = System.currentTimeMillis() + for (phase in listOf("waiting_for_approval", "waiting_for_input")) { + val status = if (phase == "waiting_for_approval") "Approval" else "Input" + for ((title, updatedAt) in listOf("Original" to now - 1200000L, "Renamed" to now)) { + AgentNotifications.receive( + context, + update("waiting", true) + mapOf( + "activity_line_0" to "$status\t$title\tProject", + "activity_phase" to phase, + "activity_since" to updatedAt.toString() + ) + ) + val card = manager.activeNotifications.single().notification + assertEquals(title, card.extras.getCharSequence(Notification.EXTRA_TITLE).toString()) + assertFalse(card.extras.getBoolean(Notification.EXTRA_SHOW_WHEN)) + assertFalse(card.extras.getBoolean(Notification.EXTRA_SHOW_CHRONOMETER)) + } } } + @Test + fun aSingleThreadUsesItsTitleAndNeverShowsAProgressBar() { + lifecycle.currentState = Lifecycle.State.RESUMED + val data = update("work", true) + mapOf( + "activity_line_0" to "Working Update dashboard Project", + "activity_phase" to "running", + ) + AgentNotifications.receive(context, data) + val working = manager.activeNotifications.single().notification + assertEquals( + "Update dashboard", + working.extras.getCharSequence(Notification.EXTRA_TITLE).toString() + ) + assertEquals( + "Working Project", + working.extras.getCharSequence(Notification.EXTRA_BIG_TEXT).toString() + ) + assertEquals(null, working.extras.getString(Notification.EXTRA_SUB_TEXT)) + assertEquals("Working", working.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) + assertFalse(working.extras.getBoolean(Notification.EXTRA_SHOW_CHRONOMETER)) + for (phase in listOf( + "waiting_for_approval", + "waiting_for_input", + "stale", + "failed", + "completed" + )) { + val active = phase != "failed" && phase != "completed" + AgentNotifications.receive( + context, + data + mapOf( + "activity_phase" to phase, + "active" to active.toString(), + "activity_expires_at" to (System.currentTimeMillis() + 900000).toString(), + ) + ) + val card = manager.activeNotifications.single().notification + assertEquals( + "android.app.Notification\$BigTextStyle", + card.extras.getString(Notification.EXTRA_TEMPLATE) + ) + assertEquals(active, NotificationCompat.isRequestPromotedOngoing(card)) + if (!active) { + assertEquals(null, card.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) + assertEquals(0, card.actions?.size ?: 0) + } + } + } + + @Test + fun olderRelayRowsStillSelectTheNativeStateAndAction() { + lifecycle.currentState = Lifecycle.State.RESUMED + AgentNotifications.receive( + context, + update("input", true) + mapOf( + "activity_line_0" to "Input Choose an icon Project", + ) + ) + val card = manager.activeNotifications.single().notification + assertEquals("Choose an icon", card.extras.getCharSequence(Notification.EXTRA_TITLE).toString()) + assertEquals("Answer", card.actions.first().title.toString()) + assertEquals(2, card.actions.size) + assertFalse(card.extras.getBoolean(Notification.EXTRA_SHOW_CHRONOMETER)) + } + + @Test + fun multipleAgentsUseTheChipCountAndFinishedThreadsRemainInTheSummary() { + lifecycle.currentState = Lifecycle.State.RESUMED + val data = update("multiple", true) + mapOf( + "activity_line_0" to "Working Build feature Project", + "activity_line_1" to "Done Write tests Project", + "activity_phase" to "running", + "activity_active_count" to "2", + ) + AgentNotifications.receive(context, data) + val card = manager.activeNotifications.single().notification + assertEquals("2 live", card.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) + assertEquals("2 working", card.extras.getCharSequence(Notification.EXTRA_TITLE).toString()) + assertEquals("Project · 2 active", card.extras.getString(Notification.EXTRA_SUB_TEXT)) + assertEquals( + "Working Build feature\nDone Write tests", + card.extras.getCharSequence(Notification.EXTRA_BIG_TEXT).toString() + ) + AgentNotifications.receive(context, data + ("activity_active_count" to "15")) + assertEquals( + "9+ live", + manager.activeNotifications.single().notification.extras + .getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT) + ) + AgentNotifications.receive( + context, + data + mapOf( + "activity_line_0" to "Failed Build feature Project", + "activity_phase" to "failed", + "activity_active_count" to "0", + "active" to "false", + "activity_expires_at" to (System.currentTimeMillis() + 900000).toString(), + ) + ) + val finished = manager.activeNotifications.single().notification + assertEquals( + "Finished, 1 failed", + finished.extras.getCharSequence(Notification.EXTRA_TITLE).toString() + ) + assertEquals("Project · 2 threads", finished.extras.getString(Notification.EXTRA_SUB_TEXT)) + } + private fun assertTimeout(card: Notification, expected: LongRange) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { assertTrue(card.timeoutAfter in expected) @@ -399,6 +556,46 @@ class AgentNotificationsTest { assertEquals(Notification.VISIBILITY_PRIVATE, card.visibility) } + @Test + fun liveUpdateChipChangesWithActivityAndClearsOnCompletion() { + lifecycle.currentState = Lifecycle.State.RESUMED + AgentNotifications.receive(context, update("work", true)) + assertEquals( + "Active", + manager.activeNotifications.single().notification.extras + .getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT) + ) + AgentNotifications.receive(context, update("input", true) + ("activity_chip" to "Review")) + val activeCard = manager.activeNotifications.single().notification + assertEquals( + "Review", + activeCard.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT) + ) + assertTrue(NotificationCompat.isRequestPromotedOngoing(activeCard)) + + AgentNotifications.receive( + context, + update("done", false) + mapOf( + "activity_chip" to "Review", + "activity_expires_at" to (System.currentTimeMillis() + 900000).toString() + ) + ) + val finishedCard = manager.activeNotifications.single().notification + assertEquals(null, finishedCard.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) + assertFalse(NotificationCompat.isRequestPromotedOngoing(finishedCard)) + assertFalse(finishedCard.flags and Notification.FLAG_ONGOING_EVENT != 0) + } + + @Test + fun blankTitleCannotMakeAnActivityIneligibleForPromotion() { + lifecycle.currentState = Lifecycle.State.RESUMED + AgentNotifications.receive(context, update("work", true) + ("activity_title" to " ")) + assertEquals( + "Agent activity", + manager.activeNotifications.single().notification.extras.getString(Notification.EXTRA_TITLE) + ) + } + @Test fun expiredMalformedAndFutureMessagesCannotDisplayOrPoisonLaterUpdates() { val invalid = update("invalid", true) diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift index 523f0d61e0b67..6f2428a6a7de2 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift @@ -87,6 +87,9 @@ public class T3ComposerEditorModule: Module { Prop("spellCheck") { (view: T3ComposerEditorView, spellCheck: Bool) in view.setSpellCheck(spellCheck) } + Prop("enterBehavior") { (view: T3ComposerEditorView, behavior: String) in + view.setEnterBehavior(behavior) + } Prop("textPasteThresholdBytes") { (view: T3ComposerEditorView, threshold: Int) in view.setTextPasteThresholdBytes(threshold) } diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 6258c81c8f971..50ac2afbcb46f 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -45,6 +45,11 @@ private struct ComposerChipStyle { let textColor: UIColor } +private enum ComposerEnterBehavior: String { + case send + case newline +} + private final class ComposerTextAttachment: NSTextAttachment { let source: String let label: String @@ -93,10 +98,12 @@ private final class ComposerTextView: UITextView { var isReadOnly = false var textPasteThresholdBytes = 0 var maxInputChars = Int.max + var enterBehavior: ComposerEnterBehavior = .send private var bypassTextPasteInterception = false override var keyCommands: [UIKeyCommand]? { var commands = super.keyCommands ?? [] + guard !isReadOnly, markedTextRange == nil else { return commands } let submit = UIKeyCommand( input: "\r", modifierFlags: .command, @@ -105,6 +112,25 @@ private final class ComposerTextView: UITextView { submit.discoverabilityTitle = "Send Message" submit.wantsPriorityOverSystemBehavior = true commands.append(submit) + if enterBehavior == .send { + let submitOnReturn = UIKeyCommand( + input: "\r", + modifierFlags: [], + action: #selector(submitMessage(_:)) + ) + submitOnReturn.discoverabilityTitle = "Send Message" + submitOnReturn.wantsPriorityOverSystemBehavior = true + commands.append(submitOnReturn) + + let newline = UIKeyCommand( + input: "\r", + modifierFlags: .shift, + action: #selector(insertNewline(_:)) + ) + newline.discoverabilityTitle = "New Line" + newline.wantsPriorityOverSystemBehavior = true + commands.append(newline) + } if textPasteThresholdBytes > 0 { let pasteAsText = UIKeyCommand( input: "v", @@ -119,9 +145,15 @@ private final class ComposerTextView: UITextView { } @objc private func submitMessage(_ sender: UIKeyCommand) { + guard !isReadOnly, markedTextRange == nil else { return } onSubmit?() } + @objc private func insertNewline(_ sender: UIKeyCommand) { + guard !isReadOnly, markedTextRange == nil else { return } + insertText("\n") + } + @objc private func pasteInline(_ sender: UIKeyCommand) { guard !isReadOnly else { return @@ -132,6 +164,9 @@ private final class ComposerTextView: UITextView { } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { + if action == #selector(submitMessage(_:)) || action == #selector(insertNewline(_:)) { + return isEditable && !isReadOnly && markedTextRange == nil + } if isReadOnly && Self.readOnlyActions.contains(NSStringFromSelector(action)) { return false } @@ -657,6 +692,10 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro textView.spellCheckingType = spellCheck ? .yes : .no } + func setEnterBehavior(_ behavior: String) { + textView.enterBehavior = ComposerEnterBehavior(rawValue: behavior) ?? .send + } + func setTextPasteThresholdBytes(_ threshold: Int) { textView.textPasteThresholdBytes = threshold } diff --git a/apps/mobile/modules/t3-markdown-text/ios/T3ContextChip.h b/apps/mobile/modules/t3-markdown-text/ios/T3ContextChip.h index 09ddd9c0fe86b..625b7ca97c7ba 100644 --- a/apps/mobile/modules/t3-markdown-text/ios/T3ContextChip.h +++ b/apps/mobile/modules/t3-markdown-text/ios/T3ContextChip.h @@ -102,6 +102,7 @@ static inline NSAttributedString *T3MarkdownTextAttachmentString( static UIFont *T3ContextChipFont(NSDictionary *payload) { CGFloat size = MAX(10, MIN(40, [payload[@"fontSize"] doubleValue])); + size *= payload[@"fontSizeMultiplier"] != nil ? [payload[@"fontSizeMultiplier"] doubleValue] : 1; return [UIFont fontWithName:@"DMSans-Medium" size:size] ?: [UIFont systemFontOfSize:size weight:UIFontWeightMedium]; } diff --git a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm index 6afd92eb94b50..e1cc7c2046b2f 100644 --- a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm +++ b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm @@ -197,12 +197,19 @@ static void applyAttachments( } if (props.nativeId.rfind("t3-chip:", 0) == 0 && fragmentLength > 0) { const std::string uri = props.nativeId.substr(3); - NSDictionary *payload = T3ContextChipPayload([NSString stringWithUTF8String:uri.c_str()]); + NSMutableDictionary *payload = + [T3ContextChipPayload([NSString stringWithUTF8String:uri.c_str()]) mutableCopy]; + // Chips must scale with the paragraph or smaller Dynamic Type sizes clip them. + // Store the scaled payload so measurement and the rendered bitmap use the same font. + payload[@"fontSizeMultiplier"] = @(fontSizeMultiplier); + NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]; + NSString *scaledUri = [@"chip:" stringByAppendingString: + [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]; const CGFloat maxWidth = std::isfinite(layoutConstraints.maximumSize.width) ? layoutConstraints.maximumSize.width : 320; const CGSize size = T3ContextChipSize(payload, maxWidth); attachmentRanges.push_back(T3MarkdownTextAttachmentRange{ - utf16Offset, 1, uri, false, + utf16Offset, 1, std::string(scaledUri.UTF8String), false, static_cast(size.width), static_cast(size.height), }); } else if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) { diff --git a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.android.tsx b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.android.tsx index 88ec2cac6d08d..1a2ad538ba025 100644 --- a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.android.tsx +++ b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.android.tsx @@ -45,8 +45,6 @@ export function SelectableMarkdownText(props: SelectableMarkdownTextProps) { [props.fileContextMenu, props.onFileContextMenuAction], ); - // Images need the upstream rich-block renderer. Text-only documents stay in - // one native Text tree so Android can select across every Markdown block. if (content.hasImage) { return ; } diff --git a/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift index 93ca038ff565e..7ad7bc27bf916 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift @@ -20,11 +20,26 @@ public final class T3KeyboardCommandsView: ExpoView { public override var canBecomeFirstResponder: Bool { true } + public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { + if action == #selector(openCommandPalette) || action == #selector(paletteNext) || action == #selector(palettePrevious) || action == #selector(paletteDismiss), + let input = window?.t3FirstResponder as? UITextInput, + input.markedTextRange != nil { + return false + } + return super.canPerformAction(action, withSender: sender) + } + public override var keyCommands: [UIKeyCommand]? { - [ + let isPad = UIDevice.current.userInterfaceIdiom == .pad + var commands = [ enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"), enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"), - enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"), + isPad + ? enabledCommand("commandPalette", input: "k", modifiers: .command, action: #selector(openCommandPalette), title: "Command Palette") + : enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"), + enabledCommand("paletteNext", input: UIKeyCommand.inputDownArrow, modifiers: [], action: #selector(paletteNext), title: "Next Result"), + enabledCommand("palettePrevious", input: UIKeyCommand.inputUpArrow, modifiers: [], action: #selector(palettePrevious), title: "Previous Result"), + enabledCommand("paletteDismiss", input: UIKeyCommand.inputEscape, modifiers: [], action: #selector(paletteDismiss), title: "Close Command Palette"), enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"), enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"), enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"), @@ -41,6 +56,18 @@ public final class T3KeyboardCommandsView: ExpoView { enabledCommand("voiceOutputMute", input: "s", modifiers: [.command, .alternate], action: #selector(muteVoiceOutput), title: "Mute or Unmute Speaker"), enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"), ].compactMap { $0 } + if isPad { + commands += (1...9).compactMap { index in + enabledCommand( + "thread.jump.\(index)", + input: String(index), + modifiers: .command, + action: #selector(jumpToThread(_:)), + title: "Go to Thread \(index)" + ) + } + } + return commands } func setEnabledCommands(_ commands: [String]) { @@ -114,6 +141,14 @@ public final class T3KeyboardCommandsView: ExpoView { @objc private func muteVoice() { emit("voiceMute") } @objc private func muteVoiceOutput() { emit("voiceOutputMute") } @objc private func newTask() { emit("newTask") } + @objc private func openCommandPalette() { emit("commandPalette") } + @objc private func paletteNext() { emit("paletteNext") } + @objc private func palettePrevious() { emit("palettePrevious") } + @objc private func paletteDismiss() { emit("paletteDismiss") } + @objc private func jumpToThread(_ sender: UIKeyCommand) { + guard let input = sender.input else { return } + emit("thread.jump.\(input)") + } @objc private func focusSearch() { emit("focusSearch") } @objc private func goBack() { emit("back") } @objc private func openFiles() { emit("files") } diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index bafdee5810888..133116d03d64c 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -40,6 +40,8 @@ void SplashScreen.preventAutoHideAsync().catch(() => { const appLinking = { prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"], + // Keep the compact thread list available beneath a directly opened thread. + config: { initialRouteName: "Home" }, // The Expo dev client launches the app via // ://expo-development-client/?url= — that URL addresses // the launcher, not app navigation. Without this filter it falls through diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 049cd28889620..a97765e2d9b90 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -23,7 +23,10 @@ import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardi import { AttachmentFileScreen } from "./features/files/AttachmentFileScreen"; import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen"; import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout"; -import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider"; +import { + HardwareKeyboardCommandOverlay, + HardwareKeyboardCommandProvider, +} from "./features/keyboard/HardwareKeyboardCommandProvider"; import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet"; import { ReviewSheet } from "./features/review/ReviewSheet"; import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen"; @@ -31,6 +34,7 @@ import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet"; import { GitCommitSheet } from "./features/threads/git/GitCommitSheet"; import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; +import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl"; import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen"; import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen"; import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen"; @@ -56,6 +60,7 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsCl import { SettingsDiagnosticsRouteScreen } from "./features/diagnostics/SettingsDiagnosticsRouteScreen"; import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; +import { SettingsKeyboardRouteScreen } from "./features/settings/SettingsKeyboardRouteScreen"; import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen"; import { SettingsOpenSourceLicenseRouteScreen, @@ -192,6 +197,13 @@ const SettingsContentStack = createNativeStackNavigator({ title: "Project Grouping", }, }), + SettingsKeyboard: createNativeStackScreen({ + screen: SettingsKeyboardRouteScreen, + linking: "keyboard", + options: { + title: "Keyboard", + }, + }), SettingsClientStorage: createNativeStackScreen({ screen: SettingsClientStorageRouteScreen, linking: "client-storage", @@ -376,22 +388,26 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([ "NewTaskSheet", "SettingsLegal", "SettingsSheet", + "ThreadQueue", "ThreadReviewComment", "ThreadSettingsSheet", ]); /** - * Pathname of the topmost NON-overlay route — the screen the workspace is - * actually "on", regardless of any sheets floating above it. + * Location of the topmost non-overlay route, including its key so thread + * selection can dismiss sheets without replacing the wrong destination. */ -function workspacePathFromState(state: NavigationState): string { +function workspaceLocationFromState(state: NavigationState) { const routes = state.routes.filter((route) => !WORKSPACE_OVERLAY_ROUTES.has(route.name)); const effectiveState = routes.length > 0 && routes.length !== state.routes.length ? ({ ...state, routes, index: routes.length - 1 } as NavigationState) : state; const path = getPathFromState(effectiveState, navigationPathConfig); - return path.startsWith("/") ? path : `/${path}`; + return { + pathname: path.startsWith("/") ? path : `/${path}`, + routeKey: effectiveState.routes[effectiveState.index]?.key, + }; } // The drain hook subscribes to the outbox, all thread shells, projects, and @@ -435,15 +451,19 @@ function RootStackLayout(props: { // workspace layout only reacts to the underlying non-overlay route. const path = getPathFromState(props.state, navigationPathConfig); const pathname = path.startsWith("/") ? path : `/${path}`; - const workspacePathname = workspacePathFromState(props.state); + const workspaceLocation = workspaceLocationFromState(props.state); return ( - + {props.children} + @@ -566,6 +586,15 @@ export const RootStack = createNativeStackNavigator({ }), }, }), + ThreadQueue: createNativeStackScreen({ + screen: ThreadQueueSheet, + options: { + ...FORM_SHEET_PRESENTATION_OPTIONS, + headerShown: false, + sheetAllowedDetents: [0.65, 0.95], + sheetGrabberVisible: true, + }, + }), GitOverview: createNativeStackScreen({ screen: GitOverviewSheet, linking: `${THREAD_LINKING_PREFIX}/git`, diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 0b4261d0c99d6..04382839c909e 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -227,8 +227,7 @@ function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) { // What it *is* decides how it presents, the same way videos are already recognised below. if (attachment.type === "image" || imageMimeType(attachment) !== null) { // A pasted-text marker does not fit the snapshot source a picture carries. - const { source: _droppedSource, ...rest } = - attachment.type === "file" ? attachment : { ...attachment, source: undefined }; + const { source: _droppedSource, ...rest } = attachment; return ( createComposerDraftContextHistory(), [draftKey]); useEffect(() => () => contextHistory.dispose(), [contextHistory]); const changeText = (text: string) => { @@ -158,6 +165,7 @@ export function ComposerEditor({ <> void; + readonly onRetry: () => void; + readonly onRemove: () => void; +}) { + const { clone } = props; + const name = projectCloneDisplayName(clone); + if (clone.phase === "running") { + return ( + + + + + Cloning {name} + + + {projectCloneProgressSummary(clone)} + + + + + ); + } + const cancelled = clone.phase === "cancelled"; + return ( + + + {cancelled ? `Cancelled cloning ${name}` : `Failed to clone ${name}`} + + {clone.error ? ( + + {clone.error} + + ) : null} + + + + + + ); +} + +function BannerAction(props: { readonly label: string; readonly onPress: () => void }) { + return ( + + {props.label} + + ); +} diff --git a/apps/mobile/src/components/ProviderIcon.tsx b/apps/mobile/src/components/ProviderIcon.tsx index 374738d0aecab..2dec5d4444bee 100644 --- a/apps/mobile/src/components/ProviderIcon.tsx +++ b/apps/mobile/src/components/ProviderIcon.tsx @@ -2,14 +2,66 @@ import { Image } from "expo-image"; import { Path, Svg } from "react-native-svg"; import { View } from "react-native"; import { providerInstanceInitials } from "@t3tools/client-runtime/state/provider-instance-display"; +import { useState } from "react"; +import { resolveOfficialAcpRegistryIconUrl } from "@t3tools/contracts"; import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider"; import { AppText as Text } from "./AppText"; type ProviderIconProps = { readonly provider: string | null | undefined; + readonly iconUrl?: string | null | undefined; readonly size?: number; }; +function AcpRegistryFallbackIcon(props: { readonly color: string; readonly size: number }) { + return ( + + + + ); +} + +function AcpRegistryProviderIcon(props: { + readonly color: string; + readonly iconUrl: string | null | undefined; + readonly size: number; +}) { + const iconUrl = resolveOfficialAcpRegistryIconUrl(props.iconUrl); + const [image, setImage] = useState<{ + readonly iconUrl: string; + readonly status: "loaded" | "failed"; + } | null>(null); + const currentImage = image?.iconUrl === iconUrl ? image : null; + const loaded = currentImage?.status === "loaded"; + + return ( + + {!loaded ? : null} + {iconUrl !== null && currentImage?.status !== "failed" ? ( + setImage({ iconUrl, status: "failed" })} + onLoad={() => setImage({ iconUrl, status: "loaded" })} + /> + ) : null} + + ); +} + export function ProviderIcon(props: ProviderIconProps) { const { themeAppearance } = useAppearancePreferences(); const isDarkMode = themeAppearance === "dark"; @@ -25,6 +77,9 @@ export function ProviderIcon(props: ProviderIconProps) { /> ); } + if (props.provider === "acpRegistry") { + return ; + } if (props.provider === "claudeAgent") { return ( @@ -64,6 +119,20 @@ export function ProviderIcon(props: ProviderIconProps) { ); } + if (props.provider === "pi") { + const foreground = isDarkMode ? "#F5F5F5" : "#0F0F0F"; + return ( + + + + + ); + } + if (props.provider === "opencode") { return ( @@ -92,6 +161,7 @@ export function ProviderIcon(props: ProviderIconProps) { * `apps/web/src/components/chat/ProviderInstanceIcon.tsx`. */ export function ProviderInstanceIcon(props: { + readonly iconUrl?: string | null; readonly provider: string | null | undefined; readonly size?: number; readonly displayName: string; @@ -102,7 +172,7 @@ export function ProviderInstanceIcon(props: { return ( - + {props.showBadge ? ( , "children"> & { + readonly children: ReactNode; + readonly interactionClassName?: string; +}) { + const { hovered, hoverGesture } = useHoverGesture(props.disabled ?? false); + return ( + + + {({ pressed }) => ( + <> + + {children} + + )} + + + ); +} diff --git a/apps/mobile/src/components/SegmentedControl.tsx b/apps/mobile/src/components/SegmentedControl.tsx new file mode 100644 index 0000000000000..04a562956c468 --- /dev/null +++ b/apps/mobile/src/components/SegmentedControl.tsx @@ -0,0 +1,74 @@ +import { Platform, Pressable, View } from "react-native"; +import Animated, { Easing, LinearTransition, ReduceMotion } from "react-native-reanimated"; +import { AppText as Text } from "./AppText"; +import { cn } from "../lib/cn"; + +export function SegmentedControl(props: { + readonly options: readonly { + readonly value: Value; + readonly label: string; + readonly accessibilityLabel?: string; + }[]; + readonly selected: Value; + readonly onSelect: (value: Value) => void; + /** The tab bar is full height; filters under it are shorter so it stays primary. */ + readonly size?: "default" | "compact"; + /** "tab" for the view switcher; filters stay plain buttons. */ + readonly role?: "tab" | "button"; + readonly className?: string; +}) { + const compact = props.size === "compact"; + return ( + + option.value === props.selected), + ) * + 100) / + props.options.length + }%`, + }} + /> + {props.options.map((option) => { + const active = option.value === props.selected; + return ( + props.onSelect(option.value)} + className={cn( + "flex-1 items-center justify-center rounded-full", + compact ? "h-9" : "h-11", + )} + > + + {option.label} + + + ); + })} + + ); +} diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts index 036869a0e61ed..98a3d3e9243c1 100644 --- a/apps/mobile/src/connection/environment-cache-store.test.ts +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -160,12 +160,14 @@ function makeDatabase() { const schemaVersions = new Map(); const removed: Array = []; const database = MobileDatabase.of({ + loadCache: (environmentId, kind, cacheKey) => + Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))), listCache: (kind) => Effect.sync(() => - [...values].filter(([key]) => key.includes(`:${kind}:`)).map(([, payload]) => payload), + [...values.entries()] + .filter(([key]) => key.split(":")[1] === kind) + .map(([, payload]) => payload), ), - loadCache: (environmentId, kind, cacheKey) => - Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))), saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) => Effect.sync(() => { const id = cacheId(environmentId, kind, cacheKey); diff --git a/apps/mobile/src/connection/environment-cache-store.ts b/apps/mobile/src/connection/environment-cache-store.ts index 1942cb7cc35d7..3cf5146e91900 100644 --- a/apps/mobile/src/connection/environment-cache-store.ts +++ b/apps/mobile/src/connection/environment-cache-store.ts @@ -12,6 +12,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as MobileDatabase from "../persistence/mobile-database"; +import { attachProjectFaviconDatabase, projectFaviconCache } from "../lib/projectFaviconCache"; const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1; const VCS_REFS_CACHE_SCHEMA_VERSION = 1; @@ -100,6 +101,7 @@ function loadDecodedCache(input: { export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () { const database = yield* MobileDatabase.MobileDatabase; + attachProjectFaviconDatabase(database); return EnvironmentCacheStore.of({ loadShell: Effect.fn("MobileEnvironmentCache.loadShell")((environmentId) => loadDecodedCache({ @@ -111,7 +113,7 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () { decode: decodeStoredShellSnapshot, select: (stored) => stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(), - }), + }).pipe(Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate()))), ), saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) { const payload = yield* encodeStoredShellSnapshot({ @@ -222,9 +224,10 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () { .pipe(Effect.mapError(mapDatabaseError("clear-vcs-refs"))), ), clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) => - database - .clearEnvironmentCache(environmentId) - .pipe(Effect.mapError(mapDatabaseError("clear-environment"))), + Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)).pipe( + Effect.andThen(database.clearEnvironmentCache(environmentId)), + Effect.mapError(mapDatabaseError("clear-environment")), + ), ), }); }); diff --git a/apps/mobile/src/features/agent-awareness/androidNotifications.test.ts b/apps/mobile/src/features/agent-awareness/androidNotifications.test.ts index 5bb472d3a4fab..c8a2eedd4cb5f 100644 --- a/apps/mobile/src/features/agent-awareness/androidNotifications.test.ts +++ b/apps/mobile/src/features/agent-awareness/androidNotifications.test.ts @@ -2,7 +2,13 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; const mocks = vi.hoisted(() => ({ os: "android", - native: null as { configure?: ReturnType; clear?: ReturnType } | null, + version: 36, + openSettings: vi.fn(), + native: null as { + configure?: ReturnType; + clear?: ReturnType; + openLiveUpdateSettings?: ReturnType; + } | null, config: { scheme: ["t3code-preview"], extra: { iosPersonalTeamBuild: false } }, requireModule: vi.fn(), })); @@ -10,7 +16,11 @@ const mocks = vi.hoisted(() => ({ vi.mock("expo", () => ({ requireOptionalNativeModule: mocks.requireModule })); vi.mock("expo-constants", () => ({ default: { expoConfig: mocks.config } })); vi.mock("react-native", () => ({ + Linking: { openSettings: mocks.openSettings }, Platform: { + get Version() { + return mocks.version; + }, get OS() { return mocks.os; }, @@ -20,12 +30,39 @@ vi.mock("react-native", () => ({ beforeEach(() => { vi.resetModules(); mocks.os = "android"; + mocks.version = 36; + mocks.openSettings.mockReset().mockResolvedValue(undefined); mocks.native = { configure: vi.fn(), clear: vi.fn() }; mocks.config.extra.iosPersonalTeamBuild = false; mocks.requireModule.mockReset().mockImplementation(() => mocks.native); }); describe("Android native notification capability", () => { + it("opens the Live Update controls on supported Android builds", async () => { + mocks.native!.openLiveUpdateSettings = vi.fn(() => true); + const { openAndroidLiveUpdateSettings, supportsAndroidLiveUpdateSettings } = + await import("./androidNotifications"); + expect(supportsAndroidLiveUpdateSettings()).toBe(true); + await openAndroidLiveUpdateSettings(); + expect(mocks.native!.openLiveUpdateSettings).toHaveBeenCalledOnce(); + expect(mocks.openSettings).not.toHaveBeenCalled(); + mocks.version = 35; + expect(supportsAndroidLiveUpdateSettings()).toBe(false); + mocks.os = "ios"; + mocks.version = 36; + expect(supportsAndroidLiveUpdateSettings()).toBe(false); + }); + + it.each([undefined, vi.fn(() => false)])( + "falls back to app settings for older binaries or missing system activities (%j)", + async (openLiveUpdateSettings) => { + if (openLiveUpdateSettings) mocks.native!.openLiveUpdateSettings = openLiveUpdateSettings; + const { openAndroidLiveUpdateSettings } = await import("./androidNotifications"); + await openAndroidLiveUpdateSettings(); + expect(mocks.openSettings).toHaveBeenCalledOnce(); + }, + ); + it("uses the installed module and the build variant's deep-link scheme", async () => { const { configureAndroidAgentNotifications, clearAndroidAgentNotifications } = await import("./androidNotifications"); diff --git a/apps/mobile/src/features/agent-awareness/androidNotifications.ts b/apps/mobile/src/features/agent-awareness/androidNotifications.ts index a65ff1758e780..9ffe586ecb812 100644 --- a/apps/mobile/src/features/agent-awareness/androidNotifications.ts +++ b/apps/mobile/src/features/agent-awareness/androidNotifications.ts @@ -1,10 +1,11 @@ import Constants from "expo-constants"; import { requireOptionalNativeModule } from "expo"; -import { Platform } from "react-native"; +import { Linking, Platform } from "react-native"; interface AndroidAgentNotifications { configure(deviceId: string, userId: string, scheme: string, ongoingEnabled: boolean): void; clear(): void; + openLiveUpdateSettings?(): boolean; } const native = @@ -33,3 +34,13 @@ export function configureAndroidAgentNotifications( export function clearAndroidAgentNotifications(): void { native?.clear?.(); } + +export function supportsAndroidLiveUpdateSettings(): boolean { + return Platform.OS === "android" && Number(Platform.Version) >= 36; +} + +export async function openAndroidLiveUpdateSettings(): Promise { + if (!native?.openLiveUpdateSettings?.()) { + await Linking.openSettings(); + } +} diff --git a/apps/mobile/src/features/agent-awareness/localNotificationEvents.test.ts b/apps/mobile/src/features/agent-awareness/localNotificationEvents.test.ts index b85e1f5718b2b..a4b31f0f3a0b3 100644 --- a/apps/mobile/src/features/agent-awareness/localNotificationEvents.test.ts +++ b/apps/mobile/src/features/agent-awareness/localNotificationEvents.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vite-plus/test"; -import { EnvironmentId, ThreadId, RunId, ProviderInstanceId } from "@t3tools/contracts"; -type NotificationThread = Parameters[0][number]; +import { EnvironmentId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts"; import { indexNotificationThreads, localAgentNotificationEvents } from "./localNotificationEvents"; +type NotificationThread = Parameters[0][number]; function thread(input: Partial = {}): NotificationThread { return { diff --git a/apps/mobile/src/features/agent-awareness/notificationPermissions.ts b/apps/mobile/src/features/agent-awareness/notificationPermissions.ts index 736f670456a31..9adcce8c12f5a 100644 --- a/apps/mobile/src/features/agent-awareness/notificationPermissions.ts +++ b/apps/mobile/src/features/agent-awareness/notificationPermissions.ts @@ -40,11 +40,10 @@ export const requestAgentNotificationPermission: Effect.Effect< if (Platform.OS === "android") { yield* Effect.tryPromise({ - try: () => - Notifications.setNotificationChannelAsync("agent-alerts", { - name: "Agent alerts", - importance: Notifications.AndroidImportance.HIGH, - }), + try: async () => { + const { ensureAndroidAgentNotificationChannel } = await import("./localNotifications"); + await ensureAndroidAgentNotificationChannel(); + }, catch: (cause) => new NotificationPermissionRequestError({ cause }), }); } diff --git a/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx b/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx new file mode 100644 index 0000000000000..702aa5f5e8eff --- /dev/null +++ b/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx @@ -0,0 +1,273 @@ +import { findErrorTraceId } from "@t3tools/client-runtime/errors"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { MenuAction } from "@react-native-menu/menu"; +import type { EnvironmentId } from "@t3tools/contracts"; +import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; +import { type ReactNode, useRef, useState } from "react"; +import { + ActivityIndicator, + Alert, + Pressable, + RefreshControl, + ScrollView, + Text, + View, +} from "react-native"; + +import { SymbolView } from "../../components/AppSymbol"; +import { showConfirmDialog } from "../../components/ConfirmDialogHost"; +import { ControlPillMenu } from "../../components/ControlPill"; +import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { + deregisterManagedRelayEnvironmentCommand, + useManagedRelayEnvironments, +} from "./managedRelayState"; + +const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }); + +function linkedAtLabel(value: string): string { + const linkedAt = new Date(value); + return Number.isNaN(linkedAt.getTime()) + ? "Link date unavailable" + : `Linked ${linkedAtFormatter.format(linkedAt)}`; +} + +function endpointLabel(environment: RelayClientEnvironmentRecord): string { + return environment.endpoint.providerKind === "cloudflare_tunnel" + ? "Managed tunnel" + : "Activity publishing only"; +} + +function confirmDeregister(environment: RelayClientEnvironmentRecord, onConfirm: () => void) { + const title = "Deregister server?"; + const message = `“${environment.label}” will be removed from this account. T3 Connect access will be revoked, any managed tunnel will be removed, and a host space will become available. Local connections on your devices are not changed.`; + if (process.env.EXPO_OS === "ios") { + Alert.alert(title, message, [ + { text: "Cancel", style: "cancel" }, + { text: "Deregister", style: "destructive", onPress: onConfirm }, + ]); + return; + } + showConfirmDialog({ title, message, confirmText: "Deregister", destructive: true, onConfirm }); +} + +/** + * The "T3 Connect" custom page inside Clerk's native user profile: every + * environment registered to the signed-in account, with account-level + * deregistration. Mirrors the web UserButton page; connections on this device + * are managed in Settings instead. + */ +export function T3ConnectProfilePage() { + const environmentsState = useManagedRelayEnvironments(); + const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, { + reportFailure: false, + }); + const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] = + useState(null); + const mutationPendingRef = useRef(false); + // Deregistered rows stay in the cached list until the refresh lands, so hide + // them by the linkedAt they had. A re-link produces a new linkedAt and shows again. + const [removedEnvironments, setRemovedEnvironments] = useState<{ + readonly accountId: string | null; + readonly linkedAtById: ReadonlyMap; + }>({ accountId: null, linkedAtById: new Map() }); + + const handleDeregister = async (environment: RelayClientEnvironmentRecord) => { + const accountId = environmentsState.accountId; + if (!accountId || mutationPendingRef.current) return; + + mutationPendingRef.current = true; + setDeregisteringEnvironmentId(environment.environmentId); + const result = await deregisterEnvironment({ + accountId, + environmentId: environment.environmentId, + }); + mutationPendingRef.current = false; + setDeregisteringEnvironmentId(null); + + if (result._tag === "Success") { + setRemovedEnvironments((current) => { + const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []); + linkedAtById.set(environment.environmentId, environment.linkedAt); + return { accountId, linkedAtById }; + }); + environmentsState.refresh(); + return; + } + if (isAtomCommandInterrupted(result)) return; + + const cause = squashAtomCommandFailure(result); + const message = cause instanceof Error ? cause.message : "Could not deregister the server."; + const traceId = findErrorTraceId(cause); + console.error("[t3-connect] Could not deregister environment", { + environmentId: environment.environmentId, + message, + traceId, + cause, + }); + Alert.alert( + "Could not deregister server", + traceId ? `${message}\n\nTrace ID: ${traceId}` : message, + traceId + ? [ + { + text: "Copy trace ID", + onPress: () => copyTextWithHaptic(traceId, { target: "connection-trace-id" }), + }, + { text: "OK", style: "cancel" }, + ] + : undefined, + ); + }; + + const removedEnvironmentLinkedAt = + removedEnvironments.accountId === environmentsState.accountId + ? removedEnvironments.linkedAtById + : new Map(); + const environments = (environmentsState.data ?? []).filter( + (environment) => + removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt, + ); + const isInitialLoad = + !environmentsState.accountId || (environmentsState.data === null && !environmentsState.error); + const errorTraceId = environmentsState.errorTraceId; + + return ( + + } + > + Registered servers + + {environmentsState.error ? ( + <> + + {errorTraceId ? ( + { + copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" }); + }} + /> + ) : null} + + ) : isInitialLoad ? ( + + + Loading environments + + ) : environments.length > 0 ? ( + environments.map((environment) => ( + + ) : ( + + confirmDeregister(environment, () => void handleDeregister(environment)) + } + > + + + + + + + ) + } + /> + )) + ) : ( + + )} + + + Connections on this device are managed in Settings. + + + ); +} + +const ENVIRONMENT_MENU_ACTIONS = [ + { id: "deregister", title: "Deregister", image: "trash", attributes: { destructive: true } }, +] satisfies MenuAction[]; + +// Layout primitives that mirror clerk-ios ClerkKitUI's profile rows so a custom +// page reads as one of Clerk's own screens. System font on purpose: Clerk's +// native views do not use the app's DM Sans. + +function ClerkSectionHeader(props: { readonly children: string }) { + return ( + + {props.children} + + ); +} + +function ClerkRow(props: { + readonly title: string; + readonly subtitle: string; + readonly accessory?: ReactNode; +}) { + return ( + + + + {props.title} + + + {props.subtitle} + + + {props.accessory} + + ); +} + +function ClerkButtonRow(props: { readonly label: string; readonly onPress: () => void }) { + return ( + + {props.label} + + ); +} diff --git a/apps/mobile/src/features/cloud/managedRelayState.ts b/apps/mobile/src/features/cloud/managedRelayState.ts index 8c41d74841e76..375bda715e120 100644 --- a/apps/mobile/src/features/cloud/managedRelayState.ts +++ b/apps/mobile/src/features/cloud/managedRelayState.ts @@ -1,9 +1,15 @@ import { useAtomValue } from "@effect/atom-react"; import { createManagedRelayQueryManager, + deregisterManagedRelayEnvironment, managedRelaySessionAtom, readManagedRelaySnapshotState, } from "@t3tools/client-runtime/relay"; +import { + createAtomCommandScheduler, + createRuntimeCommand, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; import { useCallback, useEffect } from "react"; @@ -19,6 +25,22 @@ export const managedRelayQueryManager = createManagedRelayQueryManager(managedRe cloudDebugLog(`query:${event.operation}:${event.stage}:${event.phase}`, { ...event }), }); +const managedRelayMutationScheduler = createAtomCommandScheduler(); + +export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand( + managedRelayAtomRuntime, + { + label: "mobile:managed-relay:deregister-environment", + scheduler: managedRelayMutationScheduler, + concurrency: { + mode: "serial", + key: (input: { readonly accountId: string; readonly environmentId: EnvironmentId }) => + input.accountId, + }, + execute: (input, registry) => deregisterManagedRelayEnvironment(registry, input), + }, +); + const EMPTY_ENVIRONMENTS_ATOM = Atom.make( AsyncResult.success>([]), ).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null")); diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index 9573a597f82e6..d511fd3aee917 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -204,11 +204,11 @@ function FileContent(props: { return ( {props.truncated ? ( - - + + Partial file - + Preview limited to the first 1 MB of a truncated file. diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index 00731ce5aeec3..b11f953ca718e 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -5,7 +5,7 @@ import { useEffect, useMemo, useState } from "react"; import { Platform, useWindowDimensions } from "react-native"; import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; -import { useProjects, useThreadShells } from "../../state/entities"; +import { useProjects, useNavigationThreadShells } from "../../state/entities"; import { usePendingNewTasks } from "../../state/use-pending-new-tasks"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; @@ -29,7 +29,7 @@ export function HomeRouteScreen() { const { width: windowWidth } = useWindowDimensions(); const { layout } = useAdaptiveWorkspaceLayout(); const projects = useProjects(); - const threads = useThreadShells(); + const threads = useNavigationThreadShells(); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); const { savedConnectionsById } = useSavedRemoteConnections(); const navigation = useNavigation(); diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 0901b09b40f75..add3e6a0dff39 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -1,6 +1,6 @@ import { PitbossPins } from "../threads/PitbossWork"; -import type { ThreadMoveDestination } from "../threads/threadOrder"; -import { createThreadMovePlanner } from "../threads/threadOrder"; +import { resolveThreadProviderInstance } from "../threads/thread-provider-instance"; +import { createThreadMovePlanner, type ThreadMoveDestination } from "../threads/threadOrder"; import { LegendList, type LegendListRef, @@ -38,6 +38,7 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { useThreadSearch } from "../../state/queries"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; +import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts"; import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled"; import { usePendingThreadOrder } from "../../state/thread-order"; import { environmentServerConfigsAtom } from "../../state/server"; @@ -55,11 +56,11 @@ import { ThreadListV2SettledShelfHeader, ThreadListV2SnoozedShelfHeader, } from "../threads/thread-list-v2-items"; -import { resolveThreadProviderInstance } from "../threads/thread-provider-instance"; import { buildThreadListV2Items, getThreadListV2OrderedSection, buildThreadListV2ListItems, + resolveThreadListV2ProviderDrivers, THREAD_LIST_V2_SETTLED_INITIAL_COUNT, THREAD_LIST_V2_SETTLED_PAGE_COUNT, type ThreadListV2ListItem, @@ -202,7 +203,7 @@ function deriveEmptyState(props: { return { title: "No threads yet", - detail: "Create a task to start a new coding session in one of your connected projects.", + detail: "Create a task to start a new coding runtime in one of your connected projects.", loading: false, }; } @@ -776,6 +777,11 @@ export function HomeScreen(props: HomeScreenProps) { [settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks], ); + useThreadJumpShortcuts( + threadListV2Enabled ? threadListV2Items : listLayout.items, + props.onSelectThread, + ); + const renderV2Item = useCallback( ({ item, index }: { readonly item: ThreadListV2ListItem; readonly index: number }) => { const nextItem = threadListV2Items[index + 1]; @@ -829,6 +835,13 @@ export function HomeScreen(props: HomeScreenProps) { const thread = item.item.thread; const movePlanner = item.item.pinned ? threadMovePlanners.pinned : threadMovePlanners.active; const movedId = `${thread.environmentId}:${thread.id}`; + const provider = serverConfigs + .get(thread.environmentId) + ?.providers.find( + (candidate) => + candidate.instanceId === + (thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId), + ); return ( 1 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null) @@ -1141,7 +1159,7 @@ export function HomeScreen(props: HomeScreenProps) { detail="Choose another environment or create a new task." /> ) : ( - + ) ) : null; // Use the v2 project scope for its empty state. Snoozed threads need no diff --git a/apps/mobile/src/features/home/homeListItems.test.ts b/apps/mobile/src/features/home/homeListItems.test.ts index 89727851a921d..865dc17e6d3fa 100644 --- a/apps/mobile/src/features/home/homeListItems.test.ts +++ b/apps/mobile/src/features/home/homeListItems.test.ts @@ -17,6 +17,7 @@ import { type HomeListItem, } from "./homeListItems"; import type { HomeThreadGroup } from "./homeThreadList"; +import { threadJumpTarget } from "../keyboard/threadKeyboardShortcuts"; const environmentId = EnvironmentId.make("environment-1"); @@ -100,6 +101,28 @@ function displayStates( return new Map(Object.entries(entries)); } +describe("threadJumpTarget", () => { + it("numbers only displayed threads across groups, skipping collapsed groups and pagination rows", () => { + const layout = buildHomeListLayout({ + groups: [makeGroup("collapsed", 3), makeGroup("alpha", 8), makeGroup("beta", 3)], + displayStates: displayStates({ collapsed: { collapsed: true, visibleCount: 6 } }), + }); + expect(threadJumpTarget(layout.items, "thread.jump.1")?.id).toBe("alpha-thread-0"); + expect(threadJumpTarget(layout.items, "thread.jump.7")?.id).toBe("beta-thread-0"); + expect(threadJumpTarget(layout.items, "thread.jump.9")?.id).toBe("beta-thread-2"); + }); + + it("ignores missing positions and unrelated commands", () => { + const layout = buildHomeListLayout({ + groups: [makeGroup("alpha", 1)], + displayStates: displayStates({}), + }); + expect(threadJumpTarget(layout.items, "thread.jump.2")).toBeNull(); + expect(threadJumpTarget([], "thread.jump.1")).toBeNull(); + expect(threadJumpTarget(layout.items, "commandPalette")).toBeNull(); + }); +}); + describe("buildHomeListLayout", () => { it("renders a header plus all threads for a small group without a show-more row", () => { const layout = buildHomeListLayout({ diff --git a/apps/mobile/src/features/home/threadArchive.ts b/apps/mobile/src/features/home/threadArchive.ts index 8eaf9fa541d5b..5f0e0c2d6d275 100644 --- a/apps/mobile/src/features/home/threadArchive.ts +++ b/apps/mobile/src/features/home/threadArchive.ts @@ -1,16 +1,12 @@ -import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models"; +import { + threadRuntimeCanArchive, + type ThreadRuntimeSummary, +} from "@t3tools/client-runtime/state/models"; /** * Archiving may discard queued work, but it must not detach a provider while * that provider is still executing a turn. */ export function threadCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean { - if (runtime?.status === "queued") { - return runtime.activeRunId === null; - } - return ( - runtime?.status !== "preparing" && - runtime?.status !== "starting" && - runtime?.status !== "running" - ); + return threadRuntimeCanArchive(runtime); } diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 9e06000dc28a0..4cd2040a58a7b 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -6,7 +6,6 @@ import * as Haptics from "expo-haptics"; import { useCallback, useRef } from "react"; import { Alert } from "react-native"; -import { threadCanArchive } from "./threadArchive"; import { withThreadDismissal } from "./thread-dismissal"; import { showConfirmDialog } from "../../components/ConfirmDialogHost"; import { scopedThreadKey } from "../../lib/scopedEntities"; @@ -28,6 +27,7 @@ import { threadDropLifecycle, } from "../threads/threadOrder"; import { getThreadListV2OrderedSection } from "../threads/threadListV2"; +import { threadCanArchive } from "./threadArchive"; /** Version skew: never send settle/unsettle to a server that predates them (capability defaults false on decode for older servers). */ diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx new file mode 100644 index 0000000000000..0b96f7d6a126f --- /dev/null +++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx @@ -0,0 +1,472 @@ +import { useNavigation } from "@react-navigation/native"; +import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search"; +import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts"; +import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + FlatList, + KeyboardAvoidingView, + Modal, + Pressable, + TextInput, + useWindowDimensions, + View, +} from "react-native"; + +import { GestureHandlerRootView } from "react-native-gesture-handler"; + +import { RowPressable } from "../../components/RowPressable"; +import { AppText as Text } from "../../components/AppText"; +import { SymbolView, type AppSymbolName } from "../../components/AppSymbol"; +import { GlassSurface } from "../../components/GlassSurface"; +import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; +import { T3KeyboardCommands } from "../../native/T3KeyboardCommands"; +import { useProjects, useThreadShell, useThreadShells } from "../../state/entities"; +import { useThreadSearch } from "../../state/queries"; +import { useWorkspaceState } from "../../state/workspace"; +import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; +import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; +import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match"; +import { + filterCommandPaletteItems, + nextPaletteIndex, + type CommandPaletteItem, +} from "./commandPaletteItems"; +import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands"; +import { threadJumpIndex } from "./threadKeyboardShortcuts"; + +const PALETTE_COMMANDS: ReadonlyArray = [ + "commandPalette", + "paletteDismiss", + "paletteNext", + "palettePrevious", + ...THREAD_JUMP_KEYBINDING_COMMANDS, +]; +const ROW_HEIGHT = 50; + +const ACTION_ICONS: Record = { + newTask: "square.and.pencil", + newThread: "square.and.pencil", + addProject: "folder.badge.plus", + settings: "gearshape", + appearance: "paintbrush", + environments: "desktopcomputer", + usage: "chart.bar.xaxis", + archive: "archivebox", + files: "doc.text", + terminal: "terminal", + review: "arrow.triangle.pull", + copyThreadReference: "link", +}; + +function itemIcon(item: CommandPaletteItem): AppSymbolName { + if (item.kind === "project") return "folder"; + if (item.kind === "thread") return "text.bubble"; + return ACTION_ICONS[item.key] ?? "ellipsis"; +} + +function PaletteRow(props: { + readonly item: CommandPaletteItem; + readonly index: number; + readonly selected: boolean; + readonly searchMatch?: EnvironmentThreadSearchMatch; + readonly searchQuery: string; + readonly onSelect: () => void; +}) { + return ( + + + + + + + {props.item.title} + + {props.searchMatch ? ( + + ) : props.item.detail ? ( + + {props.item.detail} + + ) : null} + + {props.index < 9 ? ( + ⌘{props.index + 1} + ) : null} + + ); +} + +/** Mounted only while open, so the app root does not subscribe to the full thread catalog. */ +export function CommandPalette(props: { + readonly pathname: string; + readonly onClose: () => void; + readonly onCommand: (command: HardwareKeyboardCommand) => void; +}) { + const navigation = useNavigation(); + const { selectThread } = useAdaptiveWorkspaceLayout(); + const runCommand = props.onCommand; + const projects = useProjects(); + const threads = useThreadShells(); + const activeThreadRef = useMemo(() => parseActiveThreadPath(props.pathname), [props.pathname]); + const activeThread = useThreadShell(activeThreadRef); + const { environments } = useWorkspaceState(); + const { savedConnectionsById } = useSavedRemoteConnections(); + const [query, setQuery] = useState(""); + const [selection, setSelection] = useState(null); + const [visible, setVisible] = useState(true); + const pendingAction = useRef<(() => void) | null>(null); + const closing = useRef(false); + const inputRef = useRef(null); + const listRef = useRef>(null); + const { width, height } = useWindowDimensions(); + const searchEnvironmentIds = useMemo( + () => + environments + .filter((environment) => environment.connectionState === "connected") + .map((environment) => environment.environmentId), + [environments], + ); + const search = useThreadSearch(searchEnvironmentIds, query.startsWith(">") ? "" : query); + const matchedThreadKeys = useMemo( + () => + new Set(search.matches.map((match) => scopedThreadKey(match.environmentId, match.threadId))), + [search.matches], + ); + const contentMatchByKey = useMemo( + () => + new Map( + search.matches + .filter((match) => match.source === "user" || match.source === "assistant") + .map((match) => [scopedThreadKey(match.environmentId, match.threadId), match]), + ), + [search.matches], + ); + const items = useMemo(() => { + const actions: CommandPaletteItem[] = [ + { + key: "newTask", + kind: "action", + title: "New thread in…", + searchTerms: ["new task", "chat", "create", "project"], + run: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }), + }, + { + key: "addProject", + kind: "action", + title: "Add project", + searchTerms: ["folder", "clone", "repository", "git"], + run: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }), + }, + { + key: "settings", + kind: "action", + title: "Open settings", + searchTerms: ["preferences", "configuration"], + run: () => + navigation.navigate("SettingsSheet", { + screen: "SettingsContent", + params: { screen: "Settings" }, + }), + }, + { + key: "appearance", + kind: "action", + title: "Appearance", + searchTerms: ["theme", "colors", "dark", "light"], + run: () => + navigation.navigate("SettingsSheet", { + screen: "SettingsContent", + params: { screen: "SettingsAppearance" }, + }), + }, + { + key: "environments", + kind: "action", + title: "Manage environments", + searchTerms: ["connections", "server", "remote"], + run: () => + navigation.navigate("SettingsSheet", { + screen: "SettingsContent", + params: { screen: "SettingsEnvironments" }, + }), + }, + { + key: "usage", + kind: "action", + title: "Usage", + searchTerms: ["limits", "accounts", "quota"], + run: () => + navigation.navigate("SettingsSheet", { + screen: "SettingsContent", + params: { screen: "SettingsUsage" }, + }), + }, + { + key: "archive", + kind: "action", + title: "Archived threads", + searchTerms: ["restore", "history"], + run: () => + navigation.navigate("SettingsSheet", { + screen: "SettingsContent", + params: { screen: "SettingsArchive" }, + }), + }, + ]; + const projectByKey = new Map( + projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]), + ); + const activeProject = activeThread + ? projectByKey.get(scopedProjectKey(activeThread.environmentId, activeThread.projectId)) + : null; + if (activeProject) { + actions.unshift({ + key: "newThread", + kind: "action", + title: `New thread in ${activeProject.title}`, + searchTerms: ["new task", "chat", "create"], + run: () => + navigation.navigate("NewTaskSheet", { + screen: "NewTaskDraft", + params: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + title: activeProject.title, + }, + }), + }); + } + if (activeThreadRef) { + const threadActions = [ + ["files", "Go to file", ["open", "files", "browse", "search"]], + ["terminal", "Open terminal", ["shell", "console"]], + ["review", "Review changes", ["diff", "git", "pull request"]], + ["copyThreadReference", "Copy PR link or thread ID", ["reference", "clipboard"]], + ] as const; + actions.push( + ...threadActions.map(([command, title, searchTerms]) => ({ + key: command, + kind: "action" as const, + title, + searchTerms, + run: () => runCommand(command), + })), + ); + } + const projectItems: CommandPaletteItem[] = projects.map((project) => ({ + key: `project:${scopedProjectKey(project.environmentId, project.id)}`, + kind: "project", + title: project.title, + detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`, + searchTerms: [project.workspaceRoot, "new thread", "project"], + run: () => + navigation.navigate("NewTaskSheet", { + screen: "NewTaskDraft", + params: { + environmentId: project.environmentId, + projectId: project.id, + title: project.title, + }, + }), + })); + const threadItems: CommandPaletteItem[] = threads + .filter((thread) => thread.archivedAt === null) + .sort((left, right) => + (right.latestUserMessageAt ?? right.updatedAt).localeCompare( + left.latestUserMessageAt ?? left.updatedAt, + ), + ) + .map((thread) => { + const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)); + const environment = + savedConnectionsById[thread.environmentId]?.environmentLabel ?? thread.environmentId; + return { + key: scopedThreadKey(thread.environmentId, thread.id), + kind: "thread", + title: thread.title || "Untitled thread", + detail: [project?.title, environment].filter(Boolean).join(" · "), + searchTerms: [ + project?.title ?? "", + environment, + thread.branch ?? "", + ...threadPullRequestSearchTerms(thread), + ], + run: () => selectThread(thread), + }; + }); + return [...actions, ...projectItems, ...threadItems]; + }, [ + activeThread, + activeThreadRef, + navigation, + projects, + runCommand, + savedConnectionsById, + selectThread, + threads, + ]); + const results = useMemo( + () => filterCommandPaletteItems(items, query, matchedThreadKeys), + [items, matchedThreadKeys, query], + ); + const selectedIndex = Math.max( + 0, + results.findIndex((item) => item.key === selection), + ); + const selectedKey = results[selectedIndex]?.key; + useEffect(() => { + if (selectedIndex === 0) { + // Centering before the list measures its height scrolls half the first row out of view. + listRef.current?.scrollToOffset({ offset: 0, animated: false }); + } else if (selectedKey !== undefined) { + listRef.current?.scrollToIndex({ index: selectedIndex, animated: false, viewPosition: 0.5 }); + } + }, [selectedIndex, selectedKey]); + + const dismissed = useRef(false); + const handleDismissed = useCallback(() => { + if (dismissed.current) return; + dismissed.current = true; + // Present navigation sheets only after UIKit has dismissed this modal. + props.onClose(); + pendingAction.current?.(); + }, [props]); + + // iOS drops Modal onDismiss when the VC is dismissed mid-presentation (e.g. + // ⌘K during the fade-in) or raced by another sheet — without a fallback the + // palette stays mounted-but-invisible and ⌘K dead-ends on a stale open state. + useEffect(() => { + if (visible) return; + const fallback = setTimeout(handleDismissed, 400); + return () => clearTimeout(fallback); + }, [visible, handleDismissed]); + + function close(run?: () => void) { + if (closing.current) return; + closing.current = true; + pendingAction.current = run ?? null; + setVisible(false); + } + + function onCommand(command: HardwareKeyboardCommand) { + if (command === "commandPalette" || command === "paletteDismiss") { + close(); + } else if (command === "paletteNext" || command === "palettePrevious") { + setSelection( + results[nextPaletteIndex(selectedIndex, command === "paletteNext" ? 1 : -1, results.length)] + ?.key ?? null, + ); + } else { + const item = results[threadJumpIndex(command)]; + if (item) close(item.run); + } + } + + return ( + inputRef.current?.focus()} + onRequestClose={() => close()} + onDismiss={handleDismissed} + > + + + + close()} + /> + + + + + { + setQuery(value); + setSelection(null); + listRef.current?.scrollToOffset({ offset: 0, animated: false }); + }} + returnKeyType="go" + submitBehavior="submit" + onSubmitEditing={() => { + const item = results[selectedIndex]; + if (item) close(item.run); + }} + /> + + + item.key} + getItemLayout={(_, index) => ({ + length: ROW_HEIGHT, + offset: ROW_HEIGHT * index, + index, + })} + contentContainerClassName="pb-2" + ListEmptyComponent={ + + {search.isPending ? "Searching…" : "No results"} + + } + renderItem={({ item, index }) => ( + close(item.run)} + /> + )} + /> + + + + + + ); +} diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx index 909bbcf5a7623..8a6aa14dbdd9f 100644 --- a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx +++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx @@ -1,6 +1,8 @@ import { StackActions, useNavigation } from "@react-navigation/native"; import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference"; import { + createContext, + use, useCallback, useEffect, useMemo, @@ -8,15 +10,15 @@ import { useState, useSyncExternalStore, type PropsWithChildren, + type ReactNode, } from "react"; import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { T3KeyboardCommands } from "../../native/T3KeyboardCommands"; -import { useProject, useThreadShell } from "../../state/entities"; -import { useEnvironmentQuery } from "../../state/query"; +import { useThreadShell } from "../../state/entities"; import type { GitActionProgress } from "../../state/use-vcs-action-state"; -import { vcsEnvironment } from "../../state/vcs"; import { GitActionProgressOverlay } from "../threads/GitActionProgressOverlay"; +import { CommandPalette } from "./CommandPalette"; import { dispatchHardwareKeyboardCommand, getHardwareKeyboardCommandRegistrationVersion, @@ -33,50 +35,33 @@ const EMPTY_COPY_FEEDBACK: GitActionProgress = { }; const COPY_FEEDBACK_DISMISS_MS = 3_000; +const CommandPaletteContext = createContext(null); + +/** Render inside the workspace so palette actions share its navigation and pane state. */ +export function HardwareKeyboardCommandOverlay() { + return use(CommandPaletteContext); +} + export function HardwareKeyboardCommandProvider({ children, pathname, }: PropsWithChildren<{ readonly pathname: string }>) { const navigation = useNavigation(); + const [paletteOpen, setPaletteOpen] = useState(false); + const closePalette = useCallback(() => setPaletteOpen(false), []); const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]); const activeThread = useThreadShell(activeThreadRef); - const activeProjectRef = useMemo( - () => - activeThread === null - ? null - : { - environmentId: activeThread.environmentId, - projectId: activeThread.projectId, - }, - [activeThread], - ); - const activeProject = useProject(activeProjectRef); - const activeThreadCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot ?? null; - const gitStatus = useEnvironmentQuery( - activeThread !== null && - activeThread.linkedPullRequest == null && - activeThread.branch !== null && - activeThreadCwd !== null - ? vcsEnvironment.status({ - environmentId: activeThread.environmentId, - input: { cwd: activeThreadCwd }, - }) - : null, - ).data; - const detectedPullRequestUrl = - activeThread?.branch != null && gitStatus?.refName === activeThread.branch - ? (gitStatus.pr?.url ?? null) - : null; const copyTarget = useMemo( () => activeThreadRef === null ? null : resolveThreadReferenceCopyTarget({ threadId: activeThread?.id ?? activeThreadRef.threadId, - linkedPullRequestUrl: activeThread?.linkedPullRequest?.url ?? null, - detectedPullRequestUrl, + pullRequests: activeThread?.pullRequests, + linkedPullRequestUrl: + (activeThread?.linkedPullRequest ?? activeThread?.branchPullRequest)?.url ?? null, }), - [activeThread, activeThreadRef, detectedPullRequestUrl], + [activeThread, activeThreadRef], ); const [copyFeedback, setCopyFeedback] = useState(EMPTY_COPY_FEEDBACK); const copyRequestIdRef = useRef(0); @@ -114,6 +99,12 @@ export function HardwareKeyboardCommandProvider({ const enabledCommands = useMemo(() => { const commands = new Set(getRegisteredHardwareKeyboardCommands()); commands.add("newTask"); + commands.add("commandPalette"); + if (pathname !== "/" && !pathname.startsWith("/threads/")) { + for (const command of commands) { + if (command.startsWith("thread.jump.")) commands.delete(command); + } + } if (pathname !== "/" || navigation.canGoBack()) commands.add("back"); if (activeThreadRef !== null) { commands.add("files"); @@ -122,10 +113,14 @@ export function HardwareKeyboardCommandProvider({ if (pathname.split("/")[4] !== "terminal") commands.add("copyThreadReference"); } return [...commands]; - }, [pathname, registrationVersion, navigation]); + }, [activeThreadRef, pathname, registrationVersion, navigation]); const onCommand = useCallback( (command: HardwareKeyboardCommand) => { + if (command === "commandPalette") { + setPaletteOpen(true); + return; + } if (dispatchHardwareKeyboardCommand(command)) return; if (command === "copyThreadReference") { @@ -180,12 +175,20 @@ export function HardwareKeyboardCommandProvider({ [copyTarget, navigation, pathname, showCopyFeedback], ); + const palette = useMemo( + () => + paletteOpen ? ( + + ) : null, + [closePalette, onCommand, paletteOpen, pathname], + ); + return ( - <> + {children} - + ); } diff --git a/apps/mobile/src/features/keyboard/commandPaletteItems.test.ts b/apps/mobile/src/features/keyboard/commandPaletteItems.test.ts new file mode 100644 index 0000000000000..2a383b80369d8 --- /dev/null +++ b/apps/mobile/src/features/keyboard/commandPaletteItems.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + filterCommandPaletteItems, + nextPaletteIndex, + type CommandPaletteItem, +} from "./commandPaletteItems"; + +function item( + key: string, + title: string, + kind: CommandPaletteItem["kind"], + searchTerms: string[] = [], +): CommandPaletteItem { + return { key, title, kind, searchTerms, run: () => {} }; +} + +const items = [ + item("new", "New thread in…", "action", ["project", "create"]), + item("settings", "Open settings", "action", ["preferences"]), + item("project", "Mobile app", "project", ["/workspaces/mobile", "new thread"]), + item("siva:one", "Keyboard shortcuts", "thread", ["Mobile app", "Siva"]), + item("mac:one", "Mobile app", "thread", ["Mac"]), +]; +const emptyMatches = new Set(); + +describe("filterCommandPaletteItems", () => { + it("shows actions and recent threads in their original order when the query is empty", () => { + expect(filterCommandPaletteItems(items, "", emptyMatches).map((item) => item.key)).toEqual([ + "new", + "settings", + "siva:one", + "mac:one", + ]); + }); + + it("matches query tokens across titles and metadata and ranks exact titles first", () => { + expect( + filterCommandPaletteItems(items, " MOBILE app ", emptyMatches).map((item) => item.key), + ).toEqual(["project", "mac:one", "siva:one"]); + expect( + filterCommandPaletteItems(items, "siva keyboard", emptyMatches).map((item) => item.key), + ).toEqual(["siva:one"]); + }); + + it("supports the desktop actions-only prefix and action aliases", () => { + expect(filterCommandPaletteItems(items, ">", emptyMatches).map((item) => item.key)).toEqual([ + "new", + "settings", + ]); + expect( + filterCommandPaletteItems(items, "> preferences", emptyMatches).map((item) => item.key), + ).toEqual(["settings"]); + expect( + filterCommandPaletteItems(items, "> new thread", emptyMatches).map((item) => item.key), + ).toEqual(["new"]); + }); + + it("includes server content matches scoped to the correct environment, except in actions-only mode", () => { + const matches = new Set(["siva:one", "project"]); + expect( + filterCommandPaletteItems(items, "message content", matches).map((item) => item.key), + ).toEqual(["siva:one"]); + expect(filterCommandPaletteItems(items, "> message content", matches)).toEqual([]); + }); +}); + +describe("nextPaletteIndex", () => { + it("wraps arrow navigation in both directions and handles empty results", () => { + expect(nextPaletteIndex(0, -1, 3)).toBe(2); + expect(nextPaletteIndex(2, 1, 3)).toBe(0); + expect(nextPaletteIndex(0, 1, 3)).toBe(1); + expect(nextPaletteIndex(0, -1, 0)).toBe(0); + expect(nextPaletteIndex(0, 1, 0)).toBe(0); + }); +}); diff --git a/apps/mobile/src/features/keyboard/commandPaletteItems.ts b/apps/mobile/src/features/keyboard/commandPaletteItems.ts new file mode 100644 index 0000000000000..6a06fd4e3387b --- /dev/null +++ b/apps/mobile/src/features/keyboard/commandPaletteItems.ts @@ -0,0 +1,46 @@ +export interface CommandPaletteItem { + readonly key: string; + readonly kind: "action" | "project" | "thread"; + readonly title: string; + readonly detail?: string; + readonly searchTerms: ReadonlyArray; + readonly run: () => void; +} + +/** `>` narrows to actions, matching the desktop palette. Stable ties retain recent-thread order. */ +export function filterCommandPaletteItems( + items: ReadonlyArray, + query: string, + matchedThreadKeys: ReadonlySet, +) { + const actionsOnly = query.startsWith(">"); + const normalized = (actionsOnly ? query.slice(1) : query).trim().toLocaleLowerCase(); + const tokens = normalized.split(/\s+/); + return items + .flatMap((item, index) => { + if (actionsOnly && item.kind !== "action") return []; + if (!normalized) return item.kind === "project" ? [] : [{ item, rank: 0, index }]; + const title = item.title.toLocaleLowerCase(); + const haystack = [title, ...item.searchTerms].join(" ").toLocaleLowerCase(); + if ( + !tokens.every((token) => haystack.includes(token)) && + !(item.kind === "thread" && matchedThreadKeys.has(item.key)) + ) + return []; + const rank = + title === normalized + ? 3 + : title.startsWith(normalized) + ? 2 + : title.includes(normalized) + ? 1 + : 0; + return [{ item, rank, index }]; + }) + .sort((left, right) => right.rank - left.rank || left.index - right.index) + .map(({ item }) => item); +} + +export function nextPaletteIndex(index: number, direction: -1 | 1, count: number) { + return count === 0 ? 0 : (index + direction + count) % count; +} diff --git a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts index 32b85d5e327f4..cbe0e409a7d35 100644 --- a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts +++ b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts @@ -1,7 +1,12 @@ -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId, type ThreadJumpKeybindingCommand } from "@t3tools/contracts"; import { useEffect } from "react"; export type HardwareKeyboardCommand = + | ThreadJumpKeybindingCommand + | "commandPalette" + | "paletteNext" + | "palettePrevious" + | "paletteDismiss" | "voiceToggle" | "voiceMute" | "voiceOutputMute" @@ -14,7 +19,7 @@ export type HardwareKeyboardCommand = | "copyThreadReference" | "toggleSidebar"; -type CommandHandler = () => boolean | void; +type CommandHandler = (command: HardwareKeyboardCommand) => boolean | void; const handlers = new Map>(); const registrationListeners = new Set<() => void>(); @@ -25,18 +30,24 @@ let registrationVersion = 0; * the first chance to consume the command, allowing focused screens to override app defaults. */ export function useHardwareKeyboardCommand( - command: HardwareKeyboardCommand, + command: HardwareKeyboardCommand | ReadonlyArray, handler: CommandHandler, ): void { useEffect(() => { - const commandHandlers = handlers.get(command) ?? new Set(); - commandHandlers.add(handler); - handlers.set(command, commandHandlers); + const commands = typeof command === "string" ? [command] : command; + for (const command of commands) { + const commandHandlers = handlers.get(command) ?? new Set(); + commandHandlers.add(handler); + handlers.set(command, commandHandlers); + } registrationVersion += 1; registrationListeners.forEach((listener) => listener()); return () => { - commandHandlers.delete(handler); - if (commandHandlers.size === 0) handlers.delete(command); + for (const command of commands) { + const commandHandlers = handlers.get(command); + commandHandlers?.delete(handler); + if (commandHandlers?.size === 0) handlers.delete(command); + } registrationVersion += 1; registrationListeners.forEach((listener) => listener()); }; @@ -63,7 +74,7 @@ export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) { const handler = handlersInRegistrationOrder[index]; if (!handler) continue; - if (handler() !== false) return true; + if (handler(command) !== false) return true; } return false; } diff --git a/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.ts b/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.ts new file mode 100644 index 0000000000000..b76d2f8a90bf4 --- /dev/null +++ b/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.ts @@ -0,0 +1,49 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts"; +import { useCallback } from "react"; + +import type { HomeListItem } from "../home/homeListItems"; +import type { ThreadListV2ListItem } from "../threads/threadListV2"; +import { + useHardwareKeyboardCommand, + type HardwareKeyboardCommand, +} from "./hardwareKeyboardCommands"; + +type ThreadShortcutListItem = + | HomeListItem + | ThreadListV2ListItem + | { readonly type: "v2-show-more" }; + +export function threadJumpIndex(command: HardwareKeyboardCommand) { + return THREAD_JUMP_KEYBINDING_COMMANDS.findIndex((candidate) => candidate === command); +} + +/** Uses the rendered list so filters, collapsed groups and shelves keep their order. */ +export function threadJumpTarget( + items: ReadonlyArray, + command: HardwareKeyboardCommand, +) { + let index = threadJumpIndex(command); + if (index < 0) return null; + for (const item of items) { + const thread = + item.type === "thread" ? item.thread : item.type === "v2-thread" ? item.item.thread : null; + if (thread !== null && index-- === 0) return thread; + } + return null; +} + +export function useThreadJumpShortcuts( + items: ReadonlyArray, + onSelectThread: (thread: EnvironmentThreadShell) => void, +) { + const jumpToThread = useCallback( + (command: HardwareKeyboardCommand) => { + const thread = threadJumpTarget(items, command); + if (thread !== null) onSelectThread(thread); + return true; + }, + [items, onSelectThread], + ); + useHardwareKeyboardCommand(THREAD_JUMP_KEYBINDING_COMMANDS, jumpToThread); +} diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 53061ed3a24c8..5dccbb6709d56 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -6,6 +6,7 @@ import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3too import { useAtomValue } from "@effect/atom-react"; import { useFocusEffect } from "@react-navigation/native"; import { + CommonActions, NavigationContext, NavigationRouteContext, StackActions, @@ -41,6 +42,7 @@ import { } from "../../lib/layout"; import { resolveThreadSelectionNavigationAction, + resolveThreadSelectionOverlayState, shouldRestorePrimarySidebar, } from "../../lib/adaptive-navigation"; import { scopedThreadKey } from "../../lib/scopedEntities"; @@ -66,6 +68,7 @@ interface AdaptiveWorkspaceContextValue { readonly panes: WorkspacePaneLayout; readonly fileInspector: FileInspectorPaneLayout; readonly primarySidebarSearchQuery: string; + readonly selectThread: (thread: EnvironmentThreadShell) => void; readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void; /** * Route screens hand their inspector pane content to the workspace so it @@ -99,6 +102,7 @@ const AdaptiveWorkspaceContext = createContext({ panes: compactPanes, fileInspector: compactFileInspector, primarySidebarSearchQuery: "", + selectThread: () => undefined, activateAuxiliaryPaneRole: () => () => undefined, registerWorkspaceInspector: () => () => undefined, setPrimarySidebarSearchQuery: () => undefined, @@ -201,6 +205,7 @@ export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefi export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode; readonly pathname: string; + readonly workspaceRouteKey: string | undefined; }) { const preferencesResult = useAtomValue(mobilePreferencesAtom); if (!AsyncResult.isSuccess(preferencesResult)) { @@ -224,6 +229,7 @@ function AdaptiveWorkspaceLayoutContent( props: { readonly children: ReactNode; readonly pathname: string; + readonly workspaceRouteKey: string | undefined; } & { readonly projectGroupingMode: SidebarProjectGroupingMode; }, @@ -419,35 +425,6 @@ function AdaptiveWorkspaceLayoutContent( }, [auxiliaryPaneRole], ); - const contextValue = useMemo( - () => ({ - layout, - panes, - fileInspector, - primarySidebarSearchQuery, - activateAuxiliaryPaneRole, - registerWorkspaceInspector, - setPrimarySidebarSearchQuery, - showAuxiliaryPane, - toggleAuxiliaryPane, - togglePrimarySidebar, - setAuxiliaryPaneWidth, - }), - [ - activateAuxiliaryPaneRole, - fileInspector, - layout, - panes, - primarySidebarSearchQuery, - registerWorkspaceInspector, - showAuxiliaryPane, - setPrimarySidebarSearchQuery, - setAuxiliaryPaneWidth, - toggleAuxiliaryPane, - togglePrimarySidebar, - ], - ); - const handleOpenSettings = useCallback(() => { navigation.navigate("SettingsSheet", { screen: "SettingsContent", @@ -537,6 +514,17 @@ function AdaptiveWorkspaceLayoutContent( usesSplitView: layout.usesSplitView, pathname, }); + const overlayState = resolveThreadSelectionOverlayState({ + state: navigation.getState(), + workspaceRouteKey: props.workspaceRouteKey, + action: navigationAction, + params, + }); + if (overlayState !== null) { + setFileInspectorPreferredVisible(false); + navigation.dispatch(CommonActions.reset(overlayState)); + return; + } if (navigationAction === "set-params") { const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id); if (nextThreadKey === selectedThreadKey) { @@ -553,7 +541,38 @@ function AdaptiveWorkspaceLayoutContent( } navigation.navigate("Thread", params); }, - [layout.usesSplitView, pathname, navigation, selectedThreadKey], + [layout.usesSplitView, pathname, navigation, selectedThreadKey, props.workspaceRouteKey], + ); + + const contextValue = useMemo( + () => ({ + layout, + panes, + fileInspector, + primarySidebarSearchQuery, + selectThread: handleSelectThread, + activateAuxiliaryPaneRole, + registerWorkspaceInspector, + setPrimarySidebarSearchQuery, + showAuxiliaryPane, + toggleAuxiliaryPane, + togglePrimarySidebar, + setAuxiliaryPaneWidth, + }), + [ + activateAuxiliaryPaneRole, + fileInspector, + handleSelectThread, + layout, + panes, + primarySidebarSearchQuery, + registerWorkspaceInspector, + showAuxiliaryPane, + setPrimarySidebarSearchQuery, + setAuxiliaryPaneWidth, + toggleAuxiliaryPane, + togglePrimarySidebar, + ], ); return ( diff --git a/apps/mobile/src/features/layout/use-fold-workspace-android-back.ts b/apps/mobile/src/features/layout/use-fold-workspace-android-back.ts deleted file mode 100644 index a9f8c9f803df5..0000000000000 --- a/apps/mobile/src/features/layout/use-fold-workspace-android-back.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { useCallback } from "react"; -import { useFocusEffect } from "@react-navigation/native"; -import { BackHandler, Platform } from "react-native"; - -import { resolveAdaptiveWorkspaceBackAction } from "../../lib/adaptive-navigation"; -import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout"; - -/** Unwinds Fold workspace chrome before Android Back leaves the thread. */ -export function useFoldWorkspaceAndroidBack() { - const { layout, panes, toggleAuxiliaryPane, togglePrimarySidebar } = useAdaptiveWorkspaceLayout(); - - useFocusEffect( - useCallback(() => { - if (Platform.OS !== "android" || !layout.usesSplitView) return; - - const subscription = BackHandler.addEventListener("hardwareBackPress", () => { - const action = resolveAdaptiveWorkspaceBackAction({ - auxiliaryPaneVisible: panes.auxiliaryPaneVisible, - primarySidebarVisible: panes.primarySidebarVisible, - }); - if (action === "close-inspector") { - toggleAuxiliaryPane(); - return true; - } - if (action === "show-sidebar") { - togglePrimarySidebar(); - return true; - } - return false; - }); - return () => subscription.remove(); - }, [ - layout.usesSplitView, - panes.auxiliaryPaneVisible, - panes.primarySidebarVisible, - toggleAuxiliaryPane, - togglePrimarySidebar, - ]), - ); -} diff --git a/apps/mobile/src/features/layout/workspace-inspector-pane.tsx b/apps/mobile/src/features/layout/workspace-inspector-pane.tsx index 851caad81fb42..18fbb8851a793 100644 --- a/apps/mobile/src/features/layout/workspace-inspector-pane.tsx +++ b/apps/mobile/src/features/layout/workspace-inspector-pane.tsx @@ -7,8 +7,11 @@ import Animated, { type SharedValue, } from "react-native-reanimated"; -import { type WorkspacePaneLayout } from "../../lib/layout"; -import { constrainFoldablePaneWidth } from "../../lib/foldable-pane-layout"; +import { + constrainAuxiliaryPaneWidth, + RESIZABLE_PANE_COMPACT_WIDTH, + type WorkspacePaneLayout, +} from "../../lib/layout"; import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation"; import { WorkspacePaneDivider } from "./workspace-pane-divider"; @@ -106,9 +109,12 @@ export function WorkspaceInspectorPane(props: { const resizeBy = useCallback( (delta: number) => { setAuxiliaryPaneWidth( - constrainFoldablePaneWidth({ + constrainAuxiliaryPaneWidth({ preferredWidth: resizeStartWidth.current + delta, availableWidth: panes.contentPaneWidth, + minimumMainWidth: RESIZABLE_PANE_COMPACT_WIDTH, + minimumPaneWidth: RESIZABLE_PANE_COMPACT_WIDTH, + maximumPaneWidth: Number.POSITIVE_INFINITY, }), ); }, diff --git a/apps/mobile/src/features/layout/workspace-pane-divider.tsx b/apps/mobile/src/features/layout/workspace-pane-divider.tsx index 63966282266f2..cf640f19106a8 100644 --- a/apps/mobile/src/features/layout/workspace-pane-divider.tsx +++ b/apps/mobile/src/features/layout/workspace-pane-divider.tsx @@ -20,7 +20,6 @@ interface WorkspacePaneDividerProps { export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) { const latestProps = useRef(props); latestProps.current = props; - const [hovered, setHovered] = useState(false); const [dragging, setDragging] = useState(false); const handleResizeStart = useCallback(() => { setDragging(true); @@ -63,7 +62,7 @@ export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) { return ( setHovered(true)} - onHoverOut={() => setHovered(false)} > diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 8d842cd8fe2e5..401297016d66c 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -49,7 +49,7 @@ import * as Order from "effect/Order"; import { AsyncResult } from "effect/unstable/reactivity"; import { cn } from "../../lib/cn"; -import { useProjects, useServerConfigs } from "../../state/entities"; +import { useProjects, useServerConfigs, waitForProject } from "../../state/entities"; import { filesystemEnvironment } from "../../state/filesystem"; import { projectEnvironment } from "../../state/projects"; import { useEnvironmentQuery } from "../../state/query"; @@ -77,6 +77,8 @@ interface EnvironmentOption { readonly connectionState: EnvironmentConnectionPhase; readonly connectionError: string | null; readonly connectionErrorTraceId: string | null; + /** Server runs clones in the background and streams progress; older servers block. */ + readonly supportsCloneTracking: boolean; } const environmentOptionOrder = Order.mapInput( @@ -366,6 +368,7 @@ function useEnvironmentOptions(): ReadonlyArray { connectionState: runtime?.connectionState ?? "available", connectionError: runtime?.connectionError ?? null, connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null, + supportsCloneTracking: config?.environment.capabilities.projectCloneTracking === true, }; }); return Arr.sort(options, environmentOptionOrder); @@ -575,6 +578,15 @@ export function AddProjectSourceScreen() { ); } +function openNewTaskDraft( + navigation: { dispatch: (action: ReturnType) => void }, + params: { environmentId: EnvironmentId; projectId: ProjectId; title: string; cloning?: "1" }, +) { + navigation.dispatch( + CommonActions.reset({ index: 0, routes: [{ name: "NewTaskDraft", params }] }), + ); +} + function useCreateProject(environment: EnvironmentOption | null) { const navigation = useNavigation(); const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); @@ -907,6 +919,10 @@ export function AddProjectDestinationScreen(props: { const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, { reportFailure: false, }); + const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, { + reportFailure: false, + }); + const navigation = useNavigation(); const environment = useEnvironmentFromParam(props.environmentId); const createProject = useCreateProject(environment); const remoteUrl = stringParam(props.remoteUrl); @@ -937,6 +953,48 @@ export function AddProjectDestinationScreen(props: { } setIsSubmitting(true); + if (environment.supportsCloneTracking) { + // The server creates the project and clones in the background; the + // draft screen shows progress and holds Start until the files land. + const projectId = ProjectId.make(uuidv4()); + const title = inferProjectTitleFromPath(resolved.path); + const startResult = await startProjectClone({ + environmentId: environment.environmentId, + input: { + projectId, + title, + createdAt: new Date().toISOString(), + remoteUrl, + destinationPath: resolved.path, + }, + }); + if (AsyncResult.isFailure(startResult)) { + setError(errorMessage(Cause.squash(startResult.cause))); + } else { + // The draft screen resolves its project from the client store, so it + // must not open before the create event has arrived (it would fall + // back to the project picker and lose the clone controls). Stay in + // the submitting state until then; the clone keeps running either way. + const project = await waitForProject( + { environmentId: environment.environmentId, projectId }, + 15_000, + ); + if (project === null) { + setError( + "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.", + ); + } else { + openNewTaskDraft(navigation, { + environmentId: environment.environmentId, + projectId, + title, + cloning: "1", + }); + } + } + setIsSubmitting(false); + return; + } const cloneResult = await cloneRepository({ environmentId: environment.environmentId, input: { @@ -959,8 +1017,10 @@ export function AddProjectDestinationScreen(props: { environment, isBrowseNavigating, isSubmitting, + navigation, pathInput, remoteUrl, + startProjectClone, ]); return ( diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index 5f86f89a5292c..38c7ed104d3c8 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -24,6 +24,7 @@ import { FlatList, Platform, Pressable, + RefreshControl, ScrollView, type NativeSyntheticEvent, StyleSheet, @@ -81,11 +82,9 @@ const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1"; const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) { return ( - - - Partial diff - - {props.notice} + + Partial diff + {props.notice} ); }); @@ -402,7 +401,11 @@ export function ReviewSheet(props: ReviewSheetProps) { selectedSection, draftMessage, }); - const NativeReviewDiffView = resolveNativeReviewDiffView()!; + // Resolution returns null while Expo registers the native view (or forever + // when the binary lacks it). Rendering a null component type crashes the + // app, so callers must fall back — ThreadFeed's ReviewCommentCard does the + // same check. + const NativeReviewDiffView = resolveNativeReviewDiffView(); const nativeReviewDiffViewRef = useRef(null); const showcasedReviewDrawRef = useRef(null); // Native pull-to-refresh on the diff surface (replaces the old Refresh menu item). @@ -604,11 +607,27 @@ export function ReviewSheet(props: ReviewSheetProps) { .filter((part): part is string => Boolean(part)) .join(" · "); - // The changed-files navigator lives in the workspace inspector column — - // the single right-hand pane per route — instead of an in-screen panel. + // The changed-files navigator drives the native diff surface via + // scrollToFile, so it is only useful when that surface resolved. In raw + // fallback mode the ref is necessarily null and the raw patch neither + // scrolls nor filters — registering the navigator would present working + // controls that cannot navigate. const showChangedFilesPane = - !showConnectionNotice && selectedSection !== null && parsedDiff.kind === "files"; + !showConnectionNotice && + selectedSection !== null && + parsedDiff.kind === "files" && + NativeReviewDiffView !== null; useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined); + // Raw fallback renders the patch inline with no inspector content, so the + // pane toggle would open an empty column — hide it in exactly that case. + const showChangedFilesToggle = + panes.supportsAuxiliaryPane && + !( + !showConnectionNotice && + selectedSection !== null && + parsedDiff.kind === "files" && + NativeReviewDiffView === null + ); const listHeader = useMemo(() => { const children: ReactElement[] = []; @@ -695,7 +714,7 @@ export function ReviewSheet(props: ReviewSheetProps) { {!isAndroid && (showSectionToolbar || panes.supportsAuxiliaryPane || gitMenuAvailable) ? ( - {panes.supportsAuxiliaryPane ? ( + {showChangedFilesToggle ? ( - ) : selectedSection && parsedDiff.kind === "files" ? ( + ) : selectedSection && parsedDiff.kind === "files" && NativeReviewDiffView ? ( void handlePullToRefresh()} + /> + } > {listHeader} {!selectedSection ? ( @@ -874,6 +903,19 @@ export function ReviewSheet(props: ReviewSheetProps) { + ) : parsedDiff.kind === "files" ? ( + // The native diff surface could not be resolved on this binary; + // degrade to the raw patch instead of crashing the app. + + + Native diff view unavailable. Showing the raw patch. + + + + {selectedSection?.diff ?? ""} + + + ) : null} )} diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx index 96d612f8c6896..e6e23fd78be92 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx @@ -1,10 +1,21 @@ import { useAuth } from "@clerk/expo"; -import { AuthView, UserProfileView } from "@clerk/expo/native"; +import { AuthView, type UserProfileCustomPage, UserProfileView } from "@clerk/expo/native"; import { StackActions, useNavigation } from "@react-navigation/native"; import { useCallback, useEffect, useLayoutEffect, useRef } from "react"; import { View } from "react-native"; import { hasCloudPublicConfig } from "../cloud/publicConfig"; +import { T3ConnectProfilePage } from "../cloud/T3ConnectProfilePage"; + +// Custom rows in Clerk's native profile. Mirrors the web UserButton pages. +const USER_PROFILE_CUSTOM_PAGES = [ + { + path: "t3-connect", + label: "T3 Connect", + icon: "globe", + content: , + }, +] satisfies UserProfileCustomPage[]; export function SettingsAuthRouteScreen() { const navigation = useNavigation(); @@ -40,7 +51,11 @@ function ConfiguredSettingsAuthRouteScreen() { {isLoaded ? ( hasBeenSignedIn.current ? ( - + ) : ( ) diff --git a/apps/mobile/src/features/settings/SettingsKeyboardRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsKeyboardRouteScreen.tsx new file mode 100644 index 0000000000000..abd6ac22266d2 --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsKeyboardRouteScreen.tsx @@ -0,0 +1,101 @@ +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useNavigation } from "@react-navigation/native"; +import { AsyncResult } from "effect/unstable/reactivity"; +import { Platform, Pressable, 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 { SymbolView } from "../../components/AppSymbol"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { + DEFAULT_COMPOSER_ENTER_BEHAVIOR, + type ComposerEnterBehavior, +} from "../../lib/composerEnterBehavior"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { SettingsSection } from "./components/SettingsSection"; + +const ENTER_BEHAVIOR_OPTIONS: ReadonlyArray<{ + readonly behavior: ComposerEnterBehavior; + readonly label: string; + readonly description: string; +}> = [ + { + behavior: "send", + label: "Send message", + description: "Return sends the message. Shift-Return inserts a new line.", + }, + { + behavior: "newline", + label: "Insert new line", + description: "Return inserts a new line. Command-Return sends the message.", + }, +]; + +export function SettingsKeyboardRouteScreen() { + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); + const preferencesResult = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; + const selectedBehavior = AsyncResult.isSuccess(preferencesResult) + ? (preferencesResult.value.composerEnterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR) + : null; + + return ( + + {Platform.OS === "android" ? ( + <> + + navigation.goBack()} /> + + ) : null} + + + {ENTER_BEHAVIOR_OPTIONS.map((option, index) => ( + savePreferences({ composerEnterBehavior: option.behavior })} + className={ + index === 0 + ? "flex-row items-center gap-4 p-4" + : "flex-row items-center gap-4 border-t border-border-subtle p-4" + } + > + + {option.label} + + {option.description} + + + {selectedBehavior === option.behavior ? ( + + ) : null} + + ))} + + + Applies to the composer when a hardware keyboard is connected. + + + + ); +} diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index d06e61270b586..4483b0fafc3c6 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -22,6 +22,10 @@ import { import { AndroidScreenHeader } from "../../components/AndroidScreenHeader"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities"; +import { + openAndroidLiveUpdateSettings, + supportsAndroidLiveUpdateSettings, +} from "../agent-awareness/androidNotifications"; import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences"; import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions"; import { @@ -572,6 +576,20 @@ function ConfiguredSettingsRouteScreen() { } onValueChange={handleLiveActivitiesChange} /> + {supportsAndroidLiveUpdateSettings() ? ( + { + void openAndroidLiveUpdateSettings().catch(() => { + Alert.alert( + "Couldn't open Settings", + "Open Android Settings, select T3 Code, then enable Live Updates in Notifications.", + ); + }); + }} + /> + ) : null} @@ -594,6 +612,9 @@ function GeneralSettingsSection() { return ( + {Platform.OS === "ios" ? ( + + ) : null} diff --git a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts index a52ee350f5ae0..2ac985a11494d 100644 --- a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts +++ b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts @@ -2,6 +2,7 @@ export type SettingsSheetTarget = | "SettingsEnvironments" | "SettingsArchive" | "SettingsAppearance" + | "SettingsKeyboard" | "SettingsProjectGrouping" | "SettingsClientStorage" | "SettingsDiagnostics" diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index ce5f397c7517e..c1eaeca783021 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -1148,20 +1148,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) return ( <> - {capturedOutput !== null && selectedThread ? ( - setCapturedOutput(null)} - onAttach={() => { - setCapturedOutput(null); - if (navigation.canGoBack()) navigation.goBack(); - }} - /> - ) : null} {!isInspector ? ( navigation.goBack() : undefined} trailing={ <> {layout.usesSplitView && !isInspector ? ( diff --git a/apps/mobile/src/features/threads/CustomSnoozeSheet.ios.tsx b/apps/mobile/src/features/threads/CustomSnoozeSheet.ios.tsx new file mode 100644 index 0000000000000..7f5b69ed224a6 --- /dev/null +++ b/apps/mobile/src/features/threads/CustomSnoozeSheet.ios.tsx @@ -0,0 +1,268 @@ +import { + Button, + DatePicker, + Host, + HStack, + Menu, + Picker, + Popover, + Spacer, + Text, + VStack, +} from "@expo/ui/swift-ui"; +import { + background, + buttonStyle, + datePickerStyle, + font, + foregroundStyle, + frame, + padding, + pickerStyle, + presentationBackground, + shapes, + tag, +} from "@expo/ui/swift-ui/modifiers"; +import { + localSnoozeDate, + localSnoozeTime, + resolveCustomSnooze, + type CustomSnoozeInput, +} from "@t3tools/client-runtime/state/thread-settled"; +import { useState } from "react"; +import { Modal, Pressable, ScrollView, View } from "react-native"; +import { AppText } from "../../components/AppText"; +import { SegmentedControl } from "../../components/SegmentedControl"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; + +const durationAmounts = Array.from({ length: 99 }, (_, index) => index + 1); +const modes = [ + { value: "date", label: "Date and time" }, + { value: "duration", label: "Duration" }, +] as const; +const units = [ + { value: "minutes", label: "Minutes" }, + { value: "hours", label: "Hours" }, + { value: "days", label: "Days" }, +] as const; + +export function CustomSnoozeSheet(props: { + readonly onClose: () => void; + readonly onSnooze: (snoozedUntil: string) => void; +}) { + const [mode, setMode] = useState("date"); + const [date, setDate] = useState(() => new Date(Date.now() + 3_600_000)); + const [amount, setAmount] = useState(2); + const [amountOpen, setAmountOpen] = useState(false); + const [unit, setUnit] = useState<"minutes" | "hours" | "days">("hours"); + const [error, setError] = useState(null); + const { themeVariables: colors, themeAppearance, appearance } = useAppearancePreferences(); + const updateDate = (value: Date) => { + setDate(value); + setError(null); + }; + + const submit = () => { + const input: CustomSnoozeInput = + mode === "date" + ? { mode, date: localSnoozeDate(date), time: localSnoozeTime(date) } + : { mode, amount: String(amount), unit }; + const snoozedUntil = resolveCustomSnooze(input, new Date()); + if (!snoozedUntil) { + setError( + mode === "date" ? "Choose a date and time in the future." : "Enter a positive duration.", + ); + return; + } + props.onSnooze(snoozedUntil); + props.onClose(); + }; + + return ( + + + + + + Cancel + + + Custom snooze + + + Snooze + + + { + setMode(value); + setError(null); + }} + role="tab" + /> + + + {mode === "date" ? "Until" : "Snooze for"} + + {mode === "date" ? ( + <> + + + + ) : ( + <> + + + + + + + { + setAmount(value); + setError(null); + }} + modifiers={[pickerStyle("wheel"), frame({ height: 160 })]} + > + {durationAmounts.map((value) => ( + + {String(value)} + + ))} + + + + + + } + > + {units.map((option) => ( + + + )} + + + {error && {error}} + + + + ); +} + +function FieldLabel(props: { readonly label: string }) { + const { themeVariables: colors } = useAppearancePreferences(); + return ( + + {props.label} + + ); +} + +function SnoozeDateField(props: { + readonly date: Date; + readonly component: "date" | "hourAndMinute"; + readonly onChange: (date: Date) => void; +}) { + const [open, setOpen] = useState(false); + const { themeVariables: colors } = useAppearancePreferences(); + return ( + + + + + + + + + ), + }; + } + const cancelled = activeProjectClone.phase === "cancelled"; + return { + id: `project-clone:${projectId}`, + variant: cancelled ? "warning" : "error", + icon: , + title: cancelled ? `Cancelled cloning ${name}` : `Failed to clone ${name}`, + description: cancelled ? "Retry to bring in the repository." : activeProjectClone.error, + actions: ( + <> + + + + ), + }; + }, [ + activeProjectClone, + activeProjectRef, + cancelProjectClone, + removeClonedProject, + retryProjectClone, + runProjectCloneAction, + ]); const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection; const handleNewThreadInActiveProject = useCallback(() => { startNewThreadForProject(activeProjectRef, handleNewThread); @@ -2564,6 +2717,12 @@ export default function ChatView(props: ChatViewProps) { visitThreadMutation, ]); + // Once a thread selects an environment, never substitute the primary + // environment's config while the selected environment is still loading. + const serverConfig = activeThread + ? (activeEnvironment?.serverConfig ?? null) + : (primaryEnvironment?.serverConfig ?? null); + const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const selectedProviderByThreadId = composerActiveProvider ?? null; const threadProvider = activeThread?.modelSelection.instanceId ?? @@ -2573,13 +2732,9 @@ export default function ChatView(props: ChatViewProps) { thread: activeThread, selectedProvider: selectedProviderByThreadId, threadProvider, + providers: providerStatuses, }); const modelPickerLockedProvider = supportsProviderSwitchingViaHandoff ? null : lockedProvider; - // Once a thread selects an environment, never substitute the primary - // environment's config while the selected environment is still loading. - const serverConfig = activeThread - ? (activeEnvironment?.serverConfig ?? null) - : (primaryEnvironment?.serverConfig ?? null); const pullRequestsCapabilityKnown = serverConfig !== null; const supportsPullRequests = serverConfig?.environment.capabilities.pullRequests === true; const attachmentEnvironmentConfig = environmentById.get(environmentId)?.serverConfig ?? null; @@ -2594,7 +2749,6 @@ export default function ChatView(props: ChatViewProps) { advertisedFileAttachmentBytes === null ? null : clampFileAttachmentUploadBytes(advertisedFileAttachmentBytes); - const clientSettingsHydrated = useClientSettingsHydrated(); const envLocked = Boolean(activeThread && (activeMessageCount > 0 || activeRuntime !== null)); const loadBalancingSettings = useClientSettings(); @@ -2609,7 +2763,6 @@ export default function ChatView(props: ChatViewProps) { (!draftThread?.branch || draftThread.environmentSelection === "auto") && !draftThread?.worktreePath, ); - const autoUpdateEnvironments = useMemo( () => automaticEnvironment @@ -2847,7 +3000,6 @@ export default function ChatView(props: ChatViewProps) { versionMismatchThreadContinuation, versionMismatchServerLabel, ]); - const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const providerInstanceEntries = useMemo( () => sortProviderInstanceEntries( @@ -2923,8 +3075,11 @@ export default function ChatView(props: ChatViewProps) { "question", activePendingUserInput ? JSON.stringify(activePendingUserInput.questions).slice(0, 2500) : null, ); - const userInputResponsesInFlight = useRef(new Set()); - const activePendingRequestKey = activePendingUserInput?.requestId ?? ""; + const activePendingRequestKey = JSON.stringify([ + environmentId, + activeThreadId, + activePendingUserInput?.requestId, + ]); const pendingQuestionDraftKeys = useMemo( () => activeThreadId @@ -2971,9 +3126,9 @@ export default function ChatView(props: ChatViewProps) { ), ); useEffect(() => { - if (!serverProjection || !activeThreadId) return; - const questionThread = { id: activeThreadId }; - const currentRequests = pendingRequests.userInputs; + if (!activeThread) return; + const questionThread = activeThread; + const currentRequests = pendingUserInputs; const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id); const retained = new Set( currentRequests.flatMap((request) => @@ -2995,7 +3150,7 @@ export default function ChatView(props: ChatViewProps) { if (key.startsWith(prefix) && !retained.has(DraftId.make(key))) clearQuestionAttachmentDraft(DraftId.make(key)); } - }, [environmentId, serverProjection, activeThreadId, pendingRequests.userInputs]); + }, [environmentId, activeThread, pendingUserInputs]); const activePendingDraftAnswers = useMemo(() => { if (!activePendingUserInput || !activeThreadId) return EMPTY_PENDING_USER_INPUT_ANSWERS; return Object.fromEntries( @@ -3071,6 +3226,111 @@ export default function ChatView(props: ChatViewProps) { hasComposerAttachments: composerHasAttachments, }); const activePendingApproval = pendingApprovals[0] ?? null; + // The open /usage-limits panel for this thread, model and turn. Only the open + // moment is stored: the rows read live provider data, so a redeemed reset + // credit or refreshed probe shows through. Anything that spends quota closes + // it: a new turn from any source, or the agent resuming after an approval or + // answered question. + const [usageLimitsPanel, setUsageLimitsPanel] = useState<{ + readonly key: string; + readonly threadKey: string; + readonly now: number; + } | null>(null); + // Null while the provider list or the thread itself is unavailable, such as + // during a reconnect; the panel then stays hidden rather than being dropped. + // A pending approval or question is part of the key: once it is answered, + // from this client or any other, the agent resumes and spends quota. + const usageLimitsKey = + activeProviderInstanceId === null || (isServerThread && activeThread === undefined) + ? null + : [ + routeThreadKey, + activeProviderInstanceId, + activeThread?.latestRun?.runId ?? "", + activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? "", + ].join(":"); + // Drop the snapshot as soon as the thread or model changes so it cannot resurface stale. + if ( + usageLimitsPanel !== null && + usageLimitsKey !== null && + usageLimitsPanel.key !== usageLimitsKey + ) { + setUsageLimitsPanel(null); + } + const usageLimitSources = serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES; + const usageLimitsReport = useMemo( + () => + usageLimitsPanel !== null && + usageLimitsKey !== null && + usageLimitsPanel.key === usageLimitsKey && + activeProviderInstanceId !== null + ? collectProviderUsageLimits( + activeProviderInstanceId, + providerStatuses, + usageLimitSources, + usageLimitsPanel.now, + ) + : null, + [ + activeProviderInstanceId, + providerStatuses, + usageLimitSources, + usageLimitsKey, + usageLimitsPanel, + ], + ); + const usageLimitsBanner = useMemo( + () => + usageLimitsReport !== null && usageLimitsPanel !== null + ? // A fresh id per opening: the stack keeps the last dismissed id as "exiting". + usageLimitsBannerItem( + `usage-limits:${usageLimitsPanel.key}:${usageLimitsPanel.now}`, + usageLimitsReport, + environmentId, + () => setUsageLimitsPanel(null), + ) + : null, + [environmentId, usageLimitsPanel, usageLimitsReport], + ); + // T3 owns /usage-limits only where Limits has data for the selected provider; + // elsewhere the name stays the provider's own and is sent through untouched. + const usageLimitsOffered = + activeProviderStatus !== null && + hasProviderUsageLimits(activeProviderStatus.driver, providerStatuses, usageLimitSources); + // Answered locally from the last Limits snapshot; the agent never sees it. + const openUsageLimits = useCallback(() => { + const now = Date.now(); + const report = + activeProviderInstanceId !== null && usageLimitsKey !== null + ? collectProviderUsageLimits( + activeProviderInstanceId, + providerStatuses, + usageLimitSources, + now, + ) + : null; + if (report && usageLimitsKey !== null) { + setUsageLimitsPanel({ key: usageLimitsKey, threadKey: routeThreadKey, now }); + return true; + } + setUsageLimitsPanel(null); + toastManager.add({ type: "info", title: "Usage limits are unavailable for this provider" }); + return false; + }, [ + activeProviderInstanceId, + providerStatuses, + routeThreadKey, + usageLimitSources, + usageLimitsKey, + ]); + // Responses can resolve after navigating away; only the originating thread's panel clears. + const clearUsageLimitsFor = useCallback( + (threadKey: string) => + setUsageLimitsPanel((current) => + current !== null && current.threadKey === threadKey ? null : current, + ), + [], + ); const { beginLocalDispatch, resetLocalDispatch, @@ -3114,8 +3374,14 @@ export default function ChatView(props: ChatViewProps) { phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint || isCompacting; const activeContextWindow = useMemo( () => - deriveLatestContextWindowSnapshot(serverVisibleTurnItems ?? [], activeThreadLiveTokenUsage), - [activeThreadLiveTokenUsage, serverVisibleTurnItems], + deriveLatestContextWindowSnapshot( + serverVisibleTurnItems ?? [], + activeThreadLiveTokenUsage, + serverProjection?.providerThreads.find( + (thread) => thread.id === serverProjection.thread.activeProviderThreadId, + ), + ), + [activeThreadLiveTokenUsage, serverVisibleTurnItems, serverProjection], ); const pendingBackgroundTasks = useMemo(() => { if (serverProjection === null || serverProjection === undefined) { @@ -3377,6 +3643,18 @@ export default function ChatView(props: ChatViewProps) { } return urls; }, [attachmentPreviewHandoffByMessageId, serverAttachmentUrlById, serverVisibleTurnItems]); + const anchoredTimelineMessages = useMemo( + () => + feedbackSubmissions.flatMap((submission) => + submission.status === "interrupted" + ? [] + : [ + { ...codexFeedbackMessage(submission), runId: null }, + { ...codexFeedbackMessage(submission, "assistant"), runId: null }, + ], + ), + [feedbackSubmissions], + ); const timelineProjectionRef = useRef<{ readonly threadKey: string | null; readonly projection: TimelineEntriesProjection; @@ -3387,6 +3665,7 @@ export default function ChatView(props: ChatViewProps) { { visibleTurnItems: serverVisibleTurnItems, optimisticMessages: optimisticUserMessages, + anchoredMessages: anchoredTimelineMessages, attachmentUrlById: timelineAttachmentUrlById, ...(serverProjection === null ? {} @@ -3402,16 +3681,12 @@ export default function ChatView(props: ChatViewProps) { return projection.entries; }, [ activeThreadKey, + anchoredTimelineMessages, optimisticUserMessages, serverVisibleTurnItems, serverProjection, timelineAttachmentUrlById, ]); - const serverMessages = useMemo( - () => - serverTimelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), - [serverTimelineEntries], - ); const draftTimelineEntries = useMemo( () => optimisticUserMessages.map( @@ -3426,6 +3701,10 @@ export default function ChatView(props: ChatViewProps) { [optimisticUserMessages], ); const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries; + const timelineMessages = useMemo( + () => timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), + [timelineEntries], + ); const displayedTimeline = resolveThreadSwitchTimeline({ loading: timelineEntries.length === 0 && threadSyncPhase !== null, activeThreadKey, @@ -3438,64 +3717,55 @@ export default function ChatView(props: ChatViewProps) { activeThreadKey, ); const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey); - // Live stages of a bootstrap worktree setup. The subscription follows the - // thread that was set up, not the route: a deleted bootstrap thread rotates - // the draft's thread id, and the failed card must survive that. const worktreeSetupOwnerKey = draftId ?? routeThreadKey; - useEffect(() => { - if (!activeRunPreparing || !activeThreadRef) return; - setWorktreeSetupRef((current) => - current?.ownerKey === worktreeSetupOwnerKey - ? current - : { - environmentId: activeThreadRef.environmentId, - threadId: activeThreadRef.threadId, - ownerKey: worktreeSetupOwnerKey, - }, - ); - }, [activeRunPreparing, activeThreadRef, worktreeSetupOwnerKey]); const worktreeSetupActive = worktreeSetupRef !== null && worktreeSetupRef.ownerKey === worktreeSetupOwnerKey; - // The setup runs on the environment that received the dispatch, so both - // the subscription and cancel target that one even if the draft's machine - // picker changes underneath. + // Keep the sending environment during local draft setup; revisiting a + // canonical thread subscribes by its durable identity. + const setupTarget = worktreeSetupActive ? worktreeSetupRef : routeThreadRef; const worktreeSetupQuery = useEnvironmentQuery( - worktreeSetupActive + worktreeSetupActive || + (activeThread?.id === routeThreadRef.threadId && + (isPreparingWorktree || activeThread.worktreePath !== null)) ? vcsEnvironment.worktreeSetup({ - environmentId: worktreeSetupRef.environmentId, - input: { threadId: worktreeSetupRef.threadId }, + environmentId: setupTarget.environmentId, + input: { threadId: setupTarget.threadId }, }) : null, ); const latestWorktreeSetup = worktreeSetupQuery.data; useEffect(() => { - // The server drops finished snapshots after a grace period and emits null. - // Hold the last real snapshot so a settled card does not vanish. if (latestWorktreeSetup) setHeldWorktreeSetup(latestWorktreeSetup); }, [latestWorktreeSetup]); - const worktreeSetup = - worktreeSetupActive && heldWorktreeSetup?.threadId === worktreeSetupRef.threadId - ? heldWorktreeSetup - : null; - // A finished card is dropped once the agent's turn shows in the timeline: - // the card belongs to the send, and the agent takes over from there. - const worktreeSetupDoneAndTurnVisible = - worktreeSetup?.phase === "done" && activeThread?.latestRun?.startedAt != null; useEffect(() => { - if (!worktreeSetupDoneAndTurnVisible) return; - setWorktreeSetupRef(null); setHeldWorktreeSetup(null); - }, [worktreeSetupDoneAndTurnVisible]); + }, [routeThreadKey]); + const liveWorktreeSetup = + heldWorktreeSetup?.threadId === setupTarget.threadId ? heldWorktreeSetup : null; + const worktreeSetup = resolveVisibleWorktreeSetup({ + live: liveWorktreeSetup, + recorded: null, + turnStarted: activeThread?.latestRun?.startedAt != null, + isWorking, + }); + // Sends wait for the agent handoff, not for the setup script: an async + // script keeps the snapshot running while the agent already works, and a + // follow-up must not be held behind a slow install. Before the first + // snapshot arrives the starting session stands in for it. + const worktreeSetupBlocksSend = + worktreeSetup !== null + ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup) + : isPreparingWorktree; const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, { reportFailure: false, }); const onCancelWorktreeSetup = useCallback(() => { - if (!worktreeSetup || !worktreeSetupRef || worktreeSetup.phase !== "running") return; + if (!worktreeSetup || worktreeSetup.phase !== "running") return; void cancelWorktreeSetup({ - environmentId: worktreeSetupRef.environmentId, + environmentId: setupTarget.environmentId, input: { threadId: worktreeSetup.threadId }, }); - }, [cancelWorktreeSetup, worktreeSetup, worktreeSetupRef]); + }, [cancelWorktreeSetup, setupTarget.environmentId, worktreeSetup]); // The setup terminal belongs to the thread that was set up. A failed // bootstrap deletes that thread and closes its terminals, so only offer the // terminal while the setup thread is still the active one. @@ -3511,35 +3781,15 @@ export default function ChatView(props: ChatViewProps) { const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState(null); const draftHeroDockRequested = activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey; - const isDraftHeroState = resolveDraftHeroState({ - isLocalDraftThread, - hasTimelineEntries: timelineEntries.length > 0, - isWorking, - draftHeroDockRequested, - backgroundSubmissionPending: false, - hasWorktreeSetupCard: worktreeSetup !== null, - }); + const isDraftHeroState = + isLocalDraftThread && + timelineEntries.length === 0 && + !isWorking && + !draftHeroDockRequested && + worktreeSetup === null; const draftHeroTransition = useDraftHeroLayoutTransition(isDraftHeroState); const captureDraftHeroComposerRect = draftHeroTransition.captureComposerRect; const { turnDiffSummaries } = useTurnDiffSummaries(serverProjection); - const turnDiffSummaryByAssistantMessageId = useMemo(() => { - const byMessageId = new Map(); - for (const summary of turnDiffSummaries) { - if (!summary.assistantMessageId) continue; - byMessageId.set(summary.assistantMessageId, summary); - } - return byMessageId; - }, [turnDiffSummaries]); - const revertTurnCountByUserMessageId = useMemo( - () => - supportsConversationRollback - ? deriveRevertTurnCountByUserMessageId({ - timelineEntries, - checkpoints: turnDiffSummaries, - }) - : new Map(), - [supportsConversationRollback, timelineEntries, turnDiffSummaries], - ); /** * The latest settled item after which files on disk may have changed. @@ -3697,21 +3947,27 @@ export default function ChatView(props: ChatViewProps) { } }, [environmentId, gitStatusCwd, liveIsGitRepo]); const isGitRepo = liveIsGitRepo ?? recallCheckoutIsRepo(environmentId, gitStatusCwd) ?? true; - // Keep a hidden, off-flow strip mounted for existing threads so the composer + // When context is enabled, keep a hidden, off-flow strip mounted so the composer // can measure whether its relocated controls fit. The visible chrome remains // content-driven: Git/environment context or controls that actually fit. const mountComposerContextStrip = shouldShowComposerContextStrip({ + isDraftHeroState, + persistInActiveThreads: settings.persistComposerContextStrip, hasActiveProject: activeProject !== null, isGitRepo, showEnvironmentIndicator: showComposerEnvironmentIndicator, hostsRestingComposerControls: routeKind === "server", }); const showComposerContextStrip = shouldShowComposerContextStrip({ + isDraftHeroState, + persistInActiveThreads: settings.persistComposerContextStrip, hasActiveProject: activeProject !== null, isGitRepo, showEnvironmentIndicator: showComposerEnvironmentIndicator, hostsRestingComposerControls: routeKind === "server" && restingComposerControlsVisible, }); + const mountComposerModelStrip = routeKind === "server" && !mountComposerContextStrip; + const showComposerModelStrip = mountComposerModelStrip && restingComposerControlsVisible; const initialDiffPanelGitScope = gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch"; const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending"; @@ -3914,15 +4170,15 @@ export default function ChatView(props: ChatViewProps) { [draftId, routeThreadKey, routeThreadRef, serverThread], ); - const interruptContextRef = useRef({ activeThread, phase, setThreadError }); - interruptContextRef.current = { activeThread, phase, setThreadError }; + const focusComposer = useCallback(() => { + composerRef.current?.focusAtEnd(); + }, [composerRef]); + const canInterruptRunningThread = activeThread !== undefined && phase === "running"; const onInterrupt = useCallback(async () => { - const { activeThread, phase, setThreadError } = interruptContextRef.current; - const input = buildRunningThreadTurnInterruptInput(activeThread, phase); - if (!input || !activeThread) return; + if (!activeThread) return; const result = await interruptThreadTurn({ - environmentId: activeThread.environmentId, - input, + environmentId, + input: { threadId: activeThread.id }, }); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); @@ -3931,13 +4187,7 @@ export default function ChatView(props: ChatViewProps) { error instanceof Error ? error.message : "Failed to interrupt the current turn.", ); } - }, [interruptThreadTurn]); - const canInterruptRunningThread = - buildRunningThreadTurnInterruptInput(activeThread, phase) !== null; - - const focusComposer = useCallback(() => { - composerRef.current?.focusAtEnd(); - }, [composerRef]); + }, [activeThread, environmentId, interruptThreadTurn, setThreadError]); useEffect(() => subscribeSnapShotComposerFocus(focusComposer), [focusComposer]); const scheduleComposerFocus = useCallback(() => { window.requestAnimationFrame(() => { @@ -3967,6 +4217,7 @@ export default function ChatView(props: ChatViewProps) { reportFailure: false, }); const queuedEditSaveInFlightRef = useRef(false); + const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false); const queuedEditImageResources = useMemo( () => (editingQueuedRun?.existingAttachments ?? []) @@ -4002,18 +4253,18 @@ export default function ChatView(props: ChatViewProps) { runId: request.runId, messageId: request.messageId, originalText: request.text, + existingAttachments: request.attachments, context: serverProjection?.messages.find((message) => message.id === request.messageId) ?.context, - existingAttachments: request.attachments, }); scheduleComposerFocus(); }, [ activeThread, - serverProjection, clearComposerDraftContent, editingQueuedRun, queuedEditDraftTargetFor, + serverProjection, scheduleComposerFocus, setComposerDraftPrompt, ], @@ -4053,17 +4304,12 @@ export default function ChatView(props: ChatViewProps) { if (serverProjection === null) return; const run = serverProjection.runs.find((candidate) => candidate.id === editingQueuedRun.runId); if (run !== undefined && run.status === "queued") return; - const store = useComposerDraftStore.getState(); - const editTarget = queuedEditDraftTargetFor(editingQueuedRun.runId); - const editDraft = store.getComposerDraft(editTarget); - const editIsDirty = - editDraft !== null && - (editDraft.prompt !== editingQueuedRun.originalText || editDraft.images.length > 0); - if ( - editIsDirty && - !composerDraftHasUserContent(store.getComposerDraft(baseComposerDraftTarget)) - ) { - store.moveComposerPromptAndImages(editTarget, baseComposerDraftTarget); + const recovery = recoverQueuedMessageEdit({ + editTarget: queuedEditDraftTargetFor(editingQueuedRun.runId), + threadTarget: baseComposerDraftTarget, + originalText: editingQueuedRun.originalText, + }); + if (recovery === "kept") { toastManager.add( stackedThreadToast({ type: "info", @@ -4071,17 +4317,14 @@ export default function ChatView(props: ChatViewProps) { description: "Your unsaved edit was kept in the composer.", }), ); - } else { - store.clearComposerContent(editTarget); - if (editIsDirty) { - toastManager.add( - stackedThreadToast({ - type: "warning", - title: "Queued message is no longer queued", - description: "Your unsaved edit was discarded.", - }), - ); - } + } else if (recovery === "discarded") { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Queued message is no longer queued", + description: "Your unsaved edit was discarded.", + }), + ); } setEditingQueuedRun(null); }, [ @@ -4602,6 +4845,18 @@ export default function ChatView(props: ChatViewProps) { threadRef: activeThreadRef, openPreview, ...(profileId === undefined ? {} : { profileId }), + }).then((result) => { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + if (error instanceof BrowserSettingsReadError) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open browser", + description: error.message, + }), + ); + } }); }, [activeThreadRef, openPreview], @@ -4610,17 +4865,6 @@ export default function ChatView(props: ChatViewProps) { if (!activeThreadRef) return; useRightPanelStore.getState().open(activeThreadRef, "agents"); }, [activeThreadRef]); - const supportsThreadPullRequests = - serverConfig?.environment.capabilities.threadPullRequests === true; - const visiblePullRequestCount = visibleThreadPullRequests( - (activeThreadShell ?? activeThread)?.pullRequests ?? [], - ).length; - const pullRequestsSurfaceAvailable = - isServerThread && supportsThreadPullRequests && visiblePullRequestCount > 0; - const addPullRequestsSurface = useCallback(() => { - if (!activeThreadRef || !pullRequestsSurfaceAvailable) return; - useRightPanelStore.getState().open(activeThreadRef, "pull-requests"); - }, [activeThreadRef, pullRequestsSurfaceAvailable]); const addDiffSurface = useCallback(() => { if (!activeThreadRef || !isServerThread || !isGitRepo) return; useRightPanelStore.getState().open(activeThreadRef, "diff"); @@ -4633,6 +4877,17 @@ export default function ChatView(props: ChatViewProps) { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().open(activeThreadRef, "files"); }, [activeProject, activeThreadRef]); + const supportsThreadPullRequests = + serverConfig?.environment.capabilities.threadPullRequests === true; + const visiblePullRequestCount = visibleThreadPullRequests( + (activeThreadShell ?? activeThread)?.pullRequests ?? [], + ).length; + const pullRequestsSurfaceAvailable = + isServerThread && supportsThreadPullRequests && visiblePullRequestCount > 0; + const addPullRequestsSurface = useCallback(() => { + if (!activeThreadRef || !pullRequestsSurfaceAvailable) return; + useRightPanelStore.getState().open(activeThreadRef, "pull-requests"); + }, [activeThreadRef, pullRequestsSurfaceAvailable]); const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState( activeThreadRef?.environmentId ?? null, ); @@ -4724,11 +4979,52 @@ export default function ChatView(props: ChatViewProps) { }, [activeProject, activeThreadRef], ); - // The shell carries server PR updates even while thread detail is still loading. - const activeThreadMetadata = activeThreadShell ?? activeThread; - const linkedThreadPullRequest = - activeThreadMetadata?.linkedPullRequest ?? activeThreadMetadata?.branchPullRequest ?? null; + // The thread's own change request, placed against the project it belongs to. Without a + // project there is nothing to resolve it against, so the caller falls back to the browser. + const persistedLinkedThreadPullRequest = isServerThread + ? (activeThreadShell?.linkedPullRequest ?? activeThread?.linkedPullRequest ?? null) + : (activeThread?.linkedPullRequest ?? null); const activeProjectRepository = activeProject?.repositoryIdentity?.displayName ?? null; + const persistedLinkedThreadPullRequestStatus = useLinkedThreadPullRequest( + activeThreadRef?.environmentId ?? null, + persistedLinkedThreadPullRequest, + ); + const replacementLinkedThreadPullRequest = useMemo(() => { + const detected = gitStatusQuery.data?.pr; + const threadBranch = activeThread?.branch; + const projectId = activeProject?.id; + if ( + persistedLinkedThreadPullRequest === null || + (persistedLinkedThreadPullRequestStatus?.pr.state !== "merged" && + persistedLinkedThreadPullRequestStatus?.pr.state !== "closed") || + gitStatusQuery.data?.refName !== threadBranch || + detected?.state !== "open" || + detected.headRef !== threadBranch || + projectId === undefined || + activeProjectRepository === null || + (persistedLinkedThreadPullRequest.projectId === projectId && + persistedLinkedThreadPullRequest.repository.toLowerCase() === + activeProjectRepository.toLowerCase() && + persistedLinkedThreadPullRequest.number === detected.number) + ) { + return null; + } + return { + projectId, + repository: activeProjectRepository, + number: detected.number, + url: detected.url, + }; + }, [ + activeProject?.id, + activeProjectRepository, + activeThread?.branch, + gitStatusQuery.data, + persistedLinkedThreadPullRequest, + persistedLinkedThreadPullRequestStatus?.pr.state, + ]); + const linkedThreadPullRequest = + replacementLinkedThreadPullRequest ?? persistedLinkedThreadPullRequest; const linkedThreadPullRequestKey = linkedThreadPullRequest ? JSON.stringify([ linkedThreadPullRequest.projectId, @@ -4736,37 +5032,74 @@ export default function ChatView(props: ChatViewProps) { linkedThreadPullRequest.number, ]) : null; - const observedThreadPullRequestRef = useRef<{ - readonly threadKey: string; - readonly reference: ThreadLinkedPullRequest | null; - } | null>(null); - const openProjectPullRequest = useCallback( - (number: number) => { - if ( - !supportsPullRequests || - !activeThreadRef || - !activeProject || - activeProjectRepository === null - ) { - return; - } - useRightPanelStore.getState().openPullRequest(activeThreadRef, { - projectId: activeProject.id, - repository: activeProjectRepository, - number, + const threadRepository = linkedThreadPullRequest?.repository ?? activeProjectRepository; + const threadPrRelinkKeysRef = useRef(new Map()); + const threadPrRelinkWriteRef = useRef(Promise.resolve()); + useEffect(() => { + if (!isServerThread || activeThreadKey === null || activeThreadRef === null) { + return; + } + if (replacementLinkedThreadPullRequest === null) { + threadPrRelinkKeysRef.current.delete(activeThreadKey); + return; + } + const relinkKey = `${replacementLinkedThreadPullRequest.projectId}:${replacementLinkedThreadPullRequest.repository}#${replacementLinkedThreadPullRequest.number}`; + if (threadPrRelinkKeysRef.current.get(activeThreadKey) === relinkKey) return; + threadPrRelinkKeysRef.current.set(activeThreadKey, relinkKey); + const openSurface = selectActiveRightPanelSurface( + useRightPanelStore.getState().byThreadKey, + activeThreadRef, + ); + if ( + openSurface?.kind === "pull-request" && + persistedLinkedThreadPullRequest !== null && + openSurface.projectId === persistedLinkedThreadPullRequest.projectId && + openSurface.repository.toLowerCase() === + persistedLinkedThreadPullRequest.repository.toLowerCase() && + openSurface.number === persistedLinkedThreadPullRequest.number + ) { + useRightPanelStore + .getState() + .openPullRequest(activeThreadRef, replacementLinkedThreadPullRequest); + } + + threadPrRelinkWriteRef.current = threadPrRelinkWriteRef.current.then(async () => { + if (threadPrRelinkKeysRef.current.get(activeThreadKey) !== relinkKey) return; + const result = await updateThreadMetadata({ + environmentId: activeThreadRef.environmentId, + input: { + threadId: activeThreadRef.threadId, + linkedPullRequest: replacementLinkedThreadPullRequest, + }, }); - }, - [activeProject, activeProjectRepository, activeThreadRef, supportsPullRequests], - ); + if (threadPrRelinkKeysRef.current.get(activeThreadKey) !== relinkKey) return; + if (result._tag !== "Failure") return; + threadPrRelinkKeysRef.current.delete(activeThreadKey); + if (isAtomCommandInterrupted(result)) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to update the thread pull request", + description: chatActionErrorMessage(squashAtomCommandFailure(result)), + }), + ); + }); + }, [ + activeThreadKey, + activeThreadRef, + isServerThread, + persistedLinkedThreadPullRequest, + replacementLinkedThreadPullRequest, + updateThreadMetadata, + ]); const activeRunningTurnId = activeRuntime?.activeRunId ?? null; - const threadRepository = linkedThreadPullRequest?.repository ?? activeProjectRepository; - const persistedLinkedThreadPullRequestStatus = useLinkedThreadPullRequest( - activeThreadRef?.environmentId ?? null, - linkedThreadPullRequest, - ); const proactivePanelObservationRef = useRef | null>(null); + const observedThreadPullRequestRef = useRef<{ + readonly threadKey: string; + readonly reference: ThreadLinkedPullRequest | null; + } | null>(null); useEffect(() => { if (!isServerThread || activeThreadKey === null || activeThreadRef === null) { @@ -4828,6 +5161,7 @@ export default function ChatView(props: ChatViewProps) { ? resolveProactiveTurnDiffAction({ checkpoint: completedCheckpoint, isGitRepo: gitStatusQuery.data?.isRepo, + activeSurfaceKind: openSurface?.kind ?? null, }) : "ignore"; const eligibleLink = @@ -4871,13 +5205,9 @@ export default function ChatView(props: ChatViewProps) { gitStatusQuery.data?.isRepo, isServerThread, latestRunSettled, - linkedThreadPullRequest, - linkedThreadPullRequestKey, onDiffPanelOpen, - pullRequestsCapabilityKnown, settings.proactivePanelsEnabled, shouldUsePlanSidebarSheet, - supportsPullRequests, threadDetailLoading, ]); const closePreviewPanel = useCallback(() => { @@ -5451,39 +5781,20 @@ export default function ChatView(props: ChatViewProps) { setTimelineAnchor({ threadKey: activeThreadKey, messageId }); }, [activeActivityRun, activeThreadKey, serverProjection]); const timelineRealContentOverflowsViewport = useCallback( - (list?: LegendListRef | null) => { - const resolvedList = list ?? legendListRef.current; - const state = resolvedList?.getState(); - if (!resolvedList || !state || state.data.length === 0) { - return false; - } - - const lastRowIndex = state.data.length - 1; - const lastRowTop = state.positionAtIndex(lastRowIndex); - const lastRowHeight = state.sizeAtIndex(lastRowIndex); - if ( - typeof lastRowTop !== "number" || - typeof lastRowHeight !== "number" || - !Number.isFinite(lastRowTop) || - !Number.isFinite(lastRowHeight) - ) { - return false; - } - - const realContentBottom = lastRowTop + Math.max(1, lastRowHeight); - const visibleScrollLength = Math.max( - 0, - (state.scrollLength ?? 0) - composerTimelineInset - CHAT_TIMELINE_ANCHOR_OFFSET, - ); - return realContentBottom > visibleScrollLength; - }, + (list?: LegendListRef | null) => + timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), { + composerInset: composerTimelineInset, + anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET, + }), [composerTimelineInset], ); const pageScrollControllerRef = useRef | null>( null, ); const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => { - if (key === "PageUp" && timelineRealContentOverflowsViewport()) { + timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end"; + composerRef.current?.collapseForTimelineScrollKey(key); + if ((key === "PageUp" && timelineRealContentOverflowsViewport()) || !isTimelineAtLogicalEnd()) { cancelTimelineLiveFollowForUserNavigation(); } }); @@ -5529,43 +5840,6 @@ export default function ChatView(props: ChatViewProps) { void legendListRef.current?.scrollToEnd?.({ animated }); }); }, []); - const displayedTimelineKeyRef = useRef(displayedTimeline.displayThreadKey); - useLayoutEffect(() => { - const displayKey = displayedTimeline.displayThreadKey; - if (displayKey === null || displayKey !== activeThreadKey) { - displayedTimelineKeyRef.current = displayKey; - return; - } - if (displayedTimelineKeyRef.current === displayKey) { - return; - } - displayedTimelineKeyRef.current = displayKey; - // Keep the list mounted across jumps; pin the newly displayed thread to - // its end the way a remount used to via initialScrollAtEnd. - scrollToEnd(); - }, [activeThreadKey, displayedTimeline.displayThreadKey, scrollToEnd]); - useLayoutEffect(() => { - if (timelineScrollModeRef.current !== "anchoring-new-turn") { - return; - } - - if ( - shouldReleaseTimelineAnchorForToolActivity({ - anchorMessageId: timelineAnchorMessageId, - liveFollowEnabled: timelineLiveFollowEnabled, - runningTurnId: activeRunningTurnId, - timelineEntries, - }) - ) { - scrollToEnd(); - } - }, [ - activeRunningTurnId, - scrollToEnd, - timelineAnchorMessageId, - timelineEntries, - timelineLiveFollowEnabled, - ]); useEffect(() => { let removeListeners: (() => void) | null = null; let frame: number | null = null; @@ -5643,8 +5917,25 @@ export default function ChatView(props: ChatViewProps) { }; // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and // pointer events entirely; without this the timeline yanks back to - // the end on the next stream chunk. + // the end on the next stream chunk. Clicking message text can leave + // DOM focus on body, so these keys must also be heard at document. const handleKeyDown = (event: KeyboardEvent) => { + if ( + !(event.target instanceof Node) || + (!scrollNode.contains(event.target) && + event.target !== document.body && + event.target !== document.documentElement) || + event.defaultPrevented || + event.isComposing || + event.altKey || + event.ctrlKey || + event.metaKey || + event.shiftKey || + eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) || + document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR) + ) { + return; + } switch (event.key) { case "PageUp": case "Home": @@ -5652,12 +5943,20 @@ export default function ChatView(props: ChatViewProps) { timelineScrollIntentRef.current = "away-from-end"; if (contentScrollsUp() && !toolGroupConsumesUpwardNavigation(event.target)) { handleManualNavigation(); + composerRef.current?.collapseForTimelineScrollKey(event.key); } break; case "PageDown": case "End": case "ArrowDown": timelineScrollIntentRef.current = "toward-end"; + if (viewportIsAwayFromEnd()) { + handleManualNavigation(); + } + composerRef.current?.collapseForTimelineScrollKey(event.key); + if (isTimelineAtLogicalEnd()) { + composerRef.current?.restoreAfterTimelineReachedEnd(); + } break; default: break; @@ -5672,12 +5971,12 @@ export default function ChatView(props: ChatViewProps) { scrollNode.addEventListener("pointerdown", handlePointerDown, { passive: true, }); - scrollNode.addEventListener("keydown", handleKeyDown); + document.addEventListener("keydown", handleKeyDown); removeListeners = () => { scrollNode.removeEventListener("wheel", handleWheel); scrollNode.removeEventListener("touchmove", handleTouchMove); scrollNode.removeEventListener("pointerdown", handlePointerDown); - scrollNode.removeEventListener("keydown", handleKeyDown); + document.removeEventListener("keydown", handleKeyDown); }; }); }; @@ -5689,7 +5988,7 @@ export default function ChatView(props: ChatViewProps) { } removeListeners?.(); }; - }, [activeThread?.id, timelineRealContentOverflowsViewport]); + }, [activeThread?.id, isTimelineAtLogicalEnd, timelineRealContentOverflowsViewport]); const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => { if (pendingTimelineAnchorRef.current === messageId) { @@ -5865,6 +6164,33 @@ export default function ChatView(props: ChatViewProps) { }; }, [activeThread?.id, focusComposer, terminalUiState.terminalOpen]); + // Tabbing back into the app lands focus wherever it last was, often the right panel or the + // body. Put it in the composer unless something that takes typing already holds it. The + // drawer terminal owns keyboard input while it is open, so it opts out here; a right panel + // terminal is a surface and is recognized by the predicate instead. Mobile is left alone so + // returning to the app does not raise the keyboard. + useEffect(() => { + if (!activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return; + let frame: number | null = null; + const onWindowFocus = () => { + if (frame !== null) window.cancelAnimationFrame(frame); + // The element that held focus receives it again after the window's own event, and the + // composer ignores that same frame so a restored focus does not lift a scroll-collapsed + // composer. Wait one more frame so this focus counts as a request to expand it. + frame = window.requestAnimationFrame(() => { + frame = window.requestAnimationFrame(() => { + frame = null; + if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposer(); + }); + }); + }; + window.addEventListener("focus", onWindowFocus); + return () => { + window.removeEventListener("focus", onWindowFocus); + if (frame !== null) window.cancelAnimationFrame(frame); + }; + }, [activeThread?.id, focusComposer, isMobileViewport, terminalUiState.terminalOpen]); + useEffect(() => { if (!activeThread?.id) return; if (activeMessageCount === 0) { @@ -5961,10 +6287,23 @@ export default function ChatView(props: ChatViewProps) { (height: number) => { const nextHeight = Math.ceil(height); if (nextHeight <= 0) return; + const modelStrip = composerOverlayElement?.querySelector( + '[data-composer-model-strip="true"]', + ); + // The model-only strip disappears on expansion; counting it again would + // add 32px of timeline padding as soon as the empty composer collapses. + const restingOnlyHeight = + modelStrip && composerRestingRef.current + ? Math.max( + 0, + modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop), + ) + : 0; const nextInset = resolveComposerTimelineInset({ currentInset: composerTimelineInsetRef.current, overlayHeight: nextHeight, isResting: composerRestingRef.current, + restingOnlyHeight, }); if (composerTimelineInsetRef.current !== nextInset) { composerTimelineInsetRef.current = nextInset; @@ -6026,49 +6365,7 @@ export default function ChatView(props: ChatViewProps) { return () => { resizeObserver.disconnect(); }; - }, [composerOverlayElement, publishComposerOverlayHeight]); - const activeThreadPr = resolveDisplayedThreadPr({ - threadBranch: activeThread?.branch ?? null, - gitStatus: gitStatusQuery.data ?? null, - snapshot: activeThreadKey ? changeRequestSnapshotByKey.get(activeThreadKey) : undefined, - retainTerminalOnBranchMismatch: activeThread?.worktreePath === null, - linkedPullRequest: linkedThreadPullRequest, - linkedPullRequestStatus: persistedLinkedThreadPullRequestStatus, - }); - const handlePullRequestTabStatusChange = useCallback( - (status: Pick) => { - if ( - threadRepository?.toLowerCase() !== status.repository.toLowerCase() || - activeThreadPr?.number !== status.number || - activeThreadPr.state === status.state - ) { - sidebarPrRefreshKeyRef.current = null; - return; - } - const refreshKey = `${activeThreadKey}:vcs:${status.repository}#${status.number}:${status.state}`; - if (sidebarPrRefreshKeyRef.current === refreshKey) return; - sidebarPrRefreshKeyRef.current = refreshKey; - if (activeThreadRef === null || gitCwd === null) return; - void refreshVcsStatus({ - environmentId: activeThreadRef.environmentId, - input: { cwd: gitCwd }, - }).then(() => { - if (sidebarPrRefreshKeyRef.current === refreshKey) { - sidebarPrRefreshKeyRef.current = null; - } - }); - }, - [ - activeThreadKey, - activeThreadPr?.number, - activeThreadPr?.state, - activeThreadRef, - gitCwd, - refreshVcsStatus, - threadRepository, - ], - ); - + }, [composerOverlayElement, publishComposerOverlayHeight, showScrollToBottom]); const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef); const activeThreadReferenceCopyTarget = useMemo( () => @@ -6077,14 +6374,13 @@ export default function ChatView(props: ChatViewProps) { : resolveThreadReferenceCopyTarget({ threadId: activeThreadId, openPanelPullRequestUrl, - pullRequests: activeThreadMetadata?.pullRequests, + pullRequests: activeThread?.pullRequests, linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null, - detectedPullRequestUrl: activeThreadPr?.url ?? null, }), [ activeThreadId, - activeThreadPr?.url, isServerThread, + activeThread?.pullRequests, linkedThreadPullRequest?.url, openPanelPullRequestUrl, ], @@ -6113,14 +6409,12 @@ export default function ChatView(props: ChatViewProps) { }, ); }, [activeThreadReferenceCopyTarget]); - // The right panel offers the thread's own change request, so it can only offer it once the - // branch has one; until then the picker says so rather than opening an empty panel. const addPullRequestSurface = useCallback(() => { - if (activeThreadPr === null) return; - openProjectPullRequest(activeThreadPr.number); - }, [activeThreadPr, openProjectPullRequest]); - const pullRequestSurfaceAvailable = - supportsPullRequests && activeThreadPr !== null && threadRepository !== null; + if (!supportsPullRequests || activeThreadRef === null || linkedThreadPullRequest === null) + return; + useRightPanelStore.getState().openPullRequest(activeThreadRef, linkedThreadPullRequest); + }, [activeThreadRef, linkedThreadPullRequest, supportsPullRequests]); + const pullRequestSurfaceAvailable = supportsPullRequests && linkedThreadPullRequest !== null; const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true; const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true; const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true; @@ -6250,8 +6544,6 @@ export default function ChatView(props: ChatViewProps) { const composerHasDraftContent = useComposerDraftStore((store) => composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)), ); - const composerHasUnsentContent = - composerHasDraftContent || (composerEditingQueuedAttachments?.length ?? 0) > 0; const nowMinute = useNowMinute(); const activeBranchMismatchKey = branchMismatchKey( activeThread?.id ?? null, @@ -6260,7 +6552,7 @@ export default function ChatView(props: ChatViewProps) { const showBranchMismatchBanner = shouldShowBranchMismatchBanner({ hasMismatch: localCheckoutBranchMismatch !== null, isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey), - composerHasContent: composerHasUnsentContent, + composerHasContent: composerHasDraftContent, wasShownForCurrentMismatch: revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey, }); @@ -6596,9 +6888,14 @@ export default function ChatView(props: ChatViewProps) { resumeCompactionBannerItem === null ? [] : [resumeCompactionBannerItem]; const wokeThreadItems = wokeThreadBannerItem === null ? [] : [wokeThreadBannerItem]; const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem]; + // The user asked for this one, so it leads the notice tier instead of trailing it. + const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner]; + const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem]; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ ...feedbackBannerItems, + ...usageLimitsItems, + ...projectCloneItems, ...systemComposerBannerItems, ...backgroundWorkItems, ...resumeCompactionItems, @@ -6608,6 +6905,8 @@ export default function ChatView(props: ChatViewProps) { } return [ ...feedbackBannerItems, + ...usageLimitsItems, + ...projectCloneItems, ...systemComposerBannerItems, ...backgroundWorkItems, ...resumeCompactionItems, @@ -6653,16 +6952,18 @@ export default function ChatView(props: ChatViewProps) { ...parkedThreadItems, ]; }, [ - feedbackBannerItems, activeBranchMismatchKey, + feedbackBannerItems, handleRestoreThreadBranch, isRestoringThreadBranch, backgroundWorkBannerItem, localCheckoutBranchMismatch, parkedThreadBannerItem, + projectCloneBannerItem, resumeCompactionBannerItem, showBranchMismatchBanner, systemComposerBannerItems, + usageLimitsBanner, wokeThreadBannerItem, ]); @@ -6744,6 +7045,17 @@ export default function ChatView(props: ChatViewProps) { terminalUiOpenByThreadRef.current[activeThreadKey] = current; }, [activeThreadKey, focusComposer, terminalUiState.terminalOpen]); + const getShortcutContext = useCallback( + () => ({ + terminalFocus: getTerminalFocusOwner() !== null, + terminalOpen: Boolean(terminalUiState.terminalOpen), + previewFocus: isPreviewFocused(), + previewOpen: previewPanelOpen, + modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false, + }), + [composerRef, previewPanelOpen, terminalUiState.terminalOpen], + ); + useEffect(() => { const handler = (event: globalThis.KeyboardEvent) => { if (preventRepeatedTerminalCloseShortcut(event, keybindings)) { @@ -6761,13 +7073,7 @@ export default function ChatView(props: ChatViewProps) { if (event.defaultPrevented && terminalFocusOwner === null) { return; } - const shortcutContext = { - terminalFocus: terminalFocusOwner !== null, - terminalOpen: Boolean(terminalUiState.terminalOpen), - previewFocus: isPreviewFocused(), - previewOpen: previewPanelOpen, - modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false, - }; + const shortcutContext = getShortcutContext(); if ( !shortcutContext.terminalFocus && @@ -6932,7 +7238,33 @@ export default function ChatView(props: ChatViewProps) { if (command === "modelPicker.toggle") { event.preventDefault(); event.stopPropagation(); - composerRef.current?.toggleModelPicker(); + if (!event.repeat) composerRef.current?.toggleModelPicker(); + return; + } + + if ( + command === "composer.host" || + command === "composer.effort" || + command === "composer.mode" || + command === "composer.workspace" + ) { + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) composerRef.current?.openControl(command); + return; + } + + if (command === "composer.branch") { + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) branchToolbarRef.current?.openBranchPicker(); + return; + } + + if (command === "composer.previousWorktree") { + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) branchToolbarRef.current?.usePreviousWorktree(); return; } @@ -6958,8 +7290,8 @@ export default function ChatView(props: ChatViewProps) { return () => window.removeEventListener("keydown", handler, true); }, [ activeProject, - activeProjectScripts, activeRightPanelSurface, + activeProjectScripts, addTerminalSurface, activeThreadRef, activeThreadPinned, @@ -6977,6 +7309,8 @@ export default function ChatView(props: ChatViewProps) { splitTerminal, splitPanelTerminal, keybindings, + handleUnsettleActiveThread, + isServerThread, onInterrupt, onToggleDiff, pinThread, @@ -6985,7 +7319,7 @@ export default function ChatView(props: ChatViewProps) { supportsSettlement, confirmAndUnpinThread, copyActiveThreadReference, - previewPanelOpen, + getShortcutContext, toggleRightPanel, toggleThreadPanel, toggleTerminalVisibility, @@ -7044,7 +7378,20 @@ export default function ChatView(props: ChatViewProps) { async (turnCount: number, messageId: MessageId, restoreFiles?: boolean) => { const localApi = readLocalApi(); if (!localApi || !activeThread || isRevertingCheckpoint) return; - const message = serverMessages.find((message) => message.id === messageId); + const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId); + const message = sourceMessage + ? { + id: sourceMessage.id, + role: sourceMessage.role, + text: sourceMessage.text, + attachments: sourceMessage.attachments, + context: sourceMessage.context, + runId: sourceMessage.runId, + streaming: false, + createdAt: DateTime.formatIso(sourceMessage.createdAt), + updatedAt: DateTime.formatIso(sourceMessage.updatedAt), + } + : undefined; if (!message || message.role !== "user") return; if (!supportsConversationRollback) { @@ -7168,79 +7515,10 @@ export default function ChatView(props: ChatViewProps) { routeThreadRef, setThreadError, supportsConversationRollback, + serverProjection, ], ); - const onCompactContext = async () => { - if (compactDisabled || !activeThread || !clientSettingsHydrated || sendInFlightRef.current) { - return; - } - const context = composerRef.current?.getSendContext(); - if (!context?.providerAvailable) return; - - // Compaction is a standalone command; the draft and its attachments stay local. - const threadId = activeThread.id; - const messageId = newMessageId(); - const createdAt = new Date().toISOString(); - sendInFlightRef.current = true; - beginLocalDispatch({ preparingWorktree: false }); - setThreadError(threadId, null); - setOptimisticUserMessages((messages) => [ - ...messages, - { - id: messageId, - role: "user", - text: "/compact", - runId: null, - createdAt, - updatedAt: createdAt, - streaming: false, - }, - ]); - scrollToEnd(); - try { - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId, - createdAt, - modelSelection: context.selectedModelSelection, - ...(localCheckoutBranchMismatch - ? { branch: localCheckoutBranchMismatch.currentBranch } - : {}), - runtimeMode, - interactionMode: context.interactionMode, - }); - const result = - settingsResult._tag === "Failure" - ? settingsResult - : await startThreadTurn({ - environmentId, - input: { - threadId, - message: { messageId, role: "user", text: "/compact", attachments: [] }, - modelSelection: context.selectedModelSelection, - runtimeMode, - interactionMode: context.interactionMode, - createdAt, - }, - }); - if (result._tag === "Failure") { - setOptimisticUserMessages((messages) => - messages.filter((message) => message.id !== messageId), - ); - resetLocalDispatch(); - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - threadId, - error instanceof Error ? error.message : "Failed to compact context.", - ); - } - } - } finally { - sendInFlightRef.current = false; - } - }; - const onRollbackCheckpoint = useCallback( async (input: { readonly checkpointId: string; readonly scopeId: string }) => { if (!activeThread || isRevertingCheckpoint) return; @@ -7284,9 +7562,9 @@ export default function ChatView(props: ChatViewProps) { ); } useComposerDraftStore.setState((store) => { - const next = new Set(store.rewindingThreadKeys); - next.delete(routeThreadKey); - return { rewindingThreadKeys: next }; + const remaining = new Set(store.rewindingThreadKeys); + remaining.delete(routeThreadKey); + return { rewindingThreadKeys: remaining }; }); }, [ @@ -7359,33 +7637,121 @@ export default function ChatView(props: ChatViewProps) { setThreadError, ], ); + const onCompactContext = async () => { + if (compactDisabled || !activeThread || !clientSettingsHydrated || sendInFlightRef.current) { + return; + } + const context = composerRef.current?.getSendContext(); + if (!context?.providerAvailable) return; - const onSend = async ( - e?: { preventDefault: () => void }, - dispatchMode: ComposerDispatchMode = "auto", - directAnnotation?: { - annotation: PreviewAnnotationPayload; - image: ComposerImageAttachment | null; - }, - ) => { - e?.preventDefault(); - const notifyDirectAnnotationAttached = () => { - if (!directAnnotation) return; - toastManager.add( - stackedThreadToast({ - type: "info", - title: "Annotation attached to draft", - description: "Sending is unavailable right now. Finish the current action, then send.", - }), - ); - }; - if ( - !activeThread || - isSendBusy || - isConnecting || - isRevertingCheckpoint || - !clientSettingsHydrated || - threadDetailLoading || + // Compaction is a standalone command; the draft and its attachments stay local. + const threadId = activeThread.id; + const messageId = newMessageId(); + const createdAt = new Date().toISOString(); + sendInFlightRef.current = true; + beginLocalDispatch(); + setThreadError(threadId, null); + setOptimisticUserMessages((messages) => [ + ...messages, + { + id: messageId, + role: "user", + text: "/compact", + runId: null, + createdAt, + updatedAt: createdAt, + streaming: false, + }, + ]); + scrollToEnd(); + try { + const settingsResult = await persistThreadSettingsForNextTurn({ + threadId, + createdAt, + modelSelection: context.selectedModelSelection, + ...(localCheckoutBranchMismatch + ? { branch: localCheckoutBranchMismatch.currentBranch } + : {}), + runtimeMode, + interactionMode: context.interactionMode, + }); + const result = + settingsResult._tag === "Failure" + ? settingsResult + : await startThreadTurn({ + environmentId, + input: { + threadId, + message: { messageId, role: "user", text: "/compact", attachments: [] }, + modelSelection: context.selectedModelSelection, + runtimeMode, + interactionMode: context.interactionMode, + createdAt, + }, + }); + if (result._tag === "Failure") { + setOptimisticUserMessages((messages) => + messages.filter((message) => message.id !== messageId), + ); + resetLocalDispatch(); + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + threadId, + error instanceof Error ? error.message : "Failed to compact context.", + ); + } + } else { + clearUsageLimitsFor(routeThreadKey); + } + } finally { + sendInFlightRef.current = false; + } + }; + + const onSend = async ( + e?: { preventDefault: () => void }, + dispatchMode: ComposerDispatchMode = "auto", + directAnnotation?: { + annotation: PreviewAnnotationPayload; + image: ComposerImageAttachment | null; + }, + ) => { + e?.preventDefault(); + // Typed out in full rather than picked from the menu. Attachments or contexts + // mean the user is sending a prompt, so those go through as usual. + if ( + usageLimitsOffered && + usageLimitsKey !== null && + !directAnnotation && + !composerHasNonPromptContent && + isUsageLimitsCommand(promptRef.current) + ) { + if (openUsageLimits()) { + promptRef.current = ""; + setComposerDraftPrompt(composerDraftTarget, ""); + composerRef.current?.resetCursorState(); + } + return; + } + + const notifyDirectAnnotationAttached = () => { + if (!directAnnotation) return; + toastManager.add( + stackedThreadToast({ + type: "info", + title: "Annotation attached to draft", + description: "Sending is unavailable right now. Finish the current action, then send.", + }), + ); + }; + if ( + !activeThread || + isSendBusy || + isConnecting || + isRevertingCheckpoint || + !clientSettingsHydrated || + threadDetailLoading || sendInFlightRef.current || feedbackUploadsInFlightRef.current.has(routeThreadKey) ) { @@ -7490,55 +7856,100 @@ export default function ChatView(props: ChatViewProps) { if (queuedEditSaveInFlightRef.current) return; const editText = promptForSend.trim(); const newEditImages = [...composerImages]; + const newEditFiles = [...composerFiles]; + const newEditAttachments = [...newEditImages, ...newEditFiles]; + if ( + editingQueuedRun.existingAttachments.length + newEditAttachments.length > + PROVIDER_SEND_TURN_MAX_ATTACHMENTS + ) { + setThreadError( + editingQueuedRun.threadId, + `A message can have at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`, + ); + return; + } if ( editText.length === 0 && editingQueuedRun.existingAttachments.length === 0 && - newEditImages.length === 0 + newEditImages.length === 0 && + newEditFiles.length === 0 ) { return; } queuedEditSaveInFlightRef.current = true; + setIsSavingQueuedEdit(true); try { - const uploads = await Promise.all( - newEditImages.map(async (image) => ({ - type: "image" as const, - id: image.id, - name: image.name, - mimeType: image.mimeType, - sizeBytes: image.sizeBytes, - dataUrl: await readFileAsDataUrl(image.file), - })), - ); + const uploads = await prepareQueuedEditAttachments({ + existingAttachments: editingQueuedRun.existingAttachments, + images: newEditImages, + files: newEditFiles, + readImage: readFileAsDataUrl, + uploadFiles: async (files) => { + const validateFiles = () => { + const config = + appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null; + const reason = fileAttachmentCapabilityBlockReason({ + files, + attachmentUploadsCapabilityKnown: config !== null, + supportsAttachmentUploads: + config?.environment.capabilities.attachmentUploads === true, + maxFileAttachmentBytes: + config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null, + }); + if (reason !== null) throw new Error(reason); + }; + validateFiles(); + for (const file of files) + startAttachmentUpload({ + environmentId, + image: file, + draftTarget: composerDraftTarget, + }); + await awaitAttachmentUploads(files.map((file) => file.id)); + validateFiles(); + const uploaded = getUploadedAttachments({ environmentId, images: files }); + if (uploaded === null) throw new Error("Retry or remove failed uploads before saving."); + return uploaded; + }, + }); const result = await editQueuedRunCommand({ environmentId: activeThread.environmentId, input: { threadId: editingQueuedRun.threadId, runId: editingQueuedRun.runId, - context: { - version: 1, - records: [ - ...(editingQueuedRun.context?.records ?? []).filter( - (record) => - !("attachmentId" in record) || - editingQueuedRun.existingAttachments.some( - (attachment) => attachment.id === record.attachmentId, - ), - ), - ...(buildMessageContext({ - terminalContexts: composerTerminalContexts, - reviewComments: composerReviewComments, - previewAnnotations: composerPreviewAnnotations, - attachments: newEditImages.map((attachment) => ({ - attachment, - attachmentId: attachment.id, - })), - })?.records ?? []), - ], - }, text: editText.length === 0 ? ATTACHMENT_ONLY_BOOTSTRAP_PROMPT : editText, edit: { messageId: editingQueuedRun.messageId, - attachments: [...editingQueuedRun.existingAttachments, ...uploads], + attachments: uploads, + context: { + version: 1, + records: [ + ...new Map( + [ + ...(editingQueuedRun.context?.records ?? []).filter( + (record) => + !("attachmentId" in record) || + editingQueuedRun.existingAttachments.some( + (attachment) => attachment.id === record.attachmentId, + ), + ), + ...(buildMessageContext({ + terminalContexts: composerTerminalContexts.filter( + (context) => context.text.trim().length > 0, + ), + reviewComments: composerReviewComments, + previewAnnotations: composerPreviewAnnotations, + attachments: newEditAttachments.map((attachment, index) => ({ + attachment, + attachmentId: + uploads[editingQueuedRun.existingAttachments.length + index]?.id ?? + attachment.id, + })), + })?.records ?? []), + ].map((record) => [record.contextId, record] as const), + ).values(), + ], + }, }, }, }); @@ -7547,13 +7958,20 @@ export default function ChatView(props: ChatViewProps) { return; } setThreadError(editingQueuedRun.threadId, null); + releaseDraftAttachments(newEditAttachments); promptRef.current = ""; clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId)); composerRef.current?.resetCursorState(); setEditingQueuedRun(null); scheduleComposerFocus(); + } catch (error) { + setThreadError( + editingQueuedRun.threadId, + error instanceof Error ? error.message : "Could not save the edited queued message.", + ); } finally { queuedEditSaveInFlightRef.current = false; + setIsSavingQueuedEdit(false); } return; } @@ -7589,7 +8007,7 @@ export default function ChatView(props: ChatViewProps) { return; } feedbackUploadsInFlightRef.current.add(routeThreadKey); - const result = await submitCodexFeedback({ + await submitCodexFeedback({ submission: { id: newMessageId(), command: trimmed, @@ -7599,7 +8017,6 @@ export default function ChatView(props: ChatViewProps) { promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); composerRef.current?.resetCursorState(); - scrollToEnd(); }, onUpdate: (submission) => { setFeedbackSubmissionsByThreadKey((current) => { @@ -7621,43 +8038,7 @@ export default function ChatView(props: ChatViewProps) { }).finally(() => { feedbackUploadsInFlightRef.current.delete(routeThreadKey); }); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not send feedback to OpenAI", - description: chatActionErrorMessage(squashAtomCommandFailure(result)), - }), - ); - } - return; - } - const feedbackId = result.value.feedbackId; - toastManager.add( - stackedThreadToast({ - type: "success", - title: "Feedback sent to OpenAI", - description: `Thread ID: ${feedbackId}`, - timeout: 0, - actionProps: { - children: "Copy ID", - onClick: () => { - void writeTextToClipboard(feedbackId, "Codex feedback thread ID").catch( - (error: unknown) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not copy thread ID", - description: chatActionErrorMessage(error), - }), - ); - }, - ); - }, - }, - }), - ); + return; } if ( @@ -7799,6 +8180,15 @@ export default function ChatView(props: ChatViewProps) { await dockStarted; } beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) }); + setWorktreeSetupRef( + baseBranchForWorktree + ? { + environmentId: activeThread.environmentId, + threadId: threadIdForSend, + ownerKey: worktreeSetupOwnerKey, + } + : null, + ); const composerImagesSnapshot = [...composerImages]; const composerFilesSnapshot = [...composerFiles]; @@ -7893,11 +8283,6 @@ export default function ChatView(props: ChatViewProps) { return; } } - setWorktreeSetupRef( - baseBranchForWorktree - ? { environmentId, threadId: threadIdForSend, ownerKey: worktreeSetupOwnerKey } - : null, - ); const turnAttachmentsPromise = Promise.all( composerAttachmentsSnapshot.map(async (attachment) => { @@ -7997,15 +8382,30 @@ export default function ChatView(props: ChatViewProps) { clearComposerDraftContent(composerDraftTarget); composerRef.current?.resetCursorState(); - const title = deriveThreadTitleSeed({ - text: trimmed, - attachments: composerImagesSnapshot, - fallbackLabels: [ - composerTerminalContextsSnapshot[0] === undefined - ? null - : formatTerminalContextLabel(composerTerminalContextsSnapshot[0]), - ], - }); + let firstComposerImageName: string | null = null; + if (composerImagesSnapshot.length > 0) { + const firstComposerImage = composerImagesSnapshot[0]; + if (firstComposerImage) { + firstComposerImageName = firstComposerImage.name; + } + } + let titleSeed = assistantCitationsToPlainText(stripInlineContextReferences(trimmed)).trim(); + if (!titleSeed) { + if (firstComposerImageName) { + titleSeed = `Image: ${firstComposerImageName}`; + } else if (composerFilesSnapshot[0]) { + titleSeed = `File: ${composerFilesSnapshot[0].name}`; + } else if (composerTerminalContextsSnapshot.length > 0) { + titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!); + } else if (composerReviewCommentsSnapshot.length > 0) { + titleSeed = `Review: ${reviewCommentContextLabel(composerReviewCommentsSnapshot[0]!)}`; + } else if (composerPreviewAnnotationsSnapshot.length > 0) { + titleSeed = previewAnnotationContextLabel(composerPreviewAnnotationsSnapshot[0]!); + } else { + titleSeed = "New thread"; + } + } + const title = truncate(titleSeed); const threadCreateModelSelection = createModelSelection( ctxSelectedModelSelection.instanceId, ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL, @@ -8123,6 +8523,10 @@ export default function ChatView(props: ChatViewProps) { failure = startResult; } else { turnStartSucceeded = true; + // The turn is under way and will spend quota, so that thread's limits + // snapshot is stale. Uploads may have outlasted a navigation, so only + // the sending thread's panel clears. + clearUsageLimitsFor(routeThreadKey); if (turnUsesAttachmentUploads) { releaseDraftAttachments(composerAttachmentsSnapshot); } @@ -8427,178 +8831,147 @@ export default function ChatView(props: ChatViewProps) { setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0)); }, [activePendingProgress, setActivePendingUserInputQuestionIndex]); - const onSubmitPlanFollowUp = useCallback( - async ({ - text, - context, - interactionMode: nextInteractionMode, - }: { - text: string; - context?: ReturnType; - interactionMode: "default" | "plan"; - // Whether the message actually went out. A `false` return tells the caller to put the - // composer back, because it cleared it before awaiting this. - }): Promise => { - if ( - !activeThread || - !isServerThread || - isSendBusy || - isConnecting || - sendInFlightRef.current - ) { - return false; - } - - const trimmed = text.trim(); - if (!trimmed) { - return false; - } + async function onSubmitPlanFollowUp({ + text, + context, + interactionMode: nextInteractionMode, + }: { + text: string; + context?: ReturnType; + interactionMode: "default" | "plan"; + }) { + if (!activeThread || !isServerThread || isSendBusy || isConnecting || sendInFlightRef.current) { + return false; + } - const sendCtx = composerRef.current?.getSendContext(); - if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) { - return false; - } - const { - selectedProvider: ctxSelectedProvider, - selectedModel: ctxSelectedModel, - selectedProviderModels: ctxSelectedProviderModels, - selectedPromptEffort: ctxSelectedPromptEffort, - selectedModelSelection: ctxSelectedModelSelection, - } = sendCtx; + const trimmed = text.trim(); + if (!trimmed) { + return false; + } - const threadIdForSend = activeThread.id; - const messageIdForSend = newMessageId(); - const messageCreatedAt = new Date().toISOString(); - const outgoingMessageText = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: trimmed, - }); + const sendCtx = composerRef.current?.getSendContext(); + if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) { + return false; + } + const { + selectedProvider: ctxSelectedProvider, + selectedModel: ctxSelectedModel, + selectedProviderModels: ctxSelectedProviderModels, + selectedPromptEffort: ctxSelectedPromptEffort, + selectedModelSelection: ctxSelectedModelSelection, + } = sendCtx; - sendInFlightRef.current = true; - beginLocalDispatch({ preparingWorktree: false }); - setThreadError(threadIdForSend, null); + const threadIdForSend = activeThread.id; + const messageIdForSend = newMessageId(); + const messageCreatedAt = new Date().toISOString(); + const outgoingMessageText = formatOutgoingPrompt({ + provider: ctxSelectedProvider, + model: ctxSelectedModel, + models: ctxSelectedProviderModels, + effort: ctxSelectedPromptEffort, + text: trimmed, + }); - scrollToEnd(); + sendInFlightRef.current = true; + beginLocalDispatch({ preparingWorktree: false }); + setThreadError(threadIdForSend, null); - setOptimisticUserMessages((existing) => [ - ...existing, - { - id: messageIdForSend, - role: "user", - text: outgoingMessageText, - ...(context ? { context } : {}), - runId: null, - createdAt: messageCreatedAt, - updatedAt: messageCreatedAt, - streaming: false, - }, - ]); + // Position this sent row once LegendList has measured the anchored tail. + isAtEndRef.current = true; + timelineScrollModeRef.current = "anchoring-new-turn"; + liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; + setTimelineLiveFollowEnabled(true); + pendingTimelineAnchorRef.current = messageIdForSend; + activeTimelineAnchorIndexRef.current = null; + showScrollDebouncer.current.cancel(); + setShowScrollToBottom(false); + setTimelineAnchor({ + threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)), + messageId: messageIdForSend, + }); - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId: threadIdForSend, + setOptimisticUserMessages((existing) => [ + ...existing, + { + id: messageIdForSend, + role: "user", + text: outgoingMessageText, + ...(context ? { context } : {}), + runId: null, createdAt: messageCreatedAt, - modelSelection: ctxSelectedModelSelection, - ...(localCheckoutBranchMismatch - ? { branch: localCheckoutBranchMismatch.currentBranch } - : {}), - runtimeMode, - interactionMode: nextInteractionMode, - }); - let failure: AtomCommandResult | null = - settingsResult._tag === "Failure" ? settingsResult : null; - - if (failure === null) { - // Keep the mode toggle and plan-follow-up banner in sync immediately - // while the same-thread implementation turn is starting. - setComposerDraftInteractionMode( - scopeThreadRef(activeThread.environmentId, threadIdForSend), - nextInteractionMode, - ); - - const startResult = await startThreadTurn({ - environmentId, - input: { - threadId: threadIdForSend, - message: { - messageId: messageIdForSend, - role: "user", - ...(appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment - .capabilities.inlineMessageContext === true - ? { text: outgoingMessageText, ...(context ? { context } : {}) } - : { - text: serializeLegacyContextMessage({ - text: outgoingMessageText, - records: context?.records ?? [], - }), - }), - attachments: [], - }, - modelSelection: ctxSelectedModelSelection, - titleSeed: activeThread.title, - runtimeMode, - interactionMode: nextInteractionMode, - ...(nextInteractionMode === "default" && activeProposedPlan - ? { - sourceProposedPlan: { - threadId: activeThread.id, - planId: activeProposedPlan.id, - }, - } - : {}), - createdAt: messageCreatedAt, - }, - }); - failure = startResult._tag === "Failure" ? startResult : null; - } + updatedAt: messageCreatedAt, + streaming: false, + }, + ]); - if (failure === null) { - setComposerDraftInteractionMode( - scopeThreadRef(activeThread.environmentId, threadIdForSend), - nextInteractionMode, - ); - acknowledgeActiveThreadWoke(); - sendInFlightRef.current = false; - return true; - } + const settingsResult = await persistThreadSettingsForNextTurn({ + threadId: threadIdForSend, + createdAt: messageCreatedAt, + modelSelection: ctxSelectedModelSelection, + ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}), + runtimeMode, + interactionMode: nextInteractionMode, + }); + let failure: AtomCommandResult | null = + settingsResult._tag === "Failure" ? settingsResult : null; - setOptimisticUserMessages((existing) => - existing.filter((message) => message.id !== messageIdForSend), + if (failure === null) { + // Keep the mode toggle and plan-follow-up banner in sync immediately + // while the same-thread implementation turn is starting. + setComposerDraftInteractionMode( + scopeThreadRef(activeThread.environmentId, threadIdForSend), + nextInteractionMode, ); - if (!isAtomCommandInterrupted(failure)) { - const error = squashAtomCommandFailure(failure); - setThreadError( - threadIdForSend, - error instanceof Error ? error.message : "Failed to send plan follow-up.", - ); - } + + const startResult = await startThreadTurn({ + environmentId, + input: { + threadId: threadIdForSend, + message: { + messageId: messageIdForSend, + role: "user", + text: outgoingMessageText, + ...(context ? { context } : {}), + attachments: [], + }, + modelSelection: ctxSelectedModelSelection, + titleSeed: activeThread.title, + runtimeMode, + interactionMode: nextInteractionMode, + ...(nextInteractionMode === "default" && activeProposedPlan + ? { + sourceProposedPlan: { + threadId: activeThread.id, + planId: activeProposedPlan.id, + }, + } + : {}), + createdAt: messageCreatedAt, + }, + }); + failure = startResult._tag === "Failure" ? startResult : null; + } + + if (failure === null) { sendInFlightRef.current = false; resetLocalDispatch(); - return false; - }, - [ - activeThread, - activeProposedPlan, - acknowledgeActiveThreadWoke, - beginLocalDispatch, - isConnecting, - isSendBusy, - isServerThread, - localCheckoutBranchMismatch, - persistThreadSettingsForNextTurn, - resetLocalDispatch, - runtimeMode, - scrollToEnd, - setComposerDraftInteractionMode, - setThreadError, - startThreadTurn, - environmentId, - composerRef, - routeThreadKey, - ], - ); + return true; + } + + setOptimisticUserMessages((existing) => + existing.filter((message) => message.id !== messageIdForSend), + ); + if (!isAtomCommandInterrupted(failure)) { + const error = squashAtomCommandFailure(failure); + setThreadError( + threadIdForSend, + error instanceof Error ? error.message : "Failed to send plan follow-up.", + ); + } + sendInFlightRef.current = false; + resetLocalDispatch(); + return false; + } const onImplementPlanInNewThread = useCallback(async () => { if ( @@ -8819,10 +9192,16 @@ export default function ChatView(props: ChatViewProps) { scheduleComposerFocus(); return; } - const nextModelSelection: ModelSelection = { - instanceId, - model: resolvedModel, - }; + // Restore this model's own remembered options; without any, start it + // from its default rather than carrying the previous model's over. + const rememberedOptions = + useComposerDraftStore.getState().stickyOptionsByModelByProvider[instanceId]?.[ + resolvedModel + ]; + const nextModelSelection: ModelSelection = + rememberedOptions !== undefined && rememberedOptions.length > 0 + ? { instanceId, model: resolvedModel, options: [...rememberedOptions] } + : { instanceId, model: resolvedModel }; const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ providers: providerStatuses, hasStartedSession: activeRuntime !== null, @@ -8843,7 +9222,9 @@ export default function ChatView(props: ChatViewProps) { setComposerDraftModelSelection( scopeThreadRef(activeThread.environmentId, activeThread.id), nextModelSelection, - { explicit: true }, + // A complete snapshot: an absent options field means "start from the + // model default", not "keep the previous model's options". + { explicit: true, replaceOptions: true }, ); setStickyComposerModelSelection(nextModelSelection); scheduleComposerFocus(); @@ -8891,80 +9272,68 @@ export default function ChatView(props: ChatViewProps) { ], ); - // V2 accepts the initial message before workspace preparation. Keep the - // cancelled run as its durable record and launch the same input locally. - const onWorktreeSetupWorkLocally = useCallback(async () => { - const message = serverProjection?.messages.find((message) => message.role === "user"); - if (!worktreeSetup || !activeThread || !activeProject || !message || sendInFlightRef.current) + // "Work locally" on the setup card: cancel the bootstrap and remember the + // draft. The cancelled dispatch deletes the half-made thread and puts the + // message back in the composer; the effect below then flips the draft to + // local mode and resends. The draft is a server thread for the whole + // setup (the bootstrap created it), so this keys off the route, not + // `isLocalDraftThread`. + const onWorktreeSetupWorkLocally = useCallback(() => { + if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) { return; - sendInFlightRef.current = true; - try { - if (worktreeSetup.phase === "running") { - const cancelled = await cancelWorktreeSetup({ - environmentId, - input: { threadId: worktreeSetup.threadId }, - }); - if (cancelled._tag !== "Success" || !cancelled.value.cancelled) return; - } - const nextThreadId = newThreadId(); - const createdAt = new Date().toISOString(); - const created = await createThread({ - environmentId, - input: { - threadId: nextThreadId, - projectId: activeProject.id, - title: activeThread.title, - modelSelection: activeThread.modelSelection, - runtimeMode: activeThread.runtimeMode, - interactionMode: activeThread.interactionMode, - branch: null, - worktreePath: null, - createdAt, - }, - }); - if (created._tag === "Failure") { - setThreadError(activeThread.id, "Could not create a local thread. Try again."); - return; - } - const result = await startThreadTurn({ - environmentId, - input: { - threadId: nextThreadId, - message: { - messageId: newMessageId(), - role: "user", - text: message.text, - attachments: message.attachments, - ...(message.context ? { context: message.context } : {}), - }, - modelSelection: activeThread.modelSelection, - runtimeMode: activeThread.runtimeMode, - interactionMode: activeThread.interactionMode, - createdAt, - }, - }); - if (result._tag === "Failure") { - setThreadError(activeThread.id, "Could not start the thread locally. Try again."); - return; - } - await navigate({ - to: "/$environmentId/$threadId", - params: { environmentId, threadId: nextThreadId }, - }); - } finally { - sendInFlightRef.current = false; } + const target = { + environmentId: setupTarget.environmentId, + input: { threadId: worktreeSetup.threadId }, + }; + void (async () => { + const result = await cancelWorktreeSetup(target); + if (result._tag !== "Success" || !result.value.cancelled) return; + setWorkLocallyResendDraftId(draftId); + })(); + }, [cancelWorktreeSetup, draftId, setupTarget.environmentId, worktreeSetup]); + const onSendRef = useRef(onSend); + onSendRef.current = onSend; + // Resend once the cancelled dispatch has settled and the composer is free. + // Every state that makes `onSend` bail and wait is part of the readiness + // check, so the flag survives a reconnect, a reverting checkpoint, or a + // feedback upload in between. What remains inside `onSend` are the checks + // that need the user to change something, and those should not auto retry. + const workLocallyResendReady = + workLocallyResendDraftId !== null && + workLocallyResendDraftId === draftId && + isLocalDraftThread && + !isSendBusy && + !isConnecting && + !isRevertingCheckpoint && + !threadDetailLoading && + clientSettingsHydrated && + !needsLoadBalancing && + !activeEnvironmentUnavailable && + !activePendingProgress && + !feedbackUploading; + useEffect(() => { + if ( + !workLocallyResendReady || + sendInFlightRef.current || + feedbackUploadsInFlightRef.current.has(routeThreadKey) + ) { + return; + } + if (sendEnvMode !== "local") { + // The draft is back; switch it to the project checkout and let the next + // render resend. + setDraftThreadContext(composerDraftTarget, { envMode: "local", startFromOrigin: false }); + return; + } + setWorkLocallyResendDraftId(null); + void onSendRef.current(); }, [ - activeThread, - activeProject, - serverProjection, - worktreeSetup, - environmentId, - cancelWorktreeSetup, - createThread, - startThreadTurn, - setThreadError, - navigate, + composerDraftTarget, + routeThreadKey, + sendEnvMode, + setDraftThreadContext, + workLocallyResendReady, ]); const onStartFromOriginChange = (nextStartFromOrigin: boolean) => { @@ -8995,33 +9364,20 @@ export default function ChatView(props: ChatViewProps) { }, [activeThreadRef, isServerThread, onDiffPanelOpen], ); - // Both the Map and the revert handler are read from refs at call-time so - // the callback reference is fully stable and never busts context identity. - const revertTurnCountRef = useRef(revertTurnCountByUserMessageId); - revertTurnCountRef.current = revertTurnCountByUserMessageId; + // The revert handler is read from a ref at call-time so the callback + // reference is fully stable and never busts TimelineRowCtx identity. const onRevertToTurnCountRef = useRef(onRevertToTurnCount); onRevertToTurnCountRef.current = onRevertToTurnCount; - const onRevertUserMessage = useCallback((messageId: MessageId) => { - const targetTurnCount = revertTurnCountRef.current.get(messageId); - if (typeof targetTurnCount !== "number") { - return; - } + const onRevertTimelineTurn = useCallback((targetTurnCount: number, messageId: MessageId) => { void onRevertToTurnCountRef.current(targetTurnCount, messageId); }, []); - // Files dropped on a sidebar row land here once the dropped-on thread is - // actually open, then take the exact same path as a workspace drop: - // validate, compress, focus the composer, never send. Kept above the - // no-active-thread early return so hook order never changes. const pendingSidebarFileDrops = useSidebarPendingFileDropStore((state) => state.pending); const consumePendingFileDrop = useSidebarPendingFileDropStore( (state) => state.consumePendingFileDrop, ); useEffect(() => { if (pendingSidebarFileDrops.length === 0) return; - // A promoting draft can mount this view with the server thread id while - // its composer is still draft-keyed; finalization would discard what we - // attach there. Only the canonical thread target may consume a drop. if ( typeof composerDraftTarget === "string" || !pendingSidebarFileDrops.some((drop) => @@ -9033,21 +9389,14 @@ export default function ChatView(props: ChatViewProps) { if (!activeThread) return; if (!composerRef.current) { const raf = window.requestAnimationFrame(() => { - if (!composerRef.current) return; - if (typeof composerDraftTarget === "string") return; - // Consume matches by target, so a newer drop that arrived meanwhile - // is collected too rather than orphaned. + if (!composerRef.current || typeof composerDraftTarget === "string") return; const files = consumePendingFileDrop(composerDraftTarget); - if (files !== null) { - composerRef.current?.addDroppedFiles(files); - } + if (files !== null) composerRef.current?.addDroppedFiles(files); }); return () => window.cancelAnimationFrame(raf); } const files = consumePendingFileDrop(composerDraftTarget); - if (files !== null) { - composerRef.current.addDroppedFiles(files); - } + if (files !== null) composerRef.current.addDroppedFiles(files); }, [ activeThread, composerDraftTarget, @@ -9069,7 +9418,7 @@ export default function ChatView(props: ChatViewProps) { threadRef={activeThreadRef} tabId={renderedRightPanelSurface.resourceId} configuredUrls={configuredPreviewUrls} - visible + visible={rightPanelOpen} onSendAnnotation={(annotation, image) => { void onSend(undefined, "auto", { annotation, image }); }} @@ -9118,6 +9467,10 @@ export default function ChatView(props: ChatViewProps) { // reader's feet. A link the agent wrote can open any other one here, and that one has to be // checkable out like it is anywhere else. { @@ -9141,7 +9494,7 @@ export default function ChatView(props: ChatViewProps) { { projectId: activeProject?.id ?? null, repository: threadRepository, - number: activeThreadPr?.number ?? null, + number: linkedThreadPullRequest?.number ?? null, }, { projectId: renderedRightPanelSurface.projectId, @@ -9153,9 +9506,6 @@ export default function ChatView(props: ChatViewProps) { : "page" } composerDraftTarget={composerDraftTarget} - {...(linkedThreadPullRequest === null - ? { onStateChange: handlePullRequestTabStatusChange } - : {})} onBack={ activeThreadRef !== null && pullRequestsSurfaceAvailable && visiblePullRequestCount > 1 ? addPullRequestsSurface @@ -9237,7 +9587,7 @@ export default function ChatView(props: ChatViewProps) { threadId: activeThread.id, ...(draftId ? { draftId } : {}), activeProjectName: activeProject?.title, - activeProjectScripts: activeProjectScripts, + activeProjectScripts: activeProject?.scripts, preferredScriptId: activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null, @@ -9405,7 +9755,7 @@ export default function ChatView(props: ChatViewProps) { ref={threadPanelPopoverAnchorRef} data-chat-header className={cn( - "col-span-2 relative bg-background transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none", + "relative bg-background transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none", isElectron ? cn( "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5", @@ -9427,13 +9777,11 @@ export default function ChatView(props: ChatViewProps) { {inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null} - {isServerThread && activeProject && ( + {isServerThread && activeProject ? ( - )} + ) : null} {/* Main content area with optional plan sidebar */}
{/* Chat column */} @@ -9497,7 +9845,7 @@ export default function ChatView(props: ChatViewProps) { />
{/* Messages Wrapper */} -
+
{settings.vimModeEnabled ? ( message.role === "user") - ? { onWorktreeSetupWorkLocally } - : {})} + {...(draftId ? { onWorktreeSetupWorkLocally } : {})} {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})} + isPreparingWorktree={ + !paintOnlyDisplayedTimeline && (isPreparingWorktree || activeRunPreparing) + } listRef={legendListRef} timelineEntries={displayedTimeline.entries} latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun} runningRunId={paintOnlyDisplayedTimeline ? null : activeRunningTurnId} - turnDiffSummaryByAssistantMessageId={ - paintOnlyDisplayedTimeline - ? EMPTY_HELD_TURN_DIFF_SUMMARIES - : turnDiffSummaryByAssistantMessageId + turnDiffSummaries={ + paintOnlyDisplayedTimeline ? EMPTY_HELD_TURN_DIFF_SUMMARIES : turnDiffSummaries } activeThreadEnvironmentId={ displayedThreadRef?.environmentId ?? activeThread.environmentId @@ -9551,16 +9895,16 @@ export default function ChatView(props: ChatViewProps) { onRollbackCheckpoint={(input) => { if (!paintOnlyDisplayedTimeline) void onRollbackCheckpoint(input); }} - revertTurnCountByUserMessageId={ - paintOnlyDisplayedTimeline - ? EMPTY_HELD_REVERT_COUNTS - : revertTurnCountByUserMessageId + supportsConversationRollback={ + !paintOnlyDisplayedTimeline && supportsConversationRollback } - onRevertUserMessage={ - paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertUserMessage + onRevertToTurnCount={ + paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertTimelineTurn } - onUseArtifactTemplate={paintOnlyDisplayedTimeline ? () => {} : useArtifactTemplate} - isRevertingCheckpoint={!paintOnlyDisplayedTimeline && isRevertingCheckpoint} + {...(!paintOnlyDisplayedTimeline + ? { onUseArtifactTemplate: useArtifactTemplate } + : {})} + isRevertingCheckpoint={isRevertingCheckpoint} onImageExpand={onExpandTimelineImage} onFileOpen={paintOnlyDisplayedTimeline ? noopHeldAttachment : openFileAttachment} onFileDownload={ @@ -9669,13 +10013,15 @@ export default function ChatView(props: ChatViewProps) { : undefined } > - - + +
+ {mountComposerModelStrip ? ( + +
+ + ) : null} {mountComposerContextStrip && (
) : null} @@ -9951,6 +10330,7 @@ export default function ChatView(props: ChatViewProps) { {rightPanelPresent && !shouldUsePlanSidebarSheet && activeThreadRef ? ( + {expandedImage && ( ; -} - -function ProjectSearchDescription(props: { - readonly environmentLabels: ReadonlyArray; - readonly grouped: boolean; - readonly location: { - readonly kind: "local" | "remote"; - readonly label: string; - readonly machine: EnvironmentMachineKind; - }; - readonly workspaceRoot: string; -}) { - if (!props.grouped) { - return ( - - - {props.location.kind === "remote" ? ( - - ) : null} - {props.location.label} - - - {props.workspaceRoot} - - ); - } - - return {props.environmentLabels.join(" · ")}; -} - function getEnvironmentBrowsePlatform(os: string | null | undefined): string { if (os === "windows") { return "Win32"; @@ -538,14 +501,14 @@ export function CommandPalette({ children }: { children: ReactNode }) { openNewThreadIn(); } else if (detail.open === "add-project") { openAddProject(); - } else if (detail.mode) { - toggleMode(detail.mode); } else if (detail.query !== undefined) { dispatch({ _tag: "OpenSearch", query: detail.query, ...(detail.linkedThreads ? { linkedThreads: detail.linkedThreads } : {}), }); + } else if (detail.mode) { + toggleMode(detail.mode); } else { setOpen(true); } @@ -658,6 +621,9 @@ function OpenCommandPaletteDialog(props: { const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, { reportFailure: false, }); + const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, { + reportFailure: false, + }); const { environments } = useEnvironments(); const desktopLocalBootstraps = useDesktopLocalBootstraps(); const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -665,35 +631,6 @@ function OpenCommandPaletteDialog(props: { const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } = useHandleNewThread(); const projects = useProjects(); - const changeRequestSnapshotByKey = useAtomValue(ThreadPr.threadChangeRequestSnapshotsAtom); - const activeThreadProject = useProject( - activeThread === null - ? null - : scopeProjectRef(activeThread.environmentId, activeThread.projectId), - ); - const activeThreadCwd = activeThread?.worktreePath ?? activeThreadProject?.workspaceRoot ?? null; - const activeThreadGitStatus = useEnvironmentQuery( - activeThread != null && - activeThread.linkedPullRequest == null && - activeThread.branch !== null && - activeThreadCwd !== null - ? vcsEnvironment.status({ - environmentId: activeThread.environmentId, - input: { cwd: activeThreadCwd }, - }) - : null, - ).data; - const detectedPullRequestUrl = - activeThread == null || activeThread.linkedPullRequest != null - ? null - : (ThreadPr.resolveDisplayedThreadPr({ - threadBranch: activeThread.branch, - gitStatus: activeThreadGitStatus ?? null, - snapshot: changeRequestSnapshotByKey.get( - scopedThreadKey(scopeThreadRef(activeThread.environmentId, activeThread.id)), - ), - retainTerminalOnBranchMismatch: activeThread.worktreePath === null, - })?.url ?? null); const referenceThreadRef = pathname === "/pull-requests" ? environments.some( @@ -714,8 +651,9 @@ function OpenCommandPaletteDialog(props: { : resolveThreadReferenceCopyTarget({ threadId: referenceThreadRef.threadId, openPanelPullRequestUrl, - linkedPullRequestUrl: activeThread?.linkedPullRequest?.url ?? null, - detectedPullRequestUrl, + pullRequests: activeThread?.pullRequests, + linkedPullRequestUrl: + activeThread?.linkedPullRequest?.url ?? activeThread?.branchPullRequest?.url ?? null, }); const copyActiveThreadReference = useCallback(async () => { const target = activeThreadReferenceCopyTarget; @@ -747,10 +685,17 @@ function OpenCommandPaletteDialog(props: { const providerEntryByEnvironmentAndInstanceId = useMemo(() => { const map = new Map(); for (const environment of environments) { + const serverConfig = environment.serverConfig; const environmentProviders = - environment.serverConfig?.providers ?? + serverConfig?.providers ?? (environment.environmentId === primaryEnvironmentId ? providers : []); - for (const entry of deriveProviderInstanceEntries(environmentProviders)) { + const derived = deriveProviderInstanceEntries(environmentProviders); + // Settings fill the ACP registry identity (agent id, icon URL) the + // derived entries alone do not carry. + const entries = serverConfig + ? applyProviderInstanceSettings(derived, serverConfig.settings) + : derived; + for (const entry of entries) { map.set(`${environment.environmentId}:${entry.instanceId}`, entry); } } @@ -1281,14 +1226,7 @@ function OpenCommandPaletteDialog(props: { projectTitleById, sortOrder: clientSettings.sidebarThreadSortOrder, icon: , - renderLeadingContent: (thread) => ( - - ), + renderLeadingContent: (thread) => , renderTrailingContent: (thread) => , renderDescription: (thread, { projectTitle }) => { const modelInstanceId = @@ -1311,6 +1249,8 @@ function OpenCommandPaletteDialog(props: { providerDisplayName={ thread.runtime?.providerName ?? providerEntry?.displayName ?? modelInstanceId } + acpRegistryAgentId={providerEntry?.acpRegistryAgentId} + acpRegistryIconUrl={providerEntry?.acpRegistryIconUrl} /> ); }, @@ -1338,9 +1278,9 @@ function OpenCommandPaletteDialog(props: { }), [ activeThreadId, - changeRequestSnapshotByKey, clientSettings.sidebarThreadSortOrder, navigate, + projectCwdById, projectByKey, projectEnvironmentLocationById, projectTitleById, @@ -2281,28 +2221,80 @@ function OpenCommandPaletteDialog(props: { return; } + // Older servers only offer the blocking clone: the palette has to wait + // for git so it can add the project afterwards. + if (browseEnvironment?.serverConfig?.environment.capabilities.projectCloneTracking !== true) { + setIsRemoteProjectCloning(true); + const cloneResult = await cloneRepository({ + environmentId: addProjectCloneFlow.environmentId, + input: { + remoteUrl: addProjectCloneFlow.remoteUrl, + destinationPath, + }, + }); + setIsRemoteProjectCloning(false); + if (cloneResult._tag === "Failure") { + if (!isAtomCommandInterrupted(cloneResult)) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Clone failed", + description: errorMessage(squashAtomCommandFailure(cloneResult)), + }), + ); + } + return; + } + await handleAddProject(cloneResult.value.cwd); + return; + } + + // The server creates the project and clones in the background; progress + // shows in a toast and in the draft's composer banner, so the palette + // closes as soon as the clone is under way. Only problems found before + // git runs (bad destination, unknown repository) come back here. + const projectId = newProjectId(); setIsRemoteProjectCloning(true); - const cloneResult = await cloneRepository({ + const startResult = await startProjectClone({ environmentId: addProjectCloneFlow.environmentId, input: { + projectId, + title: inferProjectTitleFromPath(destinationPath), + createdAt: new Date().toISOString(), remoteUrl: addProjectCloneFlow.remoteUrl, destinationPath, }, }); setIsRemoteProjectCloning(false); - if (cloneResult._tag === "Failure") { - if (!isAtomCommandInterrupted(cloneResult)) { + if (startResult._tag === "Failure") { + if (!isAtomCommandInterrupted(startResult)) { toastManager.add( stackedThreadToast({ type: "error", title: "Clone failed", - description: errorMessage(squashAtomCommandFailure(cloneResult)), + description: errorMessage(squashAtomCommandFailure(startResult)), }), ); } return; } - await handleAddProject(cloneResult.value.cwd); + setOpen(false); + const projectRef = scopeProjectRef(addProjectCloneFlow.environmentId, projectId); + // The create event usually lands before this call returns; give the shell + // stream a moment so the draft opens with its project resolved instead of + // flashing the project picker. + await waitForProject(projectRef, 3_000).catch(() => null); + const navigationResult = await settlePromise(() => handleNewThread(projectRef)); + if (navigationResult._tag === "Failure") { + const error = squashAtomCommandFailure(navigationResult); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to open project", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } } const browseTo = useCallback( @@ -2851,3 +2843,35 @@ function OpenCommandPaletteDialog(props: { ); } + +function ProjectSearchDescription(props: { + readonly environmentLabels: ReadonlyArray; + readonly grouped: boolean; + readonly location: { + readonly kind: "local" | "remote"; + readonly label: string; + readonly machine: EnvironmentMachineKind; + }; + readonly workspaceRoot: string; +}) { + if (!props.grouped) { + return ( + + + {props.location.kind === "remote" ? ( + + ) : null} + {props.location.label} + + + {props.workspaceRoot} + + ); + } + + return {props.environmentLabels.join(" · ")}; +} diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx index 6651c2f9ac5fd..977fd49488289 100644 --- a/apps/web/src/components/ComposerPromptEditor.tsx +++ b/apps/web/src/components/ComposerPromptEditor.tsx @@ -81,8 +81,8 @@ import { selectionTouchesMentionBoundary, splitPromptIntoComposerSegments, } from "~/composer-editor-mentions"; -import { dropdownNavigationKey } from "~/lib/dropdownNavigationKey"; import { collectInlineContextIds } from "~/lib/composerContextReferences"; +import { dropdownNavigationKey } from "~/lib/dropdownNavigationKey"; import { cn, isMacPlatform } from "~/lib/utils"; import { basenameOfPath } from "~/pierre-icons"; import { @@ -2406,6 +2406,7 @@ function ComposerPromptEditorInner({
void }; +const useRequest = create<{ request: Request | null }>(() => ({ request: null })); + +export function requestCustomSnooze(): Promise { + useRequest.getState().request?.resolve(null); + return new Promise((resolve) => useRequest.setState({ request: { resolve } })); +} + +function finish(choice: SnoozeChoice | null) { + const request = useRequest.getState().request; + useRequest.setState({ request: null }); + request?.resolve(choice); +} + +export function CustomSnoozeDialogHost() { + const request = useRequest((state) => state.request); + useEffect(() => () => finish(null), []); + return request ? : null; +} + +function CustomSnoozeDialog() { + const id = useId(); + const [initial] = useState(() => new Date(Date.now() + 3_600_000)); + const [mode, setMode] = useState("date"); + const [date, setDate] = useState(initial); + const [calendarOpen, setCalendarOpen] = useState(false); + const [time, setTime] = useState(localSnoozeTime(initial)); + const [amount, setAmount] = useState("2"); + const [unit, setUnit] = useState<"minutes" | "hours" | "days">("hours"); + const [error, setError] = useState(null); + const input: CustomSnoozeInput = + mode === "date" ? { mode, date: localSnoozeDate(date), time } : { mode, amount, unit }; + return ( + { + if (!open) finish(null); + }} + > + +
{ + event.preventDefault(); + const snoozedUntil = resolveCustomSnooze(input, new Date()); + if (!snoozedUntil) { + setError( + mode === "date" + ? "Choose a valid date and time in the future." + : "Enter a positive duration.", + ); + return; + } + finish({ snoozedUntil }); + }} + > + + Custom snooze + Choose when snoozed threads return to your inbox. + + + { + if (value === "date" || value === "duration") setMode(value); + setError(null); + }} + className="flex flex-col gap-4" + > + + {(["date", "duration"] as const).map((value) => ( + + {value === "date" ? "Date and time" : "Duration"} + + ))} + + + {mode === "date" ? ( +
+
+ + + + } + > + {date.toLocaleDateString(undefined, { + month: "short", + day: "numeric", + year: "numeric", + })} + + + + { + setDate(selected); + setCalendarOpen(false); + setError(null); + }} + /> + + +
+ +
+ ) : ( +
+ { + setAmount(value === null ? "" : String(value)); + setError(null); + }} + > + + + + + + + + +
+ )} +
+
+ {error && ( +

+ {error} +

+ )} +
+ + + + +
+
+
+ ); +} diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index d9600e66b58da..15cdeda643f67 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1094,7 +1094,6 @@ export default function GitActionsControl({ ? store.getDraftThreadByRef(activeThreadRef) : null, ); - const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false); const [dialogCommitMessage, setDialogCommitMessage] = useState(""); @@ -1352,6 +1351,9 @@ export default function GitActionsControl({ ...(commitMessage ? { commitMessage } : {}), ...(featureBranch ? { featureBranch } : {}), ...(filePaths ? { filePaths } : {}), + // A pull request the action opens is linked to the thread it ran beside. Drafts + // have no server thread yet, so there is nothing to link to. + ...(activeServerThread ? { threadId: activeServerThread.id } : {}), }); if (result._tag === "Failure") { diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx index e4d41d53c3a89..c643ecde02355 100644 --- a/apps/web/src/components/Icons.tsx +++ b/apps/web/src/components/Icons.tsx @@ -758,14 +758,17 @@ export const ACPRegistryIcon: Icon = ({ className, ...props }) => ( ); export const PiAgentIcon: Icon = ({ className, ...props }) => ( - - + - + ); diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx index e70cabe3bda14..b1ed65af657c4 100644 --- a/apps/web/src/components/LegacySidebar.tsx +++ b/apps/web/src/components/LegacySidebar.tsx @@ -1,31 +1,22 @@ +import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; +import { GitPullRequestIcon } from "lucide-react"; +import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests"; +import { Spinner } from "~/components/ui/spinner"; import { ArchiveIcon, ArrowUpDownIcon, ChevronRightIcon, - CloudIcon, - ContainerIcon, FolderPlusIcon, Globe2Icon, - LoaderIcon, SearchIcon, SquarePenIcon, TerminalIcon, TriangleAlertIcon, - GitPullRequestIcon, } from "lucide-react"; -import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; -import { - resolveThreadCurrentPullRequestLink, - visibleThreadPullRequests, -} from "@t3tools/shared/threadPullRequests"; - -import { Spinner } from "~/components/ui/spinner"; - import { ChangeRequestStatusIcon, prStatusIndicator, PrStatusTooltipContent, - resolveThreadPr, terminalStatusFromRunningIds, ThreadStatusLabel, ThreadWorktreeIndicator, @@ -74,6 +65,7 @@ import { settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; +import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { useNavigate, useParams, useRouter } from "@tanstack/react-router"; import { MAX_SIDEBAR_THREAD_PREVIEW_COUNT, @@ -82,7 +74,7 @@ import { type SidebarThreadPreviewCount, type SidebarThreadSortOrder, } from "@t3tools/contracts/settings"; -import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal"; +import { isDesktopLocalConnectionTarget, isWslConnectionTarget } from "../connection/desktopLocal"; import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps"; import { isElectron } from "../env"; import { useTerminalFocus } from "../hooks/useTerminalFocus"; @@ -94,7 +86,6 @@ import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; import { readThreadShell, - useProject, useProjects, useThreadShells, useThreadShellsForProjectRefs, @@ -127,9 +118,7 @@ import { useDesktopUpdateState } from "../state/desktopUpdate"; import { useThreadActions } from "../hooks/useThreadActions"; import { projectEnvironment } from "../state/projects"; -import { useEnvironmentQuery } from "../state/query"; import { threadEnvironment, useEnvironmentThread } from "../state/threads"; -import { vcsEnvironment } from "../state/vcs"; import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; import { buildThreadRouteParams, @@ -182,11 +171,15 @@ import { SidebarMenuSubItem, useSidebar, } from "./ui/sidebar"; -import { useThreadSelectionStore } from "../threadSelectionStore"; +import { + getThreadKeysToDeselectAfterDelete, + useThreadSelectionStore, +} from "../threadSelectionStore"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { archiveSelectedThreadEntries, buildMultiSelectThreadContextMenuItems, + deleteSelectedThreadEntries, getSidebarThreadIdsToPrewarm, resolveAdjacentThreadId, isContextMenuPointerDown, @@ -194,11 +187,11 @@ import { isTrailingDoubleClick, resolveProjectStatusIndicator, resolveThreadRowClassName, + resolveThreadLastVisitedAt, resolveThreadStatusPill, orderItemsByPreferredIds, shouldClearThreadSelectionOnMouseDown, sortProjectsForSidebar, - useRetainedValue, useSidebarRowSubscriptionLease, useThreadJumpHintVisibility, ThreadStatusPill, @@ -321,7 +314,6 @@ function buildThreadJumpLabelMap(input: { interface SidebarThreadRowProps { thread: SidebarThreadSummary; - projectCwd: string | null; orderedProjectThreadKeys: readonly string[]; isActive: boolean; openPullRequestsInRightPanel: boolean; @@ -363,7 +355,7 @@ interface SidebarThreadRowProps { onFileDropThreads: (threadRef: ScopedThreadRef, files: File[]) => void; } -export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) { +const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) { const { orderedProjectThreadKeys, isActive, @@ -411,7 +403,8 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr return () => window.removeEventListener("dragend", clearFileDrag); }, [isFileDragOver]); const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(isActive); - const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); + const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); + const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); const runningTerminalIds = useThreadRunningTerminalIds({ environmentId: thread.environmentId, @@ -434,33 +427,14 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null); // A desktop-local secondary backend (e.g. the WSL backend) shows up as a // bearer environment whose connection id is prefixed "local:". It runs on the - // user's own machine, so the cloud icon is misleading — label it "Local" and - // suppress the cloud icon (the project header already shows a container icon - // for desktop-local projects, see sidebarProjectGrouping). + // user's own machine, so the cloud icon is misleading, label it "Local" and + // suppress the cloud icon (the project header already shows a + // local-environment icon for desktop-local projects, see sidebarProjectGrouping). const isDesktopLocalThread = environment !== null && isDesktopLocalConnectionTarget(environment.entry.target); const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote")) : null; - // For grouped projects, the thread may belong to a different environment - // than the representative project. Look up the thread's own project cwd - // so git status (and thus PR detection) queries the correct path. - const threadProject = useProject( - useMemo( - () => scopeProjectRef(thread.environmentId, thread.projectId), - [thread.environmentId, thread.projectId], - ), - ); - const threadProjectCwd = threadProject?.workspaceRoot ?? null; - const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd; - const gitStatus = useEnvironmentQuery( - leaseLiveStatus && thread.linkedPullRequest == null && thread.branch != null && gitCwd !== null - ? vcsEnvironment.status({ - environmentId: thread.environmentId, - input: { cwd: gitCwd }, - }) - : null, - ); const isHighlighted = isActive || isSelected; const handleOpenDiscoveredPort = useCallback( (event: React.MouseEvent) => { @@ -487,8 +461,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr }, [discoveredPorts, navigateToThread, openPreview, threadRef], ); - const isThreadRunning = - thread.runtime?.status === "running" && thread.runtime.activeRunId != null; + const isThreadRunning = !threadRuntimeCanArchive(thread.runtime); const threadStatus = resolveThreadStatusPill({ thread: { ...thread, @@ -979,7 +952,6 @@ interface SidebarProjectThreadListProps { showEmptyThreadState: boolean; shouldShowThreadPanel: boolean; isThreadListExpanded: boolean; - projectCwd: string; activeRouteThreadKey: string | null; openPullRequestsInRightPanel: boolean; threadJumpLabelByKey: ReadonlyMap; @@ -1036,7 +1008,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList( showEmptyThreadState, shouldShowThreadPanel, isThreadListExpanded, - projectCwd, activeRouteThreadKey, openPullRequestsInRightPanel, threadJumpLabelByKey, @@ -1089,7 +1060,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList( ; archiveThread: ReturnType["archiveThread"]; deleteThread: ReturnType["deleteThread"]; + markThreadUnread: ReturnType["markThreadUnread"]; threadJumpLabelByKey: ReadonlyMap; attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; expandThreadListForProject: (projectKey: string) => void; @@ -1185,6 +1156,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec handleNewThread, archiveThread, deleteThread, + markThreadUnread, threadJumpLabelByKey, attachThreadListAutoAnimateRef, expandThreadListForProject, @@ -1195,6 +1167,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec isManualProjectSorting, dragHandleProps, } = props; + const environmentMachine = project.allRemoteMembersAreWsl + ? "linux" + : project.allRemoteMembersAreDesktopLocal + ? "laptop" + : "cloud"; const threadSortOrder = useClientSettings( (settings) => settings.sidebarThreadSortOrder, ); @@ -1222,7 +1199,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop); const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop); const { isMobile, setOpenMobile } = useSidebar(); - const markThreadUnread = useUiStateStore((state) => state.markThreadUnread); const setProjectExpanded = useUiStateStore((state) => state.setProjectExpanded); const toggleThreadSelection = useThreadSelectionStore((state) => state.toggleThread); const rangeSelectTo = useThreadSelectionStore((state) => state.rangeSelectTo); @@ -1346,7 +1322,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec const lastVisitedAtByThreadKey = new Map( projectThreads.map((thread, index) => [ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - threadLastVisitedAts[index] ?? null, + resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined), ]), ); const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => { @@ -1398,7 +1374,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec const lastVisitedAtByThreadKey = new Map( projectThreads.map((thread, index) => [ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - threadLastVisitedAts[index] ?? null, + resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined), ]), ); const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => { @@ -1770,11 +1746,20 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec }; }; + actionHandlers.set("project-settings", () => { + if (isMobile) setOpenMobile(false); + void router.navigate({ + to: "/projects/$projectKey", + params: { projectKey: project.projectKey }, + }); + }); + const clicked = await api.contextMenu.show( [ buildTargetedItem("rename", "Rename"), buildTargetedItem("grouping", "Group into..."), buildTargetedItem("copy-path", "Copy Path"), + { id: "project-settings", label: "Project settings", icon: "settings" }, buildTargetedItem("delete", "Remove", { destructive: true, }), @@ -1795,10 +1780,14 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec [ copyPathToClipboard, handleRemoveProject, + isMobile, openProjectGroupingDialog, openProjectRenameDialog, project.groupedProjectCount, project.memberProjects, + project.projectKey, + router, + setOpenMobile, suppressProjectClickForContextMenuRef, ], ); @@ -1907,7 +1896,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec return threadRef && thread ? [{ threadKey, threadRef, thread }] : []; }); const hasRunningThread = selectedThreadEntries.some( - ({ thread }) => thread.runtime?.status === "running" && thread.runtime.activeRunId != null, + ({ thread }) => !threadRuntimeCanArchive(thread.runtime), ); const clicked = await api.contextMenu.show( @@ -1916,8 +1905,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec ); if (clicked === "mark-unread") { - for (const { threadKey, thread } of selectedThreadEntries) { - markThreadUnread(threadKey, thread.latestRun?.completedAt); + for (const { threadRef } of selectedThreadEntries) { + markThreadUnread(threadRef); } clearSelection(); return; @@ -1977,26 +1966,27 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec if (!confirmed) return; } - const deletedThreadKeys = new Set(threadKeys); - for (const { threadRef } of selectedThreadEntries) { - const result = await deleteThread(threadRef, { - deletedThreadKeys, - }); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to delete threads", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } + const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({ + entries: selectedThreadEntries, + delete: ({ threadRef }, deletedThreadKeys) => + deleteThread(threadRef, { deletedThreadKeys }), + }); + if (firstFailure !== null) { + const firstError = squashAtomCommandFailure(firstFailure); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to delete threads", + description: firstError instanceof Error ? firstError.message : "An error occurred.", + }), + ); } - removeFromSelection(threadKeys); + removeFromSelection( + getThreadKeysToDeselectAfterDelete(threadKeys, deletedThreadKeys, (threadKey) => { + const threadRef = parseScopedThreadKey(threadKey); + return threadRef !== null && readThreadShell(threadRef) !== null; + }), + ); }, [ appSettingsConfirmThreadArchive, @@ -2305,7 +2295,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec } if (clicked === "mark-unread") { - markThreadUnread(threadKey, thread.latestRun?.completedAt); + markThreadUnread(threadRef); return; } if (clicked === "copy-path") { @@ -2439,15 +2429,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec ? "Local sandbox project" : "Remote project" } - className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center rounded-md text-icon-muted transition-opacity duration-150 max-sm:right-7 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0 max-sm:group-hover/project-header:opacity-100 max-sm:group-focus-within/project-header:opacity-100" + className="pointer-events-none absolute top-1/2 right-1.5 inline-flex size-5 -translate-y-1/2 items-center justify-center rounded-md text-icon-muted transition-opacity duration-150 max-sm:right-7 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0 max-sm:group-hover/project-header:opacity-100 max-sm:group-focus-within/project-header:opacity-100" /> } > - {project.allRemoteMembersAreDesktopLocal ? ( - - ) : ( - - )} + {project.allRemoteMembersAreDesktopLocal @@ -2488,7 +2474,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec showEmptyThreadState={showEmptyThreadState} shouldShowThreadPanel={shouldShowThreadPanel} isThreadListExpanded={isThreadListExpanded} - projectCwd={project.workspaceRoot} activeRouteThreadKey={activeRouteThreadKey} openPullRequestsInRightPanel={openPullRequestsInRightPanel} threadJumpLabelByKey={threadJumpLabelByKey} @@ -2699,7 +2684,7 @@ function LocalSecondaryStatus() { variant="default" className="rounded-2xl border-border/40 bg-accent/40 text-muted-foreground" > - + Connecting {connecting.join(", ")} @@ -2905,6 +2890,7 @@ interface SidebarProjectsContentProps { handleNewThread: ReturnType; archiveThread: ReturnType["archiveThread"]; deleteThread: ReturnType["deleteThread"]; + markThreadUnread: ReturnType["markThreadUnread"]; sortedProjects: readonly SidebarProjectSnapshot[]; expandedThreadListsByProject: ReadonlySet; activeRouteProjectKey: string | null; @@ -2947,6 +2933,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent( handleNewThread, archiveThread, deleteThread, + markThreadUnread, sortedProjects, expandedThreadListsByProject, activeRouteProjectKey, @@ -3098,6 +3085,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent( handleNewThread={handleNewThread} archiveThread={archiveThread} deleteThread={deleteThread} + markThreadUnread={markThreadUnread} threadJumpLabelByKey={threadJumpLabelByKey} attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} expandThreadListForProject={expandThreadListForProject} @@ -3131,6 +3119,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent( handleNewThread={handleNewThread} archiveThread={archiveThread} deleteThread={deleteThread} + markThreadUnread={markThreadUnread} threadJumpLabelByKey={threadJumpLabelByKey} attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} expandThreadListForProject={expandThreadListForProject} @@ -3166,7 +3155,7 @@ export default function LegacySidebar() { const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount); const updateSettings = useUpdateClientSettings(); const handleNewThread = useNewThreadHandler(); - const { archiveThread, deleteThread } = useThreadActions(); + const { archiveThread, deleteThread, markThreadUnread } = useThreadActions(); const { isMobile, setOpenMobile } = useSidebar(); const routeTarget = useParams({ strict: false, @@ -3222,6 +3211,15 @@ export default function LegacySidebar() { ), [environments], ); + const wslEnvironmentIds = useMemo( + () => + new Set( + environments + .filter((environment) => isWslConnectionTarget(environment.entry.target)) + .map((environment) => environment.environmentId), + ), + [environments], + ); const orderedProjects = useMemo(() => { return orderItemsByPreferredIds({ items: projects, @@ -3262,10 +3260,12 @@ export default function LegacySidebar() { primaryEnvironmentId, resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId), + isWslEnvironment: (environmentId) => wslEnvironmentIds.has(environmentId), }); }, [ environmentLabelById, desktopLocalEnvironmentIds, + wslEnvironmentIds, orderedProjects, projectGroupingSettings, primaryEnvironmentId, @@ -3661,11 +3661,9 @@ export default function LegacySidebar() { desktopUpdateState && showArm64IntelBuildWarning ? getArm64IntelBuildWarningDescription(desktopUpdateState) : null; - const commandPaletteShortcutLabel = shortcutLabelForCommand( - keybindings, - "commandPalette.toggle", - newThreadShortcutLabelOptions, - ); + const commandPaletteShortcutLabel = isMobile + ? null + : shortcutLabelForCommand(keybindings, "commandPalette.toggle", newThreadShortcutLabelOptions); const handleDesktopUpdateButtonClick = useCallback(async () => { const bridge = window.desktopBridge; if (!bridge || !desktopUpdateState) return; @@ -3809,6 +3807,7 @@ export default function LegacySidebar() { handleNewThread={handleNewThread} archiveThread={archiveThread} deleteThread={deleteThread} + markThreadUnread={markThreadUnread} sortedProjects={sortedProjects} expandedThreadListsByProject={expandedThreadListsByProject} activeRouteProjectKey={activeRouteProjectKey} diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx new file mode 100644 index 0000000000000..2c4a477a2f2e8 --- /dev/null +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -0,0 +1,240 @@ +import { useParams } from "@tanstack/react-router"; +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { + type AtomCommandResult, + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { + projectCloneDisplayName, + projectCloneProgressSummary, + type EnvironmentId, + type ProjectCloneSnapshot, + type ProjectId, +} from "@t3tools/contracts"; +import { useCallback, useEffect, useRef } from "react"; + +import { useNewThreadHandler } from "../hooks/useHandleNewThread"; +import { useRemoveClonedProject } from "../hooks/useRemoveClonedProject"; +import { useEnvironments } from "../state/environments"; +import { useEnvironmentProjectClones } from "../state/projectClones"; +import { sourceControlEnvironment } from "../state/sourceControl"; +import { useAtomCommand } from "../state/use-atom-command"; +import { type DraftId, useComposerDraftStore } from "../composerDraftStore"; +import { toastManager } from "./ui/toast"; +import { stackedThreadToast } from "./ui/toastHelpers"; + +/** + * One toast per clone in flight, on every environment. The palette that + * started a clone closes right away, so this is where its progress lives: + * the toast updates in place as git reports stages, then settles into a + * success or failure state with the matching action. + */ +export function ProjectCloneToastCoordinator() { + const { environments } = useEnvironments(); + return environments.map((environment) => ( + + )); +} + +interface TrackedToast { + readonly toastId: ReturnType; + /** The last snapshot rendered, so an identical redraw does not touch the toast. */ + readonly renderedKey: string; + readonly phase: ProjectCloneSnapshot["phase"]; +} + +function renderKey(clone: ProjectCloneSnapshot): string { + return `${clone.phase}:${clone.stage}:${clone.percent ?? ""}:${clone.detail ?? ""}:${clone.error ?? ""}`; +} + +function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentId }) { + const clones = useEnvironmentProjectClones(environmentId); + const handleNewThread = useNewThreadHandler(); + const { draftId: routeDraftId } = useParams({ strict: false }); + const cancelClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, { + reportFailure: false, + }); + const retryClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, { + reportFailure: false, + }); + // The toast mirrors the server's clone state, so a request that never got + // there needs its own feedback. + const runCloneAction = useCallback( + async (title: string, action: () => Promise>) => { + const result = await action(); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + }, + [], + ); + const removeClonedProject = useRemoveClonedProject(); + const toasts = useRef(new Map()); + + // Whether the user is already looking at this project's draft: the composer + // banner shows the same progress and actions there, so the toast steps + // aside and comes back if they navigate away mid-clone. + const isViewingProjectDraft = useCallback( + (projectId: ProjectId) => { + if (!routeDraftId) return false; + const draft = useComposerDraftStore.getState().getDraftSession(routeDraftId as DraftId); + return draft?.environmentId === environmentId && draft.projectId === projectId; + }, + [environmentId, routeDraftId], + ); + + const openProject = useCallback( + (projectId: ProjectId) => { + void handleNewThread(scopeProjectRef(environmentId, projectId)); + }, + [environmentId, handleNewThread], + ); + + useEffect(() => { + const seen = new Set(); + for (const clone of clones) { + seen.add(clone.projectId); + const key = renderKey(clone); + const tracked = toasts.current.get(clone.projectId); + const name = projectCloneDisplayName(clone); + // Handlers run later than this pass, so they look the toast up then. + const closeToast = () => { + const current = toasts.current.get(clone.projectId); + if (!current) return; + toastManager.close(current.toastId); + toasts.current.delete(clone.projectId); + }; + if (isViewingProjectDraft(clone.projectId)) { + closeToast(); + continue; + } + if (tracked?.renderedKey === key) continue; + + if (clone.phase === "running") { + const options = stackedThreadToast({ + type: "loading", + title: `Cloning ${name}`, + description: projectCloneProgressSummary(clone), + timeout: 0, + actionProps: { + children: "Cancel", + onClick: () => { + void runCloneAction("Failed to cancel clone", () => + cancelClone({ environmentId, input: { projectId: clone.projectId } }), + ); + }, + }, + data: { hideCopyButton: true }, + }); + if (tracked) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); + } else { + const toastId = toastManager.add(options); + toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); + } + continue; + } + + if (clone.phase === "done") { + const options = stackedThreadToast({ + type: "success", + title: `Cloned ${name}`, + description: clone.destinationPath, + timeout: 8_000, + actionProps: { + children: "Open project", + onClick: () => { + closeToast(); + openProject(clone.projectId); + }, + }, + data: { hideCopyButton: true }, + }); + if (tracked) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); + } else { + const toastId = toastManager.add(options); + toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); + } + continue; + } + + // Failed or cancelled: the project stays, pointing at an empty folder. + // Retry from here; the draft's composer banner offers the same. + const cancelled = clone.phase === "cancelled"; + const options = stackedThreadToast({ + type: cancelled ? "info" : "error", + title: cancelled ? `Cancelled cloning ${name}` : `Failed to clone ${name}`, + description: cancelled ? clone.destinationPath : (clone.error ?? "The clone failed."), + timeout: 0, + actionProps: { + children: "Retry", + onClick: () => { + void runCloneAction("Failed to retry clone", () => + retryClone({ environmentId, input: { projectId: clone.projectId } }), + ); + }, + }, + data: { + ...(cancelled ? { hideCopyButton: true } : {}), + secondaryActionProps: { + children: "Remove project", + onClick: () => { + // The server drops the clone with the project, which closes + // this toast; a failed removal leaves it (and Retry) in place. + void removeClonedProject({ environmentId, projectId: clone.projectId }); + }, + }, + }, + }); + if (tracked) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); + } else { + const toastId = toastManager.add(options); + toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); + } + } + + // A clone the server stopped tracking (done and expired, or its project + // was removed) takes its toast with it, unless it already settled into a + // timed success toast that dismisses itself. + for (const [projectId, tracked] of toasts.current) { + if (seen.has(projectId)) continue; + if (tracked.phase !== "done") toastManager.close(tracked.toastId); + toasts.current.delete(projectId); + } + }, [ + cancelClone, + clones, + environmentId, + isViewingProjectDraft, + openProject, + removeClonedProject, + retryClone, + runCloneAction, + ]); + + useEffect( + () => () => { + for (const tracked of toasts.current.values()) toastManager.close(tracked.toastId); + toasts.current.clear(); + }, + [], + ); + + return null; +} diff --git a/apps/web/src/components/ProjectFavicon.test.tsx b/apps/web/src/components/ProjectFavicon.test.tsx index 854301bee7bc0..b60cf3ae62c4a 100644 --- a/apps/web/src/components/ProjectFavicon.test.tsx +++ b/apps/web/src/components/ProjectFavicon.test.tsx @@ -122,36 +122,28 @@ describe("ProjectFavicon", () => { testState.faviconUrl = "https://environment.test/api/assets/token-a/v1-20-favicon.svg"; }); - it("shows a project-name icon when no favicon exists", () => { + it("shows the project monogram when no favicon exists", () => { testState.faviconUrl = `https://environment.test/api/assets/token/${PROJECT_FAVICON_FALLBACK_MARKER}`; const element = ProjectFavicon({ project: makeProject({ workspaceRoot: "/workspace/analytics-db", title: "analytics-db" }), }) as ReactElement<{ - readonly colorClassName?: string; - readonly emoji?: string; - readonly icon?: ComponentType<{ className?: string }>; + readonly projectName?: string; }>; - expect(element.props.icon).toBeDefined(); - expect(element.props.emoji).toBeUndefined(); - expect(element.props.colorClassName).toContain("text-cyan-600"); + expect(element.props.projectName).toBe("analytics-db"); }); - it("chooses a deterministic semantic icon", () => { + it("uses the same monogram fallback for every project category", () => { testState.faviconUrl = `https://environment.test/api/assets/token/${PROJECT_FAVICON_FALLBACK_MARKER}`; const element = ProjectFavicon({ project: makeProject({ workspaceRoot: "/workspace/agent-runtime", title: "agent-runtime" }), }) as ReactElement<{ - readonly colorClassName?: string; - readonly emoji?: string; - readonly icon?: ComponentType<{ className?: string }>; + readonly projectName?: string; }>; - expect(element.props.icon).toBeDefined(); - expect(element.props.emoji).toBeUndefined(); - expect(element.props.colorClassName).toContain("text-violet-600"); + expect(element.props.projectName).toBe("agent-runtime"); }); it("renders a saved Lucide icon and color ahead of an uploaded favicon", () => { diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index a76ea0662b1e3..b7efd124575a6 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -131,6 +131,7 @@ export default function ProjectScriptsControl({ command: fileScript.command, icon: fileScript.icon ?? "play", runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false, + waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false, keybinding: null, previewUrl: fileScript.previewUrl ?? null, autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false, diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx index a0ed3d80467fb..3fca1d748ca71 100644 --- a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx +++ b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx @@ -2,12 +2,12 @@ import { useNavigate } from "@tanstack/react-router"; import { useAtomValue } from "@effect/atom-react"; import { DownloadIcon } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef } from "react"; -import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts"; +import { type ServerProvider, type ProviderInstanceId } from "@t3tools/contracts"; import { primaryServerProvidersAtom, serverEnvironment } from "../state/server"; import { usePrimaryEnvironment } from "../state/environments"; import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal"; -import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils"; +import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon"; import { canOneClickUpdateProviderCandidate, collectProviderUpdateCandidates, @@ -35,20 +35,15 @@ type ActiveProviderUpdateToast = readonly providerCount: number; }; -function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) { - const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider]; - - if (!ProviderIcon) { - return ( - - - ); - } - +function ProviderUpdateToastIcon({ provider }: { provider: ServerProvider }) { return ( -
) : null} + {previousProviderNames.length > 0 ? ( +
+ +
+ Handed off from {previousProviderNames.join(", ")} +
+
+ ) : null} {terminalStatus ? (
void; - onSnooze: (preset: SnoozePreset) => void; + onSnooze: (preset: Pick) => void; timestampFormat: TimestampFormat; }) { const { open, onOpenChange, onSnooze, timestampFormat } = props; @@ -487,6 +570,19 @@ function SnoozePopoverButton(props: { ))} +
+ ); @@ -694,7 +790,6 @@ function SidebarSectionHeader(props: { // entirely. const SidebarDraftRow = memo(function SidebarDraftRow(props: { draftId: DraftId; - session: DraftSessionState; composer: ComposerThreadDraftState; project: ProjectFaviconProject | null; projectDisplayName: string | null; @@ -702,7 +797,7 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { onNavigate: (draftId: DraftId) => void; onDiscard: (draftId: DraftId) => void; }) { - const { composer, draftId, onDiscard, onNavigate, session } = props; + const { composer, draftId, onDiscard, onNavigate } = props; const promptPreview = replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label) .trim() @@ -892,7 +987,6 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { void; onSettle: (threadRef: ScopedThreadRef) => void; onUnsettle: (threadRef: ScopedThreadRef) => void; - onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void; + onSnooze: (threadRef: ScopedThreadRef, preset: Pick) => void; onUnsnooze: (threadRef: ScopedThreadRef) => void; onUnpin: (threadRef: ScopedThreadRef) => void; onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void; - /** - * External files dropped onto this row. The row highlights while the drag - * is over it; the callback opens the thread and hands the files to its - * composer. Absent when the sidebar cannot open server threads. - */ onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined; + changeRequestSnapshot: ThreadChangeRequestSnapshot | null; + onChangeRequestSnapshot: ( + threadKey: string, + snapshot: ThreadChangeRequestSnapshot | null, + ) => void; }) { const { isRenaming, + changeRequestSnapshot, + onChangeRequestSnapshot, onCancelRename, onCommitRename, onContextMenu, @@ -1037,7 +1138,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { const threadKey = scopedThreadKey(threadRef); const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(props.isActive); const isRegeneratingTitle = thread.titleRegeneration != null; - const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); + const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); + const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); const openPrLink = useOpenPrLink(); const runningTerminalIds = useThreadRunningTerminalIds({ @@ -1090,6 +1192,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { // switching sidebars must not light up every historical thread as unread. const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); const status = resolveSidebarThreadStatus(thread); + const isInFlight = + status === "working" || status === "waiting" || status === "approval" || status === "input"; // A woken thread reappears at its original position (the sort is // deliberately static), so the pill has to carry the weight. Snoozing is // an explicit act, so the pill clears only when the user re-engages: @@ -1127,10 +1231,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { } : status === "waiting" ? { - // The V2 runtime is idle while background tasks remain open. + // Waiting is calm background presence (post-settle background + // roster), not active progress, so the label keeps full strength. label: "Waiting", - icon: "monitoring" as const, - className: "text-sky-600 dark:text-sky-400", + icon: null, + className: "text-muted-foreground", } : status === "approval" ? { @@ -1175,7 +1280,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; - const driverKind = providerEntry?.driverKind ?? null; const showInstanceBadge = providerEntry !== null && shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values()); @@ -1200,6 +1304,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { environmentLabel={props.environmentLabel} environmentMachine={props.environmentMachine} providerEntry={providerEntry} + providerEntryByInstanceId={props.providerEntryByInstanceId} showInstanceBadge={showInstanceBadge} modelInstanceId={modelInstanceId} modelLabel={modelLabel} @@ -1257,15 +1362,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { onFileDropThreads ? makeWorkspaceFileDropHandlers({ setDragActive: setIsFileDragOver, - addFiles: (files) => { - onFileDropThreads(threadRef, files); - }, + addFiles: (files) => onFileDropThreads(threadRef, files), }) : null, [onFileDropThreads, threadRef], ); - // A drop lands on a child or outside the window entirely, so dragend is - // the reset of last resort for the row's highlight. useEffect(() => { if (!isFileDragOver) return; const clearFileDrag = () => setIsFileDragOver(false); @@ -1330,7 +1431,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { [onUnpin, threadRef], ); const handleSnoozePreset = useCallback( - (preset: SnoozePreset) => { + (preset: Pick) => { onSnooze(threadRef, preset); }, [onSnooze, threadRef], @@ -1381,8 +1482,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { // a useful hierarchy nor a reliable hover cue. Status now lives in the row // content; surface is reserved for interaction (hover, multi-select, route). const rowSurfaceClassName = cn( - "group/sidebar-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none", - variantAction === "unsettle" && "[&:not(:hover):not(:focus-within)_*]:text-secondary-label/70", + "group/sidebar-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none focus:bg-sidebar-row-selected focus:text-sidebar-foreground", props.isActive ? "bg-sidebar-row-active text-sidebar-foreground" : isSelected @@ -1393,7 +1493,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { ? "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover", isFileDragOver && "ring-1 ring-inset ring-primary/70", - // The hover tint must not clobber an active/selected row's own surface. isFileDragOver && !props.isActive && !isSelected && "bg-sidebar-row-hover", // The lifted row is an opaque card so the rows beneath it never show // through. The row tint is translucent in dark themes and the pointer @@ -1708,7 +1807,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { ); } - const diff = latestTurnDiff(thread); + const diff = latestRunDiff(thread); return (
  • ) : topStatus.icon === "failed" ? ( - ) : topStatus.icon === "monitoring" ? ( - ) : topStatus.icon === "done" ? ( ) : null} @@ -1937,23 +2034,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { /> ) : null} - {driverKind ? ( - - - - ) : null} +
  • @@ -1965,7 +2049,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { ); }); -function latestTurnDiff( +function latestRunDiff( thread: SidebarThreadSummary, ): { insertions: number; deletions: number } | null { // Shells don't carry checkpoint summaries; diff stats render only when the @@ -2098,6 +2182,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { environmentLabel={props.environmentLabel} environmentMachine={props.environmentMachine} providerEntry={providerEntry} + providerEntryByInstanceId={props.providerEntryByInstanceId} showInstanceBadge={showInstanceBadge} modelInstanceId={modelInstanceId} modelLabel={modelLabel} @@ -2113,8 +2198,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { export default function Sidebar() { const projects = useProjects(); const projectOrder = useUiStateStore((store) => store.projectOrder); - const allThreads = useThreadShells(); - const threads = useMemo(() => filterSidebarV2VisibleThreads(allThreads, null), [allThreads]); + const threads = useThreadShells(); const router = useRouter(); const { isMobile, setOpenMobile } = useSidebar(); const keybindings = useAtomValue(primaryServerKeybindingsAtom); @@ -2133,6 +2217,7 @@ export default function Sidebar() { confirmAndUnpinThread, reorderPinnedThread, reorderActiveThread, + markThreadUnread, archiveThread, deleteThread, } = useThreadActions(); @@ -2205,7 +2290,6 @@ export default function Sidebar() { const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo); - const markThreadUnread = useUiStateStore((s) => s.markThreadUnread); const markThreadVisited = useUiStateStore((s) => s.markThreadVisited); const acknowledgeWoke = useCallback( (threadRef: ScopedThreadRef, visitedAt: string) => { @@ -2284,7 +2368,7 @@ export default function Sidebar() { ], ); const projectGroups = useMemo( - () => sortLogicalProjectsForSidebar(unsortedProjectGroups, threads, sidebarProjectSortOrder), + () => sortSidebarV2ProjectGroups(unsortedProjectGroups, threads, sidebarProjectSortOrder), [sidebarProjectSortOrder, threads, unsortedProjectGroups], ); const projectGroupsRef = useRef(projectGroups); @@ -2297,7 +2381,7 @@ export default function Sidebar() { () => deriveProviderEntriesByEnvironment( [...serverConfigs].map( - ([environmentId, config]) => [environmentId, config.providers] as const, + ([environmentId, config]) => [environmentId, config.providers, config.settings] as const, ), ), [serverConfigs], @@ -2321,6 +2405,7 @@ export default function Sidebar() { ); const nowMinute = useNowMinute(); + const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom); // Snooze wake times are second-precise, so classifying with the quantized // minute would hold a woken thread on the shelf for up to a minute. The // tick is a plain counter bumped exactly at the next wake boundary (armed @@ -2508,12 +2593,9 @@ export default function Sidebar() { // memo exactly at the next wake boundary. void snoozeWakeTick; const preciseNow = new Date().toISOString(); - const visible = threads.filter( - (thread) => - thread.archivedAt === null && - (scopedProjectKeys === null || - scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)), - ); + // Subagent child threads live in the parent's Agents surface, not the + // sidebar roster (v2 models them as real threads with lineage). + const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys); const pinned: EnvironmentThreadShell[] = []; const active: EnvironmentThreadShell[] = []; const snoozed: EnvironmentThreadShell[] = []; @@ -2552,15 +2634,20 @@ export default function Sidebar() { ? projected : { ...projected, snoozedAt: thread.snoozedAt, snoozedUntil: thread.snoozedUntil }, ); - } else if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) { - // Snooze outranks settlement and pinning until the thread wakes. - snoozed.push(thread); - } else if (supportsSettlement && thread.settledOverride === "settled") { - settled.push(thread); - } else if (thread.pinnedAt != null) { - pinned.push(thread); } else { - active.push(thread); + const section = resolveSidebarThreadSection({ + snoozed: supportsSnooze && effectiveSnoozed(thread, { now: preciseNow }), + settled: supportsSettlement && thread.settledOverride === "settled", + pinned: thread.pinnedAt != null, + }); + (section === "snoozed" + ? snoozed + : section === "settled" + ? settled + : section === "pinned" + ? pinned + : active + ).push(thread); } } // One shared rule on every platform (see sortPinnedThreadsByOrderKey): @@ -2792,7 +2879,8 @@ export default function Sidebar() { } return mapping; }, [keybindings, orderedThreadKeys]); - const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility(); + const { showThreadJumpHints: showJumpHints, updateThreadJumpHintsVisibility } = + useThreadJumpHintVisibility(); // Settled threads are live shells, so opening one is plain navigation: // history stays readable without un-settling, and sending a message or @@ -2814,42 +2902,27 @@ export default function Sidebar() { [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor], ); - // Dropping files on a row opens that thread and attaches the files there. - // The composer only accepts drops for its OWN thread, so when the row is - // not the open thread we stash the files and let ChatView hand them over - // once the navigation actually lands; if the route bounced (thread gone), - // nothing will consume them, so clear instead of surprising the user later. const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop); const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop); const handleThreadFileDrop = useCallback( async (threadRef: ScopedThreadRef, files: File[]) => { - // Queued, not replaced: a second drop before the thread opens keeps - // both files, and the id lets cleanup below touch only this drop. const dropId = queuePendingFileDrop({ threadRef, files }); - // Key match alone is not "already there": during draft promotion the - // resolved route key is the server thread while the URL is still the - // draft route, and its composer would swallow the drop then discard it. const landedBefore = router.buildLocation({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef), }).pathname === router.state.location.pathname; if (landedBefore) return; + try { await navigateToThread(threadRef); - // A newer drop may have arrived while the navigation was in flight; - // clearing by id leaves those files untouched. const landed = router.buildLocation({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef), }).pathname === router.state.location.pathname; - if (!landed) { - clearPendingFileDrop(dropId); - } + if (!landed) clearPendingFileDrop(dropId); } catch { - // Navigation failed outright; nothing will consume this drop, but a - // newer drop for the same thread may still be deliverable. clearPendingFileDrop(dropId); } }, @@ -3644,7 +3717,7 @@ export default function Sidebar() { const performSnooze = useCallback( async ( threadRef: ScopedThreadRef, - preset: SnoozePreset, + preset: Pick, opts: { coSnoozingKeys?: ReadonlySet } = {}, ) => { const threadKey = scopedThreadKey(threadRef); @@ -3678,7 +3751,7 @@ export default function Sidebar() { const attemptSnooze = useCallback( ( threadRef: ScopedThreadRef, - preset: SnoozePreset, + preset: Pick, opts: { coSnoozingKeys?: ReadonlySet } = {}, ) => { void (async () => { @@ -3774,10 +3847,13 @@ export default function Sidebar() { { id: "snooze", label: `Snooze (${count})`, - children: snoozePresets.map((preset) => ({ - id: `snooze:${preset.id}`, - label: `${preset.label} (${preset.whenLabel})`, - })), + children: [ + ...snoozePresets.map((preset) => ({ + id: `snooze:${preset.id}`, + label: `${preset.label} (${preset.whenLabel})`, + })), + { id: "snooze:custom", label: "Custom…", separatorBefore: true }, + ], }, ] : []), @@ -3790,9 +3866,10 @@ export default function Sidebar() { ); if (clicked._tag === "Failure") return; if (clicked.value?.startsWith("snooze:")) { - const preset = snoozePresets.find( - (candidate) => `snooze:${candidate.id}` === clicked.value, - ); + const preset = + clicked.value === "snooze:custom" + ? await requestCustomSnooze() + : snoozePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value); if (preset) { // Post-snooze navigation must skip threads snoozing in this same // batch — they are all leaving the card block together. @@ -3897,7 +3974,7 @@ export default function Sidebar() { if (clicked.value === "mark-unread") { for (const threadKey of threadKeys) { const thread = threadByKeyRef.current.get(threadKey); - markThreadUnread(threadKey, thread?.latestRun?.completedAt); + if (thread) markThreadUnread(scopeThreadRef(thread.environmentId, thread.id)); } clearSelection(); return; @@ -4004,7 +4081,7 @@ export default function Sidebar() { isSnoozed, canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), isRegeneratingTitle, - isRunning: thread.runtime?.status === "running" && thread.runtime.activeRunId != null, + isRunning: !threadRuntimeCanArchive(thread.runtime), supports: { settlement: supportsSettlement, snooze: supportsSnooze, @@ -4018,9 +4095,10 @@ export default function Sidebar() { ); if (clicked._tag === "Failure") return; if (clicked.value?.startsWith("snooze:")) { - const preset = snoozePresets.find( - (candidate) => `snooze:${candidate.id}` === clicked.value, - ); + const preset = + clicked.value === "snooze:custom" + ? await requestCustomSnooze() + : snoozePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value); if (preset) attemptSnooze(threadRef, preset); return; } @@ -4096,7 +4174,7 @@ export default function Sidebar() { return; } case "mark-unread": - markThreadUnread(threadKey, thread.latestRun?.completedAt); + markThreadUnread(threadRef); return; case "copy-path": if (!threadWorkspacePath) { @@ -4646,7 +4724,7 @@ export default function Sidebar() { isActive={routeThreadKey === threadKey} openPullRequestsInRightPanel={routeThreadRef !== null} jumpLabel={ - showThreadJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null + showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } currentEnvironmentId={primaryEnvironmentId} environmentLabel={ @@ -4685,6 +4763,10 @@ export default function Sidebar() { onUnpin={attemptUnpin} onAcknowledgeWoke={acknowledgeWoke} onFileDropThreads={handleThreadFileDrop} + changeRequestSnapshot={ + changeRequestSnapshotByKey.get(threadKey) ?? null + } + onChangeRequestSnapshot={setThreadChangeRequestSnapshot} /> ); }; diff --git a/apps/web/src/components/ThreadCommandSubtitle.tsx b/apps/web/src/components/ThreadCommandSubtitle.tsx index 275105a79099f..522a7a000a879 100644 --- a/apps/web/src/components/ThreadCommandSubtitle.tsx +++ b/apps/web/src/components/ThreadCommandSubtitle.tsx @@ -42,6 +42,8 @@ export function ThreadCommandSubtitle(props: { isCurrent: boolean; driverKind?: ProviderDriverKind | null; providerDisplayName?: string | null; + acpRegistryAgentId?: string | undefined; + acpRegistryIconUrl?: string | undefined; variant?: ThreadCommandSubtitleVariant; className?: string; }) { @@ -95,6 +97,8 @@ export function ThreadCommandSubtitle(props: { diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.badge.test.tsx index 6273f45b494e9..479d5fa9a9b7a 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.test.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.test.tsx @@ -1,6 +1,5 @@ -import * as DateTime from "effect/DateTime"; -import { v2ThreadShell } from "./notificationTestFixtures"; import { EnvironmentId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import { act } from "react"; import { create, type ReactTestRenderer } from "react-test-renderer"; @@ -65,17 +64,73 @@ const thread = { archivedAt: null as string | null, hasPendingApprovals: false, hasPendingUserInput: false, - session: null, + session: null as { status: string } | null, latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null }, }; let renderer: ReactTestRenderer | undefined; let focused = false; let visibility = "visible"; +const SHELL_NOW = DateTime.makeUnsafe("2026-09-13T07:00:00.000Z"); + +function toV2ThreadShell(input: typeof thread) { + const latestTurn = input.latestTurn; + return { + id: input.id, + projectId: "project", + title: input.title, + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + rootThreadId: input.id, + parentThreadId: null, + relationshipToParent: null, + }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + latestRunId: latestTurn.turnId, + activeRunId: null, + status: + latestTurn.state === "completed" + ? "completed" + : latestTurn.state === "error" || input.session?.status === "error" + ? "failed" + : "running", + pendingRuntimeRequest: input.hasPendingUserInput + ? { id: "request-1", kind: "user_input", createdAt: SHELL_NOW } + : input.hasPendingApprovals + ? { id: "request-1", kind: "command", createdAt: SHELL_NOW } + : null, + latestVisibleMessage: null, + latestUserMessageAt: null, + hasActionableProposedPlan: false, + itemCount: 0, + visibleItemCount: 0, + createdAt: SHELL_NOW, + updatedAt: SHELL_NOW, + latestRunRequestedAt: SHELL_NOW, + latestRunStartedAt: SHELL_NOW, + latestRunCompletedAt: latestTurn.completedAt + ? DateTime.makeUnsafe(latestTurn.completedAt) + : undefined, + archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; +} + function shell(overrides: Partial = {}) { return { status: "live", - snapshot: Option.some({ threads: [v2Shell({ ...thread, ...overrides })] }), + snapshot: Option.some({ threads: [toV2ThreadShell({ ...thread, ...overrides })] }), }; } function complete(environment = "one", completedAt = "2026-09-13T08:00:00Z") { @@ -262,35 +317,3 @@ it("badges background failures with in-app notifications enabled", async () => { expect(state.badge).toHaveBeenLastCalledWith(1); expect(state.toast).not.toHaveBeenCalled(); }); - -function v2Shell(input: { - id: string; - title: string; - archivedAt: string | null; - hasPendingApprovals: boolean; - hasPendingUserInput: boolean; - session: { status: string } | null; - latestTurn: { turnId: string; state: string; completedAt: string | null }; -}) { - return { - ...v2ThreadShell, - id: input.id, - title: input.title, - status: - input.session?.status === "error" || input.latestTurn.state === "error" - ? "failed" - : input.latestTurn.state === "completed" - ? "completed" - : "running", - latestRunId: input.latestTurn.turnId, - latestRunCompletedAt: input.latestTurn.completedAt - ? DateTime.makeUnsafe(input.latestTurn.completedAt) - : null, - archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null, - pendingRuntimeRequest: input.hasPendingApprovals - ? { kind: "tool_approval" } - : input.hasPendingUserInput - ? { kind: "user_input" } - : null, - }; -} diff --git a/apps/web/src/components/ThreadNotificationCoordinator.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.test.tsx index 3bcef7efc5061..98460c13fc8df 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.test.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.test.tsx @@ -1,6 +1,5 @@ -import * as DateTime from "effect/DateTime"; -import { v2ThreadShell } from "./notificationTestFixtures"; import type { ClientSettings } from "@t3tools/contracts/settings"; +import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import { act } from "react"; import { create, type ReactTestRenderer } from "react-test-renderer"; @@ -31,26 +30,62 @@ const state = vi.hoisted(() => ({ }), })); +const SHELL_NOW = DateTime.makeUnsafe("2026-09-13T09:00:00.000Z"); + +function mockThreadShell() { + return { + id: "thread-1", + projectId: "project-1", + title: "Fix the login form", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + rootThreadId: "thread-1", + parentThreadId: null, + relationshipToParent: null, + }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + latestRunId: "run-1", + activeRunId: null, + status: state.completedAt + ? "completed" + : state.sessionError || state.turnError + ? "failed" + : "running", + pendingRuntimeRequest: state.input + ? { id: "request-1", kind: "user_input", createdAt: SHELL_NOW } + : state.approval + ? { id: "request-1", kind: "command", createdAt: SHELL_NOW } + : null, + latestVisibleMessage: null, + latestUserMessageAt: null, + hasActionableProposedPlan: false, + itemCount: 0, + visibleItemCount: 0, + createdAt: SHELL_NOW, + updatedAt: SHELL_NOW, + latestRunRequestedAt: SHELL_NOW, + latestRunStartedAt: SHELL_NOW, + latestRunCompletedAt: state.completedAt ? DateTime.makeUnsafe(state.completedAt) : undefined, + archivedAt: state.archivedAt ? DateTime.makeUnsafe(state.archivedAt) : null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; +} + vi.mock("@effect/atom-react", () => ({ useAtomValue: () => ({ status: state.live ? "live" : "disconnected", - snapshot: Option.some({ - threads: [ - v2Shell({ - id: "thread-1", - title: "Fix the login form", - archivedAt: state.archivedAt, - hasPendingUserInput: state.input, - hasPendingApprovals: state.approval, - session: state.sessionError ? { status: "error" } : null, - latestTurn: { - turnId: "turn-1", - state: state.turnError ? "error" : state.completedAt ? "completed" : "running", - completedAt: state.completedAt, - }, - }), - ], - }), + snapshot: Option.some({ threads: [mockThreadShell()] }), }), })); vi.mock("@tanstack/react-router", () => ({ @@ -254,35 +289,3 @@ describe("thread notifications", () => { }); }); }); - -function v2Shell(input: { - id: string; - title: string; - archivedAt: string | null; - hasPendingApprovals: boolean; - hasPendingUserInput: boolean; - session: { status: string } | null; - latestTurn: { turnId: string; state: string; completedAt: string | null }; -}) { - return { - ...v2ThreadShell, - id: input.id, - title: input.title, - status: - input.session?.status === "error" || input.latestTurn.state === "error" - ? "failed" - : input.latestTurn.state === "completed" - ? "completed" - : "running", - latestRunId: input.latestTurn.turnId, - latestRunCompletedAt: input.latestTurn.completedAt - ? DateTime.makeUnsafe(input.latestTurn.completedAt) - : null, - archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null, - pendingRuntimeRequest: input.hasPendingApprovals - ? { kind: "tool_approval" } - : input.hasPendingUserInput - ? { kind: "user_input" } - : null, - }; -} diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 0862162c26d10..fe1350389150f 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -1,4 +1,4 @@ -import { presentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { presentThreadShell } from "@t3tools/client-runtime/state/models"; import { useAtomValue } from "@effect/atom-react"; import { useNavigate, useParams } from "@tanstack/react-router"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; diff --git a/apps/web/src/components/ThreadStatusIndicators.subscriptions.test.tsx b/apps/web/src/components/ThreadStatusIndicators.subscriptions.test.tsx index b36c9615b1721..2628125363acc 100644 --- a/apps/web/src/components/ThreadStatusIndicators.subscriptions.test.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.subscriptions.test.tsx @@ -8,7 +8,7 @@ import { makeThreadFixture } from "../test-fixtures"; const state = vi.hoisted(() => ({ queries: [] as string[] })); -vi.mock("../state/entities", () => ({ useProject: () => null })); +vi.mock("../state/entities", () => ({ useProject: () => null, useServerConfigs: () => new Map() })); vi.mock("../uiStateStore", () => ({ useUiStateStore: () => undefined })); vi.mock("../state/vcs", async () => { const { AsyncResult, Atom } = await import("effect/unstable/reactivity"); diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 336a34d724ac0..e46cd0f31f361 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -4,12 +4,7 @@ import { scopeThreadRef, } from "@t3tools/client-runtime/environment"; import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; -import { - resolveThreadCurrentPullRequestLink, - resolveThreadPullRequestChains, - visibleThreadPullRequests, - type ThreadPullRequestBadge, -} from "@t3tools/shared/threadPullRequests"; + import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests"; import { resolveEnvironmentMachineKind, @@ -19,12 +14,24 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; -import { FolderGit2Icon, GitPullRequestArrowIcon, LayersIcon, TerminalIcon } from "lucide-react"; -import { useCallback, useMemo, type MouseEvent } from "react"; +import { FolderGit2Icon, TerminalIcon } from "lucide-react"; +import { useCallback, useMemo } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { useProject } from "../state/entities"; +import { + resolveThreadCurrentPullRequestLink, + resolveThreadPullRequestChains, + visibleThreadPullRequests, + type ThreadPullRequestBadge, +} from "@t3tools/shared/threadPullRequests"; +import { GitPullRequestArrowIcon, LayersIcon } from "lucide-react"; +import { type MouseEvent } from "react"; +import { buttonVariants, InlineButton } from "./ui/button"; +import { cn } from "../lib/utils"; + +import { parseChangeRequestUrl } from "../lib/openPullRequestLink"; import { useEnvironmentQuery } from "../state/query"; import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests"; import { useThreadRunningTerminalIds } from "../state/terminalSessions"; @@ -39,12 +46,10 @@ import { useSidebarRowSubscriptionLease, } from "./Sidebar.logic"; import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation"; + import type { SidebarThreadSummary } from "../types"; import { formatWorktreePathForDisplay } from "../worktreeCleanup"; -import { cn } from "../lib/utils"; -import { parseChangeRequestUrl } from "../lib/openPullRequestLink"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { buttonVariants, InlineButton } from "./ui/button"; import { pullRequestListLines } from "./pullRequest/pullRequestListLines"; export interface PrStatusIndicator { @@ -69,6 +74,7 @@ export interface LinkedThreadPullRequestStatus { readonly sourceControlProvider: NonNullable; } +/** Linked badges use persisted snapshots; only branch and legacy fallbacks lease summary reads. */ export function useLinkedThreadPullRequest( environmentId: EnvironmentId | null, linkedPullRequest: ThreadLinkedPullRequest | null | undefined, @@ -133,7 +139,10 @@ export function linkedPullRequestSnapshotStatus( }; } -export { resolveThreadPullRequestBadge } from "@t3tools/shared/threadPullRequests"; +export { + resolveThreadPullRequestBadge, + type ThreadPullRequestBadge, +} from "@t3tools/shared/threadPullRequests"; /** The glyph a row's badge wears: the layers icon for a stack, the pull-request one otherwise. */ function ThreadPullRequestBadgeIcon({ @@ -834,6 +843,7 @@ export function ThreadRowLeadingStatus({ lastVisitedAt, }, }); + const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId); const pendingLink = pr === null && supportsMultiplePullRequests diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 90b144149331b..8c32ae8335437 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,20 +1,21 @@ import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; -import { runtimeModeConfig, runtimeModeOptions } from "./runtimeModeConfig"; +import { runtimeModeConfig, runtimeModeOptions as runtimeModes } from "./runtimeModeConfig"; import { useRightPanelStore } from "~/rightPanelStore"; import { AttachmentFilePreview } from "../files/AttachmentFilePreview"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches"; import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste"; import { elementContextToPreviewAnnotation } from "../../lib/elementContext"; - +import { RefreshIcon } from "~/components/ui/refresh-icon"; import { questionAttachmentDraftId, countQuestionAttachments, useQuestionAttachmentPreparation, changeQuestionAttachmentPreparation, } from "../../questionAttachments"; - import type { + ApprovalRequestId, + KeybindingCommand, AssistantCitation, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -49,6 +50,7 @@ import { } from "@t3tools/client-runtime/text-paste"; import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; +import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; import { Fragment, memo, @@ -63,7 +65,7 @@ import { useState, useSyncExternalStore, } from "react"; -import { createPortal } from "react-dom"; +import { createPortal, flushSync } from "react-dom"; import { clampCollapsedComposerCursor, type ComposerTrigger, @@ -117,6 +119,7 @@ import { ComposerStashBadge } from "./ComposerStashBadge"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerMenuState } from "./useComposerMenuState"; import { useComposerFocusState } from "./useComposerFocusState"; +import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { ComposerTasksBadge, ComposerTasksContent, @@ -249,6 +252,7 @@ import { ProviderModelPicker } from "./ProviderModelPicker"; import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommandMenu"; import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu"; +import { ComposerImageThumbnail } from "./ComposerImageThumbnail"; import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; @@ -313,10 +317,10 @@ import { pendingDraftWork } from "./pendingDraftWork"; import { createComposerScrollGestureState, recordComposerScrollGestureEvent, + shouldCollapseComposerForScrollKey, resetComposerScrollGesture, suppressActiveComposerScrollGesture, } from "./composerScrollGesture"; -import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame"; function ComposerVideoThumbnail({ file }: { file: File }) { @@ -411,13 +415,23 @@ function useComposerRestingTransition( const previousCollapsedRef = useRef(isCollapsed); const previousRestingRef = useRef(isResting); const previousHeightRef = useRef(null); + const previousModelStripHeightRef = useRef(null); const previousContentOffsetsRef = useRef<{ promptFromTop: number | null; promptHeight: number | null; actionFromBottom: number | null; - }>({ promptFromTop: null, promptHeight: null, actionFromBottom: null }); + controlsFromBottom: number | null; + controlsFromLeft: number | null; + surfaceBottomInset: number | null; + }>({ + promptFromTop: null, + promptHeight: null, + actionFromBottom: null, + controlsFromBottom: null, + controlsFromLeft: null, + surfaceBottomInset: null, + }); const animationRef = useRef(null); - const animationTargetHeightRef = useRef(null); const contentAnimationsRef = useRef([]); const stateChangeAnimationsRef = useRef([]); const pinnedOverlayRef = useRef(null); @@ -441,6 +455,8 @@ function useComposerRestingTransition( const element = elementRef.current; const footer = element?.querySelector('[data-chat-composer-footer="true"]'); element?.style.removeProperty("overflow"); + element?.style.removeProperty("clip-path"); + element?.style.removeProperty("overflow-clip-margin"); element ?.querySelector('[data-chat-composer-surface="true"]') ?.style.removeProperty("height"); @@ -450,6 +466,22 @@ function useComposerRestingTransition( footer?.style.removeProperty("left"); footer?.style.removeProperty("right"); footer?.style.removeProperty("height"); + const shell = element?.closest('[data-slot="composer-shell"]'); + shell?.removeAttribute("data-model-strip-transition"); + const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); + for (const property of [ + "position", + "top", + "visibility", + "height", + "min-height", + "padding-top", + "align-items", + "z-index", + "pointer-events", + ]) { + modelStrip?.style.removeProperty(property); + } clearOverlayPin(); }, [clearOverlayPin]); @@ -468,10 +500,21 @@ function useComposerRestingTransition( (candidate) => candidate.getClientRects().length > 0, ) ?? null; const prompt = visibleTransitionElement( - '[data-testid="composer-editor"], [data-chat-composer-transition-prompt="true"]', + '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', ); const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]'); const footer = element.querySelector('[data-chat-composer-footer="true"]'); + const continuousControls = + element.dataset.inlineRestingControls === "true" || + element.dataset.modelOnlyStrip === "true"; + const controls = nextIsCollapsed + ? restingControlsRef.current + : element.querySelector('[data-chat-composer-controls="left"]'); + + const shell = element.closest('[data-slot="composer-shell"]'); + const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); + const interruptedStripHeight = + animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null; const interruptedAnimation = animationRef.current; const interruptedPromptTop = interruptedAnimation ? (prompt?.getBoundingClientRect().top ?? null) @@ -479,10 +522,15 @@ function useComposerRestingTransition( const interruptedActionTop = interruptedAnimation ? (action?.getBoundingClientRect().top ?? null) : null; + const interruptedControlsLeft = interruptedAnimation + ? (controls?.getBoundingClientRect().left ?? null) + : null; + const interruptedControlsTop = interruptedAnimation + ? (controls?.getBoundingClientRect().top ?? null) + : null; const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null; - const interruptedTargetHeight = animationTargetHeightRef.current; const interruptedCurrentTime = typeof interruptedAnimation?.currentTime === "number" ? interruptedAnimation.currentTime @@ -508,21 +556,24 @@ function useComposerRestingTransition( const nextRect = element.getBoundingClientRect(); const nextHeight = nextRect.height; + const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null; // The chat view resize-observes the overlay to place the timeline // inset, the scroll-to-end pill, and the mini player. Publishing the // destination height here turns that feedback into one update instead // of a ChatView re-render on every animation frame. const overlay = element.closest('[data-chat-composer-overlay="true"]'); - const overlayHeight = overlay?.getBoundingClientRect().height ?? null; + const overlayRect = overlay?.getBoundingClientRect(); + const overlayHeight = overlayRect?.height ?? null; if (overlayHeight !== null) { onOverlayHeightChange(overlayHeight); } const nextPromptRect = prompt?.getBoundingClientRect() ?? null; const nextPromptTop = nextPromptRect?.top ?? null; const nextActionTop = action?.getBoundingClientRect().top ?? null; + const nextControlsRect = controls?.getBoundingClientRect() ?? null; + const nextControlsTop = nextControlsRect?.top ?? null; + const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1; const previousHeight = interruptedHeight ?? previousHeightRef.current; - const targetChanged = - interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5; const prefersReducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches; const shouldAnimate = shouldAnimateComposerRestingTransition({ hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current, @@ -541,10 +592,19 @@ function useComposerRestingTransition( ? Math.max(1, interruptedDuration - interruptedCurrentTime) : COMPOSER_RESTING_TRANSITION_DURATION_MS; const duration = - interruptedHeight !== null && !targetChanged + interruptedHeight !== null && !stateChanged ? remainingDuration : COMPOSER_RESTING_TRANSITION_DURATION_MS; element.style.overflow = "clip"; + if (modelStrip) { + // The model controls cross the input's lower edge on their way to the strip. + const controlsClearance = Math.max( + nextModelStripHeight ?? 0, + previousModelStripHeightRef.current ?? 0, + ); + element.style.overflowClipMargin = `${controlsClearance}px`; + element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`; + } surface.style.height = "100%"; // Pinning the overlay at the destination height keeps the resize @@ -567,7 +627,7 @@ function useComposerRestingTransition( if (footer) { footer.style.position = "absolute"; footer.style.top = "auto"; - footer.style.bottom = "1px"; + footer.style.bottom = `${String(footerBottom)}px`; footer.style.height = "3rem"; if (nextIsCollapsed) { footer.style.left = "auto"; @@ -578,38 +638,73 @@ function useComposerRestingTransition( } } + let stripAnimation: Animation | null = null; + if (modelStrip) { + const stripHeight = modelStrip.getBoundingClientRect().height; + const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop); + const fromHeight = + interruptedStripHeight ?? + (previousCollapsedRef.current + ? (previousModelStripHeightRef.current ?? stripHeight) + : stripOverlap); + const toHeight = nextIsCollapsed ? stripHeight : stripOverlap; + modelStrip.style.position = "relative"; + modelStrip.style.top = "auto"; + modelStrip.style.visibility = "visible"; + modelStrip.style.minHeight = "0"; + // Padding must not impose a 24px minimum on the 16px overlap endpoint. + // Keep the controls bottom-aligned while the strip retracts behind the input. + modelStrip.style.paddingTop = "0"; + modelStrip.style.alignItems = "flex-end"; + modelStrip.style.pointerEvents = "none"; + modelStrip.style.zIndex = "20"; + shell?.setAttribute("data-model-strip-transition", "true"); + stripAnimation = modelStrip.animate( + [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }], + { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" }, + ); + } + const animation = element.animate( [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }], { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, + fill: "both", }, ); animationRef.current = animation; - animationTargetHeightRef.current = nextHeight; const animatedRect = element.getBoundingClientRect(); + const previousBottom = + overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null + ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset + : animatedRect.bottom; + const bottomShift = previousBottom - animatedRect.bottom; const previousPromptTop = interruptedPromptTop ?? (previousContentOffsetsRef.current.promptFromTop === null ? null - : animatedRect.top + previousContentOffsetsRef.current.promptFromTop); + : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop); const previousActionTop = interruptedActionTop ?? (previousContentOffsetsRef.current.actionFromBottom === null ? null - : animatedRect.bottom - previousContentOffsetsRef.current.actionFromBottom); - const contentAnimations: Animation[] = []; + : previousBottom - previousContentOffsetsRef.current.actionFromBottom); + const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : []; const animateContentPosition = ( content: HTMLElement | null, previousTop: number | null, + previousLeft: number | null = null, ) => { if (!content || previousTop === null) return; - const offset = previousTop - content.getBoundingClientRect().top; - if (Math.abs(offset) < 0.5) return; + const rect = content.getBoundingClientRect(); + const offset = previousTop - rect.top; + const offsetX = previousLeft === null ? 0 : previousLeft - rect.left; + if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return; contentAnimations.push( content.animate( - [{ transform: `translateY(${String(offset)}px)` }, { transform: "none" }], + [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }], { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, @@ -619,6 +714,19 @@ function useComposerRestingTransition( }; animateContentPosition(prompt, previousPromptTop); animateContentPosition(action, previousActionTop); + if (continuousControls) { + const previousControlsTop = + interruptedControlsTop ?? + (previousContentOffsetsRef.current.controlsFromBottom === null + ? null + : previousBottom - previousContentOffsetsRef.current.controlsFromBottom); + const previousControlsLeft = + interruptedControlsLeft ?? + (previousContentOffsetsRef.current.controlsFromLeft === null + ? null + : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft); + animateContentPosition(controls, previousControlsTop, previousControlsLeft); + } contentAnimationsRef.current = contentAnimations; if (stateChanged) { @@ -662,7 +770,7 @@ function useComposerRestingTransition( const arrivingControls = nextIsCollapsed ? restingControlsRef.current : element.querySelector('[data-chat-composer-controls="left"]'); - if (arrivingControls) { + if (arrivingControls && !continuousControls) { const drift = nextIsCollapsed ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX; @@ -718,9 +826,10 @@ function useComposerRestingTransition( } } animationRef.current = null; - animationTargetHeightRef.current = null; contentAnimationsRef.current = []; stateChangeAnimationsRef.current = []; + animation.cancel(); + stripAnimation?.cancel(); clearTransitionStyles(); }; void animation.finished.catch(() => undefined).then(() => finishTransition(false)); @@ -732,15 +841,18 @@ function useComposerRestingTransition( duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS, ); } else { - animationTargetHeightRef.current = null; } previousCollapsedRef.current = nextIsCollapsed; previousHeightRef.current = nextHeight; + previousModelStripHeightRef.current = nextModelStripHeight; previousContentOffsetsRef.current = { promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top, promptHeight: nextPromptRect?.height ?? null, actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop, + controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop, + controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left, + surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null, }; }, [clearTransitionStyles, onOverlayHeightChange, restingControlsRef], @@ -794,22 +906,34 @@ function useComposerRestingTransition( (candidate) => candidate.getClientRects().length > 0, ) ?? null; const promptRect = visibleTransitionElement( - '[data-testid="composer-editor"], [data-chat-composer-transition-prompt="true"]', + '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', )?.getBoundingClientRect(); const actionTop = visibleTransitionElement( '[data-chat-composer-transition-actions="true"]', )?.getBoundingClientRect().top; + const controlsRect = ( + isCollapsedRef.current + ? restingControlsRef.current + : visibleTransitionElement('[data-chat-composer-controls="left"]') + )?.getBoundingClientRect(); previousHeightRef.current = elementRect.height; previousContentOffsetsRef.current = { promptFromTop: promptRect === undefined ? null : promptRect.top - elementRect.top, promptHeight: promptRect?.height ?? null, actionFromBottom: actionTop === undefined ? null : elementRect.bottom - actionTop, + controlsFromBottom: + controlsRect === undefined ? null : elementRect.bottom - controlsRect.top, + controlsFromLeft: controlsRect === undefined ? null : controlsRect.left - elementRect.left, + surfaceBottomInset: + (element + .closest('[data-chat-composer-overlay="true"]') + ?.getBoundingClientRect().bottom ?? elementRect.bottom) - elementRect.bottom, }; }); observer.observe(element); if (body) observer.observe(body); return () => observer.disconnect(); - }, [transitionToCurrentGeometry]); + }, [restingControlsRef, transitionToCurrentGeometry]); useEffect(() => { // Host discovery and width measurement settle through layout updates on @@ -823,7 +947,6 @@ function useComposerRestingTransition( } animationRef.current?.cancel(); animationRef.current = null; - animationTargetHeightRef.current = null; for (const animation of contentAnimationsRef.current) animation.cancel(); contentAnimationsRef.current = []; for (const animation of stateChangeAnimationsRef.current) animation.cancel(); @@ -928,13 +1051,12 @@ import { Select, SelectItem, SelectPopup, SelectValue } from "../ui/select"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { toastManager } from "../ui/toast"; import { + FileIcon, BotIcon, CircleAlertIcon, - FileIcon, PaperclipIcon, PencilRulerIcon, PlayIcon, - RotateCcwIcon, XIcon, } from "lucide-react"; import { proposedPlanTitle } from "../../proposedPlan"; @@ -953,6 +1075,7 @@ import { type ChatMessage, type SessionPhase, type Thread, + type ThreadShell, videoMimeType, } from "../../types"; import { @@ -1038,10 +1161,17 @@ function useRestingComposerControlsLayout(host: HTMLDivElement | null) { return { controlsRef, hiddenBlockCount: layout.hiddenCount, controlsVisible: layout.visible }; } +type RuntimeModeOption = { mode: RuntimeMode } & (typeof runtimeModeConfig)[RuntimeMode]; +const runtimeModeOptions = runtimeModes.map((mode) => ({ mode, ...runtimeModeConfig[mode] })); +const supervisedRuntimeModeOption = { + mode: "approval-required" as const, + ...runtimeModeConfig["approval-required"], +}; const ComposerFooterModeControls = memo(function ComposerFooterModeControls(props: { showInteractionModeToggle: boolean; interactionMode: ProviderInteractionMode; runtimeMode: RuntimeMode; + runtimeModeOptions: ReadonlyArray; size?: "sm" | "xs"; hidden?: boolean; onToggleInteractionMode: () => void; @@ -1049,7 +1179,9 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop }) { const size = props.size ?? "sm"; const [open, setOpen] = useComposerMenuState(props.hidden); - const runtimeModeOption = runtimeModeConfig[props.runtimeMode]; + const runtimeModeOption = + props.runtimeModeOptions.find((option) => option.mode === props.runtimeMode) ?? + supervisedRuntimeModeOption; const RuntimeModeIcon = runtimeModeOption.icon; const interactionModeTooltip = props.interactionMode === "plan" @@ -1114,6 +1246,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop {runtimeModeOption.label} - {runtimeModeOptions.map((mode) => { - const option = runtimeModeConfig[mode]; + {props.runtimeModeOptions.map((option) => { const OptionIcon = option.icon; return ( - +
    @@ -1229,6 +1366,7 @@ export interface ChatComposerHandle { focusAt: (cursor: number) => void; /** Expand the desktop composer at the timeline end without taking focus. */ restoreAfterTimelineReachedEnd: () => void; + collapseForTimelineScrollKey: (key: string) => void; addDroppedFiles: (files: File[]) => void; hasPendingAttachments: () => boolean; insertTextAtEnd: ( @@ -1243,6 +1381,7 @@ export interface ChatComposerHandle { ) => boolean; openModelPicker: () => void; toggleModelPicker: () => void; + openControl: (command: KeybindingCommand) => void; isModelPickerOpen: () => boolean; compactContext: () => void; readSnapshot: () => { @@ -1286,7 +1425,6 @@ export interface ChatComposerHandle { // -------------------------------------------------------------------------- export interface ChatComposerProps { - promptHistoryMessages: readonly ChatMessage[]; composerDraftTarget: ScopedThreadRef | DraftId; environmentId: EnvironmentId; attachmentUploadsCapabilityKnown: boolean; @@ -1301,7 +1439,10 @@ export interface ChatComposerProps { activeThreadId: ThreadId | null; activeThreadEnvironmentId: EnvironmentId | undefined; activeThread: Thread | undefined; - + /** The routed server thread's shell, present before its detail loads. */ + activeThreadShell: ThreadShell | null; + /** Timeline messages including optimistic sends, for ArrowUp prompt recall. */ + promptHistoryMessages: ReadonlyArray; isServerThread: boolean; isLocalDraftThread: boolean; forceExpandedOnMobile: boolean; @@ -1315,6 +1456,8 @@ export interface ChatComposerProps { sendDisabledReason: string | null; isPreparingWorktree: boolean; bannerItems: readonly ComposerBannerStackItem[]; + /** Picking /usage-limits from the menu is the action itself; the draft keeps nothing of it. */ + onUsageLimitsCommand?: (() => void) | undefined; environmentUnavailable: { readonly label: string; readonly connection: EnvironmentConnectionPresentation; @@ -1360,7 +1503,6 @@ export interface ChatComposerProps { activeProjectDefaultModelSelection: ModelSelection | null | undefined; activeThreadModelSelection: ModelSelection | null | undefined; codexRealtimeVoice: CodexRealtimeVoiceController; - timelineOverflows: boolean; // Context window activeContextWindow: ContextWindowSnapshot | null; @@ -1381,6 +1523,8 @@ export interface ChatComposerProps { onRestingControlsVisibilityChange: (visible: boolean) => void; getTimelineScrollableNode: () => HTMLElement | null; isTimelineAtLogicalEnd: () => boolean; + /** Whether the timeline has more content than fits above the composer. */ + timelineOverflows: boolean; onComposerOverlayHeightChange: (height: number) => void; /** * Whether the desktop resting layout is active. Reported from a layout @@ -1449,8 +1593,6 @@ export interface ChatComposerProps { // -------------------------------------------------------------------------- export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) { - const { promptHistoryMessages } = props; - const promptHistoryPositionRef = useRef(null); const { composerDraftTarget, environmentId, @@ -1464,6 +1606,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeThreadId, activeThreadEnvironmentId: _activeThreadEnvironmentId, activeThread, + promptHistoryMessages, isServerThread: _isServerThread, isLocalDraftThread: _isLocalDraftThread, forceExpandedOnMobile, @@ -1494,7 +1637,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeProjectDefaultModelSelection, activeThreadModelSelection, codexRealtimeVoice, - timelineOverflows, activeContextWindow, compactThreadUnavailable, compactDisabled, @@ -1511,6 +1653,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onRestingControlsVisibilityChange, getTimelineScrollableNode, isTimelineAtLogicalEnd, + timelineOverflows, onComposerOverlayHeightChange, onRestingChange, promptRef, @@ -1545,23 +1688,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) editingQueuedAttachments, onRemoveEditingQueuedAttachment, } = props; - const composerVimDisplayRef = useRef({ - mode: "NORMAL", - pending: "", - }); - const composerVimModeIndicatorRef = useRef(null); - const updateComposerVimDisplay = useCallback((display: ComposerVimModeDisplay) => { - composerVimDisplayRef.current = display; - const indicator = composerVimModeIndicatorRef.current; - if (indicator) - indicator.textContent = display.pending ? `${display.mode} ${display.pending}` : display.mode; - }, []); - const setComposerVimModeIndicator = useCallback((indicator: HTMLSpanElement | null) => { - composerVimModeIndicatorRef.current = indicator; - if (!indicator) return; - const display = composerVimDisplayRef.current; - indicator.textContent = display.pending ? `${display.mode} ${display.pending}` : display.mode; - }, []); const activeTasksProgress = props.threadSyncPhase === null ? props.activeTasksProgress : null; const activeTaskSteps = props.threadSyncPhase === null ? props.activeTaskSteps : null; // Non-null while a queued message is loaded for editing. The primary action @@ -1900,6 +2026,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // disabled. const selectedProvider: ProviderDriverKind = selectedProviderEntry?.driverKind ?? requestedDriverKind; + const supportedRuntimeModes = selectedProviderEntry?.snapshot.supportedRuntimeModes; + const compatibleRuntimeModeOptions = + supportedRuntimeModes && supportedRuntimeModes.length > 0 + ? runtimeModeOptions.filter((option) => supportedRuntimeModes.includes(option.mode)) + : runtimeModeOptions; + // Older threads can contain a mode their current provider no longer offers. + // Display the provider's first supported mode, which is also its safe legacy + // fallback, without mutating persisted state until the user makes a choice. + const compatibleRuntimeMode = compatibleRuntimeModeOptions.some( + (option) => option.mode === runtimeMode, + ) + ? runtimeMode + : (compatibleRuntimeModeOptions[0]?.mode ?? runtimeMode); const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({ threadRef: composerDraftTarget, @@ -1924,6 +2063,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) () => selectedProviderEntry?.snapshot ?? null, [selectedProviderEntry], ); + const codexRealtimeVoiceVersionSupported = supportsCodexRealtimeVoiceVersion( + selectedProviderStatus?.version ?? null, + ); const compactCommandAvailable = providerSupportsManualCompaction(selectedProviderEntry); const selectedProviderSkills = selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd) @@ -1985,9 +2127,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } }, retryLater); }, [environmentId, gitCwd, prompt, refreshProviders, selectedProviderEntry]); - const codexRealtimeVoiceVersionSupported = supportsCodexRealtimeVoiceVersion( - selectedProviderStatus?.version ?? null, - ); const selectedProviderModels = useMemo>( () => selectedProviderEntry?.models ?? [], [selectedProviderEntry], @@ -2061,6 +2200,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Context window // ------------------------------------------------------------------ + const activeThreadModelDisplayName = useMemo( () => resolveContextWindowModelDisplayName(activeThreadModelSelection, modelOptionsByInstance), [activeThreadModelSelection, modelOptionsByInstance], @@ -2068,7 +2208,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const reserveContextWindowMeter = shouldReserveContextWindowMeter({ meterEnabled: settings.contextWindowMeterEnabled, detailLoading: props.threadSyncPhase === "loading", - threadStarted: threadShellHasStarted(props.activeThread), + threadStarted: threadShellHasStarted(props.activeThreadShell), providerReportsContextWindow: selectedProviderStatus ? selectedProviderStatus.reportsContextWindow === true : null, @@ -2084,6 +2224,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) detectComposerTrigger(prompt, prompt.length), ); const [composerHighlightedItemId, setComposerHighlightedItemId] = useState(null); + // Active ArrowUp recall. Cleared on edit and on thread switch. + const promptHistoryPositionRef = useRef(null); const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState( null, ); @@ -2121,6 +2263,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // Refs // ------------------------------------------------------------------ const composerEditorRef = useRef(null); + const composerVimDisplayRef = useRef({ mode: "NORMAL", pending: "" }); + const composerVimModeIndicatorRef = useRef(null); + const updateComposerVimDisplay = useCallback((display: ComposerVimModeDisplay) => { + composerVimDisplayRef.current = display; + const indicator = composerVimModeIndicatorRef.current; + if (indicator) + indicator.textContent = display.pending ? `${display.mode} ${display.pending}` : display.mode; + }, []); + const setComposerVimModeIndicator = useCallback((indicator: HTMLSpanElement | null) => { + composerVimModeIndicatorRef.current = indicator; + if (!indicator) return; + const display = composerVimDisplayRef.current; + indicator.textContent = display.pending ? `${display.mode} ${display.pending}` : display.mode; + }, []); const pasteAsTextShortcutUntilRef = useRef(0); const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set }>({ targetKey: "", @@ -2139,8 +2295,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const mobileComposerExpandFrameRef = useRef(null); const mobileComposerExpandReleaseFrameRef = useRef(null); const mobileComposerExpandInFlightRef = useRef(false); - const desktopOutsidePointerInFlightRef = useRef(false); - const desktopOutsidePointerReleaseTimeoutRef = useRef(null); const composerScrollCollapseTimeoutRef = useRef(null); const composerScrollCollapseEligibleRef = useRef(false); const windowRefocusInFlightRef = useRef(false); @@ -2630,11 +2784,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComposerOwned: true, } satisfies Parameters[0]; const providerTraitsPicker = renderProviderTraitsPicker(providerTraitsPickerInput); + const [inlineRestingControlsHost, setInlineRestingControlsHost] = useState( + null, + ); const { controlsRef: restingComposerControlsRef, hiddenBlockCount: restingControlsHiddenBlockCount, controlsVisible: restingControlsVisible, - } = useRestingComposerControlsLayout(restingControlsHost); + } = useRestingComposerControlsLayout(restingControlsHost ?? inlineRestingControlsHost); const pendingPrimaryAction = useMemo( () => activePendingProgress @@ -3552,6 +3709,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; }, [readComposerSnapshot]); + const { onUsageLimitsCommand } = props; const onSelectComposerItem = useCallback( (item: ComposerCommandItem) => { if (composerSelectLockRef.current) return; @@ -3602,6 +3760,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return; } if (item.type === "provider-slash-command") { + if (item.command.name === USAGE_LIMITS_COMMAND.name && onUsageLimitsCommand) { + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + focusEditorAfterReplace: false, + }); + if (applied) { + setComposerHighlightedItemId(null); + onUsageLimitsCommand(); + } + return; + } const replacement = `/${item.command.name} `; const replacementRangeEnd = extendReplacementRangeForTrailingSpace( snapshot.value, @@ -3674,6 +3843,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) composerDraftTarget, handleInteractionModeChange, planModeUiEnabled, + onUsageLimitsCommand, resolveActiveComposerTrigger, ], ); @@ -4681,13 +4851,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const expandedComposerImages = isComposerResting ? standaloneComposerImages.filter((image) => pendingSnapShotIdSet.has(image.id)) : standaloneComposerImages; - // The relocated controls live in the context strip whenever the composer is - // collapsed for any reason, the desktop resting layout or the phone - // collapse. Both leave the footer unrendered, so the strip is the only place - // to see or change the model without expanding the composer. - const composerControlsInStrip = isComposerResting || isComposerCollapsedMobile; - const composerControlsVisibleInStrip = composerControlsInStrip && restingControlsVisible; - const composerControlsHidden = composerControlsInStrip && !restingControlsVisible; + // Keep collapsed controls inside the input when workspace context is hidden. + const composerControlsCollapsed = isComposerResting || isComposerCollapsedMobile; + const showInlineRestingControls = composerControlsCollapsed && restingControlsHost === null; + const composerControlsVisibleInStrip = + composerControlsCollapsed && restingControlsHost !== null && restingControlsVisible; + const composerControlsHidden = composerControlsCollapsed && !restingControlsVisible; if (composerControlsHidden && isComposerModelPickerOpen) { setIsComposerModelPickerOpen(false); } @@ -4723,9 +4892,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }} > {image.previewUrl ? ( - + + } + /> ) : ( - + )} ))} @@ -4751,7 +4937,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
    ) : null; const composerMainSurfaceRef = useComposerRestingTransition( - composerControlsInStrip, + composerControlsCollapsed, isComposerResting, restingComposerControlsRef, onComposerOverlayHeightChange, @@ -4761,11 +4947,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const canScrollCollapseComposer = canTrackComposerScrollGesture && settings.composerCollapseOnScroll && + !hasMultilinePrompt && !composerHasExpandedChrome && !showInlineTasksBadge; - // Scrolling only has something to collapse while the composer is expanded. - // With blur collapse off that includes an unfocused composer, so the wheel - // handler keys off this rather than editor focus. + // Scrolling only has something to collapse while the composer is expanded, + // focused or not, so the wheel handler keys off the resting state rather + // than editor focus. composerScrollCollapseEligibleRef.current = canScrollCollapseComposer && !isComposerResting; useEffect(() => { @@ -4864,8 +5051,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setIsComposerScrollCollapsed, ]); - const restingHiddenBlockCount = composerControlsInStrip ? restingControlsHiddenBlockCount : 0; - const composerControlsCompact = !composerControlsInStrip && isComposerFooterCompact; + const restingHiddenBlockCount = composerControlsCollapsed ? restingControlsHiddenBlockCount : 0; + const composerControlsCompact = !composerControlsCollapsed && isComposerFooterCompact; const restingProviderTraitsPicker = renderProviderTraitsPicker({ ...providerTraitsPickerInput, size: "xs", @@ -4878,8 +5065,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) id: "traits", content: ( <> - - {composerControlsInStrip ? restingProviderTraitsPicker : providerTraitsPicker} + + {composerControlsCollapsed ? restingProviderTraitsPicker : providerTraitsPicker} ), }, @@ -4891,8 +5078,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
    ); })} - {composerControlsInStrip ? ( + {composerControlsCollapsed ? (
    diff --git a/apps/web/src/components/chat/ChatHeader.test.ts b/apps/web/src/components/chat/ChatHeader.test.ts new file mode 100644 index 0000000000000..71d8b1a891ecd --- /dev/null +++ b/apps/web/src/components/chat/ChatHeader.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vite-plus/test"; +import { resolveRenameCommit } from "./ChatHeader"; + +describe("resolveRenameCommit", () => { + it("commits a trimmed changed title", () => { + expect(resolveRenameCommit({ title: " New title ", originalTitle: "Old" })).toEqual({ + action: "commit", + title: "New title", + }); + }); + + it("rejects empty and whitespace-only titles", () => { + expect(resolveRenameCommit({ title: " ", originalTitle: "Old" })).toEqual({ + action: "reject-empty", + }); + }); + + it("no-ops when the trimmed title is unchanged", () => { + expect(resolveRenameCommit({ title: " Old ", originalTitle: "Old" })).toEqual({ + action: "noop", + }); + }); +}); diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 65d3ac6ce068c..4a62c393d7dbd 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -1,111 +1,332 @@ -import { type EnvironmentId } from "@t3tools/contracts"; -import { memo } from "react"; - +import { type EnvironmentId, type ThreadId } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { ChevronDownIcon } from "lucide-react"; +import { + memo, + useCallback, + useEffect, + useMemo, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, + type MouseEvent as ReactMouseEvent, +} from "react"; +import { isTrailingDoubleClick } from "../Sidebar.logic"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { toastManager } from "../ui/toast"; +import { useThreadActionMenu } from "~/hooks/useThreadActionMenu"; import { readLocalApi } from "~/localApi"; - -import { cn } from "~/lib/utils"; +import { threadEnvironment } from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; import { ProjectFavicon } from "../ProjectFavicon"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + WorkspaceBreadcrumb, + WorkspaceBreadcrumbItem, + WorkspaceBreadcrumbSeparator, +} from "../WorkspaceBreadcrumb"; +import { cn } from "~/lib/utils"; interface ChatHeaderProps { activeThreadEnvironmentId: EnvironmentId; + activeThreadId: ThreadId; activeThreadTitle: string; - activeProjectName: string | undefined; - activeProjectCwd: string | null; - activeProjectFaviconPath: string | null; - activeProjectIcon: import("@t3tools/contracts").ProjectIconOverride | null; - + /** Drafts have no server thread yet, so the title carries no action menu. */ + isServerThread: boolean; + activeProject: EnvironmentProject | null; rightPanelOpen: boolean; onNewThreadInProject: () => void; onOpenProjectSettings?: (() => void) | undefined; } +/** + * Rename commit rule shared with the sidebar's inline rename: trim, reject + * empty (the caller toasts), and skip the mutation when nothing changed. + */ +export function resolveRenameCommit(input: { + readonly title: string; + readonly originalTitle: string; +}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } { + const trimmed = input.title.trim(); + if (trimmed.length === 0) return { action: "reject-empty" }; + if (trimmed === input.originalTitle) return { action: "noop" }; + return { action: "commit", title: trimmed }; +} + +// How long a click on the thread title waits before opening the action menu, +// so a double-click-to-rename can cancel it first. Only the native desktop +// menu needs this: it swallows input while open, so the wait must cover the +// OS double-click interval. The browser fallback menu keeps seeing DOM +// events (the second click dismisses it and dblclick still fires), so it +// opens immediately. +const TITLE_MENU_OPEN_DELAY_MS = 500; export const ChatHeader = memo(function ChatHeader({ activeThreadEnvironmentId, + activeThreadId, activeThreadTitle, - activeProjectName, - activeProjectCwd, - activeProjectFaviconPath, - activeProjectIcon, - + isServerThread, + activeProject, rightPanelOpen, onNewThreadInProject, onOpenProjectSettings, }: ChatHeaderProps) { + const activeProjectName = activeProject?.title; + const activeProjectCwd = activeProject?.workspaceRoot ?? null; + const activeThreadRef = useMemo( + () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId), + [activeThreadEnvironmentId, activeThreadId], + ); + const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { + reportFailure: false, + }); + // Inline rename, keyed by thread: navigating away drops an in-progress + // rename instead of committing stale text. Cleared on thread change (not + // just hidden) so returning to the thread doesn't revive the old draft. + const [renaming, setRenaming] = useState<{ + threadId: ThreadId; + environmentId: EnvironmentId; + title: string; + } | null>(null); + if ( + renaming !== null && + (renaming.threadId !== activeThreadId || renaming.environmentId !== activeThreadEnvironmentId) + ) { + setRenaming(null); + } + const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null; + const renameCommittedRef = useRef(false); + const startRename = useCallback(() => { + renameCommittedRef.current = false; + setRenaming({ + threadId: activeThreadId, + environmentId: activeThreadEnvironmentId, + title: activeThreadTitle, + }); + }, [activeThreadEnvironmentId, activeThreadId, activeThreadTitle]); + const commitRename = useCallback( + (title: string) => { + setRenaming(null); + const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle }); + if (resolution.action === "reject-empty") { + toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); + return; + } + if (resolution.action === "noop") return; + void updateThreadMetadata({ + environmentId: activeThreadEnvironmentId, + input: { threadId: activeThreadId, title: resolution.title }, + }).then((result) => { + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Failed to rename thread", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } + }); + }, + [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata], + ); + const { openMenu, closeMenu } = useThreadActionMenu({ + threadRef: isServerThread ? activeThreadRef : null, + projectCwd: activeProjectCwd, + onStartRename: startRename, + }); + const titleButtonRef = useRef(null); + const titleMenuTimerRef = useRef(null); + const cancelPendingTitleMenu = useCallback(() => { + if (titleMenuTimerRef.current === null) return; + clearTimeout(titleMenuTimerRef.current); + titleMenuTimerRef.current = null; + }, []); + // Drop a pending menu-open when the thread changes or the header unmounts, + // so it can never fire for a thread the user already left. + useEffect( + () => () => { + cancelPendingTitleMenu(); + }, + [activeThreadEnvironmentId, activeThreadId, cancelPendingTitleMenu], + ); + const openTitleMenuNow = useCallback(() => { + cancelPendingTitleMenu(); + const rect = titleButtonRef.current?.getBoundingClientRect(); + if (!rect) return; + openMenu({ x: rect.left, y: rect.bottom + 4 }); + }, [cancelPendingTitleMenu, openMenu]); + const openMenuFromTitle = useCallback( + (event: ReactMouseEvent) => { + // The trailing click of a double-click belongs to rename, not the menu. + if (isTrailingDoubleClick(event.detail)) return; + // Keyboard activation and the explicit chevron affordance can never be + // the first half of a double-click, so they open without waiting. + const clickedChevron = + (event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null; + if (event.detail === 0 || clickedChevron || window.desktopBridge === undefined) { + openTitleMenuNow(); + return; + } + // Stay pending long enough for dblclick to cancel the open before the + // native menu appears and swallows the second click. + cancelPendingTitleMenu(); + titleMenuTimerRef.current = window.setTimeout(() => { + titleMenuTimerRef.current = null; + openTitleMenuNow(); + }, TITLE_MENU_OPEN_DELAY_MS); + }, + [cancelPendingTitleMenu, openTitleMenuNow], + ); + const handleTitleDoubleClick = useCallback( + (event: ReactMouseEvent) => { + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + // The chevron is the explicit menu affordance; only the title text renames. + if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return; + cancelPendingTitleMenu(); + closeMenu(); + startRename(); + }, + [cancelPendingTitleMenu, closeMenu, startRename], + ); + const handleHeaderContextMenu = useCallback( + (event: ReactMouseEvent) => { + if (renamingTitle !== null) return; + if (!isServerThread && onOpenProjectSettings === undefined) return; + cancelPendingTitleMenu(); + event.preventDefault(); + if (!isServerThread) { + const api = readLocalApi(); + if (!api) return; + void api.contextMenu + .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], { + x: event.clientX, + y: event.clientY, + }) + .then((action) => { + if (action === "project-settings") onOpenProjectSettings?.(); + }); + return; + } + openMenu({ x: event.clientX, y: event.clientY }); + }, + [cancelPendingTitleMenu, isServerThread, onOpenProjectSettings, openMenu, renamingTitle], + ); + const handleRenameKeyDown = useCallback( + (event: ReactKeyboardEvent) => { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; + if (event.key === "Enter") { + renameCommittedRef.current = true; + commitRename(event.currentTarget.value); + } else if (event.key === "Escape") { + renameCommittedRef.current = true; + setRenaming(null); + } + }, + [commitRename], + ); return (
    { - event.preventDefault(); - const api = readLocalApi(); - if (!api) return; - void api.contextMenu - .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], { - x: event.clientX, - y: event.clientY, - }) - .then((action) => { - if (action === "project-settings") onOpenProjectSettings(); - }); - } - } className={cn( "flex min-w-0 flex-1 items-center gap-2 sm:gap-3", rightPanelOpen ? "pr-10" : "pr-24", )} + onContextMenu={handleHeaderContextMenu} > -
    + {/* The project always leads the header: knowing which project a thread lives in is priority zero, and the thread title alone doesn't answer it. */} - {activeProjectName ? ( - + {activeProject ? ( + <> + + + + } + > + + {activeProjectName} + + New thread in {activeProjectName} + + + + + ) : null} + + {renamingTitle !== null ? ( + { + if (renameCommittedRef.current) return; + // Focus landing on a navigation button means the rename was + // abandoned — discard it rather than persisting a half-draft. + if ( + event.relatedTarget instanceof HTMLElement && + event.relatedTarget.closest("button") + ) { + setRenaming(null); + return; + } + commitRename(event.currentTarget.value); + }} + onFocus={(event) => event.currentTarget.select()} + onKeyDown={handleRenameKeyDown} + /> + ) : isServerThread ? ( } > - {activeThreadTitle} + - {activeProjectName} - New thread in {activeProjectName} + {activeThreadTitle} - - / - - - ) : null} - - - {activeThreadTitle} - - } - /> - {activeThreadTitle} - -
    + ) : ( + + + {activeThreadTitle} + + } + /> + {activeThreadTitle} + + )} + +
    ); }); diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx index 039f12d408735..ffa21ac9a460e 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx @@ -16,6 +16,10 @@ import { useComposerMenuState } from "./useComposerMenuState"; export const CompactComposerControlsMenu = memo(function CompactComposerControlsMenu(props: { interactionMode: ProviderInteractionMode; runtimeMode: RuntimeMode; + runtimeModeOptions: ReadonlyArray<{ + readonly mode: RuntimeMode; + readonly label: string; + }>; showInteractionModeToggle: boolean; traitsMenuContent?: ReactNode; size?: "sm" | "xs"; @@ -40,6 +44,9 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls variant="ghost" className={size === "xs" ? "shrink-0" : "shrink-0 px-2"} aria-label="More composer controls" + data-composer-shortcut={ + props.traitsMenuContent ? "composer.mode composer.effort" : "composer.mode" + } /> } > @@ -76,10 +83,11 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls props.onRuntimeModeChange(value as RuntimeMode); }} > - Supervised - Auto-accept edits - Auto - Full access + {props.runtimeModeOptions.map((option) => ( + + {option.label} + + ))} diff --git a/apps/web/src/components/chat/ComposerImageThumbnail.tsx b/apps/web/src/components/chat/ComposerImageThumbnail.tsx new file mode 100644 index 0000000000000..c803d5693009f --- /dev/null +++ b/apps/web/src/components/chat/ComposerImageThumbnail.tsx @@ -0,0 +1,29 @@ +import { memo, useEffect, useState, type ReactNode } from "react"; + +import { createComposerImageThumbnail } from "../../lib/imageCompression"; + +/** Keep full-resolution image decoding out of composer rerenders. */ +export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({ + file, + alt, + className, + fallback, +}: { + file: File; + alt: string; + className: string; + fallback: ReactNode; +}) { + const [preview, setPreview] = useState<{ file: File; src: string | null } | null>(null); + useEffect(() => { + let active = true; + void createComposerImageThumbnail(file).then((src) => { + if (active) setPreview({ file, src }); + }); + return () => { + active = false; + }; + }, [file]); + const src = preview?.file === file ? preview.src : null; + return src ? {alt} : fallback; +}); diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx index e8a10559af0b7..34f9467e42c4b 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx @@ -21,12 +21,13 @@ const prompt: PendingUserInput = { multiSelect: false, }, ], + dismissible: true, }; -function renderPanel() { +function renderPanel(pendingUserInput: PendingUserInput = prompt) { return renderToStaticMarkup( { expect(markup).toMatch(new RegExp(`]*\\sid="${controlledId}"`)); }); + it("offers dismiss only for async questions", () => { + expect(renderPanel()).toContain("data-pending-user-input-dismiss"); + expect(renderPanel({ ...prompt, dismissible: false })).not.toContain( + "data-pending-user-input-dismiss", + ); + }); + it("starts expanded so the question and its options are visible", () => { const markup = renderPanel(); diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index f300abc7f9dca..4f8b9742b85f6 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -206,7 +206,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( ) : null} - {prompt.responseMode === "message" ? ( + {prompt.dismissible ? ( // Sits inside the trigger button, so stop the click from toggling // the disclosure. Dismiss closes the question without a reply. ) { data-slot="composer-host" className={cn( "relative z-10 w-full rounded-[22px] shadow-[0_12px_28px_-18px_rgb(0_0_0/40%)] after:z-1 dark:shadow-none", + "group-data-model-strip-transition/composer-surface:bg-[color-mix(in_srgb,var(--chat-composer-glass-surface)_var(--glass-opacity),transparent)] group-data-model-strip-transition/composer-surface:backdrop-blur-(--glass-blur)", outlineClasses, contextSeamClasses, "group-has-data-[composer-banner-surface=attached]/composer-surface:shadow-none group-has-data-[composer-banner-surface=attached]/composer-surface:after:hidden", diff --git a/apps/web/src/components/chat/ContextWindowMeter.logic.test.ts b/apps/web/src/components/chat/ContextWindowMeter.logic.test.ts index 6036fb9cbd569..d97e9393486a7 100644 --- a/apps/web/src/components/chat/ContextWindowMeter.logic.test.ts +++ b/apps/web/src/components/chat/ContextWindowMeter.logic.test.ts @@ -5,6 +5,7 @@ import { formatContextWindowCompactionMessage, hasAvailableCompactionProvider, hasDismissedResumeCompaction, + formatContextWindowCost, resolveContextWindowModelDisplayName, shouldOfferResumeCompaction, shouldReserveContextWindowMeter, @@ -286,3 +287,10 @@ describe("shouldReserveContextWindowMeter", () => { ); }); }); + +describe("formatContextWindowCost", () => { + it("keeps ordinary and sub-cent ACP costs readable", () => { + expect(formatContextWindowCost({ amount: 0.42, currency: "USD" })).toBe("USD 0.42"); + expect(formatContextWindowCost({ amount: 0.0042, currency: "USD" })).toBe("USD 0.0042"); + }); +}); diff --git a/apps/web/src/components/chat/ContextWindowMeter.logic.ts b/apps/web/src/components/chat/ContextWindowMeter.logic.ts index a04582a0426d9..390caab18fbf6 100644 --- a/apps/web/src/components/chat/ContextWindowMeter.logic.ts +++ b/apps/web/src/components/chat/ContextWindowMeter.logic.ts @@ -135,3 +135,11 @@ export function shouldReserveContextWindowMeter(input: { input.providerReportsContextWindow !== false ); } + +export function formatContextWindowCost(cost: { + readonly amount: number; + readonly currency: string; +}): string { + const fractionDigits = Math.abs(cost.amount) > 0 && Math.abs(cost.amount) < 0.01 ? 4 : 2; + return `${cost.currency} ${cost.amount.toFixed(fractionDigits)}`; +} diff --git a/apps/web/src/components/chat/ContextWindowMeter.tsx b/apps/web/src/components/chat/ContextWindowMeter.tsx index 3e52f6e2d86dd..8c7f1ac3d854e 100644 --- a/apps/web/src/components/chat/ContextWindowMeter.tsx +++ b/apps/web/src/components/chat/ContextWindowMeter.tsx @@ -1,7 +1,10 @@ import { Button } from "../ui/button"; import { type ContextWindowSnapshot, formatContextWindowTokens } from "~/lib/contextWindow"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; -import { formatContextWindowCompactionMessage } from "./ContextWindowMeter.logic"; +import { + formatContextWindowCompactionMessage, + formatContextWindowCost, +} from "./ContextWindowMeter.logic"; import { Minimize2Icon } from "lucide-react"; import { composerFloatingLayerProps } from "./composerEventScope"; @@ -132,6 +135,14 @@ export function ContextWindowMeter(props: {
    ) : null} + {usage.cost != null ? ( +
    + Cost + + {formatContextWindowCost(usage.cost)} + +
    + ) : null} {usage.compactsAutomatically ? (
    {formatContextWindowCompactionMessage(modelDisplayName, usage.autoCompactThreshold)} diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index d0c23939b1861..9963235de1d74 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1,8 +1,8 @@ +import { ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts"; import { - ApprovalRequestId, CheckpointRef, - ThreadId, TurnItemId, + RuntimeRequestId, type OrchestrationV2ProjectedTurnItem, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -10,10 +10,9 @@ import { deriveTimelineEntriesFromVisibleTurnItems, deriveTimelineEntriesFromVisibleTurnItemsWithState, workEntryDisplayIndicatesToolFailure, - type WorkLogEntry, } from "../../session-logic"; import { makeStreamingTimelineFixture } from "../../test-fixtures"; -import type { ChatMessage, TurnDiffSummary } from "../../types"; +import type { TurnDiffSummary } from "../../types"; import { describe, expect, it } from "vite-plus/test"; import { MessageId, RunId } from "@t3tools/contracts"; import { @@ -29,7 +28,6 @@ import { shouldPreserveAssistantLineBreaks, type MessagesTimelineRow, resolveTimelineToolPresentation, - summarizeToolGroup, workEntryDisplayLabel, } from "./MessagesTimeline.logic"; @@ -196,8 +194,8 @@ describe("work entry labels", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const directRow = rows.find((row) => row.kind === "work"); expect(directRow).toMatchObject({ @@ -491,6 +489,86 @@ describe("resolveAssistantMessageCopyState", () => { }); describe("deriveMessagesTimelineRows", () => { + it.each(["waiting", "completed"] as const)( + "groups approval and user-input requests with commands without expanding them when %s", + (status) => { + const fixture = makeStreamingTimelineFixture(); + const source = fixture.visibleTurnItems[0]!; + const common = { + ...source.item, + threadId: fixture.threadId, + runId: fixture.runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + status, + }; + const items: OrchestrationV2ProjectedTurnItem["item"][] = [ + { + ...common, + id: TurnItemId.make("command"), + type: "command_execution", + input: "pwd", + output: "", + }, + { + ...common, + id: TurnItemId.make("approval"), + type: "approval_request", + requestId: RuntimeRequestId.make("approval-request"), + requestKind: "command", + prompt: "Allow pwd?", + }, + { + ...common, + id: TurnItemId.make("input"), + type: "user_input_request", + requestId: RuntimeRequestId.make("input-request"), + questions: [], + }, + ]; + const entries = deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.map((item, position) => ({ + ...source, + item, + position, + sourceItemId: item.id, + })), + optimisticMessages: [], + }); + expect(entries.map((entry) => entry.kind)).toEqual(["work", "work", "work"]); + const rows = deriveMessagesTimelineRows({ + timelineEntries: entries, + isWorking: status === "waiting", + runningRunId: fixture.runId, + activeTurnStartedAt: fixture.time(0), + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + const workRows = rows.filter((row) => row.kind === "work-toggle" || row.kind === "work-live"); + expect(workRows).toHaveLength(1); + expect(workRows[0]).toMatchObject({ expanded: false }); + const expandedRows = deriveMessagesTimelineRows({ + timelineEntries: entries, + isWorking: status === "waiting", + runningRunId: fixture.runId, + activeTurnStartedAt: fixture.time(0), + turnDiffSummaries: [], + supportsConversationRollback: false, + expandedWorkGroupIds: new Set([workRows[0]!.groupId]), + }); + const expanded = expandedRows.find((row) => row.kind === "work" && row.isExpandedToolGroup); + expect( + expanded?.kind === "work" && expanded.groupedEntries.map((entry) => entry.itemType), + ).toEqual(["command_execution", "approval_request", "user_input_request"]); + expect(rows.some((row) => row.kind === "event")).toBe(false); + expect(workRows[0]).not.toMatchObject({ expanded: true }); + expect(workRows[0]).not.toMatchObject({ isExpandedToolGroup: true }); + }, + ); + it.each(["running", "completed", "superseded"] as const)( "keeps system notices visible as non-failing warnings through %s work", (state) => { @@ -580,8 +658,8 @@ describe("deriveMessagesTimelineRows", () => { startedAt: notice.createdAt, completedAt: state === "running" ? null : notice.createdAt, }, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const row = rows.find( (row) => row.kind === "work" && row.groupedEntries.includes(notice.entry), @@ -608,8 +686,8 @@ describe("deriveMessagesTimelineRows", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows).toEqual([ @@ -618,10 +696,74 @@ describe("deriveMessagesTimelineRows", () => { id: "compaction-entry", createdAt: "2026-01-01T00:00:00Z", label: "Compacted context 899K → 19K tokens", + active: false, }, ]); }); + it("gives live compaction the activity slot and restores Thinking when it completes", () => { + const fixture = makeStreamingTimelineFixture(); + const last = fixture.visibleTurnItems.at(-1)!; + if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture"); + const compact = { + ...last, + item: { + ...last.item, + type: "compaction" as const, + status: "running" as const, + driver: null, + beforeTokenCount: 899_000, + }, + }; + const input = { + isWorking: true, + runningRunId: fixture.runId, + activeTurnStartedAt: fixture.time(5), + turnDiffSummaries: [], + supportsConversationRollback: false, + }; + const runningEntries = deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: [...fixture.visibleTurnItems.slice(0, -1), compact], + optimisticMessages: [], + }); + const runningRows = deriveMessagesTimelineRows({ ...input, timelineEntries: runningEntries }); + expect(runningRows.find((row) => row.kind === "context-compaction")).toMatchObject({ + active: true, + label: "Compacting context", + }); + expect(runningRows.some((row) => row.kind === "thinking")).toBe(false); + + const completedRows = deriveMessagesTimelineRows({ + ...input, + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: [ + ...fixture.visibleTurnItems.slice(0, -1), + { + ...compact, + item: { ...compact.item, status: "completed", afterTokenCount: 19_000 }, + }, + ], + optimisticMessages: [], + }), + }); + expect(completedRows.find((row) => row.kind === "context-compaction")).toMatchObject({ + active: false, + label: "Context compacted 899K → 19K tokens", + }); + expect(completedRows.at(-1)?.kind).toBe("thinking"); + + const settledRows = deriveMessagesTimelineRows({ + ...input, + isWorking: false, + timelineEntries: runningEntries, + }); + expect(settledRows.find((row) => row.kind === "context-compaction")).toMatchObject({ + active: false, + }); + const stable = computeStableMessagesTimelineRows(runningRows, { result: [], byId: new Map() }); + expect(computeStableMessagesTimelineRows(settledRows, stable).result).toEqual(settledRows); + }); + it("only enables assistant copy for the terminal assistant message in a turn", () => { const rows = deriveMessagesTimelineRows({ timelineEntries: [ @@ -671,8 +813,8 @@ describe("deriveMessagesTimelineRows", () => { expandedRunIds: new Set(["turn-1" as never]), isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const assistantRows = rows.filter( @@ -725,8 +867,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const assistantRows = rows.filter( @@ -759,7 +901,8 @@ describe("deriveMessagesTimelineRows", () => { id: "user-1" as never, role: "user", text: "Do the thing", - runId: null, + runId: "turn-1" as never, + inputIntent: "turn_start", createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", streaming: false, @@ -782,10 +925,8 @@ describe("deriveMessagesTimelineRows", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map([ - ["assistant-1" as never, assistantTurnDiffSummary], - ]), - revertTurnCountByUserMessageId: new Map([["user-1" as never, 1]]), + turnDiffSummaries: [assistantTurnDiffSummary], + supportsConversationRollback: true, }); const userRow = rows.find( @@ -863,8 +1004,8 @@ describe("deriveMessagesTimelineRows", () => { timelineEntries, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const foldRow = collapsedRows.find( @@ -886,8 +1027,8 @@ describe("deriveMessagesTimelineRows", () => { expandedRunIds: new Set(["turn-1" as never]), isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(expandedRows.map((row) => row.id)).toEqual([ @@ -902,7 +1043,7 @@ describe("deriveMessagesTimelineRows", () => { ).toBeDefined(); }); - it("keeps a tool group after the terminal response visible when the turn is folded", () => { + it.each([1, 2, 3])("folds %i completed activities after the terminal response", (count) => { const runId = RunId.make("turn-1"); const timelineEntries = [ { @@ -924,14 +1065,14 @@ describe("deriveMessagesTimelineRows", () => { message: { id: "assistant-final" as never, role: "assistant" as const, - text: "I could not finish the task.", + text: "CI is re-running. Waiting.", runId, createdAt: "2026-01-01T00:00:05Z", updatedAt: "2026-01-01T00:00:06Z", streaming: false, }, }, - ...Array.from({ length: 3 }, (_, index) => ({ + ...Array.from({ length: count }, (_, index) => ({ id: `work-entry-after-text-${index}`, kind: "work" as const, createdAt: `2026-01-01T00:00:0${index + 7}Z`, @@ -950,43 +1091,57 @@ describe("deriveMessagesTimelineRows", () => { const input = { latestRun: { runId, - status: "failed" as const, + status: "completed" as const, startedAt: "2026-01-01T00:00:00Z", completedAt: "2026-01-01T00:00:10Z", }, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }; const rows = deriveMessagesTimelineRows({ ...input, timelineEntries }); - expect(rows.map((row) => row.id)).toEqual([ - "turn-fold:turn-1", - "assistant-final-entry", - "work-toggle:work-entry-after-text-0", - "assistant-meta:assistant-final", - ]); - expect(rows.at(-2)).toMatchObject({ - kind: "work-toggle", - hiddenCount: 3, - summary: "Ran 3 commands", - }); - expect(rows.at(-1)).toMatchObject({ - kind: "assistant-meta", - message: { id: "assistant-final" }, - showAssistantCopyButton: true, - }); - expect(rows.at(-3)).toMatchObject({ - kind: "message", - showAssistantMeta: false, - showAssistantCopyButton: false, + expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]); + const expanded = deriveMessagesTimelineRows({ + ...input, + timelineEntries, + expandedRunIds: new Set([runId]), }); expect( - deriveMessagesTimelineRows({ ...input, timelineEntries: timelineEntries.slice(0, 3) }).map( - (row) => row.id, + expanded.some( + (row) => + row.id === "work-entry-after-text-0" || + (row.kind === "work-toggle" && + row.id === "work-toggle:work-entry-after-text-0" && + row.hiddenCount === count), ), - ).toEqual(["turn-fold:turn-1", "assistant-final-entry"]); + ).toBe(true); + + // A late failure must remain visible even though successful work is folded. + const failedEntries = timelineEntries.map((entry) => + entry.kind === "work" && entry.id === "work-entry-after-text-0" + ? { ...entry, entry: { ...entry.entry, toolLifecycleStatus: "failed" as const } } + : entry, + ); + const failedRows = deriveMessagesTimelineRows({ ...input, timelineEntries: failedEntries }); + expect(failedRows.some((row) => row.id === "work-entry-after-text-0")).toBe(true); + + const pendingEntries = timelineEntries.map((entry) => + entry.kind === "work" && entry.id === "work-entry-after-text-0" + ? { ...entry, entry: { ...entry.entry, toolLifecycleStatus: "inProgress" as const } } + : entry, + ); + const pendingRows = deriveMessagesTimelineRows({ + ...input, + timelineEntries: pendingEntries, + latestRun: { ...input.latestRun, status: "running", completedAt: null }, + isWorking: true, + activeTurnStartedAt: input.latestRun.startedAt, + }); + expect( + pendingRows.some((row) => row.kind === "work-live" && row.entry.id === "work-after-text-0"), + ).toBe(true); }); it("folds all assistant messages before the terminal message", () => { @@ -1039,8 +1194,8 @@ describe("deriveMessagesTimelineRows", () => { timelineEntries, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]); @@ -1142,8 +1297,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:14Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const foldRow = rows.find( @@ -1179,8 +1334,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows).toEqual([ @@ -1193,6 +1348,48 @@ describe("deriveMessagesTimelineRows", () => { ]); }); + it("keeps the working header below the initiating prompt across repeated steers", () => { + const runId = RunId.make("steered-run"); + const startedAt = "2026-01-01T00:00:00Z"; + const prompt = (id: string, inputIntent: "steer" | "send") => ({ + id, + kind: "message" as const, + createdAt: startedAt, + message: { + id: MessageId.make(id), + role: "user" as const, + text: id, + runId, + ...(inputIntent === "steer" ? { inputIntent } : {}), + createdAt: startedAt, + updatedAt: startedAt, + streaming: false, + }, + }); + const timelineEntries = [prompt("initial-prompt", "send")]; + for (let index = 0; index < 3; index += 1) { + const rows = deriveMessagesTimelineRows({ + timelineEntries, + latestRun: { runId, status: "running", startedAt, completedAt: null }, + isWorking: true, + activeTurnStartedAt: startedAt, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(rows.slice(0, 2).map((row) => row.id)).toEqual([ + "initial-prompt", + "working-indicator-row", + ]); + expect(rows.filter((row) => row.kind === "working")).toEqual([ + expect.objectContaining({ createdAt: startedAt }), + ]); + expect(rows.filter((row) => row.kind === "message").map((row) => row.id)).toEqual( + timelineEntries.map((entry) => entry.id), + ); + timelineEntries.push(prompt(`steer-${index}`, "steer")); + } + }); + it("keeps the previous turn folded while a newly sent message awaits its turn", () => { // Right after send, isWorking is true but latestRun still points at the // previous, settled turn — it must stay folded through that window. @@ -1247,8 +1444,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:01:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.map((row) => row.id)).toEqual([ @@ -1301,8 +1498,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.some((row) => row.kind === "turn-fold")).toBe(false); @@ -1395,8 +1592,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:01:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.some((row) => row.kind === "turn-fold")).toBe(false); @@ -1405,7 +1602,7 @@ describe("deriveMessagesTimelineRows", () => { rows.findIndex((row) => row.id === "old-work-entry"), ); expect(rows.find((row) => row.id === "working-indicator-row")).toMatchObject({ - createdAt: "2026-01-01T00:00:00Z", + createdAt: "2026-01-01T00:01:00Z", }); expect(rows.find((row) => row.id === "old-commentary-entry")).toMatchObject({ showAssistantMeta: false, @@ -1475,8 +1672,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.map((row) => row.kind)).toEqual(["working", "work-live"]); @@ -1548,8 +1745,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.map((row) => row.kind)).toEqual(["working", "work", "message", "work-live"]); @@ -1616,8 +1813,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.map((row) => row.kind)).toEqual(["working", "work-live", "message", "work-live"]); @@ -1663,8 +1860,8 @@ describe("deriveMessagesTimelineRows", () => { latestRun: null, isWorking: true, activeTurnStartedAt: "2026-01-01T00:01:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.some((row) => row.kind === "work-live")).toBe(false); @@ -1724,8 +1921,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.filter((row) => row.kind === "work-live").map((row) => row.entry.id)).toEqual([ @@ -1736,7 +1933,7 @@ describe("deriveMessagesTimelineRows", () => { it.each([ [undefined, true], ["inProgress", true], - ["completed", true], + ["completed", false], ["failed", null], ["declined", false], ["stopped", false], @@ -1769,8 +1966,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const workLiveRow = rows.find((row) => row.kind === "work-live"); @@ -1779,7 +1976,6 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.at(-1)).toMatchObject({ kind: "thinking", id: "live-activity-row" }); } else { expect(workLiveRow).toMatchObject({ active }); - if (active) expect(rows.some((row) => row.kind === "thinking")).toBe(false); } }, ); @@ -1818,8 +2014,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const initialRows = deriveRows(null); @@ -1896,8 +2092,8 @@ describe("deriveMessagesTimelineRows", () => { runningRunId: "turn-2" as never, isWorking: true, activeTurnStartedAt: "2026-01-01T00:01:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.runId)).toEqual([ @@ -1941,8 +2137,8 @@ describe("deriveMessagesTimelineRows", () => { expandedRunIds: new Set(["turn-1" as never]), isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const assistantRows = rows.filter( @@ -1979,8 +2175,8 @@ describe("deriveMessagesTimelineRows", () => { }, isWorking: true, activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const assistantRow = rows.find( @@ -2043,8 +2239,8 @@ describe("deriveMessagesTimelineRows", () => { timelineEntries, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }; const collapsedRows = deriveMessagesTimelineRows(baseInput); const expandedRows = deriveMessagesTimelineRows({ @@ -2074,84 +2270,6 @@ describe("deriveMessagesTimelineRows", () => { }); }); - it("keeps user input in its own row through tool grouping and turn folding", () => { - const runId = RunId.make("answer-turn"); - const time = (second: number) => new Date(Date.UTC(2026, 8, 8, 0, 0, second)).toISOString(); - const answer: WorkLogEntry = { - id: "answer-submitted", - createdAt: time(3), - runId, - tone: "info", - label: "User input submitted", - sourceActivityKind: "user-input.answer-submitted", - questionAnswer: { - requestId: ApprovalRequestId.make("answer-request"), - answers: { scope: "Use the private repository" }, - questionTextById: { scope: "Which repository?" }, - attachmentsByQuestionId: {}, - }, - }; - const tools: WorkLogEntry[] = [1, 2, 4, 5].map((second) => ({ - id: `tool-${second}`, - createdAt: time(second), - runId, - tone: "tool", - label: "Ran command", - command: "git status", - toolCallId: `call-${second}`, - toolLifecycleStatus: "completed", - sourceActivityKind: "tool.completed", - })); - const input = { - timelineEntries: deriveTimelineEntries([], [], [...tools, answer]), - latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(6) }, - isWorking: false, - activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), - } satisfies Parameters[0]; - const collapsed = deriveMessagesTimelineRows(input); - expect(collapsed.map((row) => row.kind)).toEqual(["turn-fold", "work"]); - const expanded = deriveMessagesTimelineRows({ ...input, expandedRunIds: new Set([runId]) }); - expect(expanded.map((row) => row.kind)).toEqual([ - "turn-fold", - "work-toggle", - "work", - "work-toggle", - ]); - const expandedGroups = deriveMessagesTimelineRows({ - ...input, - expandedRunIds: new Set([runId]), - expandedWorkGroupIds: new Set( - expanded.flatMap((row) => (row.kind === "work-toggle" ? [row.groupId] : [])), - ), - }); - expect( - expandedGroups.flatMap((row) => - row.kind === "work" && row.isExpandedToolGroup ? [row.groupedEntries] : [], - ), - ).toEqual([tools.slice(0, 2), tools.slice(2)]); - const active = deriveMessagesTimelineRows({ - ...input, - latestRun: { ...input.latestRun, status: "running", completedAt: null }, - runningRunId: runId, - isWorking: true, - activeTurnStartedAt: time(0), - }); - for (const rows of [collapsed, expanded, expandedGroups, active]) { - const answerRows = rows.filter( - (row) => - (row.kind === "work" || row.kind === "work-live") && row.groupedEntries.includes(answer), - ); - expect(answerRows).toMatchObject([ - { kind: "work", groupedEntries: [answer], isExpandedToolGroup: false }, - ]); - } - expect(active.find((row) => row.kind === "work-live")).toMatchObject({ - groupedEntries: tools.slice(2), - }); - }); - it("deduplicates integration sources and uses the first source icon for the group", () => { const chromeSource = { key: "browser-use:chrome", @@ -2215,8 +2333,8 @@ describe("deriveMessagesTimelineRows", () => { timelineEntries, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(row).toMatchObject({ @@ -2256,8 +2374,8 @@ describe("deriveMessagesTimelineRows", () => { expandedRunIds: new Set([runId]), runningRunId: isWorking ? runId : null, activeTurnStartedAt: isWorking ? createdAt : null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }; const collapsedRows = deriveMessagesTimelineRows(input); const collapsedGroup = collapsedRows.find( @@ -2302,8 +2420,8 @@ describe("deriveMessagesTimelineRows", () => { timelineEntries, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.find((row) => row.kind === "work-toggle")).toMatchObject({ @@ -2349,8 +2467,8 @@ describe("deriveMessagesTimelineRows", () => { timelineEntries, isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.find((row) => row.kind === "work-toggle")).toMatchObject({ @@ -2406,8 +2524,8 @@ describe("computeStableMessagesTimelineRows", () => { runningRunId: runId, isWorking: true, activeTurnStartedAt: startedAt, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }; const assistantEntry = { id: "assistant-entry", @@ -2484,8 +2602,8 @@ describe("computeStableMessagesTimelineRows", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const initial = computeStableMessagesTimelineRows(rows, { @@ -2533,8 +2651,8 @@ describe("computeStableMessagesTimelineRows", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const firstRows = createRows(); @@ -2589,8 +2707,8 @@ describe("computeStableMessagesTimelineRows", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const initial = computeStableMessagesTimelineRows(firstRows, { @@ -2605,121 +2723,6 @@ describe("computeStableMessagesTimelineRows", () => { }); }); -describe("summarizeToolGroup", () => { - const now = DateTime.makeUnsafe("2026-08-29T00:00:00Z"); - function work(overrides: Partial = {}): WorkLogEntry { - return { - id: "tool", - createdAt: "2026-08-29T00:00:00Z", - label: "Tool call", - tone: "tool", - toolLifecycleStatus: "completed", - ...overrides, - }; - } - function t3(toolName: string, input: unknown = {}, output: unknown = {}): WorkLogEntry { - return work({ - itemType: "dynamic_tool", - toolTitle: "Friendly display name", - structuredPayload: { - id: TurnItemId.make("tool"), - threadId: ThreadId.make("parent"), - runId: RunId.make("run"), - nodeId: null, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 0, - status: "completed", - title: "Friendly display name", - startedAt: now, - completedAt: now, - updatedAt: now, - type: "dynamic_tool", - toolName, - input, - output, - }, - }); - } - - it("summarizes commands and thread messages using canonical names despite humanized titles", () => { - const entries = [ - work({ command: "git diff" }), - ...["mcp__t3-code__t3_thread_send", "t3_code.t3_thread_send", "t3_thread_send"].map( - (toolName, i) => - t3( - toolName, - { threadId: `thread-${i}` }, - { messageId: `message-${i}`, threadId: `thread-${i}` }, - ), - ), - work({ command: "git status" }), - ]; - expect(summarizeToolGroup(entries)).toEqual({ - summary: "Ran 2 commands and sent messages to 3 threads", - hasFailure: false, - }); - }); - - it("prioritizes actions over polling, caps the clauses, and retains an omitted failure", () => { - const status = t3("task_status", { taskId: "task-1" }, { taskId: "task-1", status: "running" }); - expect( - summarizeToolGroup([ - status, - status, - status, - work({ command: "git diff" }), - t3( - "t3_thread_send", - { threadId: "thread-1" }, - { threadId: "thread-1", messageId: "message-1" }, - ), - t3( - "schedule_task", - {}, - { isError: true, content: [{ type: "text", text: "Schedule rejected" }] }, - ), - status, - ]), - ).toEqual({ - summary: "Ran 1 command, sent 1 message to 1 thread, and performed 5 other actions", - hasFailure: true, - }); - }); - - it("counts status checks without treating the reported child failure as a failed tool", () => { - const status = { - ...t3("task_status", { taskId: "task-1" }, { taskId: "task-1", status: "failed" }), - detail: "Child failed: command not found", - }; - expect( - summarizeToolGroup([ - t3("delegate_task", {}, { taskId: "task-1" }), - t3("delegate_task", {}, { taskId: "task-2" }), - status, - status, - status, - status, - ]), - ).toEqual({ - summary: "Delegated 2 tasks and checked task status 4 times", - hasFailure: false, - }); - }); - - it("leaves foreign, unknown, and preview tools generic instead of guessing from display titles", () => { - expect( - summarizeToolGroup([ - { ...t3("mcp__github__t3_thread_send"), toolTitle: "t3-code.t3_thread_send" }, - t3("t3-code.future_tool"), - t3("t3-code.preview_snapshot"), - ]), - ).toEqual({ summary: "Used 3 tools", hasFailure: false }); - }); -}); - describe("resolveTimelineToolPresentation", () => { it("pretty prints Claude and Cursor T3 MCP tool names", () => { expect(resolveTimelineToolPresentation("mcp__t3-code__t3_thread_read")).toEqual({ @@ -2833,8 +2836,8 @@ describe("v2 run and attempt history", () => { const collapsedRows = deriveMessagesTimelineRows({ timelineEntries, isWorking: false, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); const foldRow = collapsedRows.find( @@ -2856,8 +2859,8 @@ describe("v2 run and attempt history", () => { timelineEntries, expandedRunIds: new Set(["turn-1" as never]), isWorking: false, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(expandedRows.map((row) => row.id)).toEqual([ @@ -2876,8 +2879,8 @@ describe("v2 run and attempt history", () => { expandedRunIds: new Set(["turn-1" as never]), expandedWorkGroupIds: new Set(["work-group:work-entry-1"]), isWorking: false, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); // Expanding the activity preserves tool output and provider recovery details. const expandedWork = openedActivity.find((row) => row.kind === "work"); @@ -2886,7 +2889,7 @@ describe("v2 run and attempt history", () => { expect.objectContaining({ id: "provider-recovered" }), ]); }); - it("keeps persistent cards after the Worked-for row when they arrive before commentary", () => { + it("hides subagents in folded turns when they arrive before commentary", () => { const timelineEntries = [ { id: "user-entry", @@ -2946,14 +2949,13 @@ describe("v2 run and attempt history", () => { const collapsedRows = deriveMessagesTimelineRows({ timelineEntries, isWorking: false, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(collapsedRows.map((row) => row.id)).toEqual([ "user-entry", "turn-fold:turn-1", - "subagent-card-entry", "assistant-final-entry", ]); }); @@ -3072,8 +3074,8 @@ describe("v2 run and attempt history", () => { completedAt: null, }, isWorking: false, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }; const collapsedRows = deriveMessagesTimelineRows(common); @@ -3165,8 +3167,8 @@ describe("v2 run and attempt history", () => { completedAt: "2026-01-01T00:00:03Z", }, isWorking: false, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), + turnDiffSummaries: [], + supportsConversationRollback: false, }); expect(rows.map((row) => row.id)).toEqual(["work-entry", "interrupt-result"]); @@ -3190,21 +3192,18 @@ describe("streaming v2 row projection", () => { runningRunId: source.runId, isWorking: true, activeTurnStartedAt: source.time(5), - turnDiffSummaryByAssistantMessageId: new Map([ - [ - MessageId.make("history-assistant"), - { - runId: source.historyRunId, - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("refs/t3/checkpoints/history"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("history-assistant"), - completedAt: source.time(4), - }, - ], - ]), - revertTurnCountByUserMessageId: new Map([[MessageId.make("history-user"), 0]]), + turnDiffSummaries: [ + { + runId: source.historyRunId, + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/history"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("history-assistant"), + completedAt: source.time(4), + }, + ] satisfies ReadonlyArray, + supportsConversationRollback: true, } satisfies Parameters[0]; return { ...source, timelineInput, timeline, input }; } @@ -3239,19 +3238,13 @@ describe("streaming v2 row projection", () => { timelineInput, initial.timeline, ); - // The actual v2 selectors recreate shell/checkpoint summaries and maps on - // every projection event, even when their contents did not change. + // The actual v2 selectors recreate shell/checkpoint summaries on every + // projection event, even when their contents did not change. const input = { ...initial.input, timelineEntries: timeline.entries, latestRun: { ...initial.input.latestRun }, - turnDiffSummaryByAssistantMessageId: new Map( - [...initial.input.turnDiffSummaryByAssistantMessageId].map(([key, value]) => [ - key, - { ...value }, - ]), - ), - revertTurnCountByUserMessageId: new Map(initial.input.revertTurnCountByUserMessageId), + turnDiffSummaries: initial.input.turnDiffSummaries.map((summary) => ({ ...summary })), }; const next = deriveMessagesTimelineRowsWithState(input, previous); expect(next.rows).toEqual( @@ -3483,80 +3476,353 @@ describe("streaming v2 row projection", () => { ].map((row, position) => ({ ...row, position })), }; check(); - check({ revertTurnCountByUserMessageId: new Map([[MessageId.make("live-user"), 3]]) }); + check({ supportsConversationRollback: false }); check({ - turnDiffSummaryByAssistantMessageId: new Map( - [...initial.input.turnDiffSummaryByAssistantMessageId].map(([key, value]) => [ - key, - { ...value, status: "stale" }, - ]), - ), + turnDiffSummaries: initial.input.turnDiffSummaries.map((summary) => ({ + ...summary, + status: "stale" as const, + })), }); }); }); -function deriveTimelineEntries( - messages: readonly ChatMessage[], - _plans: readonly never[], - work: readonly WorkLogEntry[], -): import("../../session-logic").TimelineEntry[] { - return [ - ...messages.map((message) => ({ - kind: "message" as const, - id: message.id, - createdAt: message.createdAt, - message, - })), - ...work.map((entry) => ({ - kind: "work" as const, - id: entry.id, - createdAt: entry.createdAt, - entry, - })), - ].sort((a, b) => a.createdAt.localeCompare(b.createdAt)); -} - -it.each(["running", "cancelled", "failed"] as const)( - "keeps the %s setup card directly after the first user message", - (phase) => { - const createdAt = "2026-09-14T00:00:00.000Z"; +describe("linked timeline resources", () => { + const runId = RunId.make("resource-run"); + const event = (id: string, type: "subagent" | "thread_created", eventRunId = runId) => ({ + id, + kind: "event" as const, + createdAt: "2026-09-08T10:00:02Z", + projectedItem: { item: { id, type, runId: eventRunId } } as OrchestrationV2ProjectedTurnItem, + }); + const common = { isWorking: false, turnDiffSummaries: [], supportsConversationRollback: false }; + + it("groups adjacent subagents without merging across a resource or run boundary", () => { const rows = deriveMessagesTimelineRows({ + ...common, timelineEntries: [ - { - kind: "message", - id: "user-entry", - createdAt, - message: { - id: MessageId.make("user-message"), - runId: null, - role: "user", - text: "Start work", - createdAt, - updatedAt: createdAt, - streaming: false, - }, + event("a", "subagent"), + event("b", "subagent"), + event("c", "thread_created"), + event("d", "subagent"), + event("e", "subagent", RunId.make("other-run")), + ], + expandedRunIds: new Set([runId, RunId.make("other-run")]), + }); + expect(rows.map((row) => row.id)).toEqual([ + "turn-fold:resource-run", + "a", + "c", + "d", + "turn-fold:other-run", + "e", + ]); + expect(rows[1]).toMatchObject({ subagents: [{ item: { id: "a" } }, { item: { id: "b" } }] }); + }); + + it("keeps created-chat summaries after the final answer and folds only their timeline rows", () => { + const timelineEntries = [ + { + kind: "message" as const, + id: "intro", + createdAt: "2026-09-08T10:00:00Z", + message: { + id: MessageId.make("intro"), + role: "assistant" as const, + text: "Creating the chat", + runId, + streaming: false, + createdAt: "2026-09-08T10:00:00Z", + updatedAt: "2026-09-08T10:00:00Z", + }, + }, + event("created", "thread_created"), + { + kind: "message" as const, + id: "final", + createdAt: "2026-09-08T10:00:04Z", + message: { + id: MessageId.make("final"), + role: "assistant" as const, + text: "Chat is ready", + runId, + streaming: false, + createdAt: "2026-09-08T10:00:04Z", + updatedAt: "2026-09-08T10:00:04Z", }, + }, + ]; + const collapsed = deriveMessagesTimelineRows({ ...common, timelineEntries }); + expect(collapsed.map((row) => row.id)).toEqual([ + "turn-fold:resource-run", + "final", + "summary:created", + "assistant-meta:final", + ]); + expect(collapsed.find((row) => row.id === "summary:created")).toMatchObject({ + resourceSummary: true, + }); + const expanded = deriveMessagesTimelineRows({ + ...common, + timelineEntries, + expandedRunIds: new Set([runId]), + }); + expect(expanded.map((row) => row.id)).toEqual([ + "turn-fold:resource-run", + "intro", + "created", + "final", + "summary:created", + "assistant-meta:final", + ]); + }); +}); + +it.each([true, false])( + "keeps a wake notification visible outside folded work, working=%s", + (isWorking) => { + const fixture = makeStreamingTimelineFixture(); + const source = fixture.visibleTurnItems.find((row) => row.item.type === "user_message")!; + if (source.item.type !== "user_message") throw new Error("Expected user message fixture"); + const notification = { + ...source, + item: { + ...source.item, + type: "notification" as const, + source: { kind: "background_task" as const }, + outcome: "completed" as const, + summary: "Delegated task finished", + }, + }; + const entries = deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: fixture.visibleTurnItems.map((row) => + row === source ? notification : row, + ), + optimisticMessages: [], + }); + const rows = deriveMessagesTimelineRows({ + timelineEntries: entries, + isWorking, + runningRunId: fixture.runId, + activeTurnStartedAt: fixture.time(0), + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect( + rows.some( + (row) => + row.kind === "work" && + row.groupedEntries.some((entry) => entry.label === "Delegated task finished"), + ), + ).toBe(true); + }, +); + +it.each([true, false])( + "keeps completed responses folded across notification wakes, working=%s", + (isWorking) => { + const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString(); + const work = (id: string, run: string, second: number, notification = false) => ({ + kind: "work" as const, + id, + createdAt: time(second), + entry: { + id, + runId: RunId.make(run), + createdAt: time(second), + label: id, + tone: "info" as const, + ...(notification ? { itemType: "notification" as const } : {}), + }, + }); + const answer = (id: string, run: string, second: number) => ({ + kind: "message" as const, + id, + createdAt: time(second), + message: { + id: MessageId.make(id), + role: "assistant" as const, + text: id, + runId: RunId.make(run), + createdAt: time(second), + updatedAt: time(second), + streaming: false, + }, + }); + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + work("launch-tools", "initial", 1), + answer("launched", "initial", 5), + work("notification-a", "wake-a", 20, true), + work("read-a", "wake-a", 21), + answer("ack-a", "wake-a", 25), + work("notification-b", "wake-b", 40, true), + work("read-b", "wake-b", 41), + ...(!isWorking ? [answer("ack-b", "wake-b", 45)] : []), ], - isWorking: phase === "running", - activeTurnStartedAt: null, - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), - worktreeSetup: { - threadId: ThreadId.make("setup-thread"), - phase, - startedAt: createdAt, - endedAt: phase === "running" ? null : createdAt, - branch: null, - baseRef: "main", - worktreePath: null, - setupScript: null, - stages: [], - error: null, - sequence: 1, - }, - }); - expect(rows[0]).toMatchObject({ kind: "message", message: { role: "user" } }); - expect(rows[1]).toMatchObject({ kind: "worktree-setup", snapshot: { phase } }); - expect(rows.some((row) => row.kind === "working" || row.kind === "thinking")).toBe(false); + latestRun: { + runId: RunId.make("wake-b"), + status: isWorking ? "running" : "completed", + startedAt: time(40), + completedAt: isWorking ? null : time(45), + }, + isWorking, + activeTurnStartedAt: time(40), + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + const ids = rows.map((row) => row.id); + expect(ids).toContain("turn-fold:initial"); + expect(ids).not.toContain("launch-tools"); + expect(ids).toContain("turn-fold:wake-a"); + expect(ids.indexOf("notification-a")).toBeLessThan(ids.indexOf("turn-fold:wake-a")); + expect(ids.indexOf("turn-fold:wake-a")).toBeLessThan(ids.indexOf("ack-a")); + const boundary = isWorking ? "working-indicator-row" : "turn-fold:wake-b"; + expect(ids).toContain(boundary); + expect(ids.indexOf("notification-b")).toBeLessThan(ids.indexOf(boundary)); + if (isWorking) expect(rows.find((row) => row.id === boundary)?.createdAt).toBe(time(40)); }, ); + +it("shows the worktree setup card instead of the working placeholder", () => { + const snapshot: WorktreeSetupSnapshot = { + threadId: ThreadId.make("thread-setup"), + phase: "running", + startedAt: "2026-01-01T00:00:00Z", + endedAt: null, + branch: "feature", + baseRef: "main", + worktreePath: null, + setupScript: null, + stages: [], + error: null, + sequence: 3, + }; + const userEntry = { + id: "user-entry", + kind: "message", + createdAt: "2026-01-01T00:00:00Z", + message: { + id: "user-1" as never, + role: "user", + text: "Build it", + runId: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + streaming: false, + }, + } as const; + const assistantEntry = { + id: "assistant-entry", + kind: "message", + createdAt: "2026-01-01T00:00:30Z", + message: { + id: "assistant-1" as never, + role: "assistant", + text: "On it", + runId: "turn-1" as never, + createdAt: "2026-01-01T00:00:30Z", + updatedAt: "2026-01-01T00:00:30Z", + streaming: true, + }, + } as const; + const withoutMessages = deriveMessagesTimelineRows({ + timelineEntries: [], + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaries: [], + supportsConversationRollback: false, + worktreeSetup: snapshot, + }); + expect(withoutMessages).toEqual([ + { + kind: "worktree-setup", + id: "worktree-setup-row", + createdAt: "2026-01-01T00:00:00Z", + snapshot, + embedded: false, + }, + ]); + + // A failed setup never handed off, so the card stays under the send. + const withMessages = deriveMessagesTimelineRows({ + timelineEntries: [userEntry, assistantEntry], + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaries: [], + supportsConversationRollback: false, + worktreeSetup: { ...snapshot, phase: "failed" }, + }); + expect(withMessages.map((row) => row.kind)).toEqual([ + "message", + "worktree-setup", + "working", + "message", + ]); + + // Once the agent stage is done the setup script may still be running in + // the background: the turn owns the header and the script row follows it. + const stage = (id: "agent" | "setup-script", status: "done" | "running") => + ({ + id, + status, + startedAt: "2026-01-01T00:00:10Z", + endedAt: status === "done" ? "2026-01-01T00:00:11Z" : null, + percent: null, + detail: null, + tail: [], + }) as const; + const asyncSnapshot: WorktreeSetupSnapshot = { + ...snapshot, + stages: [stage("setup-script", "running"), stage("agent", "done")], + }; + const liveTurn = { + runId: "turn-1" as never, + status: "running", + startedAt: "2026-01-01T00:00:11Z", + completedAt: null, + } as const; + const asyncRows = deriveMessagesTimelineRows({ + timelineEntries: [userEntry], + latestRun: liveTurn, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaries: [], + supportsConversationRollback: false, + worktreeSetup: asyncSnapshot, + }); + expect(asyncRows.map((row) => row.kind)).toEqual([ + "message", + "working", + "worktree-setup", + "thinking", + ]); + expect(asyncRows[2]).toMatchObject({ kind: "worktree-setup", embedded: true }); + + // Dispatched but not yet visible as a turn: the full card stays put so + // nothing collapses during the handoff. + const handoffRows = deriveMessagesTimelineRows({ + timelineEntries: [userEntry], + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaries: [], + supportsConversationRollback: false, + worktreeSetup: asyncSnapshot, + }); + expect(handoffRows.map((row) => row.kind)).toEqual(["message", "worktree-setup"]); + expect(handoffRows[1]).toMatchObject({ kind: "worktree-setup", embedded: false }); + + // A script that already finished has nothing left to show once the turn is live. + const finishedRows = deriveMessagesTimelineRows({ + timelineEntries: [userEntry], + latestRun: liveTurn, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaries: [], + supportsConversationRollback: false, + worktreeSetup: { + ...asyncSnapshot, + stages: [stage("setup-script", "done"), stage("agent", "done")], + }, + }); + expect(finishedRows.map((row) => row.kind)).toEqual(["message", "working", "thinking"]); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 4cd865624795a..22ed19819ac35 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -13,11 +13,10 @@ import { } from "@t3tools/client-runtime/work-log/presentation"; export { normalizeCompactToolLabel, - summarizeToolGroup, toolGroupAction, - workLogEntryIsLocalCodeSearch, } from "@t3tools/client-runtime/work-log/presentation"; import { + deriveRevertTurnCountByUserMessageId, formatDuration, isStreamingMessageTextUpdate, isStreamingTurnItemTextUpdate, @@ -32,10 +31,10 @@ import { import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types"; import { type MessageId, + type WorktreeSetupSnapshot, type OrchestrationV2ProjectedTurnItem, type RunAttemptId, type RunId, - type WorktreeSetupSnapshot, } from "@t3tools/contracts"; import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell"; import { @@ -132,11 +131,11 @@ export function workEntryIsVisibleInGroup( !workEntryIndicatesToolNeutralStatus(entry) ); } -export const TIMELINE_MINIMAP_ITEM_SPACING = 8; +const TIMELINE_MINIMAP_ITEM_SPACING = 8; export const TIMELINE_MINIMAP_MIN_ITEMS = 2; -export const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)"; -export const TIMELINE_CONTENT_MAX_WIDTH = 768; -export const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48; +const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)"; +const TIMELINE_CONTENT_MAX_WIDTH = 768; +const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48; export interface WorkGroupScrollAnchor { readonly entryId: string; @@ -180,7 +179,7 @@ export interface TimelineEndState { * while streaming content grows under the viewport, so follow re-arms within * this distance of the real content bottom instead. */ -export const TIMELINE_FOLLOW_REARM_THRESHOLD_PX = 40; +const TIMELINE_FOLLOW_REARM_THRESHOLD_PX = 40; export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined { if (!state) { @@ -270,9 +269,9 @@ export function resolveTimelineMinimapHasPersistentGutter(viewportWidth: number) return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER; } -export const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12; -export const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40; -export const TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH = "22rem"; +const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12; +const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40; +const TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH = "22rem"; /** * The minimap overlays the viewport's left edge while the content column is @@ -342,6 +341,13 @@ export type TimelineLatestRun = Pick< const LIVE_ACTIVITY_ROW_ID = "live-activity-row"; export type MessagesTimelineRow = + | { + kind: "worktree-setup"; + id: string; + createdAt: string | null; + snapshot: WorktreeSetupSnapshot; + embedded: boolean; + } | { kind: "work"; id: string; @@ -407,6 +413,7 @@ export type MessagesTimelineRow = id: string; createdAt: string; label: string; + active: boolean; } | { kind: "message"; @@ -435,18 +442,14 @@ export type MessagesTimelineRow = id: string; createdAt: string; projectedItem: OrchestrationV2ProjectedTurnItem; + subagents?: ReadonlyArray; + resourceSummary?: boolean; } | { kind: "proposed-plan"; id: string; createdAt: string; proposedPlan: ProposedPlan; - } - | { - kind: "worktree-setup"; - id: string; - createdAt: string | null; - snapshot: WorktreeSetupSnapshot; }; export interface StableMessagesTimelineRowsState { @@ -623,7 +626,10 @@ function timelineEntryFoldRunId(entry: TimelineEntry): RunId | null { if (entry.kind === "work") { return entry.entry.runId ?? null; } - if (entry.kind === "event" && timelineEntryIsPersistentResourceCard(entry)) { + if ( + entry.kind === "event" && + (timelineEntryIsPersistentResourceCard(entry) || entry.projectedItem.item.type === "subagent") + ) { return entry.projectedItem.item.runId; } return null; @@ -633,11 +639,13 @@ function timelineEntryFoldRunId(entry: TimelineEntry): RunId | null { * A promptless provider restart replaces the native turn without adding a * user message. Keep every provider turn since the latest user message in one * visual response until the replacement turn settles. A steer has its own - * user message, so it naturally starts a new visual response. + * user message; an automatic wake has a notification. Both start a new visual response. */ -function lastUserMessageIndex(timelineEntries: ReadonlyArray): number { +function lastResponseBoundaryIndex(timelineEntries: ReadonlyArray): number { return timelineEntries.findLastIndex( - (entry) => entry.kind === "message" && entry.message.role === "user", + (entry) => + (entry.kind === "message" && entry.message.role === "user") || + (entry.kind === "work" && entry.entry.itemType === "notification"), ); } @@ -656,8 +664,12 @@ function deriveActiveVisualResponseRunIds(input: { return runIds; } - const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries); - for (let index = latestUserMessageIndex + 1; index < input.timelineEntries.length; index += 1) { + const latestResponseBoundaryIndex = lastResponseBoundaryIndex(input.timelineEntries); + for ( + let index = latestResponseBoundaryIndex + 1; + index < input.timelineEntries.length; + index += 1 + ) { const runId = timelineEntryRunId(input.timelineEntries[index]!); if (runId !== null) { runIds.add(runId); @@ -668,8 +680,8 @@ function deriveActiveVisualResponseRunIds(input: { /** * Settled turns fold activity before their terminal assistant message behind - * a "Worked for ..." row. A single ordinary activity after that message joins - * the fold, while larger groups and failures stay visible as a trailing summary. + * a "Worked for ..." row. Ordinary trailing work joins the fold, while failures + * and work still in progress stay visible. */ function deriveTurnFolds(input: { timelineEntries: ReadonlyArray; @@ -694,7 +706,7 @@ function deriveTurnFolds(input: { terminalEntry: Extract | null; hasStreamingMessage: boolean; /** - * The user message that kicked the turn off. Entry timestamps alone + * The user message or notification that kicked the turn off. Entry timestamps alone * undercount the duration (the first entry appears only once the * provider starts producing output), and a turn cut short by a steer may * hold a single instantaneous commentary message. @@ -705,8 +717,11 @@ function deriveTurnFolds(input: { let pendingUserBoundary: string | null = null; for (const entry of input.timelineEntries) { - if (entry.kind === "message" && entry.message.role === "user") { - pendingUserBoundary = entry.message.createdAt; + if ( + (entry.kind === "message" && entry.message.role === "user") || + (entry.kind === "work" && entry.entry.itemType === "notification") + ) { + pendingUserBoundary = entry.createdAt; continue; } const runId = timelineEntryFoldRunId(entry); @@ -756,21 +771,19 @@ function deriveTurnFolds(input: { } const isCompaction = entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction"; - const isSingleTrailingActivity = - group.entries.length === terminalEntryIndex + 2 && + const isFoldableTrailingActivity = entry.kind === "work" && + entry.entry.toolLifecycleStatus !== "inProgress" && !workEntryDisplayIndicatesToolFailure(entry.entry); - if (!isCompaction && index > terminalEntryIndex && !isSingleTrailingActivity) { + if (!isCompaction && index > terminalEntryIndex && !isFoldableTrailingActivity) { continue; } // Linked resources can outlive their launching run and stay visible // after the surrounding work folds. - if ( - timelineEntryIsPersistentResourceCard(entry) || - (entry.kind === "work" && entry.entry.questionAnswer !== undefined) - ) { + if (timelineEntryIsPersistentResourceCard(entry)) { continue; } + if (entry.kind === "work" && entry.entry.itemType === "notification") continue; hiddenEntryIds.add(entry.id); } if (hiddenEntryIds.size === 0) { @@ -864,6 +877,15 @@ function attachTrailingToolGroupsToAssistant( lastTrailingWorkIndex = index; continue; } + if ( + candidate.kind === "event" && + candidate.resourceSummary && + candidate.projectedItem.item.runId === runId + ) { + hasTrailingToolGroup = true; + lastTrailingWorkIndex = index; + continue; + } if ( candidate.kind === "work" && candidate.groupedEntries.some((entry) => entry.runId === runId) @@ -920,10 +942,25 @@ export function deriveMessagesTimelineRows(input: { expandedWorkGroupIds?: ReadonlySet; isWorking: boolean; activeTurnStartedAt?: string | null; - turnDiffSummaryByAssistantMessageId: ReadonlyMap; - revertTurnCountByUserMessageId: ReadonlyMap; + turnDiffSummaries: ReadonlyArray; + supportsConversationRollback: boolean; + /** Task ids of subagents still working, used by the active tool indicator. */ + liveAgentTaskIds?: ReadonlySet | undefined; + /** Live bootstrap progress. Renders a stage card under the first user message. */ worktreeSetup?: WorktreeSetupSnapshot | null; }): MessagesTimelineRow[] { + const turnDiffSummaryByAssistantMessageId = new Map(); + for (const summary of input.turnDiffSummaries) { + if (summary.assistantMessageId) { + turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary); + } + } + const revertTurnCountByUserMessageId = input.supportsConversationRollback + ? deriveRevertTurnCountByUserMessageId({ + timelineEntries: input.timelineEntries, + checkpoints: input.turnDiffSummaries, + }) + : new Map(); const nextRows: MessagesTimelineRow[] = []; const durationStartByMessageId = computeMessageDurationStart( input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), @@ -964,13 +1001,19 @@ export function deriveMessagesTimelineRows(input: { entry.toolLifecycleStatus === "inProgress" && entry.runId === unsettledRunId; - // The active run's header row ("Working for ...") anchors right after the - // latest user message, or at the run's first owned work entry when one - // already rendered above it. + // A steer continues the current turn. Keep its elapsed-time header below + // the initiating prompt (or automatic wake), rather than moving it down. let activeTurnHeaderIndex = input.timelineEntries.length; if (input.isWorking) { - const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries); - activeTurnHeaderIndex = latestUserMessageIndex + 1; + activeTurnHeaderIndex = + input.timelineEntries.findLastIndex( + (entry) => + (entry.kind === "message" && + entry.message.role === "user" && + entry.message.inputIntent !== "steer" && + entry.message.inputIntent !== "promoted_queued_to_steer") || + (entry.kind === "work" && entry.entry.itemType === "notification"), + ) + 1; } // Contiguous trailing work entries of the active run collapse into one live @@ -985,9 +1028,9 @@ export function deriveMessagesTimelineRows(input: { if ( entry.kind !== "work" || entry.entry.tone === "error" || - entry.entry.questionAnswer !== undefined || entry.entry.sourceActivityKind === "runtime.error" || entry.entry.itemType === "system_notice" || + entry.entry.itemType === "notification" || entry.entry.runId == null || !activeVisualResponseRunIds.has(entry.entry.runId) || entry.entry.sourceActivityKind === "context-compaction" || @@ -1017,14 +1060,13 @@ export function deriveMessagesTimelineRows(input: { const latestToolKeepsActivityLive = latestRunningToolEntry !== undefined || (latestVisibleToolEntry !== undefined && - (workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry) || - (latestVisibleToolEntry.entry.toolLifecycleStatus === "completed" && - !workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry)))); + workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry)); const latestToolFailed = latestRunningToolEntry === undefined && latestVisibleToolEntry !== undefined && latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" && workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry); + const activeWorkPlacementEntryId = latestVisibleToolEntry?.id; const activeWorkRow = activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed @@ -1048,20 +1090,14 @@ export function deriveMessagesTimelineRows(input: { activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [], ); const appendWorkingRow = () => { - const latestUserMessage = input.timelineEntries[lastUserMessageIndex(input.timelineEntries)]; - const visualResponseStartedAt = - activeVisualResponseRunIds.size > 1 && - latestUserMessage?.kind === "message" && - latestUserMessage.message.role === "user" - ? latestUserMessage.message.createdAt - : input.activeTurnStartedAt; nextRows.push({ kind: "working", id: "working-indicator-row", - createdAt: visualResponseStartedAt ?? null, + createdAt: input.activeTurnStartedAt ?? null, }); }; let hasActivityRow = false; + let hasActiveCompaction = false; const appendActiveWorkRows = () => { if (activeWorkRow === null) return; nextRows.push(activeWorkRow); @@ -1140,21 +1176,24 @@ export function deriveMessagesTimelineRows(input: { timelineEntry.kind === "work" && timelineEntry.entry.sourceActivityKind === "context-compaction" ) { + const active = workEntryIsInActiveRun(timelineEntry.entry); + hasActiveCompaction ||= active; nextRows.push({ kind: "context-compaction", id: timelineEntry.id, createdAt: timelineEntry.createdAt, label: timelineEntry.entry.label, + active, }); continue; } if (timelineEntry.kind === "work") { if ( - timelineEntry.entry.questionAnswer !== undefined || timelineEntry.entry.tone === "error" || timelineEntry.entry.sourceActivityKind === "runtime.error" || - timelineEntry.entry.itemType === "system_notice" + timelineEntry.entry.itemType === "system_notice" || + timelineEntry.entry.itemType === "notification" ) { nextRows.push({ kind: "work", @@ -1172,11 +1211,11 @@ export function deriveMessagesTimelineRows(input: { if ( !nextEntry || nextEntry.kind !== "work" || - nextEntry.entry.questionAnswer !== undefined || nextEntry.entry.sourceActivityKind === "context-compaction" || nextEntry.entry.tone === "error" || nextEntry.entry.sourceActivityKind === "runtime.error" || nextEntry.entry.itemType === "system_notice" || + nextEntry.entry.itemType === "notification" || activeWorkEntryIds.has(nextEntry.id) || collapsedEntryIds.has(nextEntry.id) || collapsedSupersededEntryIds.has(nextEntry.id) || @@ -1304,6 +1343,22 @@ export function deriveMessagesTimelineRows(input: { } if (timelineEntry.kind === "event") { + const previous = nextRows.at(-1); + if ( + timelineEntry.projectedItem.item.type === "subagent" && + previous?.kind === "event" && + previous.projectedItem.item.type === "subagent" && + previous.projectedItem.item.runId === timelineEntry.projectedItem.item.runId + ) { + nextRows[nextRows.length - 1] = { + ...previous, + subagents: [ + ...(previous.subagents ?? [previous.projectedItem]), + timelineEntry.projectedItem, + ], + }; + continue; + } nextRows.push({ kind: "event", id: timelineEntry.id, @@ -1344,24 +1399,32 @@ export function deriveMessagesTimelineRows(input: { assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress, assistantTurnDiffSummary: timelineEntry.message.role === "assistant" - ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id) + ? turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id) : undefined, revertTurnCount: timelineEntry.message.role === "user" - ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id) + ? revertTurnCountByUserMessageId.get(timelineEntry.message.id) : undefined, }); } - // The setup card takes the place of the working and thinking placeholders - // while a worktree is being prepared. It stays after the setup settles so a - // failure and its actions remain visible until the thread state moves on. - if (input.worktreeSetup) { + // Until the agent's turn is live, the setup card takes the place of the + // working and thinking placeholders. It stays after a failed or cancelled + // setup so the outcome and its actions remain visible until the thread + // state moves on. "Live" means the turn is in the timeline, not just that + // the server dispatched it: the card must not collapse in the gap between. + const setupHandedOff = + input.worktreeSetup !== null && + input.worktreeSetup !== undefined && + worktreeSetupAgentStarted(input.worktreeSetup) && + input.latestRun?.startedAt != null; + if (input.worktreeSetup && !setupHandedOff) { const setupRow = { kind: "worktree-setup", id: WORKTREE_SETUP_ROW_ID, createdAt: input.worktreeSetup.startedAt, snapshot: input.worktreeSetup, + embedded: false, } as const; // Sit directly under the first user message: a finished snapshot can // outlive the first assistant reply, and it belongs to the send, not the @@ -1380,7 +1443,32 @@ export function deriveMessagesTimelineRows(input: { if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) { appendWorkingRow(); } - if (input.isWorking && (!hasActivityRow || latestToolFailed)) { + // An async setup script outlives the handoff. The turn owns the header, so + // the script's row sits first under it, ahead of the agent's own work. A + // script that already finished (or never ran) has nothing left to show. + const setupScriptStage = input.worktreeSetup?.stages.find((stage) => stage.id === "setup-script"); + if ( + input.worktreeSetup && + setupHandedOff && + (setupScriptStage?.status === "running" || setupScriptStage?.status === "failed") + ) { + const setupRow = { + kind: "worktree-setup", + id: WORKTREE_SETUP_ROW_ID, + createdAt: input.worktreeSetup.startedAt, + snapshot: input.worktreeSetup, + embedded: true, + } as const; + const workingRowIndex = nextRows.findIndex((row) => row.kind === "working"); + if (workingRowIndex >= 0) { + nextRows.splice(workingRowIndex + 1, 0, setupRow); + } else { + // The turn already finished (or has not been dispatched yet): the row + // trails the reply so a still-running script stays visible after it. + nextRows.push(setupRow); + } + } + if (input.isWorking && !hasActiveCompaction && (!hasActivityRow || latestToolFailed)) { nextRows.push({ kind: "thinking", id: LIVE_ACTIVITY_ROW_ID, @@ -1388,10 +1476,66 @@ export function deriveMessagesTimelineRows(input: { }); } - return attachTrailingToolGroupsToAssistant(nextRows); + return attachTrailingToolGroupsToAssistant( + attachCreatedThreadSummaries(nextRows, input.timelineEntries), + ); } -export const WORKTREE_SETUP_ROW_ID = "worktree-setup-row"; +// Keep created chats below the final answer even when the work that created them folds away. +function attachCreatedThreadSummaries( + rows: MessagesTimelineRow[], + timelineEntries: ReadonlyArray, +): MessagesTimelineRow[] { + const terminalIndexes = new Map(); + const collapsedRuns = new Set(); + const createdByRun = new Map>>(); + for (const [index, row] of rows.entries()) { + if (row.kind === "message" && row.showAssistantMeta && row.message.runId) { + terminalIndexes.set(row.message.runId, index); + } + if (row.kind === "turn-fold" && !row.expanded) collapsedRuns.add(row.runId); + } + for (const entry of timelineEntries) { + const projectedItem = + entry.kind === "work" + ? entry.entry.projectedItem + : entry.kind === "event" + ? entry.projectedItem + : undefined; + if (projectedItem?.item.type === "thread_created" && projectedItem.item.runId) { + const runId = projectedItem.item.runId; + const entries = createdByRun.get(runId) ?? []; + entries.push({ kind: "event", id: entry.id, createdAt: entry.createdAt, projectedItem }); + createdByRun.set(runId, entries); + } + } + return rows.flatMap((row, index): MessagesTimelineRow[] => { + if (row.kind === "event" && row.projectedItem.item.type === "thread_created") { + const runId = row.projectedItem.item.runId; + const terminalIndex = runId === null ? undefined : terminalIndexes.get(runId); + if (terminalIndex !== undefined && (collapsedRuns.has(runId!) || index > terminalIndex)) + return []; + } + if (row.kind === "message" && row.showAssistantMeta && row.message.runId) { + return [ + row, + ...(createdByRun.get(row.message.runId) ?? []).map((entry) => ({ + ...entry, + id: `summary:${entry.id}`, + resourceSummary: true, + })), + ]; + } + return [row]; + }); +} + +const WORKTREE_SETUP_ROW_ID = "worktree-setup-row"; + +/** True once the bootstrap handed off to the agent (async setup script may still run). */ +export function worktreeSetupAgentStarted(snapshot: WorktreeSetupSnapshot): boolean { + return snapshot.stages.some((stage) => stage.id === "agent" && stage.status === "done"); +} type MessagesTimelineRowsInput = Parameters[0]; @@ -1401,13 +1545,13 @@ export interface MessagesTimelineRowsProjection { } function sameCheckpointSummaries( - previous: MessagesTimelineRowsInput["turnDiffSummaryByAssistantMessageId"], - next: MessagesTimelineRowsInput["turnDiffSummaryByAssistantMessageId"], + previous: MessagesTimelineRowsInput["turnDiffSummaries"], + next: MessagesTimelineRowsInput["turnDiffSummaries"], ): boolean { if (previous === next) return true; - if (previous.size !== next.size) return false; - for (const [id, summary] of previous) { - if (!shallow(summary, next.get(id))) return false; + if (previous.length !== next.length) return false; + for (const [index, summary] of previous.entries()) { + if (!shallow(summary, next[index])) return false; } return true; } @@ -1419,15 +1563,19 @@ function replaceStreamingMessageRows( const { timelineEntries: previousEntries, latestRun: previousRun, - turnDiffSummaryByAssistantMessageId: previousCheckpoints, - revertTurnCountByUserMessageId: previousReverts, + turnDiffSummaries: previousCheckpoints, + expandedRunIds: previousExpandedRuns, + expandedAttemptIds: previousExpandedAttempts, + expandedWorkGroupIds: previousExpandedGroups, ...previousContext } = previous.input; const { timelineEntries, latestRun, - turnDiffSummaryByAssistantMessageId, - revertTurnCountByUserMessageId, + turnDiffSummaries, + expandedRunIds, + expandedAttemptIds, + expandedWorkGroupIds, ...context } = input; // V2 shell and checkpoint selectors produce fresh summaries for each event. @@ -1436,8 +1584,10 @@ function replaceStreamingMessageRows( timelineEntries.length !== previousEntries.length || !shallow(previousContext, context) || !shallow(previousRun, latestRun) || - !shallow(previousReverts, revertTurnCountByUserMessageId) || - !sameCheckpointSummaries(previousCheckpoints, turnDiffSummaryByAssistantMessageId) + !shallow(previousExpandedRuns, expandedRunIds) || + !shallow(previousExpandedAttempts, expandedAttemptIds) || + !shallow(previousExpandedGroups, expandedWorkGroupIds) || + !sameCheckpointSummaries(previousCheckpoints, turnDiffSummaries) ) { return null; } @@ -1551,14 +1701,18 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "context-compaction": { const bc = b as typeof a; - return a.createdAt === bc.createdAt && a.label === bc.label; + return a.createdAt === bc.createdAt && a.label === bc.label && a.active === bc.active; } case "proposed-plan": return a.proposedPlan === (b as typeof a).proposedPlan; case "event": - return a.projectedItem === (b as typeof a).projectedItem; + return ( + a.projectedItem === (b as typeof a).projectedItem && + a.resourceSummary === (b as typeof a).resourceSummary && + Equal.equals(a.subagents, (b as typeof a).subagents) + ); case "work": { const bw = b as typeof a; diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index d73f18e871609..1c45f1237774c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -1,6 +1,4 @@ -import { ApprovalRequestId } from "@t3tools/contracts"; import { CheckpointRef, EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts"; - import { act, createRef, useLayoutEffect, type ReactNode, type Ref } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { create, type ReactTestRenderer } from "react-test-renderer"; @@ -9,7 +7,7 @@ import { useComposerFocusState } from "./useComposerFocusState"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import type { LegendListRef } from "@legendapp/list/react"; -const activityTestState = vi.hoisted(() => ({ expanded: false })); +const activityTestState = vi.hoisted(() => ({ expanded: false, expandedRuns: false })); vi.mock("../DiffWorkerPoolProvider", () => ({ DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => children, @@ -23,6 +21,9 @@ vi.mock("./MessagesTimeline.logic", async (importOriginal) => { input: Parameters[0], previous: Parameters[1], ) { + if (activityTestState.expandedRuns) { + input = { ...input, expandedRunIds: new Set([RunId.make("run-1")]) }; + } const projection = logic.deriveMessagesTimelineRowsWithState(input, previous); if (!activityTestState.expanded) return projection; return logic.deriveMessagesTimelineRowsWithState({ @@ -39,6 +40,7 @@ vi.mock("./MessagesTimeline.logic", async (importOriginal) => { beforeEach(() => { activityTestState.expanded = false; + activityTestState.expandedRuns = false; }); vi.mock("@legendapp/list/react", async () => { @@ -219,14 +221,14 @@ function buildProps() { activeTurnInProgress: false, listRef: createRef(), latestRun: null, - turnDiffSummaryByAssistantMessageId: new Map(), + turnDiffSummaries: [], routeThreadKey: "environment-local:thread-1", onOpenTurnDiff: () => {}, onOpenThread: () => {}, onForkFromRun: async () => {}, onRollbackCheckpoint: () => {}, - revertTurnCountByUserMessageId: new Map(), - onRevertUserMessage: () => {}, + supportsConversationRollback: false, + onRevertToTurnCount: () => {}, isRevertingCheckpoint: false, openingVideoAttachmentId: null, onImageExpand: () => {}, @@ -307,104 +309,51 @@ function buildSnapShotTimelineEntry(previewUrl?: string) { } describe("MessagesTimeline", () => { - it("renders previous and next controls with the minimap", () => { - const first = buildUserTimelineEntry("First turn"); - const secondBase = buildUserTimelineEntry("Second turn"); - const second = { - ...secondBase, - id: "entry-2", - message: { - ...secondBase.message, - id: MessageId.make("message-2"), - }, - }; - const markup = renderToStaticMarkup( - , - ); - - expect(markup).toContain('aria-label="Previous turn"'); - expect(markup).toContain('aria-label="Next turn"'); - }); - - // Expanding history uses this suite's existing test renderer, deprecated in - // React 19. Migrate these interaction tests together when a DOM test setup is added. - it.each([{}, { text: "Text-only answer", file: "Answer with a file" }])( - "renders attachment-only question history alongside text answers: %j", - async (answers) => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.stubGlobal("requestAnimationFrame", () => 0); - vi.stubGlobal("cancelAnimationFrame", () => {}); - let renderer: ReactTestRenderer | undefined; - try { - await act(() => { - renderer = create( - { + activityTestState.expanded = true; + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.stubGlobal("requestAnimationFrame", () => 0); + vi.stubGlobal("cancelAnimationFrame", () => {}); + let renderer: ReactTestRenderer | undefined; + try { + await act(() => { + renderer = create( + , - ); - }); - // V2 renders one typed question row rather than a legacy activity wrapper. - const questionToggle = renderer!.root.find( - (node) => - node.props["aria-label"]?.startsWith("Question answer submitted:") && - node.props["aria-expanded"] === false, - ); - expect(questionToggle.props["aria-label"]).toContain( - Object.values(answers)[0] ?? "spec.txt", + }, + ]} + />, ); - expect(JSON.stringify(renderer!.toJSON())).not.toContain("Provide a spec"); - await act(() => questionToggle.props.onClick()); - const markup = JSON.stringify(renderer!.toJSON()); - expect(markup.match(/Provide a spec/g)).toHaveLength(1); - expect(markup).toContain("spec.txt"); - expect(markup).toContain("Provide a screenshot"); - expect(markup).toContain("shot.png"); - for (const answer of Object.values(answers)) expect(markup).toContain(answer); - await act(() => questionToggle.props.onClick()); - expect(JSON.stringify(renderer!.toJSON())).not.toContain("Provide a spec"); - } finally { - await act(() => renderer?.unmount()); - } - }, - ); + }); + const row = renderer!.root.findByProps({ "aria-label": "Example tool" }); + await act(() => row.props.onClick()); + const visible = JSON.stringify(renderer!.toJSON()); + expect(visible).toContain("KEEP_TOOL_INPUT"); + expect(visible).not.toContain("RAW_CACHED_TOOL_OUTPUT"); + await act(() => row.props.onClick()); + expect(JSON.stringify(renderer!.toJSON())).not.toContain("KEEP_TOOL_INPUT"); + } finally { + await act(() => renderer?.unmount()); + } + }); it.each([ { toolLifecycleStatus: "inProgress", isAtEnd: true }, @@ -435,11 +384,12 @@ describe("MessagesTimeline", () => { getState: () => ({ isAtEnd: timelineIsAtEnd }), getScrollableNode: () => null, } as unknown as LegendListRef; - let isResting = true; + let isResting = false; + let composerState: ReturnType | undefined; function ThreadProbe() { const composer = useComposerFocusState(); - useLayoutEffect(() => composer.setIsComposerScrollCollapsed(true), []); useLayoutEffect(() => { + composerState = composer; isResting = shouldUseRestingComposerLayout({ isExistingThread: true, isMobileViewport: false, @@ -479,6 +429,8 @@ describe("MessagesTimeline", () => { await act(() => { renderer = create(); }); + // The user scrolled up to read, so the composer is resting. + await act(() => composerState!.setIsComposerScrollCollapsed(true)); const toggle = renderer!.root.findByProps({ "aria-expanded": false }); await act(() => toggle.props.onClick()); await flushFrame(); @@ -644,10 +596,10 @@ describe("MessagesTimeline", () => { />, ); - expect(markup).toContain('aria-label="Load earlier activity"'); - expect(markup).toContain("Load earlier activity"); + expect(markup).toContain('aria-label="Load earlier turns"'); + expect(markup).toContain("Load earlier turns"); expect(markup).toContain("Earlier activity could not be loaded."); - expect(markup.indexOf("Load earlier activity")).toBeLessThan(markup.indexOf("Recent activity")); + expect(markup.indexOf("Load earlier turns")).toBeLessThan(markup.indexOf("Recent activity")); }); it("keeps an empty bounded timeline actionable while earlier history loads", () => { @@ -664,7 +616,7 @@ describe("MessagesTimeline", () => { />, ); - expect(markup).toContain("Loading earlier activity…"); + expect(markup).toContain("Loading earlier turns…"); expect(markup).toContain("disabled"); expect(markup).not.toContain("Send a message to start the conversation."); }); @@ -713,22 +665,17 @@ describe("MessagesTimeline", () => { }, }, ]} - turnDiffSummaryByAssistantMessageId={ - new Map([ - [ - assistantMessageId, - { - runId, - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("checkpoint-with-files"), - status: "ready", - files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }], - assistantMessageId, - completedAt: MESSAGE_CREATED_AT, - }, - ], - ]) - } + turnDiffSummaries={[ + { + runId, + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("checkpoint-with-files"), + status: "ready", + files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }], + assistantMessageId, + completedAt: MESSAGE_CREATED_AT, + }, + ]} />, ); @@ -881,6 +828,38 @@ describe("MessagesTimeline", () => { expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240); }); + it("renders SnapShot window details after the preview resolves", () => { + const onAnchorReady = vi.fn(); + const firstEntry = buildSnapShotTimelineEntry("data:image/png;base64,iVBORw0KGgo="); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("Terminal"); + expect(markup).toContain("t3code — Tests"); + expect(markup).toContain('src="data:image/png;base64,aWNvbg=="'); + expect(onAnchorReady).toHaveBeenCalledOnce(); + expect(onAnchorReady).toHaveBeenCalledWith(firstEntry.message.id, 0); + }); + + it("does not render SnapShot window details before the preview resolves", () => { + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("screenshot.png"); + expect(markup).not.toContain("Terminal"); + expect(markup).not.toContain("t3code — Tests"); + expect(markup).not.toContain('src="data:image/png;base64,aWNvbg=="'); + expect(markup).not.toContain("h-28 w-52 max-w-full"); + }); + it("does not reserve end space for a follow-up user message", () => { const onAnchorReady = vi.fn(); const firstEntry = buildUserTimelineEntry("First prompt."); @@ -1644,7 +1623,7 @@ describe("MessagesTimeline", () => { expect(bareMarkup).not.toContain("Full conversation context"); }); - it("renders created threads as linked cards outside the work log", async () => { + it("renders created threads as lean rows with inline chat links", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { expect(markup).toContain('data-v2-item-type="thread_created"'); expect(markup).toContain('aria-label="Open Claude research thread"'); expect(markup).toContain("Claude research thread"); - expect(markup).toContain("claude-default · claude-sonnet-4-6"); + expect(markup).toContain("Open chat"); expect(markup).not.toContain("Work Log"); }); @@ -1786,7 +1765,8 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain('aria-label="Hidden work includes a failure"'); }); - it("renders live subagent progress on the persistent linked card", async () => { + it("keeps live subagent progress available on the inline thread link", async () => { + activityTestState.expandedRuns = true; const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { expect(markup).not.toContain("Work Log"); }); - it("discloses the full Codex subagent result without projecting child events", async () => { + it("keeps the completed subagent result on its thread link without a separate disclosure", async () => { + activityTestState.expandedRuns = true; const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { ); expect(markup).toContain('data-v2-item-type="subagent"'); - expect(markup).toContain('data-v2-subagent-result-disclosure="true"'); - expect(markup).toContain('data-v2-subagent-result="true"'); - expect(markup).toContain('aria-label="Show full result for Isolation report"'); + expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); + expect(markup).not.toContain('data-v2-subagent-result="true"'); + expect(markup).toContain('aria-label="Open Isolation report"'); expect(markup).toContain('aria-label="Open Isolation report"'); expect(markup).toContain("Tests should be isolated."); expect(markup).toContain("Result: no shared state."); @@ -1896,6 +1877,7 @@ describe("MessagesTimeline", () => { }); it("keeps live progress when a running subagent streams a partial result", async () => { + activityTestState.expandedRuns = true; const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { }); it("shows the streamed result while a subagent runs without progress", async () => { + activityTestState.expandedRuns = true; const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { }); it("treats a cancelled subagent result as partial output", async () => { + activityTestState.expandedRuns = true; const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { }); it("falls back to progress when a completed subagent result is whitespace-only", async () => { + activityTestState.expandedRuns = true; const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( {}; const NOOP_USE_ARTIFACT_TEMPLATE = () => {}; const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {}; @@ -80,6 +80,7 @@ import { workEntrySignalsSevereFailure, workLogEntryIsToolLike, } from "../../session-logic"; +import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates"; import { type ChatMessage, type ChatFileAttachment, @@ -117,12 +118,12 @@ import { MinusIcon, Redo2Icon, Minimize2Icon, + SearchIcon, SmartphoneIcon, SquarePenIcon, TerminalIcon, Undo2Icon, HammerIcon, - SearchIcon, WrenchIcon, XIcon, ZapIcon, @@ -148,6 +149,10 @@ import { } from "./SnapShotAttachmentDetails"; import { ProposedPlanCard } from "./ProposedPlanCard"; import { ChangedFilesCard } from "./ChangedFilesTree"; +import { + CHAT_TIMELINE_ANCHOR_OFFSET, + timelineContentOverflowsViewport, +} from "./timelineScrollAnchoring"; import { MessageCopyButton } from "./MessageCopyButton"; import { PierreEntryIcon } from "./PierreEntryIcon"; import { inferEntryKindFromPath } from "../../pierre-icons"; @@ -238,7 +243,7 @@ import { isV2LifecycleItem, V2LifecycleRow, type HandoffTimelineRun } from "./V2 import { TimelineSystemDivider } from "./TimelineSystemDivider"; import { SkillInlineText } from "./SkillInlineText"; - +import { deriveAgentSpawnSummary } from "./agentSpawnSummary"; import { formatWorkspaceRelativePath } from "../../filePathDisplay"; import { buildReviewCommentRenderablePatch, @@ -254,7 +259,6 @@ import { // --------------------------------------------------------------------------- interface TimelineRowSharedState { - openPullRequest: (event: MouseEvent, url: string) => void; citationRequest: AssistantCitationTarget | null; listRef: React.RefObject; timestampFormat: TimestampFormat; @@ -269,8 +273,10 @@ interface TimelineRowSharedState { /** Projection runs, for recovering handoff models on legacy items. */ runs: ReadonlyArray; activeThreadEnvironmentId: EnvironmentId; - onRevertUserMessage: (messageId: MessageId) => void; + onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void; + onUseArtifactTemplate: (template: CodexArtifactTemplate) => void; onImageExpand: (preview: ExpandedImagePreview) => void; + displayThreadKey?: string; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void; onForkFromRun: (input: { @@ -284,14 +290,14 @@ interface TimelineRowSharedState { onToggleTurnFold: (runId: RunId) => void; onToggleAttemptFold: (attemptId: RunAttemptId) => void; onFileOpen: (attachment: ChatFileAttachment) => void; - onUseArtifactTemplate: (template: CodexArtifactTemplate) => void; onFileDownload: (attachment: ChatFileAttachment) => void; + openPullRequest: (event: MouseEvent, url: string) => void; onToggleWorkGroup: (groupId: string, anchorKey: string) => void; onToggleWorkEntry: (anchorKey: string, collapsed: boolean) => void; - workGroupViewState: WorkGroupViewState; onCancelWorktreeSetup: (() => void) | null; onWorktreeSetupWorkLocally: (() => void) | null; onOpenWorktreeSetupTerminal: ((terminalId: string) => void) | null; + workGroupViewState: WorkGroupViewState; } interface TimelineRowActivityState { @@ -362,7 +368,6 @@ export interface MessagesTimelineHistoryControls { } interface MessagesTimelineProps { - displayThreadKey?: string; citationRequest?: AssistantCitationRequest | null; citationHistoryLoading?: boolean; onCiteAssistantText?: ( @@ -372,19 +377,20 @@ interface MessagesTimelineProps { isWorking: boolean; activeTurnInProgress: boolean; activeTurnStartedAt?: string | null; - isPreparingWorktree?: boolean; - isCompacting?: boolean; - /** Live bootstrap progress for this thread, or null when none is tracked. */ worktreeSetup?: WorktreeSetupSnapshot | null; onCancelWorktreeSetup?: () => void; onWorktreeSetupWorkLocally?: () => void; onOpenWorktreeSetupTerminal?: (terminalId: string) => void; + isPreparingWorktree?: boolean; + isCompacting?: boolean; + listRef: React.RefObject; timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; runningRunId?: RunId | null; - turnDiffSummaryByAssistantMessageId: Map; + turnDiffSummaries: ReadonlyArray; routeThreadKey: string; + displayThreadKey?: string; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void; parentThreadLink?: { @@ -399,12 +405,12 @@ interface MessagesTimelineProps { readonly checkpointId: string; readonly scopeId: string; }) => void; - revertTurnCountByUserMessageId: Map; - onRevertUserMessage: (messageId: MessageId) => void; + supportsConversationRollback: boolean; + onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void; + onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void; isRevertingCheckpoint: boolean; onImageExpand: (preview: ExpandedImagePreview) => void; onFileOpen?: (attachment: ChatFileAttachment) => void; - onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void; onFileDownload?: (attachment: ChatFileAttachment) => void; activeThreadEnvironmentId: EnvironmentId; markdownCwd: string | undefined; @@ -419,7 +425,6 @@ interface MessagesTimelineProps { onAnchorSizeChanged: (messageId: MessageId, size: number) => void; contentInsetEndAdjustment: number; onIsAtEndChange: (isAtEnd: boolean) => void; - onContentOverflowChange?: (overflows: boolean) => void; /** * Whether the timeline should keep pinning to the live edge as content * grows. Off while the user is reading history; LegendList's own @@ -427,6 +432,11 @@ interface MessagesTimelineProps { * scroll-mode refs whenever the user drifts near the bottom. */ liveFollowEnabled: boolean; + /** + * Whether the real rows extend past the viewport above the composer. + * Reported after scrolls, row size changes, and viewport resizes. + */ + onContentOverflowChange?: (overflows: boolean) => void; onToolOutputCollapsedAtEnd?: () => void; onManualNavigation: () => void; hideEmptyPlaceholder?: boolean; @@ -457,7 +467,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ timelineEntries, latestRun, runningRunId = null, - turnDiffSummaryByAssistantMessageId, + turnDiffSummaries, routeThreadKey, displayThreadKey, onOpenTurnDiff, @@ -465,12 +475,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({ parentThreadLink = null, onForkFromRun, onRollbackCheckpoint, - revertTurnCountByUserMessageId, - onRevertUserMessage, + supportsConversationRollback, + onRevertToTurnCount, + onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE, isRevertingCheckpoint, onImageExpand, onFileOpen = NOOP_OPEN_ATTACHMENT, - onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE, onFileDownload = NOOP_OPEN_ATTACHMENT, activeThreadEnvironmentId, markdownCwd, @@ -494,25 +504,22 @@ export const MessagesTimeline = memo(function MessagesTimeline({ historyControls, loadEarlier = null, }: MessagesTimelineProps) { - const listIdentityKey = displayThreadKey ?? routeThreadKey; - const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState>(new Set()); const [expandedRunIds, setExpandedRunIds] = useState>(new Set()); const [expandedAttemptIds, setExpandedAttemptIds] = useState>( new Set(), ); - useEffect(() => { - setExpandedWorkGroupIds(new Set()); - setExpandedRunIds(new Set()); - setExpandedAttemptIds(new Set()); - }, [listIdentityKey]); + const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState>(new Set()); + const listIdentityKey = displayThreadKey ?? routeThreadKey; + const previousLatestRunRef = useRef(latestRun); const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)"); - const listIdentityRef = useRef(listIdentityKey); - const previousLatestTurnRef = useRef(latestRun); - const [settlingListIdentity, setSettlingListIdentity] = useState(null); - if (listIdentityRef.current !== listIdentityKey) { - listIdentityRef.current = listIdentityKey; - previousLatestTurnRef.current = latestRun; + const [settlingListIdentity, setSettlingListIdentity] = useState(listIdentityKey); + const [expansionThreadKey, setExpansionThreadKey] = useState(listIdentityKey); + if (expansionThreadKey !== listIdentityKey) { + setExpansionThreadKey(listIdentityKey); setSettlingListIdentity(listIdentityKey); + setExpandedRunIds(new Set()); + setExpandedAttemptIds(new Set()); + setExpandedWorkGroupIds(new Set()); } const citationThreadRef = useMemo(() => parseScopedThreadKey(routeThreadKey), [routeThreadKey]); const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined); @@ -635,7 +642,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ // An in-session interrupt leaves its turn expanded so the user keeps their // place; the next turn (or a reload, since this is local state) folds it. - const previousLatestRunRef = useRef(latestRun); + useEffect(() => { const previous = previousLatestRunRef.current; previousLatestRunRef.current = latestRun; @@ -667,8 +674,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({ readonly workspaceRoot: string | undefined; readonly projection: MessagesTimelineRowsProjection; } | null>(null); - // Match the row header's liveness, retaining projection input identity - // across unrelated panel updates. const rawRows = useMemo(() => { const previous = rowsProjectionRef.current; const projection = deriveMessagesTimelineRowsWithState( @@ -681,8 +686,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ expandedWorkGroupIds, isWorking, activeTurnStartedAt, - turnDiffSummaryByAssistantMessageId, - revertTurnCountByUserMessageId, + turnDiffSummaries, + supportsConversationRollback, worktreeSetup, }, previous?.threadKey === listIdentityKey && previous.workspaceRoot === workspaceRoot @@ -703,8 +708,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ expandedWorkGroupIds, isWorking, activeTurnStartedAt, - turnDiffSummaryByAssistantMessageId, - revertTurnCountByUserMessageId, + turnDiffSummaries, + supportsConversationRollback, worktreeSetup, ]); const rows = useStableRows(rawRows, listIdentityKey); @@ -909,7 +914,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ providerStatuses, runs, activeThreadEnvironmentId, - onRevertUserMessage, + onRevertToTurnCount, onImageExpand, onFileOpen, onUseArtifactTemplate, @@ -923,10 +928,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onToggleAttemptFold, onToggleWorkGroup, onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure, - workGroupViewState, onCancelWorktreeSetup: onCancelWorktreeSetup ?? null, onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null, onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null, + workGroupViewState, }), [ readyCitationRequest, @@ -941,7 +946,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ providerStatuses, runs, activeThreadEnvironmentId, - onRevertUserMessage, + onRevertToTurnCount, onImageExpand, onFileOpen, onUseArtifactTemplate, @@ -955,23 +960,25 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onToggleAttemptFold, onToggleWorkGroup, suspendEndScrollMaintenanceForDisclosure, - workGroupViewState, onCancelWorktreeSetup, onWorktreeSetupWorkLocally, onOpenWorktreeSetupTerminal, + workGroupViewState, ], ); + const compactionAwaitingRow = + isCompacting && !rows.some((row) => row.kind === "context-compaction" && row.active); const activityState = useMemo( () => ({ isWorking, - isCompacting, + isCompacting: compactionAwaitingRow, isRevertingCheckpoint, activeTurnInProgress, isPreparingWorktree, latestRunId: latestRun?.runId ?? null, }), [ - isCompacting, + compactionAwaitingRow, activeTurnInProgress, isPreparingWorktree, isRevertingCheckpoint, @@ -1122,18 +1129,17 @@ function TimelineHistoryControl(props: MessagesTimelineHistoryControls) { } return (
    -
    +
    {props.hasMoreHistory ? ( - + {props.loading ? "Loading earlier turns…" : "Load earlier turns"} + ) : null} {props.error !== null ? (

    @@ -1467,6 +1473,7 @@ type TimelineRow = MessagesTimelineRow; const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: TimelineRow }) { const isExpandedToolGroup = row.kind === "work" && row.isExpandedToolGroup; + const isSubagentGroup = row.kind === "event" && row.projectedItem.item.type === "subagent"; const isExpandedToolGroupHeader = (row.kind === "work-toggle" && row.expanded) || (row.kind === "work-live" && row.expanded); @@ -1475,7 +1482,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time className={cn( // Commentary (non-terminal assistant) rows carry no metadata row, so // they sit closer to the work that follows them. - isExpandedToolGroup + isExpandedToolGroup || isSubagentGroup ? "pb-1" : isExpandedToolGroupHeader ? "pb-0" @@ -1488,9 +1495,9 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time row.kind === "work-live" || row.kind === "work-toggle" || row.kind === "thinking" || + row.kind === "worktree-setup" || row.kind === "event" || - row.kind === "attempt-fold" || - row.kind === "worktree-setup" + row.kind === "attempt-fold" ? "pb-2" : "pb-4", (row.kind === "message" && row.message.role === "assistant") || @@ -1526,8 +1533,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time {row.kind === "proposed-plan" ? : null} {row.kind === "working" ? : null} {row.kind === "thinking" ? : null} - {row.kind === "event" ? : null} {row.kind === "worktree-setup" ? : null} + {row.kind === "event" ? : null}

    ); }); @@ -1547,8 +1554,11 @@ function WorktreeSetupTimelineRow({ return ( ); @@ -1566,9 +1576,22 @@ function ContextCompactionTimelineRow({ className="mx-auto flex w-full max-w-3xl items-center gap-3 py-1 text-muted-foreground text-xs" > - -
    @@ -1605,6 +1628,10 @@ function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) { } label={file.name} preload="visible" + onOpen={() => { + const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file); + if (preview) ctx.onImageExpand(preview); + }} className="block aspect-[4/3] w-full" videoClassName="aspect-auto size-full rounded-lg border border-border/80" stateClassName="aspect-auto min-h-full rounded-lg border border-border/80 bg-black text-white" @@ -1657,6 +1684,7 @@ function UserTimelineRow({ row }: { row: Extract !isImageAttachment(attachment) && !isFileAttachment(attachment), ); + const userMessage = resolveUserMessagePresentation(row.message); const resolvedContext = useMemo(() => resolveUserMessageContext(row.message), [row.message]); const previewImages = useMemo( () => userImages.filter((image) => image.name.startsWith("preview-annotation-")), @@ -1782,7 +1810,27 @@ function UserTimelineRow({ row }: { row: Extract - {row.message.createdBy === "agent" ? ( + {userMessage.isAutomation ? ( +

    + {userMessage.scheduledTaskId ? ( + + Sent by automation + + ) : ( + "Sent by automation" + )} +

    + ) : row.message.createdBy === "agent" ? (

    ) : null} -

    +
    {typeof revertTurnCount === "number" && ( - + )} {resolvedContext.text && ( ; - recordsById: ReadonlyMap; - userImages: ReadonlyArray; - previewImages: ReadonlyArray; - annotationRecordIds: ReadonlyArray; -}): ChatImageAttachment | null { - const screenshotRecord = input.record.screenshotContextId - ? asKnownContextRecord(input.recordsById.get(input.record.screenshotContextId)) - : undefined; - return ( - (screenshotRecord?.kind === "image" - ? input.userImages.find((image) => image.id === screenshotRecord.attachmentId) - : undefined) ?? - input.previewImages.find( - (image) => image.name === `preview-annotation-${input.record.annotationId}.png`, - ) ?? - input.previewImages[input.annotationRecordIds.indexOf(input.record.contextId)] ?? - null - ); -} - function UserMessageIntentMarker({ intent, }: { - readonly intent: NonNullable; + readonly intent: NonNullable; }) { const presentation = intent === "queued_turn" @@ -2023,7 +2049,35 @@ function UserMessageIntentMarker({ ); } -function RevertUserMessageButton({ messageId }: { messageId: MessageId }) { +export function resolvePreviewAnnotationImage(input: { + record: Extract; + recordsById: ReadonlyMap; + userImages: ReadonlyArray; + previewImages: ReadonlyArray; + annotationRecordIds: ReadonlyArray; +}): ChatImageAttachment | null { + const screenshotRecord = input.record.screenshotContextId + ? asKnownContextRecord(input.recordsById.get(input.record.screenshotContextId)) + : undefined; + return ( + (screenshotRecord?.kind === "image" + ? input.userImages.find((image) => image.id === screenshotRecord.attachmentId) + : undefined) ?? + input.previewImages.find( + (image) => image.name === `preview-annotation-${input.record.annotationId}.png`, + ) ?? + input.previewImages[input.annotationRecordIds.indexOf(input.record.contextId)] ?? + null + ); +} + +function RevertUserMessageButton({ + turnCount, + messageId, +}: { + turnCount: number; + messageId: MessageId; +}) { const ctx = use(TimelineRowCtx); const activity = use(TimelineRowActivityCtx); @@ -2036,8 +2090,8 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) { size="xs" variant="ghost" disabled={activity.isRevertingCheckpoint || activity.isWorking} - onClick={() => ctx.onRevertUserMessage(messageId)} - aria-label="Revert to this message" + onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)} + aria-label="Edit from here" /> } > @@ -2360,20 +2414,6 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): { icon: MinusIcon, }; } - case "approval_request": - return { - label: "Approval requested", - detail: item.prompt ?? item.requestKind, - tone: item.status === "failed" ? "danger" : "warning", - icon: MessageCircleIcon, - }; - case "user_input_request": - return { - label: "Input requested", - detail: item.questions.map((question) => question.question).join("\n"), - tone: item.status === "failed" ? "danger" : "warning", - icon: MessageCircleIcon, - }; case "todo_list": { const steps = item.steps.map((step) => `${step.status}: ${step.text}`).join("\n"); return { @@ -2396,10 +2436,31 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): { function V2EventTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const { item, visibility, sourceThreadId } = row.projectedItem; + if (item.type === "subagent") { + return ( +
    + {(row.subagents ?? [row.projectedItem]).map((projected) => ( + + ))} +
    + ); + } if (isV2LifecycleItem(item)) { return ( void; }) { if (!turnSummary) return null; @@ -3126,6 +3190,7 @@ function AssistantChangedFilesSectionInner({ checkpointFiles: TurnDiffSummary["files"]; routeThreadKey: string; resolvedTheme: "light" | "dark"; + displayThreadKey?: string; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; }) { const persistedExpanded = useUiStateStore( @@ -4227,7 +4292,7 @@ function buildToolCallExpandedBody( viewedImagePath: string | null, ): string | null { const blocks: string[] = []; - const seen = new Set(); + const seen = new Set([visibleLabel.trim()]); const addBlock = (value: string | null | undefined) => { const text = value?.trim(); if (!text || seen.has(text)) return; @@ -4235,7 +4300,15 @@ function buildToolCallExpandedBody( blocks.push(text); }; if (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) { - addBlock(`Tool call\n${JSON.stringify(workEntry.toolData, null, 2)}`); + const input = + workEntry.structuredPayload?.type === "dynamic_tool" + ? workEntry.structuredPayload.input + : workEntry.toolData !== null && + typeof workEntry.toolData === "object" && + "input" in workEntry.toolData + ? workEntry.toolData.input + : undefined; + if (input !== undefined) addBlock(`Tool input\n${JSON.stringify(input, null, 2)}`); } const command = workEntry.command?.trim(); const raw = workEntryRawCommand(workEntry); @@ -4266,7 +4339,7 @@ function buildToolCallExpandedBody( addBlock([...new Set(changedFiles)].join("\n")); } if (workEntry.structuredPayload !== undefined) { - const structured = JSON.stringify(workEntry.structuredPayload, null, 2); + const structured = JSON.stringify(toolItemForDisplay(workEntry.structuredPayload), null, 2); if (structured && !blocks.includes(structured)) { blocks.push(structured); } @@ -4286,12 +4359,10 @@ const toolCallExpandedBodyClassName = "max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-secondary-label text-[length:var(--font-size-code,0.6875rem)] leading-relaxed select-text"; function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName { - if ( - workEntry.itemType === "user_input_request" || - workEntry.questionAnswer || - workEntry.sourceActivityKind === "user-input.requested" || - workEntry.sourceActivityKind === "user-input.resolved" - ) { + if (workEntry.structuredPayload?.type === "notification") { + return workEntry.structuredPayload.outcome === "failed" ? "circle-alert" : "zap"; + } + if (workEntry.itemType === "user_input_request" || workEntry.itemType === "approval_request") { return "message-circle"; } if (workEntry.toolSurface) return workEntry.toolSurface; @@ -4334,6 +4405,10 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { const { workEntry, workspaceRoot, isExpandedToolGroupEntry = false, displayLabel } = props; const ctx = use(TimelineRowCtx); const { threadRef, onImageExpand } = ctx; + const createdThread = + workEntry.projectedItem?.item.type === "thread_created" + ? workEntry.projectedItem.item + : undefined; const groupView = use(WorkGroupViewCtx); const [expanded, setExpanded] = useState( () => groupView?.state.expandedEntries.has(workEntry.id) ?? false, @@ -4361,9 +4436,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { showWarningIndicator || showDestructiveRowStyle ? undefined : (workEntry.toolIcon ?? workEntry.toolSource?.icon); - const previewText = workEntry.questionAnswer - ? workEntry.label - : (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot)); + const previewText = displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot); const answerPreview = workEntry.questionAnswer ? getQuestionAnswerPreview(workEntry.questionAnswer) : null; @@ -4376,9 +4449,8 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { }) : null; const canExpand = + previewText.trim().length > 0 || (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) || - Boolean(workEntry.questionAnswer) || - (showFailedIndicator && previewText.trim().length > 0) || Boolean( workEntryRawCommand(workEntry) || workEntry.command?.trim() || @@ -4394,8 +4466,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { viewedImage ? viewedImagePath : null, ) : null; - const canExpandProjectedItem = - canExpand || workEntry.questionAnswer !== undefined || workEntry.projectedItem !== undefined; + const canExpandProjectedItem = canExpand || workEntry.projectedItem !== undefined; // Reserve destructive row styling for severe failures, not routine tool errors. const iconWrapperClass = cn( "flex size-6 shrink-0 items-center justify-center", @@ -4439,7 +4510,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { return (
    + {createdThread ? ( + + ) : null} {showFailedIndicator && !showDestructiveRowStyle && !toolIconAcceptsTint(entryIconName, entryToolIcon) ? ( @@ -4506,10 +4589,10 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { )} aria-hidden > - @@ -4527,22 +4610,24 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { alt={viewedImage.alt} srcFragment={viewedImage.srcFragment} workspaceRoot={workspaceRoot} - style={{ maxHeight: "16rem" }} + maxHeightRem={16} onImageExpand={onImageExpand} />
    ) : null} + {expanded && workEntry.questionAnswer ? ( + + ) : null} {expanded && + !workEntry.questionAnswer && canExpandProjectedItem && - (expandedBody || workEntry.projectedItem || workEntry.questionAnswer) ? ( + (expandedBody || workEntry.projectedItem) ? (
    - {workEntry.questionAnswer ? ( - - ) : workEntry.projectedItem ? ( + {workEntry.projectedItem ? ( void; }) { - const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null; const providerLabel = props.model.subProvider ? `${props.providerDisplayName} · ${props.model.subProvider}` : props.providerDisplayName; @@ -85,7 +86,14 @@ export const ModelListRow = memo(function ModelListRow(props: {
    {props.showProvider && (
    - {ProviderIcon ? : null} + {providerLabel} diff --git a/apps/web/src/components/chat/ModelPickerContent.test.ts b/apps/web/src/components/chat/ModelPickerContent.test.ts index 5b9cfd0ff5f29..50db51bfa068c 100644 --- a/apps/web/src/components/chat/ModelPickerContent.test.ts +++ b/apps/web/src/components/chat/ModelPickerContent.test.ts @@ -8,6 +8,7 @@ import { describe, expect, it } from "vite-plus/test"; import { deriveProviderInstanceEntries } from "../../providerInstances"; import { + adjacentModelPickerProvider, resolveModelPickerSelectedModel, shouldIncludeModelPickerOption, shouldOfferModelPickerSetup, @@ -213,3 +214,74 @@ describe("shouldOfferModelPickerSetup", () => { ).toBe(true); }); }); + +describe("adjacentModelPickerProvider", () => { + const codex = entry("ready", "codex"); + const claude = entry("ready", "claudeAgent"); + const unavailable = entry("error"); + const input = { + entries: [codex, unavailable, claude], + disabledInstanceIds: undefined, + selectableUnavailableInstanceIds: undefined, + }; + + it("wraps through favorites and ready instances, skipping unavailable providers", () => { + expect( + adjacentModelPickerProvider({ ...input, selectedInstanceId: codex.instanceId, direction: 1 }), + ).toBe(claude.instanceId); + expect( + adjacentModelPickerProvider({ ...input, selectedInstanceId: "favorites", direction: -1 }), + ).toBe(claude.instanceId); + expect( + adjacentModelPickerProvider({ + ...input, + selectedInstanceId: claude.instanceId, + direction: 1, + }), + ).toBe("favorites"); + }); + + it("keeps thread locks and the selected unavailable catalog", () => { + expect( + adjacentModelPickerProvider({ + ...input, + disabledInstanceIds: new Set([claude.instanceId]), + selectedInstanceId: codex.instanceId, + direction: 1, + }), + ).toBe("favorites"); + expect( + adjacentModelPickerProvider({ + ...input, + selectableUnavailableInstanceIds: new Set([unavailable.instanceId]), + selectedInstanceId: codex.instanceId, + direction: 1, + }), + ).toBe(unavailable.instanceId); + }); + + it("handles an empty catalog and a removed selection in either direction", () => { + expect( + adjacentModelPickerProvider({ + ...input, + entries: [], + selectedInstanceId: codex.instanceId, + direction: -1, + }), + ).toBe("favorites"); + expect( + adjacentModelPickerProvider({ + ...input, + selectedInstanceId: unavailable.instanceId, + direction: 1, + }), + ).toBe("favorites"); + expect( + adjacentModelPickerProvider({ + ...input, + selectedInstanceId: unavailable.instanceId, + direction: -1, + }), + ).toBe(claude.instanceId); + }); +}); diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 63dea7844c468..7059d06f6c31e 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -57,6 +57,8 @@ type ModelPickerItem = { driverKind: ProviderDriverKind; instanceDisplayName: string; instanceAccentColor?: string | undefined; + acpRegistryAgentId?: string | undefined; + acpRegistryIconUrl?: string | undefined; continuationGroupKey?: string | undefined; isLegacy?: boolean | undefined; isUnavailable?: boolean | undefined; @@ -113,6 +115,34 @@ export function shouldOfferModelPickerSetup( ); } +export function adjacentModelPickerProvider(input: { + entries: ReadonlyArray; + selectedInstanceId: ProviderInstanceId | "favorites"; + direction: 1 | -1; + disabledInstanceIds: ReadonlySet | undefined; + selectableUnavailableInstanceIds: ReadonlySet | undefined; +}) { + const providers: Array = [ + "favorites", + ...input.entries + .filter( + (entry) => + !input.disabledInstanceIds?.has(entry.instanceId) && + (isProviderInstancePickerReady(entry) || + input.selectableUnavailableInstanceIds?.has(entry.instanceId)), + ) + .map((entry) => entry.instanceId), + ]; + const index = providers.indexOf(input.selectedInstanceId); + return providers[ + index < 0 + ? input.direction === 1 + ? 0 + : providers.length - 1 + : (index + input.direction + providers.length) % providers.length + ]!; +} + const EMPTY_MODEL_JUMP_LABELS = new Map(); function ModelListSeparator() { @@ -339,6 +369,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { driverKind: entry.driverKind, instanceDisplayName: entry.displayName, ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}), + ...(entry.acpRegistryAgentId ? { acpRegistryAgentId: entry.acpRegistryAgentId } : {}), + ...(entry.acpRegistryIconUrl ? { acpRegistryIconUrl: entry.acpRegistryIconUrl } : {}), ...(entry.continuationGroupKey ? { continuationGroupKey: entry.continuationGroupKey } : {}), @@ -687,6 +719,20 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { platform: navigator.platform, context: modelJumpShortcutContext, }); + if (command === "modelPicker.previousProvider" || command === "modelPicker.nextProvider") { + event.preventDefault(); + event.stopPropagation(); + const next = adjacentModelPickerProvider({ + entries: sidebarInstanceEntries, + selectedInstanceId, + direction: command === "modelPicker.nextProvider" ? 1 : -1, + disabledInstanceIds: lockedDisabledInstanceIds, + selectableUnavailableInstanceIds, + }); + setSearchQuery(""); + handleSelectInstance(next); + return; + } const jumpIndex = modelPickerJumpIndexFromCommand(command ?? ""); if (jumpIndex === null) { return; @@ -710,7 +756,17 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { return () => { window.removeEventListener("keydown", onWindowKeyDown, true); }; - }, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]); + }, [ + handleModelSelect, + handleSelectInstance, + keybindings, + lockedDisabledInstanceIds, + modelJumpModelKeys, + modelJumpShortcutContext, + selectableUnavailableInstanceIds, + selectedInstanceId, + sidebarInstanceEntries, + ]); useLayoutEffect(() => { setShowTopScrollFade(false); @@ -737,6 +793,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { setSearchQuery(e.target.value)} onKeyDown={(e) => { + if ( + showSidebar && + !e.altKey && + !e.ctrlKey && + !e.metaKey && + ((e.key === "ArrowLeft" && !e.shiftKey && searchQuery.length === 0) || + (e.key === "Tab" && e.shiftKey)) + ) { + const sidebar = e.currentTarget + .closest("[data-model-picker-content]") + ?.querySelector("[data-model-picker-sidebar]"); + const button = + sidebar?.querySelector( + 'button[aria-pressed="true"]:not(:disabled)', + ) ?? sidebar?.querySelector("button:not(:disabled)"); + if (button) { + e.preventDefault(); + e.stopPropagation(); + button.focus(); + return; + } + } if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); @@ -889,6 +968,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { driverKind={model.driverKind} providerDisplayName={model.instanceDisplayName} providerAccentColor={model.instanceAccentColor} + acpRegistryAgentId={model.acpRegistryAgentId} + acpRegistryIconUrl={model.acpRegistryIconUrl} isFavorite={favoritesSet.has( providerModelKey(model.instanceId, model.slug), )} diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx index dd53270268ba4..927b1bb3f2f0c 100644 --- a/apps/web/src/components/chat/ModelPickerSidebar.tsx +++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx @@ -1,3 +1,4 @@ +import { Toolbar } from "@base-ui/react/toolbar"; import { type ProviderInstanceId } from "@t3tools/contracts"; import { memo, useLayoutEffect, useRef, useState } from "react"; import { SparklesIcon, StarIcon } from "lucide-react"; @@ -43,6 +44,7 @@ const PICKER_TOOLTIP_CLASS = "max-w-64 text-balance font-normal leading-snug"; export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { selectedInstanceId: ProviderInstanceId | "favorites"; onSelectInstance: (instanceId: ProviderInstanceId | "favorites") => void; + onFocusSearch: () => void; /** * Instance entries to render as rail buttons. Each entry becomes one icon * keyed by `instanceId`, so the default built-in Codex and a user-authored @@ -87,7 +89,20 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { }, [props.instanceEntries, props.selectedInstanceId, showFavorites]); return ( -
    + { + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; + if (event.key === "ArrowRight") { + event.preventDefault(); + props.onFocusSearch(); + return; + } + }} + >
    {selectedIndicatorTop !== null ? ( @@ -107,16 +122,17 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { handleSelect("favorites")} type="button" aria-label="Favorites" + aria-pressed={props.selectedInstanceId === "favorites"} > - + } /> (current === entry.instanceId ? null : current)) } disabled={isDisabled} + focusableWhenDisabled={!isDisabled} + aria-pressed={isSelected} type="button" aria-label={ isUnavailable || isContextDisabled @@ -184,6 +202,8 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { driverKind={entry.driverKind} displayName={entry.displayName} accentColor={entry.accentColor} + acpRegistryAgentId={entry.acpRegistryAgentId} + acpRegistryIconUrl={entry.acpRegistryIconUrl} showBadge={showInstanceBadge} className="size-6" iconClassName="size-5" @@ -203,7 +223,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { ) : null} - + ); const trigger = isDisabled ? ( @@ -234,6 +254,6 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { })}
    -
    + ); }); diff --git a/apps/web/src/components/chat/OpenInPicker.test.ts b/apps/web/src/components/chat/OpenInPicker.test.ts index 96c9795bd5a9e..df4b668c882a2 100644 --- a/apps/web/src/components/chat/OpenInPicker.test.ts +++ b/apps/web/src/components/chat/OpenInPicker.test.ts @@ -1,3 +1,6 @@ +import { FolderClosedIcon } from "lucide-react"; +import { FileExplorerIcon, FinderIcon } from "../Icons"; +import { resolveOpenInOptions } from "./OpenInPicker"; import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; @@ -61,3 +64,24 @@ describe("shouldShowOpenInPicker", () => { ).toBe(false); }); }); + +describe("resolveOpenInOptions", () => { + it.each([ + ["MacIntel", "Finder", FinderIcon], + ["Win32", "File Explorer", FileExplorerIcon], + ["Linux x86_64", "Files", FolderClosedIcon], + ] as const)("includes the file manager with its icon on %s", (platform, label, Icon) => { + expect(resolveOpenInOptions(platform, ["cursor", "vscode", "file-manager"])).toEqual([ + expect.objectContaining({ value: "cursor", label: "Cursor" }), + expect.objectContaining({ value: "vscode", label: "VS Code" }), + expect.objectContaining({ value: "file-manager", label, Icon }), + ]); + }); + + it("omits the file manager when unavailable or using remote editors", () => { + expect(resolveOpenInOptions("MacIntel", ["vscode"])).toEqual([ + expect.objectContaining({ value: "vscode" }), + ]); + expect(resolveOpenInOptions("MacIntel", [])).toEqual([]); + }); +}); diff --git a/apps/web/src/components/chat/ProviderInstanceIcon.test.ts b/apps/web/src/components/chat/ProviderInstanceIcon.test.ts new file mode 100644 index 0000000000000..edc68c599fb05 --- /dev/null +++ b/apps/web/src/components/chat/ProviderInstanceIcon.test.ts @@ -0,0 +1,32 @@ +import { ProviderDriverKind } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { resolveProviderInstanceAcpRegistryIconUrl } from "./ProviderInstanceIcon"; + +describe("resolveProviderInstanceAcpRegistryIconUrl", () => { + it("uses allowlisted catalog metadata and rejects untrusted overrides", () => { + expect( + resolveProviderInstanceAcpRegistryIconUrl({ + driverKind: ProviderDriverKind.make("acpRegistry"), + agentId: "kilo", + iconUrl: "https://cdn.agentclientprotocol.com/registry/icons/kilo.svg", + }), + ).toBe("https://cdn.agentclientprotocol.com/registry/icons/kilo.svg"); + expect( + resolveProviderInstanceAcpRegistryIconUrl({ + driverKind: ProviderDriverKind.make("acpRegistry"), + agentId: "generic-agent", + iconUrl: "https://example.com/not-official.svg", + }), + ).toBe("https://cdn.agentclientprotocol.com/registry/v1/latest/generic-agent.svg"); + }); + + it("does not resolve registry icons for other provider drivers", () => { + expect( + resolveProviderInstanceAcpRegistryIconUrl({ + driverKind: ProviderDriverKind.make("codex"), + agentId: "kilo", + }), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/ProviderInstanceIcon.tsx b/apps/web/src/components/chat/ProviderInstanceIcon.tsx index 4a40ed15bcb32..95f672df9abba 100644 --- a/apps/web/src/components/chat/ProviderInstanceIcon.tsx +++ b/apps/web/src/components/chat/ProviderInstanceIcon.tsx @@ -1,16 +1,54 @@ import { type CSSProperties, memo } from "react"; -import { type ProviderDriverKind } from "@t3tools/contracts"; + import { providerInstanceInitials } from "@t3tools/client-runtime/state/provider-instance-display"; -import { PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils"; +import { ProviderDriverKind } from "@t3tools/contracts"; +import { + AntigravityIcon, + ClaudeAI, + CursorIcon, + GrokIcon, + Icon, + OpenAI, + OpenCodeIcon, + PiAgentIcon, +} from "../Icons"; + import { cn } from "~/lib/utils"; +import { + AcpRegistryAgentIcon, + officialAcpRegistryIconUrlForAgentId, + resolveOfficialAcpRegistryIconUrl, +} from "../settings/AcpRegistryIcon"; + +const PROVIDER_ICON_BY_PROVIDER: Partial> = { + [ProviderDriverKind.make("codex")]: OpenAI, + [ProviderDriverKind.make("claudeAgent")]: ClaudeAI, + [ProviderDriverKind.make("opencode")]: OpenCodeIcon, + [ProviderDriverKind.make("cursor")]: CursorIcon, + [ProviderDriverKind.make("grok")]: GrokIcon, + [ProviderDriverKind.make("antigravity")]: AntigravityIcon, + [ProviderDriverKind.make("pi")]: PiAgentIcon, +}; -export { providerInstanceInitials }; +export function resolveProviderInstanceAcpRegistryIconUrl(input: { + readonly driverKind: ProviderDriverKind; + readonly agentId?: string | undefined; + readonly iconUrl?: string | undefined; +}): string | null { + if (input.driverKind !== "acpRegistry") return null; + return ( + resolveOfficialAcpRegistryIconUrl(input.iconUrl ?? null) ?? + officialAcpRegistryIconUrlForAgentId(input.agentId?.trim() || null) + ); +} export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: { driverKind: ProviderDriverKind; displayName: string; accentColor?: string | undefined; + acpRegistryAgentId?: string | undefined; + acpRegistryIconUrl?: string | undefined; showBadge?: boolean; badgeContent?: "initials" | "none"; className?: string; @@ -25,6 +63,12 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: { ? ({ "--provider-accent": props.accentColor } as CSSProperties) : undefined; const badgeContent = props.badgeContent ?? "initials"; + const isAcpRegistry = props.driverKind === "acpRegistry"; + const acpRegistryIconUrl = resolveProviderInstanceAcpRegistryIconUrl({ + driverKind: props.driverKind, + agentId: props.acpRegistryAgentId, + iconUrl: props.acpRegistryIconUrl, + }); return ( - {Icon ? ( + {isAcpRegistry ? ( + + ) : Icon ? ( ) : ( diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 6f777399451d0..e1c689599a9d8 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -42,6 +42,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { activeProviderIconClassName?: string; instanceIndicatorBackground?: string; size?: ComposerControlSize; + compact?: boolean; isComposerOwned?: boolean; disabled?: boolean; terminalOpen?: boolean; @@ -173,7 +174,9 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { data-chat-provider-model-picker="true" className={cn( "min-w-0 shrink justify-between whitespace-nowrap", - !props.isComposerOwned && "max-w-48 sm:max-w-56", + props.compact + ? "max-w-42 shrink-0" + : !props.isComposerOwned && "max-w-48 sm:max-w-56", props.triggerClassName, )} disabled={props.disabled} @@ -188,6 +191,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { driverKind={activeEntry.driverKind} displayName={activeEntry.displayName} accentColor={activeEntry.accentColor} + acpRegistryAgentId={activeEntry.acpRegistryAgentId} + acpRegistryIconUrl={activeEntry.acpRegistryIconUrl} showBadge={showInstanceBadge} className="size-4" iconClassName={cn("size-4", props.activeProviderIconClassName)} diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index 47ce59efde52b..0a863e0bd4462 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -618,6 +618,7 @@ export const TraitsPicker = memo(function TraitsPicker({ - {item.output !== undefined ? : null} {item.exitCode !== undefined ? (

    Process exited with code {item.exitCode} @@ -156,26 +156,40 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec ) : null} {item.type === "file_change" ? ( -

    - - {formatWorkspaceRelativePath(item.fileName, props.workspaceRoot)} - - {item.additions !== undefined || item.deletions !== undefined ? ( - - +{item.additions ?? 0}{" "} - -{item.deletions ?? 0} +
    +
    + + {formatWorkspaceRelativePath(item.fileName, props.workspaceRoot)} + {item.additions !== undefined || item.deletions !== undefined ? ( + + +{item.additions ?? 0}{" "} + -{item.deletions ?? 0} + + ) : null} + {item.runId !== null ? ( + + ) : null} +
    + {item.changes !== undefined && item.changes.length > 0 ? ( +
      + {item.changes.map((change, index) => ( +
    • + {change.operation} {change.oldPath ? `${change.oldPath} → ` : ""} + {formatWorkspaceRelativePath(change.path, props.workspaceRoot)} + {change.fileType || change.mimeType + ? ` (${[change.fileType, change.mimeType].filter(Boolean).join(", ")})` + : ""} +
    • + ))} +
    ) : null} - {item.runId !== null ? ( - - ) : null} - {item.diffStr ? : null}
    ) : null} @@ -225,21 +239,11 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec ) : null} {item.type === "dynamic_tool" ? ( -
    -
    -

    - Input -

    - -
    - {item.output !== undefined ? ( -
    -

    - Output -

    - -
    - ) : null} +
    +

    + Input +

    +
    ) : null} @@ -304,7 +308,7 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec Structured details
    - +
    diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 079ddc8a62d1e..5c9d51567f4b0 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -1,29 +1,31 @@ import { Fragment } from "react"; -import type { - OrchestrationV2Run, - OrchestrationV2TurnItem, - ProviderInstanceId, - ServerProvider, - ThreadId, +import { + ProviderDriverKind, + type OrchestrationV2Run, + type OrchestrationV2TurnItem, + type ProviderInstanceId, + type ServerProvider, + type ThreadId, } from "@t3tools/contracts"; import type { TimestampFormat } from "@t3tools/contracts/settings"; import { ArrowRightLeftIcon, ArrowRightIcon, BotIcon, - ChevronDownIcon, - ExternalLinkIcon, GitForkIcon, MessageSquareIcon, MinusIcon, - type LucideIcon, XIcon, } from "lucide-react"; +import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; +import { cn } from "../../lib/utils"; import { getProviderInstanceEntry } from "../../providerInstances"; import { formatShortTimestamp } from "../../timestampFormat"; -import { PROVIDER_ICON_BY_PROVIDER, getTriggerDisplayModelName } from "./providerIconUtils"; +import { getTriggerDisplayModelName } from "./providerIconUtils"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; import { TimelineSystemDivider } from "./TimelineSystemDivider"; +import { T3Wordmark } from "../T3Wordmark"; const LIFECYCLE_TYPES = new Set([ "run_interrupt_request", @@ -39,13 +41,6 @@ export function isV2LifecycleItem(item: OrchestrationV2TurnItem): boolean { return LIFECYCLE_TYPES.has(item.type); } -// Aborted subagents (cancelled/interrupted) keep whatever result text had -// streamed before the abort, so only completed/failed results are final. -const FINAL_RESULT_SUBAGENT_STATUSES = new Set([ - "completed", - "failed", -]); - // Once a subagent stops, its last streamed result says more than the stale // progress line; while it runs, live progress comes first. const TERMINAL_SUBAGENT_STATUSES = new Set([ @@ -67,6 +62,7 @@ export type HandoffTimelineRun = Pick< export function V2LifecycleRow(props: { readonly item: OrchestrationV2TurnItem; + readonly resourceSummary?: boolean | undefined; readonly createdAt: string; readonly timestampFormat: TimestampFormat; readonly providerStatuses: ReadonlyArray; @@ -108,12 +104,16 @@ export function V2LifecycleRow(props: { item.beforeTokenCount === undefined && item.afterTokenCount === undefined ? null : `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`; + const label = + item.status === "failed" + ? "Context compaction failed" + : item.status === "cancelled" || item.status === "interrupted" + ? "Context compaction stopped" + : item.status === "pending" || item.status === "running" || item.status === "waiting" + ? "Compacting context" + : "Context compacted"; return ( - + ); } if (item.type === "handoff") { @@ -186,33 +186,62 @@ export function V2LifecycleRow(props: { ); } if (item.type === "thread_created") { + if (props.resourceSummary) { + return ( +
    + + + + + {item.title ?? "Created thread"} + + +
    + ); + } return ( - +
    + + + + + Created thread{item.title ? ` · ${item.title}` : ""} + + +
    ); } if (item.type === "subagent") { const streamedResult = item.result?.trim() ? item.result : null; - const finalResult = FINAL_RESULT_SUBAGENT_STATUSES.has(item.status) ? streamedResult : null; const detail = TERMINAL_SUBAGENT_STATUSES.has(item.status) ? (streamedResult ?? item.progress ?? item.prompt) : (item.progress ?? streamedResult ?? item.prompt); return ( - ); @@ -220,85 +249,71 @@ export function V2LifecycleRow(props: { return null; } -function RelatedThreadCard(props: { - readonly itemType: "subagent" | "thread_created"; - readonly icon: LucideIcon; +function SubagentTimelineLink(props: { readonly title: string; readonly detail: string; - readonly expandedDetail?: string | null; - readonly badge: string; + readonly status: OrchestrationV2TurnItem["status"]; readonly threadId: ThreadId | null; readonly onOpenThread: (threadId: ThreadId) => void; }) { - const Icon = props.icon; const threadId = props.threadId; - const expandedDetail = props.expandedDetail ?? null; + const statusLabel = props.status.replaceAll("_", " "); const content = ( <> - - {props.title} - {props.detail} - - {props.badge} + + + + {props.title} ); - - if (expandedDetail !== null) { - return ( -
    -
    - - {content} - -
    -

    - {expandedDetail} -

    -
    -
    - {threadId === null ? null : ( - - )} -
    - ); - } - - return threadId === null ? ( + return (
    - {content} + + + {content} + + ) : ( + + ) + } + /> + + {props.title} · {statusLabel} + {props.detail ? `\n${props.detail}` : ""} + +
    - ) : ( - ); } @@ -325,19 +340,13 @@ function latestRunModelBefore( return latest?.modelSelection.model; } -/** - * One side of a context handoff: the provider's brand icon plus the model's - * display name. Falls back to the raw model slug when the instance no longer - * lists it, and to the instance display name (or id) when no model was - * recorded on the item. - */ +/** Provider icon with the resolved handoff model available on hover or focus. */ function HandoffEndpoint(props: { readonly providers: ReadonlyArray; readonly instanceId: ProviderInstanceId; readonly model?: string | undefined; }) { const entry = getProviderInstanceEntry(props.providers, props.instanceId); - const Icon = entry === undefined ? null : (PROVIDER_ICON_BY_PROVIDER[entry.driverKind] ?? null); const model = props.model?.trim(); const providerModel = model === undefined || model.length === 0 @@ -350,9 +359,26 @@ function HandoffEndpoint(props: { ? model : (entry?.displayName ?? props.instanceId); return ( - - {Icon === null ? null : + + + +
    + } + /> + {label} + ); } diff --git a/apps/web/src/components/chat/WorktreeSetupCard.tsx b/apps/web/src/components/chat/WorktreeSetupCard.tsx index 8b838fb81cc95..6fe54269cd106 100644 --- a/apps/web/src/components/chat/WorktreeSetupCard.tsx +++ b/apps/web/src/components/chat/WorktreeSetupCard.tsx @@ -10,16 +10,16 @@ import { ChevronRightIcon, CircleAlertIcon, CircleIcon, - GitBranchIcon, LaptopIcon, MinusIcon, TerminalIcon, XIcon, } from "lucide-react"; -import { useEffect, useState } from "react"; +import { useEffect, useState, type ReactNode } from "react"; import { Button } from "~/components/ui/button"; import { Spinner } from "~/components/ui/spinner"; +import { observeVisibleAnimation } from "~/lib/visibleAnimation"; import { cn } from "~/lib/utils"; interface WorktreeSetupCardProps { @@ -74,20 +74,95 @@ function StageIcon({ status }: { status: WorktreeSetupStage["status"] }) { function stageRowClassName(status: WorktreeSetupStage["status"]): string { switch (status) { - case "running": - return "text-foreground"; case "failed": return "text-destructive-foreground"; case "warning": return "text-warning-foreground"; case "pending": + return "text-secondary-label opacity-40"; + case "running": case "skipped": - return "text-secondary-label opacity-50"; case "done": return "text-secondary-label"; } } +/** Same shimmer treatment as the live tool rows in the timeline. */ +function ShimmerOverlay({ children }: { children: ReactNode }) { + return ( + + + {children} + + + ); +} + +function headerLabel(snapshot: WorktreeSetupSnapshot): string { + switch (snapshot.phase) { + case "running": + return "Setting up worktree…"; + case "done": + return snapshot.stages.some((stage) => stage.status === "failed") + ? "Worktree ready, setup script failed" + : "Worktree ready"; + case "failed": + return "Worktree setup failed"; + case "cancelled": + return "Worktree setup cancelled"; + } +} + +/** + * Occupies the same slot, with the same metrics, as the "Working for" header + * so the handoff to the agent's turn only swaps the text. + */ +function SetupHeaderRow({ + snapshot, + totalElapsed, +}: { + snapshot: WorktreeSetupSnapshot; + totalElapsed: number | null; +}) { + const running = snapshot.phase === "running"; + const failed = snapshot.phase === "failed"; + const finishedWithFailedStage = + snapshot.phase === "done" && snapshot.stages.some((stage) => stage.status === "failed"); + const text = headerLabel(snapshot); + const tone = failed + ? "text-destructive-foreground" + : finishedWithFailedStage + ? "text-warning-foreground" + : "text-muted-foreground"; + return ( +
    +
    + + {text} + {running ? {text} : null} + + {totalElapsed !== null ? ( + + {formatDuration(totalElapsed)} + + ) : null} +
    +
    + ); +} + +/** One stage, rendered like a live work entry row. */ function StageRow({ stage, nowMs, @@ -100,44 +175,49 @@ function StageRow({ const elapsed = stageElapsedMs(stage, nowMs); const label = stage.id === "setup-script" && scriptName ? scriptName : worktreeSetupStageLabel(stage.id); - const showBar = stage.id === "checkout" && stage.status === "running" && stage.percent !== null; + const running = stage.status === "running"; const trailing = stage.status === "pending" ? null : stage.status === "skipped" ? (stage.detail ?? "skipped") - : stage.detail; - + : stage.id === "checkout" && running && stage.percent !== null + ? `${stage.percent}%` + : stage.detail; return (
    - + {label} - - {showBar ? ( - <> - - + {trailing ? ( + + {trailing} + + ) : null} + {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? ( + + {formatDuration(elapsed)} + + ) : null} + {running ? ( + + + + - {stage.percent}% - - ) : null} - {!showBar && trailing ? {trailing} : null} - {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? ( - {formatDuration(elapsed)} - ) : null} - + {label} + + + ) : null}
    ); } @@ -158,19 +238,35 @@ function OutputTail({ lines, failed }: { lines: ReadonlyArray; failed: b ); } -function headerLabel(snapshot: WorktreeSetupSnapshot): string { - switch (snapshot.phase) { - case "running": - return "Creating worktree"; - case "done": - return snapshot.stages.some((stage) => stage.status === "failed") - ? "Worktree ready, setup script failed" - : "Worktree ready"; - case "failed": - return "Worktree setup failed"; - case "cancelled": - return "Worktree setup cancelled"; - } +function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) { + return ( +
    + {snapshot.branch ? ( + <> +
    Branch
    +
    {snapshot.branch}
    + + ) : null} + {snapshot.baseRef ? ( + <> +
    Base
    +
    {snapshot.baseRef}
    + + ) : null} + {snapshot.worktreePath ? ( + <> +
    Path
    +
    {snapshot.worktreePath}
    + + ) : null} + {snapshot.setupScript ? ( + <> +
    Setup
    +
    {snapshot.setupScript.command}
    + + ) : null} +
    + ); } export function WorktreeSetupCard({ @@ -178,7 +274,14 @@ export function WorktreeSetupCard({ onCancel, onWorkLocally, onOpenTerminal, -}: WorktreeSetupCardProps) { + embedded = false, +}: WorktreeSetupCardProps & { + /** + * The agent already started (async setup script), so the turn owns the + * "Working for" header and only the script's row sits among the worklog. + */ + embedded?: boolean; +}) { const running = snapshot.phase === "running"; const nowMs = useNowWhile(running); const [detailsOpen, setDetailsOpen] = useState(false); @@ -188,79 +291,35 @@ export function WorktreeSetupCard({ return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null; })(); const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script"); - const failed = snapshot.phase === "failed"; - const finishedWithFailedStage = - snapshot.phase === "done" && snapshot.stages.some((stage) => stage.status === "failed"); - const headerClassName = failed - ? "text-destructive-foreground" - : finishedWithFailedStage - ? "text-warning-foreground" - : snapshot.phase === "cancelled" - ? "text-muted-foreground" - : "text-secondary-label"; + const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending"; + const stages = embedded + ? snapshot.stages.filter((stage) => stage.id === "setup-script") + : snapshot.stages; return ( -
    -
    - - - - {headerLabel(snapshot)} - {totalElapsed !== null ? ( - - {formatDuration(totalElapsed)} - - ) : null} +
    + {embedded ? null : } +
    + {stages.map((stage) => ( +
    + + {stage.id === "setup-script" && + (stage.status === "running" || stage.status === "failed") ? ( + + ) : null} +
    + ))}
    - {snapshot.stages.map((stage) => ( -
    - - {stage.id === "setup-script" && - (stage.status === "running" || stage.status === "failed") ? ( - - ) : null} -
    - ))} - - {failed && snapshot.error ? ( -

    {snapshot.error}

    + {snapshot.phase === "failed" && snapshot.error ? ( +

    {snapshot.error}

    ) : null} - {detailsOpen ? ( -
    - {snapshot.branch ? ( - <> -
    Branch
    -
    {snapshot.branch}
    - - ) : null} - {snapshot.baseRef ? ( - <> -
    Base
    -
    {snapshot.baseRef}
    - - ) : null} - {snapshot.worktreePath ? ( - <> -
    Path
    -
    {snapshot.worktreePath}
    - - ) : null} - {snapshot.setupScript ? ( - <> -
    Setup
    -
    {snapshot.setupScript.command}
    - - ) : null} -
    - ) : null} + {detailsOpen ? : null} -
    + {/* Indented so the first label lines up with the stage labels: the icon + column, minus the xs button's own horizontal padding. */} +
    - - {onOpenTerminal && setupStage && setupStage.status !== "pending" ? ( - ) : null} {onWorkLocally ? ( - ) : null} {onCancel && running ? ( - diff --git a/apps/web/src/components/chat/providerIconUtils.ts b/apps/web/src/components/chat/providerIconUtils.ts index db0e5ca222f3a..557d62d742db8 100644 --- a/apps/web/src/components/chat/providerIconUtils.ts +++ b/apps/web/src/components/chat/providerIconUtils.ts @@ -1,23 +1,3 @@ -import { ProviderDriverKind } from "@t3tools/contracts"; -import { - AntigravityIcon, - ClaudeAI, - CursorIcon, - GrokIcon, - Icon, - OpenAI, - OpenCodeIcon, -} from "../Icons"; - -export const PROVIDER_ICON_BY_PROVIDER: Partial> = { - [ProviderDriverKind.make("codex")]: OpenAI, - [ProviderDriverKind.make("claudeAgent")]: ClaudeAI, - [ProviderDriverKind.make("opencode")]: OpenCodeIcon, - [ProviderDriverKind.make("cursor")]: CursorIcon, - [ProviderDriverKind.make("grok")]: GrokIcon, - [ProviderDriverKind.make("antigravity")]: AntigravityIcon, -}; - export type ModelEsque = { slug: string; name: string; diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts new file mode 100644 index 0000000000000..579b546fb651e --- /dev/null +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -0,0 +1,123 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { beforeEach, describe, expect, it } from "vite-plus/test"; +import { + DraftId, + useComposerDraftStore, + type ComposerFileAttachment, + type ComposerImageAttachment, +} from "../../composerDraftStore"; +import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit"; + +const environmentId = EnvironmentId.make("remote-environment"); +const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); +const editTarget = DraftId.make("queued-edit:test"); +const file: ComposerFileAttachment = { + type: "file", + id: "file:report", + name: "report.pdf", + mimeType: "application/pdf", + sizeBytes: 6, + file: new File(["report"], "report.pdf", { type: "application/pdf" }), +}; +const image: ComposerImageAttachment = { + type: "image", + id: "image:screen", + name: "screen.png", + mimeType: "image/png", + sizeBytes: 5, + file: new File(["image"], "screen.png", { type: "image/png" }), + previewUrl: "blob:screen", +}; +const uploadedFile = { + type: "file" as const, + id: "upload:report", + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, +}; + +describe("queued message file edits", () => { + beforeEach(() => { + useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} }); + }); + + for (const images of [[], [image]]) { + it(`preserves a generic file in a ${images.length === 0 ? "file-only" : "mixed"} save`, async () => { + const attachments = await prepareQueuedEditAttachments({ + existingAttachments: [], + images, + files: [file], + uploadFiles: async () => [uploadedFile], + readImage: async () => "data:image/png;base64,aW1hZ2U=", + }); + expect(attachments.at(-1)).toEqual(uploadedFile); + expect(attachments.length).toBe(images.length + 1); + if (images.length > 0) + expect(attachments[0]).toMatchObject({ + type: "image", + dataUrl: "data:image/png;base64,aW1hZ2U=", + }); + }); + } + + it("retains saved attachments alongside newly uploaded files", async () => { + const saved = { ...uploadedFile, id: "saved:earlier" }; + const attachments = await prepareQueuedEditAttachments({ + existingAttachments: [saved], + images: [], + files: [file], + uploadFiles: async () => [uploadedFile], + readImage: async () => "unused", + }); + expect(attachments).toEqual([saved, uploadedFile]); + }); + + it("fails a save instead of dropping a file whose upload is missing", async () => { + await expect( + prepareQueuedEditAttachments({ + existingAttachments: [], + images: [image], + files: [file], + uploadFiles: async () => [], + readImage: async () => "image", + }), + ).rejects.toThrow("Retry or remove"); + }); + + it("keeps file-only edits when another client starts the queued run", () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(editTarget, "Original message"); + store.addFiles(editTarget, [file]); + expect( + recoverQueuedMessageEdit({ editTarget, threadTarget, originalText: "Original message" }), + ).toBe("kept"); + expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Original message"); + expect(store.getComposerDraft(threadTarget)?.files).toEqual([file]); + expect(store.getComposerDraft(editTarget)).toBeNull(); + }); + + it("preserves uploaded file references when a remote queue advance interrupts the edit", () => { + const store = useComposerDraftStore.getState(); + const uploaded = { + ...file, + file: null, + uploadedAttachmentId: uploadedFile.id, + uploadEnvironmentId: environmentId, + }; + store.addFiles(editTarget, [uploaded]); + expect(recoverQueuedMessageEdit({ editTarget, threadTarget, originalText: "" })).toBe("kept"); + expect(store.getComposerDraft(threadTarget)?.files).toEqual([uploaded]); + }); + + it("does not overwrite a separate draft when the queued run leaves", () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(threadTarget, "Separate draft"); + store.addFiles(editTarget, [file]); + expect(recoverQueuedMessageEdit({ editTarget, threadTarget, originalText: "" })).toBe( + "discarded", + ); + expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Separate draft"); + expect(store.getComposerDraft(editTarget)).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts new file mode 100644 index 0000000000000..b20ddb83c22a9 --- /dev/null +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -0,0 +1,54 @@ +import type { ChatAttachment } from "@t3tools/contracts"; +import { + composerDraftHasUserContent, + useComposerDraftStore, + type ComposerFileAttachment, + type ComposerImageAttachment, + type ComposerThreadTarget, +} from "../../composerDraftStore"; + +/** Keep an unsaved edit when its queued run starts or is removed remotely. */ +export function recoverQueuedMessageEdit(input: { + readonly editTarget: ComposerThreadTarget; + readonly threadTarget: ComposerThreadTarget; + readonly originalText: string; +}): "kept" | "discarded" | "clean" { + const store = useComposerDraftStore.getState(); + const draft = store.getComposerDraft(input.editTarget); + const dirty = + draft !== null && + (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0); + if (dirty && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget))) { + store.moveComposerPromptAndImages(input.editTarget, input.threadTarget); + return "kept"; + } + store.clearComposerContent(input.editTarget); + return dirty ? "discarded" : "clean"; +} + +/** Generic files need upload references; images also support the inline transport. */ +export async function prepareQueuedEditAttachments(input: { + readonly existingAttachments: ReadonlyArray; + readonly images: ReadonlyArray; + readonly files: ReadonlyArray; + readonly uploadFiles: ( + files: ReadonlyArray, + ) => Promise>; + readonly readImage: (file: File) => Promise; +}) { + const files = input.files.length === 0 ? [] : await input.uploadFiles(input.files); + if (files.length !== input.files.length) + throw new Error("Retry or remove failed uploads before saving."); + const images = await Promise.all( + input.images.map(async (image) => ({ + type: "image" as const, + id: image.id, + name: image.name, + mimeType: image.mimeType, + sizeBytes: image.sizeBytes, + dataUrl: await input.readImage(image.file), + ...(image.source ? { source: image.source } : {}), + })), + ); + return [...input.existingAttachments, ...images, ...files]; +} diff --git a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx index 5d5c280bb81c6..afe0dbc31c5ee 100644 --- a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx +++ b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx @@ -1,16 +1,12 @@ -import { useAuth, useClerk, useUser } from "@clerk/react"; -import { encodeConnectAuthCode, readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth"; +import { useAuth, useClerk } from "@clerk/react"; +import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth"; import { useCallback, useEffect, useRef, useState } from "react"; import { buildConnectCliClerkAuthorizeUrl, connectCliSignInRedirectUrl, - readConnectCliAuthState, - readConnectCliCallbackResult, - rememberConnectCliAuthState, } from "../../cloud/connectCliAuth"; import { isElectron } from "../../env"; -import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { AuthSurfaceShell } from "../auth/AuthSurfaceShell"; import { resolveClerkSignInProps } from "../clerk/authRedirect"; import { Button } from "../ui/button"; @@ -45,10 +41,10 @@ const invalidLinkMessage = { } as const; /** - * /connect: the URL the CLI prints for both flows. Waits for a Clerk session, - * then forwards the CLI's PKCE request to Clerk's authorize endpoint — with a - * loopback redirect URI when the request carries a port, so the code returns - * straight to the waiting CLI, and the hosted callback page otherwise. + * /connect: the URL the CLI prints for the loopback flow. Waits for a Clerk + * session, then forwards the CLI's PKCE request to Clerk's authorize endpoint + * with the loopback redirect URI so the code returns straight to the waiting + * CLI. Headless hosts use Clerk's device authorization page instead. */ export function ConnectCliAuthorizeSurface() { const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href))); @@ -61,9 +57,6 @@ export function ConnectCliAuthorizeSurface() { if (!request) { return; } - // Clerk redirects to the authorize endpoint itself once sign-in completes, - // so the callback's state check has to be armed before handing off. - rememberConnectCliAuthState(request.state); clerk.openSignIn( resolveClerkSignInProps( connectCliSignInRedirectUrl(request, window.location.href), @@ -88,7 +81,6 @@ export function ConnectCliAuthorizeSurface() { return; } redirecting.current = true; - rememberConnectCliAuthState(request.state); window.location.assign(authorizeUrl); }, [isLoaded, isSignedIn, openSignIn, request]); @@ -103,11 +95,7 @@ export function ConnectCliAuthorizeSurface() { return ( ); } - -/** - * /connect/callback: Clerk's redirect target. Shows the one-time code the - * user enters in the waiting terminal. - */ -export function ConnectCliCallbackSurface() { - const [result] = useState(readConnectCliCallbackResult); - const [expectedState] = useState(readConnectCliAuthState); - const { user } = useUser(); - const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "authentication code" }); - - if (!result) { - return ( - - - - ); - } - - // Fail closed: the legitimate callback always lands in the same browser - // that visited /connect (which recorded the state), so a missing or - // mismatched state means this page was reached some other way — the CSRF - // shape the state parameter exists to stop. Refuse to display a code. - if (expectedState === null || expectedState !== result.state) { - return ( - - - - ); - } - - const accountLabel = user?.primaryEmailAddress?.emailAddress ?? user?.username ?? null; - const authCode = encodeConnectAuthCode(result); - - return ( - - - -
    -
    - - One-time authorization code - - expires shortly -
    - - {authCode} - -
    - -
    - -
    - -

    - Only enter this code in a terminal session you started yourself. Anyone holding it can link - their machine to your T3 Connect account while it is valid. -

    -
    - ); -} diff --git a/apps/web/src/components/composerFooterLayout.test.ts b/apps/web/src/components/composerFooterLayout.test.ts index 5c0e4327d959e..fce841e6200b6 100644 --- a/apps/web/src/components/composerFooterLayout.test.ts +++ b/apps/web/src/components/composerFooterLayout.test.ts @@ -90,6 +90,34 @@ describe("resolveComposerTimelineInset", () => { ).toBe(200); }); + it("uses the measured expanded height while the resting strip host is mounting", () => { + expect( + resolveComposerTimelineInset({ currentInset: 172, overlayHeight: 110, isResting: true }), + ).toBe(172); + }); + + it("keeps timeline padding stable when the model-only strip appears on collapse", () => { + const expanded = resolveComposerTimelineInset({ + currentInset: 0, + overlayHeight: 172, + isResting: false, + }); + const collapsed = resolveComposerTimelineInset({ + currentInset: expanded, + overlayHeight: 110, + isResting: true, + restingOnlyHeight: 32, + }); + expect(collapsed).toBe(expanded); + expect( + resolveComposerTimelineInset({ + currentInset: collapsed, + overlayHeight: 172, + isResting: false, + }), + ).toBe(expanded); + }); + it("reserves the empty expansion when no larger height is known", () => { expect( resolveComposerTimelineInset({ currentInset: 0, overlayHeight: 60, isResting: true }), diff --git a/apps/web/src/components/composerFooterLayout.ts b/apps/web/src/components/composerFooterLayout.ts index 42f466c2ae9d6..7d5bbd6e03a85 100644 --- a/apps/web/src/components/composerFooterLayout.ts +++ b/apps/web/src/components/composerFooterLayout.ts @@ -36,10 +36,8 @@ export function shouldUseRestingComposerLayout(input: { // line and overlays its actions; non-image attachment and context // rows keep their natural height above it while image previews move inline. // Banners and the tasks badge dock above the surface, so they are absent - // too. Whether the context strip can host the relocated controls is - // deliberately absent here: resting reclaims vertical space at every - // desktop width, and where the strip is missing or too narrow the controls - // simply return when the composer is focused. + // too. The context strip is optional: collapsed controls use it when + // present and otherwise occupy a compact row inside the composer. // // Only a timeline scroll rests the composer: the user asked for it with the // gesture, and it lifts on the next composer interaction. Losing focus never @@ -74,18 +72,25 @@ export const COMPOSER_RESTING_EXPANSION_MIN_PX = 94; * an expanded one. Reserving only the resting height lets a scroll to the end * land flush against the short composer, and the expansion that follows then * covers the last rows because the timeline never moves for footer growth. - * While resting, the reservation keeps the last expanded height, or at least - * the resting height plus the empty expansion, so expanding again changes - * nothing above the composer. An expanded measurement is authoritative and - * may shrink it. + * While resting, keep the measured expanded height. Estimate the empty + * expansion only before that measurement exists: strip mounting can otherwise + * inflate the estimate mid-transition and move the timeline. An expanded + * measurement is authoritative and may shrink the reservation. */ export function resolveComposerTimelineInset(input: { currentInset: number; overlayHeight: number; isResting: boolean; + restingOnlyHeight?: number; }): number { return input.isResting - ? Math.max(input.currentInset, input.overlayHeight + COMPOSER_RESTING_EXPANSION_MIN_PX) + ? Math.max( + input.currentInset, + input.overlayHeight + + (input.currentInset === 0 + ? COMPOSER_RESTING_EXPANSION_MIN_PX - (input.restingOnlyHeight ?? 0) + : 0), + ) : input.overlayHeight; } diff --git a/apps/web/src/components/files/fileEditorLanguageReadiness.test.ts b/apps/web/src/components/files/fileEditorLanguageReadiness.test.ts index 927d963c45981..d6f64a55c9b18 100644 --- a/apps/web/src/components/files/fileEditorLanguageReadiness.test.ts +++ b/apps/web/src/components/files/fileEditorLanguageReadiness.test.ts @@ -40,6 +40,7 @@ const source = "export const View = () =>
    Ready
    ;"; let pool: WorkerPoolManager; let renderer: FileRenderer; let terminationPromises: Promise[]; +const pendingAnimationFrames = new Set>(); class WorkerTransport { private readonly worker = new NodeWorkerThreads.Worker( @@ -96,10 +97,18 @@ function firstEnter(highlighter: DiffsHighlighter, file: FileContents, language: beforeEach(async () => { terminationPromises = []; - vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => - setImmediate(() => callback(0)), - ); - vi.stubGlobal("cancelAnimationFrame", clearImmediate); + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { + const handle = setImmediate(() => { + pendingAnimationFrames.delete(handle); + callback(0); + }); + pendingAnimationFrames.add(handle); + return handle; + }); + vi.stubGlobal("cancelAnimationFrame", (handle: ReturnType) => { + pendingAnimationFrames.delete(handle); + clearImmediate(handle); + }); vi.stubGlobal("window", { matchMedia: () => ({ matches: true }) }); await disposeHighlighter(); pool = new WorkerPoolManager( @@ -118,6 +127,8 @@ afterEach(async () => { await disposeHighlighter(); // Drain the pool's final state broadcast before removing the animation frame stubs. await new Promise((resolve) => setImmediate(resolve)); + for (const handle of pendingAnimationFrames) clearImmediate(handle); + pendingAnimationFrames.clear(); vi.unstubAllGlobals(); }); diff --git a/apps/web/src/components/media/MediaVideoPlayer.tsx b/apps/web/src/components/media/MediaVideoPlayer.tsx index 6f2b15e7a73e2..9bf65102bf70f 100644 --- a/apps/web/src/components/media/MediaVideoPlayer.tsx +++ b/apps/web/src/components/media/MediaVideoPlayer.tsx @@ -1,4 +1,4 @@ -import { RotateCwIcon, TriangleAlertIcon } from "lucide-react"; +import { PlayIcon, RotateCwIcon, TriangleAlertIcon } from "lucide-react"; import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react"; import { cn } from "../../lib/utils"; @@ -15,6 +15,8 @@ interface MediaVideoPlayerProps { readonly revision?: string | null | undefined; readonly preload?: "visible" | "metadata" | undefined; readonly autoPlay?: boolean | undefined; + /** Presents a still thumbnail whose full surface opens the video in a viewer. */ + readonly onOpen?: (() => void) | undefined; readonly className?: string | undefined; readonly videoClassName?: string | undefined; /** Styles the loading and failure panels, which otherwise assume an inline light surface. */ @@ -34,6 +36,7 @@ export function MediaVideoPlayer({ revision = null, preload = "visible", autoPlay = false, + onOpen, className, videoClassName, stateClassName, @@ -131,7 +134,7 @@ export function MediaVideoPlayer({ style={style} data-markdown-copy={copyMarkdown} > - {failed ? ( + {failed && !onOpen ? (
    - ) : src !== null ? ( + ) : src !== null && !failed ? (
    +
    | null, action: PullRequestAction, ): boolean { @@ -285,20 +278,6 @@ export function isPullRequestConflicting( return detail?.state === "open" && detail.mergeability === "conflicting"; } -/** - * One live action holds the slot. A conflicting change cannot be merged now, so the slot goes to - * the thing that would help instead of a Merge button that only ever says no. - */ -export function resolvePullRequestPrimaryAction( - detail: PullRequestActionableDetail | null, -): "ready" | "merge" | "resolve" | null { - if (detail === null || detail.state !== "open") return null; - if (detail.isDraft && canPerformPullRequestAction(detail, "ready")) return "ready"; - if (!canPerformPullRequestAction(detail, "merge")) return null; - if (isPullRequestConflicting(detail)) return "resolve"; - return allowedPullRequestMergeMethods(detail).length > 0 ? "merge" : null; -} - /** The checks as one word. Failing outranks running: a red run is already worth acting on. */ export type PullRequestChecksState = "none" | "pending" | "failing" | "passing"; diff --git a/apps/web/src/components/settings/AcpRegistryIcon.test.ts b/apps/web/src/components/settings/AcpRegistryIcon.test.ts new file mode 100644 index 0000000000000..39e65f644c7dc --- /dev/null +++ b/apps/web/src/components/settings/AcpRegistryIcon.test.ts @@ -0,0 +1,206 @@ +import type { ReactElement } from "react"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { visitElements } from "../../test/reactElementTree"; +import { reactHookHarness as hooks } from "../../test/reactHookHarness"; + +vi.mock("react", async (importOriginal) => { + const actual = await importOriginal(); + const { reactHookHarness } = await import("../../test/reactHookHarness"); + return { + ...actual, + useEffect: (effect: () => void | (() => void)) => effect(), + useState: reactHookHarness.useState, + useId: () => "acp-icon-test-filter", + }; +}); + +import { + AcpRegistryAgentIcon, + loadCachedAcpRegistryIcon, + officialAcpRegistryIconUrlForAgentId, + resolveOfficialAcpRegistryIconUrl, +} from "./AcpRegistryIcon"; + +describe("ACP Registry icon cache", () => { + const stored = new Map(); + const match = vi.fn(async (url: string) => stored.get(url)?.clone()); + const put = vi.fn(async (url: string, response: Response) => { + stored.set(url, response.clone()); + }); + const fetchIcon = vi.fn(); + + beforeEach(() => { + hooks.reset(); + stored.clear(); + match.mockClear(); + put.mockClear(); + fetchIcon.mockReset(); + vi.stubGlobal("caches", { open: vi.fn(async () => ({ match, put })) }); + vi.stubGlobal("fetch", fetchIcon); + }); + + it("single-flights the first fetch and serves later reads from persistent cache", async () => { + const url = "https://cdn.agentclientprotocol.com/registry/icons/cache-test.svg"; + fetchIcon.mockResolvedValue( + new Response("", { + status: 200, + headers: { "content-type": "image/svg+xml" }, + }), + ); + + const [first, concurrent] = await Promise.all([ + loadCachedAcpRegistryIcon(url), + loadCachedAcpRegistryIcon(url), + ]); + const cached = await loadCachedAcpRegistryIcon(url); + + expect(first.type).toBe("image/svg+xml"); + expect(concurrent.size).toBe(first.size); + expect(cached.size).toBe(first.size); + expect(fetchIcon).toHaveBeenCalledOnce(); + expect(put).toHaveBeenCalledOnce(); + }); + + it("rejects oversized image responses before caching", async () => { + const url = "https://cdn.agentclientprotocol.com/registry/icons/oversized.svg"; + fetchIcon.mockResolvedValue( + new Response("too large", { + status: 200, + headers: { + "content-length": String(513 * 1_024), + "content-type": "image/svg+xml", + }, + }), + ); + + await expect(loadCachedAcpRegistryIcon(url)).rejects.toThrow("too large"); + expect(put).not.toHaveBeenCalled(); + }); + + it("falls back to the network when CacheStorage cannot be opened", async () => { + const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg"; + vi.stubGlobal("caches", { + open: vi.fn(async () => { + throw new Error("CacheStorage unavailable"); + }), + }); + fetchIcon.mockResolvedValue( + new Response("", { + status: 200, + headers: { "content-type": "image/svg+xml" }, + }), + ); + + await expect(loadCachedAcpRegistryIcon(url)).resolves.toMatchObject({ + type: "image/svg+xml", + }); + expect(fetchIcon).toHaveBeenCalledWith(url, { + credentials: "omit", + redirect: "error", + referrerPolicy: "no-referrer", + }); + }); + + it("accepts only credential-free HTTPS URLs on the official CDN", () => { + expect( + resolveOfficialAcpRegistryIconUrl( + "https://cdn.agentclientprotocol.com/registry/icons/gemini.png", + ), + ).toBe("https://cdn.agentclientprotocol.com/registry/icons/gemini.png"); + expect( + resolveOfficialAcpRegistryIconUrl("http://cdn.agentclientprotocol.com/icon.png"), + ).toBeNull(); + expect( + resolveOfficialAcpRegistryIconUrl("https://cdn.agentclientprotocol.com.evil/icon.png"), + ).toBeNull(); + expect( + resolveOfficialAcpRegistryIconUrl("https://user@cdn.agentclientprotocol.com/icon.png"), + ).toBeNull(); + expect( + resolveOfficialAcpRegistryIconUrl("https://cdn.agentclientprotocol.com:8443/icon.png"), + ).toBeNull(); + expect(officialAcpRegistryIconUrlForAgentId("kilo")).toBe( + "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg", + ); + expect(officialAcpRegistryIconUrlForAgentId("../kilo")).toBeNull(); + }); + + it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => { + const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg"; + // The official CDN serves no CORS headers, so the fetch can reject even + // though native loading works. + fetchIcon.mockRejectedValue(new TypeError("Failed to fetch")); + hooks.beginRender(); + AcpRegistryAgentIcon({ icon: url }); + + await new Promise((resolve) => setTimeout(resolve, 0)); + hooks.beginRender(); + const tree = AcpRegistryAgentIcon({ icon: url }) as ReactElement>; + const image = visitElements(tree, (element) => element.type === "img"); + expect(image?.props).toMatchObject({ src: url, referrerPolicy: "no-referrer" }); + expect( + visitElements(tree, (element) => element.props["data-slot"] === "acp-icon-fallback"), + ).not.toBeNull(); + }); + + it("renders only the validated blob object URL and keeps the fallback until load", async () => { + const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg"; + const objectUrl = "blob:t3/kilo-icon"; + Object.assign(URL, { + createObjectURL: vi.fn(() => objectUrl), + revokeObjectURL: vi.fn(), + }); + fetchIcon.mockResolvedValue( + new Response("", { + status: 200, + headers: { "content-type": "image/svg+xml" }, + }), + ); + hooks.beginRender(); + const validating = AcpRegistryAgentIcon({ icon: url }) as ReactElement>; + + // The raw CDN URL is never rendered; only the fallback shows while the + // blob is fetched and validated. + expect(visitElements(validating, (element) => element.type === "img")).toBeNull(); + expect( + visitElements(validating, (element) => element.props["data-slot"] === "acp-icon-fallback"), + ).not.toBeNull(); + + await new Promise((resolve) => setTimeout(resolve, 0)); + hooks.beginRender(); + const loading = AcpRegistryAgentIcon({ icon: url }) as ReactElement>; + const loadingImage = visitElements(loading, (element) => element.type === "img"); + + expect(loadingImage?.props).toMatchObject({ + src: objectUrl, + alt: "", + decoding: "async", + referrerPolicy: "no-referrer", + }); + expect(loadingImage?.props.className).not.toContain("dark:invert"); + expect(loadingImage?.props.className).toContain("invisible"); + expect( + visitElements(loading, (element) => element.props["data-slot"] === "acp-icon-fallback"), + ).not.toBeNull(); + + (loadingImage?.props.onLoad as (() => void) | undefined)?.(); + hooks.beginRender(); + const loaded = AcpRegistryAgentIcon({ icon: url }) as ReactElement>; + expect( + visitElements(loaded, (element) => element.type === "img")?.props.className, + ).not.toContain("invisible"); + expect( + visitElements(loaded, (element) => element.props["data-slot"] === "acp-icon-fallback"), + ).toBeNull(); + + const loadedImage = visitElements(loaded, (element) => element.type === "img"); + (loadedImage?.props.onError as (() => void) | undefined)?.(); + hooks.beginRender(); + const failed = AcpRegistryAgentIcon({ icon: url }) as ReactElement>; + expect(visitElements(failed, (element) => element.type === "img")).toBeNull(); + expect( + visitElements(failed, (element) => element.props["data-slot"] === "acp-icon-fallback"), + ).not.toBeNull(); + }); +}); diff --git a/apps/web/src/components/settings/AcpRegistryIcon.tsx b/apps/web/src/components/settings/AcpRegistryIcon.tsx new file mode 100644 index 0000000000000..62553177d14e3 --- /dev/null +++ b/apps/web/src/components/settings/AcpRegistryIcon.tsx @@ -0,0 +1,170 @@ +import { useEffect, useId, useState } from "react"; +import { + resolveOfficialAcpRegistryIconUrl, + officialAcpRegistryIconUrlForAgentId, +} from "@t3tools/contracts"; + +import { cn } from "../../lib/utils"; +import { ACPRegistryIcon } from "../Icons"; + +const ACP_REGISTRY_ICON_CACHE = "t3-acp-registry-icons-v1"; +const MAX_ICON_BYTES = 512 * 1_024; +const inFlightIcons = new Map>(); + +export { officialAcpRegistryIconUrlForAgentId, resolveOfficialAcpRegistryIconUrl }; + +async function checkedIconBlob(response: Response): Promise { + if (!response.ok || response.redirected) throw new Error("ACP registry icon request failed."); + const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim() ?? ""; + if (!contentType.startsWith("image/")) throw new Error("ACP registry icon was not an image."); + const contentLength = Number(response.headers.get("content-length")); + if (Number.isFinite(contentLength) && contentLength > MAX_ICON_BYTES) { + throw new Error("ACP registry icon was too large."); + } + const bytes = await response.arrayBuffer(); + if (bytes.byteLength > MAX_ICON_BYTES) throw new Error("ACP registry icon was too large."); + return new Blob([bytes], { type: contentType }); +} + +/** Fetches an official icon once, then serves it from persistent browser cache. */ +export function loadCachedAcpRegistryIcon(iconUrl: string): Promise { + if (resolveOfficialAcpRegistryIconUrl(iconUrl) !== iconUrl) { + return Promise.reject(new Error("ACP registry icon URL was not allowed.")); + } + const pending = inFlightIcons.get(iconUrl); + if (pending) return pending; + const load = (async () => { + let cache: Cache | null = null; + if (typeof caches !== "undefined") { + try { + cache = await caches.open(ACP_REGISTRY_ICON_CACHE); + } catch { + // Some privacy modes expose CacheStorage but reject access. Icons can + // still load normally from the allowlisted registry CDN. + } + } + if (cache !== null) { + try { + const cached = await cache.match(iconUrl); + if (cached) return await checkedIconBlob(cached); + } catch { + // Ignore unreadable or invalid cache entries and repair from network. + } + } + + const response = await fetch(iconUrl, { + credentials: "omit", + redirect: "error", + referrerPolicy: "no-referrer", + }); + const clone = response.clone(); + const blob = await checkedIconBlob(response); + await cache?.put(iconUrl, clone).catch(() => undefined); + return blob; + })(); + inFlightIcons.set(iconUrl, load); + void load.then( + () => inFlightIcons.delete(iconUrl), + () => inFlightIcons.delete(iconUrl), + ); + return load; +} + +export function AcpRegistryAgentIcon({ + icon, + className, + fallbackClassName, +}: { + readonly icon: string | null; + readonly className?: string; + readonly fallbackClassName?: string; +}) { + const colorFilterId = useId(); + const iconUrl = resolveOfficialAcpRegistryIconUrl(icon); + const [image, setImage] = useState<{ + readonly iconUrl: string; + readonly source: string; + readonly status: "loading" | "loaded" | "failed"; + } | null>(null); + const currentImage = image?.iconUrl === iconUrl ? image : null; + // Render only after the load pipeline resolves: the validated blob when the + // fetch succeeds, or the raw allowlisted CDN URL when it fails (the official + // CDN serves no CORS headers, so the validating fetch is often blocked in + // cross-origin browser contexts while native loading still works). + const source = currentImage?.source ?? null; + const status = currentImage?.status ?? "loading"; + + useEffect(() => { + if (iconUrl === null) return; + let active = true; + let objectUrl: string | null = null; + void loadCachedAcpRegistryIcon(iconUrl) + .then((blob) => { + if (!active) return; + objectUrl = URL.createObjectURL(blob); + setImage({ iconUrl, source: objectUrl, status: "loading" }); + }) + .catch(() => { + if (!active) return; + setImage((current) => + current?.iconUrl === iconUrl ? current : { iconUrl, source: iconUrl, status: "loading" }, + ); + }); + return () => { + active = false; + if (objectUrl !== null) URL.revokeObjectURL(objectUrl); + }; + }, [iconUrl]); + + return ( + + {/* Registry glyphs are monochrome. Recolor their alpha rather than + inverting RGB values; external images cannot inherit currentColor. + A local SVG filter also works when CDN CORS prevents CSS masks. */} + + + + + + + + + {status !== "loaded" ? ( + + ) : null} + {source !== null && status !== "failed" ? ( + { + if (iconUrl === null) return; + setImage((current) => + current?.iconUrl === iconUrl && current.source !== source + ? current + : { iconUrl, source, status: "failed" }, + ); + }} + onLoad={() => { + if (iconUrl !== null) setImage({ iconUrl, source, status: "loaded" }); + }} + /> + ) : null} + + ); +} diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx new file mode 100644 index 0000000000000..36aecc1a48940 --- /dev/null +++ b/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx @@ -0,0 +1,331 @@ +import type { ReactElement } from "react"; +import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { visitElements } from "../../test/reactElementTree"; +import { reactHookHarness as hooks } from "../../test/reactHookHarness"; + +const atoms = vi.hoisted(() => ({ + search: Symbol("acp-search"), + prepare: Symbol("acp-prepare"), +})); + +const state = vi.hoisted(() => ({ + result: null as { readonly agents: ReadonlyArray } | null, + error: null as string | null, + isPending: false, + refresh: vi.fn(), + search: vi.fn(() => atoms.search), + prepare: vi.fn(), +})); + +const lifecycle = vi.hoisted(() => ({ + cleanups: [] as Array<() => void>, +})); + +vi.mock("react", async (importOriginal) => { + const actual = await importOriginal(); + const { reactHookHarness } = await import("../../test/reactHookHarness"); + return { + ...actual, + useEffect: (effect: () => void | (() => void)) => { + const cleanup = effect(); + if (cleanup) lifecycle.cleanups.push(cleanup); + }, + useRef: reactHookHarness.useRef, + useLayoutEffect: (effect: () => void | (() => void)) => { + const cleanup = effect(); + if (cleanup) lifecycle.cleanups.push(cleanup); + }, + useState: reactHookHarness.useState, + }; +}); + +vi.mock("react/compiler-runtime", async () => { + const { reactHookHarness } = await import("../../test/reactHookHarness"); + return { c: reactHookHarness.useMemoCache }; +}); + +vi.mock("../../state/server", () => ({ + serverEnvironment: { + searchAcpRegistry: state.search, + prepareAcpRegistryAgent: atoms.prepare, + }, +})); + +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: () => ({ + data: state.result, + error: state.error, + isPending: state.isPending, + refresh: state.refresh, + }), +})); + +vi.mock("../../state/use-atom-command", () => ({ + useAtomCommand: () => state.prepare, +})); + +vi.mock("@t3tools/client-runtime/state/runtime", () => ({ + isAtomCommandInterrupted: () => false, + squashAtomCommandFailure: () => new Error("Prepare failed."), +})); + +import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep"; + +const environmentId = EnvironmentId.make("remote-device"); +const gemini: AcpRegistrySearchAgent = { + id: "gemini", + name: "Gemini CLI", + version: "1.2.3", + description: "Google's agent", + authors: ["Google ", "Contributor"], + license: "Apache-2.0", + website: "https://example.com/docs", + repository: "https://example.com/source", + icon: "https://example.com/icon.png", + distribution: "npx", + integrity: "registry", +}; + +function render(options?: { + readonly configured?: boolean; + readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void; +}): ReactElement> { + hooks.beginRender(); + return AcpRegistrySearchStep({ + environmentId, + providerInstances: options?.configured + ? { + acpRegistry_gemini: { + driver: ProviderDriverKind.make("acpRegistry"), + config: { agentId: "gemini" }, + }, + } + : {}, + onPrepared: options?.onPrepared ?? vi.fn(), + onManualConfiguration: vi.fn(), + }) as ReactElement>; +} + +function findByAriaLabel( + tree: ReactElement>, + label: string, +): ReactElement> { + const found = visitElements(tree, (element) => element.props["aria-label"] === label); + expect(found).not.toBeNull(); + return found!; +} + +describe("AcpRegistrySearchStep", () => { + beforeEach(() => { + hooks.reset(); + state.result = null; + state.error = null; + state.isPending = false; + state.refresh.mockReset(); + state.search.mockClear(); + state.prepare.mockReset().mockResolvedValue({ + _tag: "Success", + value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true }, + }); + lifecycle.cleanups = []; + vi.stubGlobal( + "fetch", + vi.fn(() => new Promise(() => {})), + ); + }); + + it("loads the full compatible catalog on open and narrows it with a search", () => { + const initial = render(); + expect(state.search).toHaveBeenLastCalledWith({ + environmentId, + input: { query: "" }, + }); + + const input = findByAriaLabel(initial, "Search ACP Registry"); + expect(input.props.size).toBe("sm"); + (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.( + { currentTarget: { value: " Gemini " } }, + ); + const narrowedDraft = render(); + const form = visitElements(narrowedDraft, (element) => element.type === "form"); + (form?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.({ + preventDefault: vi.fn(), + }); + + render(); + expect(state.search).toHaveBeenLastCalledWith({ + environmentId, + input: { query: "Gemini" }, + }); + }); + + it("renders deterministic loading, error, and empty states", () => { + state.isPending = true; + expect( + visitElements(render(), (element) => element.props.children === "Searching the registry..."), + ).not.toBeNull(); + + state.isPending = false; + state.error = "Registry unavailable."; + expect( + visitElements(render(), (element) => element.props.children === "Registry unavailable."), + ).not.toBeNull(); + + state.error = null; + state.result = { agents: [] }; + expect( + visitElements(render(), (element) => element.props.children === "No compatible agents found"), + ).not.toBeNull(); + }); + + it("keeps same-query refreshes visible and announced while retaining results", () => { + const first = render(); + const suggestion = visitElements(first, (element) => element.props.children === "Codex"); + (suggestion?.props.onClick as (() => void) | undefined)?.(); + + state.result = { agents: [gemini] }; + const resultTree = render(); + expect(state.search).toHaveBeenCalledWith({ + environmentId, + input: { query: "Codex" }, + }); + const form = visitElements(resultTree, (element) => element.type === "form"); + (form?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.({ + preventDefault: vi.fn(), + }); + expect(state.refresh).toHaveBeenCalledOnce(); + + state.isPending = true; + const refreshingTree = render(); + expect( + visitElements( + refreshingTree, + (element) => element.props.children === "Refreshing registry results...", + ), + ).not.toBeNull(); + expect( + visitElements( + refreshingTree, + (element) => + element.props.role === "status" && + element.props.children === "Refreshing ACP Registry results.", + ), + ).not.toBeNull(); + expect(findByAriaLabel(refreshingTree, "Add Gemini CLI")).not.toBeNull(); + }); + + it("prepares a result before handing it back to the wizard", async () => { + state.prepare.mockResolvedValueOnce({ + _tag: "Success", + value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true }, + }); + state.result = { agents: [gemini] }; + const onPrepared = vi.fn(); + const tree = render({ onPrepared }); + + const add = findByAriaLabel(tree, "Add Gemini CLI"); + (add.props.onClick as (() => void) | undefined)?.(); + await Promise.resolve(); + await Promise.resolve(); + + expect(state.prepare).toHaveBeenCalledWith({ + environmentId, + input: { agentId: "gemini" }, + }); + expect(onPrepared).toHaveBeenCalledWith({ + ...gemini, + version: "2.0.0", + distribution: "binary", + }); + }); + + it("ignores a stale prepare completion", async () => { + let resolveFirst!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void; + let resolveSecond!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void; + state.prepare + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirst = resolve; + }), + ) + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveSecond = resolve; + }), + ); + state.result = { agents: [gemini] }; + const onPrepared = vi.fn(); + const tree = render({ onPrepared }); + const add = findByAriaLabel(tree, "Add Gemini CLI"); + + (add.props.onClick as (() => void) | undefined)?.(); + (add.props.onClick as (() => void) | undefined)?.(); + resolveFirst({ _tag: "Success", value: {} }); + await Promise.resolve(); + expect(onPrepared).not.toHaveBeenCalled(); + + resolveSecond({ _tag: "Success", value: {} }); + await Promise.resolve(); + expect(onPrepared).toHaveBeenCalledOnce(); + }); + + it("ignores prepare completion after unmount", async () => { + let resolvePrepare!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void; + state.prepare.mockImplementationOnce( + () => + new Promise((resolve) => { + resolvePrepare = resolve; + }), + ); + state.result = { agents: [gemini] }; + const onPrepared = vi.fn(); + const tree = render({ onPrepared }); + + const add = findByAriaLabel(tree, "Add Gemini CLI"); + (add.props.onClick as (() => void) | undefined)?.(); + for (const cleanup of lifecycle.cleanups) cleanup(); + resolvePrepare({ _tag: "Success", value: {} }); + await Promise.resolve(); + + expect(onPrepared).not.toHaveBeenCalled(); + }); + + it("renders existing registry configuration as already added", () => { + state.result = { agents: [gemini] }; + const tree = render({ configured: true }); + const added = findByAriaLabel(tree, "Already added Gemini CLI"); + + expect(added.props.disabled).toBe(true); + }); + + it("shows catalog metadata, uniquely named reference links, and a local icon fallback", () => { + state.result = { agents: [gemini] }; + const tree = render(); + + // Author emails are stripped, registry-integrity gets no marker, and the + // version renders beside the name instead of inside the meta line. + for (const item of ["Google +1", "v1.2.3", "npx", "Apache-2.0"]) { + expect(visitElements(tree, (element) => element.props.children === item)).not.toBeNull(); + } + for (const absent of ["Registry", "✓ checksum"]) { + expect(visitElements(tree, (element) => element.props.children === absent)).toBeNull(); + } + expect( + visitElements( + tree, + (element) => element.props["aria-label"] === "Open documentation for Gemini CLI (gemini)", + ), + ).not.toBeNull(); + expect( + visitElements( + tree, + (element) => element.props["aria-label"] === "Open source for Gemini CLI (gemini)", + ), + ).not.toBeNull(); + expect(visitElements(tree, (element) => element.type === "img")).toBeNull(); + }); +}); diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx new file mode 100644 index 0000000000000..1e0fb679e5813 --- /dev/null +++ b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx @@ -0,0 +1,336 @@ +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { + AcpRegistryPrepareResult, + AcpRegistrySearchAgent, + EnvironmentId, + ProviderInstanceConfig, +} from "@t3tools/contracts"; +import { ExternalLinkIcon, SearchIcon } from "lucide-react"; +import { type FormEvent, useEffect, useLayoutEffect, useRef, useState } from "react"; + +import { serverEnvironment } from "../../state/server"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { Button } from "../ui/button"; +import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; +import { ScrollArea } from "../ui/scroll-area"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { isConfiguredAcpRegistryAgent } from "./AddProviderInstanceDialog.logic"; +import { ProviderDriverKind } from "@t3tools/contracts"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; + +const SUGGESTED_SEARCHES = ["Codex", "Copilot", "Kimi"] as const; +function errorMessage(error: unknown): string { + return error instanceof Error && error.message.trim() + ? error.message + : "The ACP could not be prepared."; +} + +function authorDisplayName(author: string): string { + // Registry authors may be "Name " package-style strings. + return author.replace(/<[^>]*>/g, "").trim(); +} + +function authorSummary(authors: ReadonlyArray): string | null { + const names = authors.map(authorDisplayName).filter((name) => name.length > 0); + const first = names[0]; + if (!first) return null; + return names.length === 1 ? first : `${first} +${names.length - 1}`; +} + +function metadata(entry: AcpRegistrySearchAgent): ReadonlyArray { + return [authorSummary(entry.authors), entry.distribution, entry.license].filter( + (value): value is string => Boolean(value), + ); +} + +interface AcpRegistrySearchStepProps { + readonly environmentId: EnvironmentId; + readonly providerInstances: Readonly>; + readonly onPrepared: (agent: AcpRegistrySearchAgent) => void; + readonly onManualConfiguration: () => void; + readonly onLoadingChange?: (loading: boolean) => void; +} + +function applyAcpRegistryPrepareResult( + agent: AcpRegistrySearchAgent, + prepared: AcpRegistryPrepareResult, +): AcpRegistrySearchAgent { + return { + ...agent, + id: prepared.agentId, + version: prepared.version, + distribution: prepared.distribution, + }; +} + +export function AcpRegistrySearchStep({ + environmentId, + providerInstances, + onPrepared, + onManualConfiguration, + onLoadingChange, +}: AcpRegistrySearchStepProps) { + const [query, setQuery] = useState(""); + // An empty registry query is the compact compatible catalog. Start there so + // entering this step is useful before the user knows what to search for. + const [submittedQuery, setSubmittedQuery] = useState(""); + const [preparingId, setPreparingId] = useState(null); + const [prepareError, setPrepareError] = useState(null); + const prepareGeneration = useRef(0); + const search = useEnvironmentQuery( + serverEnvironment.searchAcpRegistry({ + environmentId, + input: { query: submittedQuery }, + }), + ); + const prepareAgent = useAtomCommand(serverEnvironment.prepareAcpRegistryAgent, { + reportFailure: false, + }); + + useEffect( + () => () => { + prepareGeneration.current += 1; + }, + [], + ); + + const submitSearch = (nextQuery: string) => { + const trimmed = nextQuery.trim(); + setQuery(trimmed); + setPrepareError(null); + if (trimmed === submittedQuery) { + search.refresh(); + } else { + setSubmittedQuery(trimmed); + } + }; + + const handleSearch = (event: FormEvent) => { + event.preventDefault(); + submitSearch(query); + }; + + const handlePrepare = async (agent: AcpRegistrySearchAgent) => { + const generation = ++prepareGeneration.current; + setPrepareError(null); + setPreparingId(agent.id); + const result = await prepareAgent({ environmentId, input: { agentId: agent.id } }); + if (prepareGeneration.current !== generation) return; + setPreparingId(null); + if (result._tag === "Success") { + onPrepared(applyAcpRegistryPrepareResult(agent, result.value)); + return; + } + if (!isAtomCommandInterrupted(result)) { + setPrepareError(errorMessage(squashAtomCommandFailure(result))); + } + }; + + const results = search.data?.agents ?? null; + const isInitialSearch = search.isPending && results === null; + const isRefreshing = search.isPending && results !== null; + const resultCount = results?.length ?? 0; + + useLayoutEffect(() => { + onLoadingChange?.(search.isPending); + return () => onLoadingChange?.(false); + }, [onLoadingChange, search.isPending]); + + return ( +
    +
    +

    + Find an ACP agent +

    +

    + Search compatible agents in the official ACP Registry for this environment. +

    +
    + +
    + + + + + setQuery(event.currentTarget.value)} + placeholder="Search by agent, author, or description" + size="sm" + type="search" + value={query} + /> + + +
    + + {!isInitialSearch ? ( +
    + Try + {SUGGESTED_SEARCHES.map((suggestion) => ( + + ))} +
    + ) : null} + +
    + {isInitialSearch + ? "Searching the ACP Registry." + : isRefreshing + ? "Refreshing ACP Registry results." + : results + ? `${resultCount} compatible ${resultCount === 1 ? "agent" : "agents"} found.` + : ""} +
    + + {search.error || prepareError ? ( +
    + {prepareError ?? search.error} +
    + ) : null} + + {isInitialSearch ? ( +
    + Searching the registry... +
    + ) : null} + + {isRefreshing ? ( +

    Refreshing registry results...

    + ) : null} + + {results ? ( + results.length === 0 ? ( +
    +

    No compatible agents found

    +

    Try a broader search.

    +
    + ) : ( + + {/* The overlay scrollbar takes no layout space, so the rows + reserve its lane explicitly. */} +
    + {results.map((agent) => { + const alreadyAdded = isConfiguredAcpRegistryAgent(providerInstances, agent.id); + const isPreparing = preparingId === agent.id; + const progressLabel = agent.distribution === "binary" ? "Downloading" : "Preparing"; + return ( +
    +
    +
    + +
    +
    +

    + {agent.name} +

    + + {`v${agent.version}`} + +
    +

    + {agent.description || + "An agent available through the official ACP Registry."} +

    +
    +
    + +
    +
    +
    + ); + })} +
    + + ) + ) : null} + + {/* DialogPanel collapses its own bottom padding when the dialog footer + is bare, so this row carries the breathing room itself. */} +
    +

    + Authentication is completed separately with the selected agent. +

    + +
    +
    + ); +} diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx new file mode 100644 index 0000000000000..17c673efa594b --- /dev/null +++ b/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx @@ -0,0 +1,294 @@ +import type { ReactElement } from "react"; +import { + EnvironmentId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, + type ServerProvider, +} from "@t3tools/contracts"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { visitElements } from "../../test/reactElementTree"; +import { reactHookHarness as hooks } from "../../test/reactHookHarness"; + +const atoms = vi.hoisted(() => ({ + list: Symbol("list-acp-sessions"), + import: Symbol("import-acp-session"), + delete: Symbol("delete-acp-session"), + listProviders: Symbol("list-acp-providers"), + setProvider: Symbol("set-acp-provider"), + disableProvider: Symbol("disable-acp-provider"), + logout: Symbol("logout-acp"), +})); + +const commands = vi.hoisted(() => ({ + list: vi.fn(), + import: vi.fn(), + delete: vi.fn(), + listProviders: vi.fn(), + setProvider: vi.fn(), + disableProvider: vi.fn(), + logout: vi.fn(), +})); + +const dialogs = vi.hoisted(() => ({ confirm: vi.fn() })); + +vi.mock("react", async (importOriginal) => { + const actual = await importOriginal(); + const { reactHookHarness } = await import("../../test/reactHookHarness"); + return { + ...actual, + useState: reactHookHarness.useState, + }; +}); + +vi.mock("react/compiler-runtime", async () => { + const { reactHookHarness } = await import("../../test/reactHookHarness"); + return { c: reactHookHarness.useMemoCache }; +}); + +vi.mock("../../state/server", () => ({ + serverEnvironment: { + listAcpRegistrySessions: atoms.list, + importAcpRegistrySession: atoms.import, + deleteAcpRegistrySession: atoms.delete, + listAcpRegistryProviders: atoms.listProviders, + setAcpRegistryProvider: atoms.setProvider, + disableAcpRegistryProvider: atoms.disableProvider, + logoutAcpRegistry: atoms.logout, + }, +})); + +vi.mock("../../state/use-atom-command", () => ({ + useAtomCommand: (atom: symbol) => { + if (atom === atoms.list) return commands.list; + if (atom === atoms.import) return commands.import; + if (atom === atoms.delete) return commands.delete; + if (atom === atoms.listProviders) return commands.listProviders; + if (atom === atoms.setProvider) return commands.setProvider; + if (atom === atoms.disableProvider) return commands.disableProvider; + return commands.logout; + }, +})); + +vi.mock("../../localApi", () => ({ + ensureLocalApi: () => ({ dialogs }), +})); + +import { AcpSessionManagementSection } from "./AcpSessionManagementSection"; + +const environmentId = EnvironmentId.make("remote-device"); +const instanceId = ProviderInstanceId.make("acpRegistry_antigravity"); +const projectId = ProjectId.make("project-antigravity"); +const session = { + sessionId: "native-session-1", + cwd: "/workspace/antigravity", + additionalDirectories: [], + title: "Native Antigravity session", + updatedAt: "2026-08-23T00:00:00Z", + importedThreadId: null, +} as const; +const provider = { + instanceId, + driver: ProviderDriverKind.make("acpRegistry"), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated", canLogout: true }, + nativeSessions: { canList: true, canLoad: true, canResume: true, canDelete: true }, + configurableProviders: true, + checkedAt: "2026-08-23T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], +} satisfies ServerProvider; + +function render(): ReactElement> { + hooks.beginRender(); + return AcpSessionManagementSection({ + environmentId, + instanceId, + provider, + projects: [{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }], + readOnly: false, + }) as ReactElement>; +} + +function findByLabel( + tree: ReactElement>, + label: string, +): ReactElement> { + const found = visitElements(tree, (element) => element.props.children === label); + expect(found).not.toBeNull(); + return found!; +} + +function findByAriaLabel( + tree: ReactElement>, + label: string, +): ReactElement> { + const found = visitElements(tree, (element) => element.props["aria-label"] === label); + expect(found).not.toBeNull(); + return found!; +} + +async function flushPromises(): Promise { + await Promise.resolve(); + await Promise.resolve(); +} + +describe("AcpSessionManagementSection", () => { + beforeEach(() => { + hooks.reset(); + commands.list.mockReset().mockResolvedValue({ + _tag: "Success", + value: { + sessions: [session], + nextCursor: null, + canLoad: true, + canResume: true, + canDelete: true, + }, + }); + commands.import.mockReset().mockResolvedValue({ + _tag: "Success", + value: { threadId: ThreadId.make("thread-imported"), imported: true }, + }); + commands.delete.mockReset().mockResolvedValue({ + _tag: "Success", + value: { deleted: true }, + }); + commands.listProviders.mockReset().mockResolvedValue({ + _tag: "Success", + value: { + providers: [ + { + providerId: "google", + supported: ["openai"], + required: false, + current: { apiType: "openai", baseUrl: "https://api.example.test/v1" }, + }, + ], + }, + }); + commands.setProvider.mockReset().mockResolvedValue({ + _tag: "Success", + value: { configured: true }, + }); + commands.disableProvider.mockReset().mockResolvedValue({ + _tag: "Success", + value: { disabled: true }, + }); + commands.logout.mockReset().mockResolvedValue({ + _tag: "Success", + value: { loggedOut: true }, + }); + dialogs.confirm.mockReset().mockResolvedValue(true); + }); + + it("lists and imports native sessions through the owning environment", async () => { + const initial = render(); + (findByLabel(initial, "List sessions").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + + expect(commands.list).toHaveBeenCalledWith({ + environmentId, + input: { instanceId, projectId }, + }); + + const listed = render(); + (findByLabel(listed, "Import").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + + expect(commands.import).toHaveBeenCalledWith({ + environmentId, + input: { + instanceId, + projectId, + sessionId: session.sessionId, + title: session.title, + updatedAt: session.updatedAt, + }, + }); + expect(findByLabel(render(), "Imported")).not.toBeNull(); + }); + + it("logs out the provider instance through the owning environment", async () => { + const tree = render(); + (findByLabel(tree, "Log out").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + + expect(commands.logout).toHaveBeenCalledWith({ + environmentId, + input: { instanceId }, + }); + }); + + it("deletes unimported native sessions after destructive confirmation", async () => { + (findByLabel(render(), "List sessions").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + (findByLabel(render(), "Delete").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + + expect(dialogs.confirm).toHaveBeenCalledOnce(); + expect(commands.delete).toHaveBeenCalledWith({ + environmentId, + input: { instanceId, projectId, sessionId: session.sessionId }, + }); + }); + + it("locks the project picker while a project-scoped request is pending", async () => { + let resolveProviders!: (result: { + readonly _tag: "Success"; + readonly value: { readonly providers: [] }; + }) => void; + commands.listProviders.mockReturnValueOnce( + new Promise((resolve) => { + resolveProviders = resolve; + }), + ); + (findByLabel(render(), "List providers").props.onClick as (() => void) | undefined)?.(); + + const projectSelect = visitElements( + render(), + (element) => + element.props.value === projectId && typeof element.props.onValueChange === "function", + ); + expect(projectSelect?.props.disabled).toBe(true); + resolveProviders({ _tag: "Success", value: { providers: [] } }); + await flushPromises(); + }); + + it("lists, saves, and disables configurable ACP providers", async () => { + (findByLabel(render(), "List providers").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + + expect(commands.listProviders).toHaveBeenCalledWith({ + environmentId, + input: { instanceId, projectId }, + }); + const providers = render(); + expect(findByAriaLabel(providers, "google protocol").props.size).toBe("sm"); + (findByLabel(providers, "Save").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + expect(commands.setProvider).toHaveBeenCalledWith({ + environmentId, + input: { + instanceId, + projectId, + providerId: "google", + apiType: "openai", + baseUrl: "https://api.example.test/v1", + }, + }); + + (findByLabel(render(), "Disable").props.onClick as (() => void) | undefined)?.(); + await flushPromises(); + expect(commands.disableProvider).toHaveBeenCalledWith({ + environmentId, + input: { instanceId, projectId, providerId: "google" }, + }); + }); +}); diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.tsx new file mode 100644 index 0000000000000..e66dbba60ad6e --- /dev/null +++ b/apps/web/src/components/settings/AcpSessionManagementSection.tsx @@ -0,0 +1,567 @@ +import type { + AcpRegistryConfigurableProvider, + AcpRegistrySession, + EnvironmentId, + ProjectId, + ProviderInstanceId, + ServerProvider, +} from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { useState } from "react"; + +import { ensureLocalApi } from "../../localApi"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { toastManager } from "../ui/toast"; + +interface AcpSessionProject { + readonly id: ProjectId; + readonly title: string; + readonly workspaceRoot: string; +} + +function reportFailure(title: string, result: AtomCommandResult) { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title, + description: error instanceof Error ? error.message : "The ACP operation failed.", + }); +} + +export function AcpSessionManagementSection(props: { + readonly environmentId: EnvironmentId; + readonly instanceId: ProviderInstanceId; + readonly provider: ServerProvider; + readonly projects: ReadonlyArray; + readonly readOnly: boolean; +}) { + const [projectId, setProjectId] = useState(props.projects[0]?.id ?? null); + const [sessions, setSessions] = useState>([]); + const [nextCursor, setNextCursor] = useState(null); + const [loading, setLoading] = useState(false); + const [importingSessionId, setImportingSessionId] = useState(null); + const [deletingSessionId, setDeletingSessionId] = useState(null); + const [loggingOut, setLoggingOut] = useState(false); + const [providers, setProviders] = useState>([]); + const [loadingProviders, setLoadingProviders] = useState(false); + const [savingProviderId, setSavingProviderId] = useState(null); + const [providerDrafts, setProviderDrafts] = useState< + Readonly> + >({}); + const listSessions = useAtomCommand(serverEnvironment.listAcpRegistrySessions, { + reportFailure: false, + }); + const importSession = useAtomCommand(serverEnvironment.importAcpRegistrySession, { + reportFailure: false, + }); + const deleteSession = useAtomCommand(serverEnvironment.deleteAcpRegistrySession, { + reportFailure: false, + }); + const listProviders = useAtomCommand(serverEnvironment.listAcpRegistryProviders, { + reportFailure: false, + }); + const setProvider = useAtomCommand(serverEnvironment.setAcpRegistryProvider, { + reportFailure: false, + }); + const disableProvider = useAtomCommand(serverEnvironment.disableAcpRegistryProvider, { + reportFailure: false, + }); + const logout = useAtomCommand(serverEnvironment.logoutAcpRegistry, { reportFailure: false }); + const canList = props.provider.nativeSessions?.canList === true; + const canImport = + props.provider.nativeSessions?.canLoad === true || + props.provider.nativeSessions?.canResume === true; + const canLogout = props.provider.auth.canLogout === true; + const canDelete = props.provider.nativeSessions?.canDelete === true; + const canConfigureProviders = props.provider.configurableProviders === true; + const projectOperationPending = + loading || + importingSessionId !== null || + deletingSessionId !== null || + loadingProviders || + savingProviderId !== null; + + if (!canList && !canLogout && !canConfigureProviders) return null; + + const loadSessions = async (cursor?: string) => { + if (projectId === null || loading) return; + setLoading(true); + const result = await listSessions({ + environmentId: props.environmentId, + input: { + instanceId: props.instanceId, + projectId, + ...(cursor === undefined ? {} : { cursor }), + }, + }); + setLoading(false); + if (result._tag === "Success") { + setSessions((current) => + cursor === undefined ? result.value.sessions : [...current, ...result.value.sessions], + ); + setNextCursor(result.value.nextCursor); + return; + } + reportFailure("Could not list ACP sessions", result); + }; + + const importNativeSession = async (session: AcpRegistrySession) => { + if (projectId === null || importingSessionId !== null) return; + setImportingSessionId(session.sessionId); + const result = await importSession({ + environmentId: props.environmentId, + input: { + instanceId: props.instanceId, + projectId, + sessionId: session.sessionId, + title: session.title, + updatedAt: session.updatedAt, + }, + }); + setImportingSessionId(null); + if (result._tag === "Success") { + setSessions((current) => + current.map((candidate) => + candidate.sessionId === session.sessionId + ? { ...candidate, importedThreadId: result.value.threadId } + : candidate, + ), + ); + toastManager.add({ + type: "success", + title: result.value.imported ? "ACP session imported" : "ACP session already imported", + }); + return; + } + reportFailure("Could not import ACP session", result); + }; + + const deleteNativeSession = async (session: AcpRegistrySession) => { + if (projectId === null || deletingSessionId !== null || session.importedThreadId !== null) + return; + const confirmed = await ensureLocalApi().dialogs.confirm( + `Permanently delete native ACP session "${session.title ?? session.sessionId}"?`, + { variant: "destructive" }, + ); + if (!confirmed) return; + setDeletingSessionId(session.sessionId); + const result = await deleteSession({ + environmentId: props.environmentId, + input: { instanceId: props.instanceId, projectId, sessionId: session.sessionId }, + }); + setDeletingSessionId(null); + if (result._tag === "Success") { + setSessions((current) => + current.filter((candidate) => candidate.sessionId !== session.sessionId), + ); + toastManager.add({ type: "success", title: "ACP session deleted" }); + return; + } + reportFailure("Could not delete ACP session", result); + }; + + const loadProviders = async () => { + if (projectId === null || loadingProviders) return; + setLoadingProviders(true); + const result = await listProviders({ + environmentId: props.environmentId, + input: { instanceId: props.instanceId, projectId }, + }); + setLoadingProviders(false); + if (result._tag === "Success") { + setProviders(result.value.providers); + setProviderDrafts( + Object.fromEntries( + result.value.providers.map((provider) => [ + provider.providerId, + { + apiType: provider.current?.apiType ?? provider.supported[0] ?? "", + baseUrl: provider.current?.baseUrl ?? "", + headers: "", + }, + ]), + ), + ); + return; + } + reportFailure("Could not list ACP providers", result); + }; + + const saveProvider = async (provider: AcpRegistryConfigurableProvider) => { + if (projectId === null || savingProviderId !== null) return; + const draft = providerDrafts[provider.providerId]; + if (draft === undefined || draft.apiType.length === 0 || draft.baseUrl.length === 0) return; + let headers: Record | undefined; + if (draft.headers.trim().length > 0) { + try { + const parsed: unknown = JSON.parse(draft.headers); + if ( + typeof parsed !== "object" || + parsed === null || + Array.isArray(parsed) || + !Object.values(parsed).every((value) => typeof value === "string") + ) { + throw new Error("Headers must be a JSON object with string values."); + } + headers = parsed as Record; + } catch (error) { + toastManager.add({ + type: "error", + title: "Invalid provider headers", + description: error instanceof Error ? error.message : "Headers must be valid JSON.", + }); + return; + } + } + setSavingProviderId(provider.providerId); + const result = await setProvider({ + environmentId: props.environmentId, + input: { + instanceId: props.instanceId, + projectId, + providerId: provider.providerId, + apiType: draft.apiType, + baseUrl: draft.baseUrl, + ...(headers === undefined ? {} : { headers }), + }, + }); + setSavingProviderId(null); + if (result._tag === "Success") { + toastManager.add({ type: "success", title: "ACP provider configured" }); + await loadProviders(); + return; + } + reportFailure("Could not configure ACP provider", result); + }; + + const disableConfiguredProvider = async (provider: AcpRegistryConfigurableProvider) => { + if (projectId === null || savingProviderId !== null || provider.required) return; + const confirmed = await ensureLocalApi().dialogs.confirm( + `Disable ACP provider "${provider.providerId}"?`, + { variant: "destructive" }, + ); + if (!confirmed) return; + setSavingProviderId(provider.providerId); + const result = await disableProvider({ + environmentId: props.environmentId, + input: { instanceId: props.instanceId, projectId, providerId: provider.providerId }, + }); + setSavingProviderId(null); + if (result._tag === "Success") { + toastManager.add({ type: "success", title: "ACP provider disabled" }); + await loadProviders(); + return; + } + reportFailure("Could not disable ACP provider", result); + }; + + const logoutProvider = async () => { + if (loggingOut) return; + setLoggingOut(true); + const result = await logout({ + environmentId: props.environmentId, + input: { instanceId: props.instanceId }, + }); + setLoggingOut(false); + if (result._tag === "Success") { + setSessions([]); + setNextCursor(null); + toastManager.add({ type: "success", title: "Logged out of ACP agent" }); + return; + } + reportFailure("Could not log out of ACP agent", result); + }; + + return ( +
    +
    +
    +

    Native sessions

    +

    + Resume agent-owned conversations as T3 threads. +

    +
    + {canLogout ? ( + + ) : null} +
    + + {canList ? ( + props.projects.length === 0 ? ( +

    + Add a project on this device before importing native sessions. +

    + ) : ( + <> +
    + + +
    + + {sessions.length > 0 ? ( +
    + {sessions.map((session) => ( +
    +
    +

    + {session.title ?? session.sessionId} +

    + + {session.sessionId} + +
    +
    + + {canDelete ? ( + + ) : null} +
    +
    + ))} +
    + ) : null} + + {nextCursor !== null ? ( + + ) : null} + + ) + ) : null} + + {canConfigureProviders ? ( +
    +
    +
    +

    Agent providers

    +

    + Configure non-secret routing. Headers are write-only. +

    +
    + +
    + + {!canList && props.projects.length > 1 ? ( + + ) : null} + + {providers.length > 0 ? ( +
    + {providers.map((provider) => { + const draft = providerDrafts[provider.providerId] ?? { + apiType: provider.current?.apiType ?? provider.supported[0] ?? "", + baseUrl: provider.current?.baseUrl ?? "", + headers: "", + }; + const updateDraft = (update: Partial) => + setProviderDrafts((current) => ({ + ...current, + [provider.providerId]: { ...draft, ...update }, + })); + return ( +
    +
    +
    +

    + {provider.providerId} +

    +

    + {provider.current === null ? "Disabled" : "Configured"} + {provider.required ? " · Required" : ""} +

    +
    +
    + + {!provider.required && provider.current !== null ? ( + + ) : null} +
    +
    +
    + + updateDraft({ baseUrl: value })} + /> +
    + updateDraft({ headers: value })} + /> +
    + ); + })} +
    + ) : null} +
    + ) : null} +
    + ); +} diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx index 3c502c624ddd1..c6ad48ee3056f 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx @@ -1,11 +1,13 @@ -import { EnvironmentId } from "@t3tools/contracts"; +import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts"; import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { visitElements } from "../../test/reactElementTree"; import { reactHookHarness as hooks } from "../../test/reactHookHarness"; const settingsHooks = vi.hoisted(() => ({ read: vi.fn(() => ({ providerInstances: {} })), - update: vi.fn(() => vi.fn()), + mutate: vi.fn(), + useMutation: vi.fn(), })); vi.mock("react", async (importOriginal) => { @@ -23,32 +25,137 @@ vi.mock("react/compiler-runtime", async () => { return { c: reactHookHarness.useMemoCache }; }); +vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + squashAtomCommandFailure: () => new Error("The settings update failed."), +})); + vi.mock("../../hooks/useSettings", () => ({ useEnvironmentSettings: settingsHooks.read, - useUpdateEnvironmentSettings: settingsHooks.update, + usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation, })); import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog"; const remoteEnvironmentId = EnvironmentId.make("remote-device"); +const preparedAgent: AcpRegistrySearchAgent = { + id: "kilo", + name: "Kilo Code", + version: "4.2.0", + description: "Kilo ACP agent", + authors: ["Kilo"], + license: "Apache-2.0", + website: null, + repository: null, + icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg", + distribution: "binary", + integrity: "sha256", +}; + +function render(onOpenChange = vi.fn()) { + hooks.beginRender(); + return AddProviderInstanceDialog({ + open: true, + environmentId: remoteEnvironmentId, + environmentLabel: "Remote device", + onOpenChange, + }); +} + +function findByChildren(tree: ReturnType, children: string) { + const result = visitElements(tree, (element) => element.props.children === children); + expect(result).not.toBeNull(); + return result!; +} + +async function selectPreparedAcp() { + const initial = render(); + const driverGroup = visitElements( + initial, + (element) => element.props["aria-labelledby"] === "add-instance-driver-label", + ); + (driverGroup?.props.onValueChange as ((value: string) => void) | undefined)?.("acpRegistry"); + + const driverStep = render(); + (findByChildren(driverStep, "Next").props.onClick as (() => void) | undefined)?.(); + + const searchStep = render(); + const search = visitElements( + searchStep, + (element) => + typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep", + ); + expect(search).not.toBeNull(); + (search?.props.onPrepared as ((agent: AcpRegistrySearchAgent) => void) | undefined)?.( + preparedAgent, + ); +} describe("AddProviderInstanceDialog environment routing", () => { beforeEach(() => { hooks.reset(); settingsHooks.read.mockClear(); - settingsHooks.update.mockClear(); + settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} }); + settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate); }); it("reads and writes settings through the supplied environment", () => { - hooks.beginRender(); - AddProviderInstanceDialog({ - open: true, - environmentId: remoteEnvironmentId, - environmentLabel: "Remote device", - onOpenChange: vi.fn(), - }); + render(); expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId); - expect(settingsHooks.update).toHaveBeenCalledWith(remoteEnvironmentId); + expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId); + }); + + it("awaits an atomic create before closing and retains prepared ACP metadata", async () => { + const onOpenChange = vi.fn(); + let resolveMutation!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void; + settingsHooks.mutate.mockReturnValueOnce( + new Promise((resolve) => { + resolveMutation = resolve; + }), + ); + await selectPreparedAcp(); + + const identityStep = render(onOpenChange); + expect( + visitElements(identityStep, (element) => { + const content = JSON.stringify(element.props.children); + return content?.includes("4.2.0") === true && content.includes("binary"); + }), + ).not.toBeNull(); + (findByChildren(identityStep, "Add instance").props.onClick as (() => void) | undefined)?.(); + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "acpRegistry_kilo_code", + instance: { + driver: ProviderDriverKind.make("acpRegistry"), + enabled: true, + displayName: "Kilo Code", + config: { + agentId: "kilo", + distribution: "auto", + registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg", + }, + }, + }); + expect(onOpenChange).not.toHaveBeenCalled(); + + resolveMutation({ _tag: "Success", value: {} }); + await Promise.resolve(); + await Promise.resolve(); + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + + it("keeps the dialog open when the atomic upsert fails", async () => { + settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") }); + const onOpenChange = vi.fn(); + await selectPreparedAcp(); + + const identityStep = render(onOpenChange); + (findByChildren(identityStep, "Add instance").props.onClick as (() => void) | undefined)?.(); + await Promise.resolve(); + await Promise.resolve(); + + expect(onOpenChange).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts b/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts index fdffa9a190eaf..983012331eb95 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts @@ -3,8 +3,71 @@ export type WizardNavigation = | { readonly kind: "blocked"; readonly step: number; readonly error: string }; const IDENTITY_STEP = 1; +const ACP_REGISTRY_IDENTITY_STEP = 2; export const ADD_PROVIDER_WIZARD_STEPS = ["Driver", "Identity", "Config"] as const; +export const ACP_REGISTRY_WIZARD_STEPS = ["Driver", "Find ACP", "Identity"] as const; + +export interface ProviderIdentityDraft { + readonly label: string; + readonly accentColor: string; + readonly instanceIdOverride: string | null; +} + +const EMPTY_PROVIDER_IDENTITY_DRAFT: ProviderIdentityDraft = { + label: "", + accentColor: "", + instanceIdOverride: null, +}; + +export function getProviderIdentityDraft( + drafts: Readonly>, + driver: string, +): ProviderIdentityDraft { + return drafts[driver] ?? EMPTY_PROVIDER_IDENTITY_DRAFT; +} + +export function updateProviderIdentityDraft( + drafts: Readonly>, + driver: string, + update: Partial, +): Record { + return { + ...drafts, + [driver]: { ...getProviderIdentityDraft(drafts, driver), ...update }, + }; +} + +export function deriveAvailableInstanceId( + derive: (label: string) => string, + label: string, + existing: ReadonlySet, +): string { + const base = derive(label); + if (!base || !existing.has(base)) return base; + + for (let suffix = 2; ; suffix += 1) { + const suffixText = `_${suffix}`; + const candidate = `${base.slice(0, 64 - suffixText.length)}${suffixText}`; + if (!existing.has(candidate)) return candidate; + } +} + +export function isConfiguredAcpRegistryAgent( + instances: Readonly>, + agentId: string, +): boolean { + return Object.values(instances).some((instance) => { + if ( + instance.driver !== "acpRegistry" || + !instance.config || + typeof instance.config !== "object" + ) { + return false; + } + return (instance.config as Record).agentId === agentId; + }); +} /** * Resolve navigation within the add-provider wizard. @@ -18,19 +81,52 @@ export function resolveWizardNavigation( currentStep: number, requestedStep: number, stepCount: number, - validation: { readonly instanceIdError: string | null }, + validation: { + readonly instanceIdError: string | null; + readonly identityStep?: number; + readonly prerequisite?: { + readonly step: number; + readonly error: string | null; + }; + }, ): WizardNavigation { const lastStep = Math.max(0, stepCount - 1); const targetStep = Math.max(0, Math.min(lastStep, requestedStep)); - const movesForwardPastIdentity = currentStep <= IDENTITY_STEP && targetStep > IDENTITY_STEP; + const identityStep = validation.identityStep ?? IDENTITY_STEP; + const prerequisite = validation.prerequisite; + + if (prerequisite?.error && currentStep <= prerequisite.step && targetStep > prerequisite.step) { + return { + kind: "blocked", + step: Math.min(prerequisite.step, lastStep), + error: prerequisite.error, + }; + } + + const movesForwardPastIdentity = currentStep <= identityStep && targetStep > identityStep; if (movesForwardPastIdentity && validation.instanceIdError !== null) { return { kind: "blocked", - step: Math.min(IDENTITY_STEP, lastStep), + step: Math.min(identityStep, lastStep), error: validation.instanceIdError, }; } return { kind: "navigate", step: targetStep }; } + +export function resolveAcpRegistryWizardNavigation( + currentStep: number, + requestedStep: number, + validation: { + readonly instanceIdError: string | null; + readonly selectionError: string | null; + }, +): WizardNavigation { + return resolveWizardNavigation(currentStep, requestedStep, ACP_REGISTRY_WIZARD_STEPS.length, { + instanceIdError: validation.instanceIdError, + identityStep: ACP_REGISTRY_IDENTITY_STEP, + prerequisite: { step: 1, error: validation.selectionError }, + }); +} diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.test.ts b/apps/web/src/components/settings/AddProviderInstanceDialog.test.ts index 594d2e4537e33..a5eae71e3e5e4 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.test.ts +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.test.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from "vite-plus/test"; -import { resolveWizardNavigation } from "./AddProviderInstanceDialog.logic"; +import { + deriveAvailableInstanceId, + getProviderIdentityDraft, + isConfiguredAcpRegistryAgent, + resolveAcpRegistryWizardNavigation, + resolveWizardNavigation, + updateProviderIdentityDraft, +} from "./AddProviderInstanceDialog.logic"; describe("resolveWizardNavigation", () => { const invalidId = { instanceIdError: "Instance ID is required." }; @@ -42,3 +49,69 @@ describe("resolveWizardNavigation", () => { expect(resolveWizardNavigation(0, -1, 3, invalidId)).toEqual({ kind: "navigate", step: 0 }); }); }); + +describe("ACP Registry wizard", () => { + it("requires a prepared result or valid manual configuration before Identity", () => { + expect( + resolveAcpRegistryWizardNavigation(1, 2, { + instanceIdError: null, + selectionError: "Select an ACP or configure one manually.", + }), + ).toEqual({ + kind: "blocked", + step: 1, + error: "Select an ACP or configure one manually.", + }); + + expect( + resolveAcpRegistryWizardNavigation(1, 2, { + instanceIdError: null, + selectionError: null, + }), + ).toEqual({ kind: "navigate", step: 2 }); + }); + + it("derives a collision-free instance id without exceeding the slug limit", () => { + const derive = (label: string) => `acpRegistry_${label}`; + const existing = new Set(["acpRegistry_gemini", "acpRegistry_gemini_2"]); + + expect(deriveAvailableInstanceId(derive, "gemini", existing)).toBe("acpRegistry_gemini_3"); + + const longBase = `acpRegistry_${"a".repeat(48)}`; + expect(deriveAvailableInstanceId(() => longBase, "ignored", new Set([longBase]))).toHaveLength( + 62, + ); + }); + + it("only marks matching ACP Registry instances as already added", () => { + const instances = { + codex: { driver: "codex", config: { agentId: "gemini" } }, + registry: { driver: "acpRegistry", config: { agentId: "gemini" } }, + }; + + expect(isConfiguredAcpRegistryAgent(instances, "gemini")).toBe(true); + expect(isConfiguredAcpRegistryAgent(instances, "codex")).toBe(false); + }); + + it("keeps registry-prefilled identity separate from other drivers", () => { + const registryDrafts = updateProviderIdentityDraft({}, "acpRegistry", { + label: "Gemini CLI", + instanceIdOverride: "acpRegistry_gemini_cli", + }); + + expect(getProviderIdentityDraft(registryDrafts, "codex")).toEqual({ + label: "", + accentColor: "", + instanceIdOverride: null, + }); + + const drafts = updateProviderIdentityDraft(registryDrafts, "codex", { + label: "Work", + instanceIdOverride: "codex_work", + }); + expect(getProviderIdentityDraft(drafts, "acpRegistry")).toMatchObject({ + label: "Gemini CLI", + instanceIdOverride: "acpRegistry_gemini_cli", + }); + }); +}); diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index 38ae720a96074..5ce50ac1e47c3 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -1,29 +1,28 @@ "use client"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; + import { Radio as RadioPrimitive } from "@base-ui/react/radio"; import { CheckIcon } from "lucide-react"; import { useMemo, useState } from "react"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { + type AcpRegistrySearchAgent, ProviderInstanceId, ProviderDriverKind, type EnvironmentId, type ProviderInstanceConfig, } from "@t3tools/contracts"; -import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings"; +import { + useEnvironmentSettings, + usePersistEnvironmentProviderInstanceMutation, +} from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; import { normalizeProviderAccentColor } from "../../providerInstances"; import { Button } from "../ui/button"; -import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons"; -import { - Dialog, - DialogDescription, - DialogFooter, - DialogHeader, - DialogPopup, - DialogTitle, -} from "../ui/dialog"; - +import { Gemini, GithubCopilotIcon, type Icon } from "../Icons"; +import { Dialog } from "../ui/dialog"; import { Badge } from "../ui/badge"; import { Input } from "../ui/input"; import { RadioGroup } from "../ui/radio-group"; @@ -33,10 +32,18 @@ import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSe import { WizardPanel, WizardPopup, WizardHeader, WizardFooter } from "../ui/wizard"; import { ADD_PROVIDER_WIZARD_STEPS, + ACP_REGISTRY_WIZARD_STEPS, + deriveAvailableInstanceId, + getProviderIdentityDraft, + resolveAcpRegistryWizardNavigation, resolveWizardNavigation, + updateProviderIdentityDraft, + type ProviderIdentityDraft, type WizardNavigation, } from "./AddProviderInstanceDialog.logic"; import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps"; +import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep"; +import { resolveOfficialAcpRegistryIconUrl } from "./AcpRegistryIcon"; const PROVIDER_ACCENT_SWATCHES = [ "#2563eb", @@ -49,7 +56,7 @@ const PROVIDER_ACCENT_SWATCHES = [ /** * Normalize a user-provided label into a slug suffix for the instance id. - * The full id is formed by prefixing the driver slug — e.g. label "Work" on + * The full id is formed by prefixing the driver slug. For example, label "Work" on * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the * final composed id stays under the 64-char slug cap enforced by * `ProviderInstanceId` in `@t3tools/contracts`. @@ -70,6 +77,7 @@ function deriveInstanceId(driver: ProviderDriverKind, label: string): string { const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/; const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex"); +const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!; const EMPTY_CONFIG_DRAFT: Record = {}; interface ComingSoonDriverOption { @@ -89,11 +97,6 @@ const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [ label: "Gemini", icon: Gemini, }, - { - value: ProviderDriverKind.make("piAgent"), - label: "Pi Agent", - icon: PiAgentIcon, - }, ]; /** @@ -125,19 +128,23 @@ export function AddProviderInstanceDialog({ onOpenChange, }: AddProviderInstanceDialogProps) { const settings = useEnvironmentSettings(environmentId); - const updateSettings = useUpdateEnvironmentSettings(environmentId); + const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId); const [wizardStep, setWizardStep] = useState(0); const [driver, setDriver] = useState(DEFAULT_DRIVER_KIND); - const [label, setLabel] = useState(""); - const [accentColor, setAccentColor] = useState(""); - const [instanceIdOverride, setInstanceIdOverride] = useState(null); + const [identityByDriver, setIdentityByDriver] = useState>( + {}, + ); + const [selectedAcp, setSelectedAcp] = useState(null); + const [isManualAcpConfiguration, setIsManualAcpConfiguration] = useState(false); + const [isRegistryLoading, setIsRegistryLoading] = useState(false); // Driver-specific config drafts keyed by driver so toggling between drivers // during the same dialog session does not lose in-progress input. const [configByDriver, setConfigByDriver] = useState>>({}); // Errors are suppressed until the user has tried to submit once. After that // they update live so fixing the problem clears the message in place. const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false); + const [isSaving, setIsSaving] = useState(false); const existingIds = useMemo( () => new Set(Object.keys(settings.providerInstances ?? {})), @@ -145,6 +152,11 @@ export function AddProviderInstanceDialog({ ); const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION; + const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND; + const { label, accentColor, instanceIdOverride } = getProviderIdentityDraft( + identityByDriver, + driver, + ); const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label); const driverSettingsFields = useMemo( () => deriveProviderSettingsFields(driverOption), @@ -152,10 +164,18 @@ export function AddProviderInstanceDialog({ ); const instanceIdError = validateInstanceId(instanceId, existingIds); const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null; + const identityStep = isAcpRegistry ? 2 : 1; const previewLabel = label.trim() || `${driverOption.label} Workspace`; - const wizardStepSummaries = [driverOption.label, previewLabel, null] as const; const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT; + const manualAgentId = typeof configDraft.agentId === "string" ? configDraft.agentId.trim() : ""; + const acpSelectionError = + selectedAcp !== null || (isManualAcpConfiguration && manualAgentId.length > 0) + ? null + : "Select an ACP or configure one manually."; + const wizardStepSummaries = isAcpRegistry + ? ([driverOption.label, selectedAcp?.name ?? (manualAgentId || null), previewLabel] as const) + : ([driverOption.label, previewLabel, null] as const); const setConfigDraft = (config: Record | undefined) => { setConfigByDriver((existing) => { const next = { ...existing }; @@ -167,6 +187,9 @@ export function AddProviderInstanceDialog({ return next; }); }; + const setIdentityDraft = (update: Partial) => { + setIdentityByDriver((existing) => updateProviderIdentityDraft(existing, driver, update)); + }; const applyWizardNavigation = (navigation: WizardNavigation) => { if (navigation.kind === "blocked") { @@ -177,15 +200,62 @@ export function AddProviderInstanceDialog({ const navigateToStep = (requestedStep: number) => { applyWizardNavigation( - resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, { - instanceIdError, + isAcpRegistry + ? resolveAcpRegistryWizardNavigation(wizardStep, requestedStep, { + instanceIdError, + selectionError: acpSelectionError, + }) + : resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, { + instanceIdError, + }), + ); + }; + + const handleAcpPrepared = (agent: AcpRegistrySearchAgent) => { + const nextLabel = agent.name; + const registryIconUrl = resolveOfficialAcpRegistryIconUrl(agent.icon); + const nextInstanceId = deriveAvailableInstanceId( + (candidateLabel) => deriveInstanceId(ACP_REGISTRY_DRIVER_KIND, candidateLabel), + nextLabel, + existingIds, + ); + setSelectedAcp(agent); + setIsManualAcpConfiguration(false); + setIdentityByDriver((existing) => + updateProviderIdentityDraft(existing, ACP_REGISTRY_DRIVER_KIND, { + label: nextLabel, + instanceIdOverride: nextInstanceId, + }), + ); + setConfigByDriver((existing) => ({ + ...existing, + [ACP_REGISTRY_DRIVER_KIND]: { + agentId: agent.id, + distribution: "auto", + ...(registryIconUrl ? { registryIconUrl } : {}), + }, + })); + setHasAttemptedSubmit(false); + setWizardStep(2); + }; + + const handleManualAcpConfiguration = () => { + setSelectedAcp(null); + setIsManualAcpConfiguration(true); + setConfigDraft(undefined); + setIdentityByDriver((existing) => + updateProviderIdentityDraft(existing, ACP_REGISTRY_DRIVER_KIND, { + label: "", + instanceIdOverride: null, }), ); + setHasAttemptedSubmit(false); }; - const handleSave = () => { + const handleSave = async () => { + if (isSaving) return; setHasAttemptedSubmit(true); - if (instanceIdError !== null) return; + if (instanceIdError !== null || (isAcpRegistry && acpSelectionError !== null)) return; const config = configByDriver[driver] ?? {}; const hasConfig = Object.keys(config).length > 0; @@ -203,25 +273,39 @@ export function AddProviderInstanceDialog({ // keeps the type boundary honest and guards against any future drift in // the slug rules. const brandedId = ProviderInstanceId.make(instanceId); - const nextMap = { - ...settings.providerInstances, - [brandedId]: nextInstance, - }; - try { - updateSettings({ providerInstances: nextMap }); - toastManager.add({ - type: "success", - title: "Provider instance added", - description: `${driverOption.label} instance '${instanceId}' was added.`, - }); - onOpenChange(false); - } catch (error) { + setIsSaving(true); + const result = await persistProviderInstance({ + operation: "create", + instanceId: brandedId, + instance: nextInstance, + }); + if (result._tag === "Failure") { + const error = squashAtomCommandFailure(result); + setIsSaving(false); toastManager.add({ type: "error", title: "Could not add provider instance", - description: error instanceof Error ? error.message : "Update failed.", + description: error instanceof Error ? error.message : "The settings update failed.", }); + return; } + const referenceUrl = selectedAcp?.website ?? selectedAcp?.repository; + toastManager.add({ + type: "success", + title: "Provider instance added", + description: isAcpRegistry + ? `${selectedAcp?.name ?? manualAgentId} was added. Complete the agent's advertised authentication on the server; T3 Code detects it automatically.` + : `${driverOption.label} instance '${instanceId}' was added.`, + ...(referenceUrl + ? { + actionProps: { + children: selectedAcp?.website ? "Agent docs" : "Agent source", + onClick: () => window.open(referenceUrl, "_blank", "noopener,noreferrer"), + }, + } + : {}), + }); + onOpenChange(false); }; return ( @@ -231,39 +315,61 @@ export function AddProviderInstanceDialog({ title="Add provider instance" description={ <> - Configure an additional provider instance on {environmentLabel} — for example, a + Configure an additional provider instance on {environmentLabel}. For example, add a second Codex install pointed at a different workspace. } > - + {isAcpRegistry ? ( + + ) : ( + + )} - +
    Driver
    setDriver(ProviderDriverKind.make(value))} + onValueChange={(value) => { + setDriver(ProviderDriverKind.make(value)); + setHasAttemptedSubmit(false); + }} aria-labelledby="add-instance-driver-label" className="grid grid-cols-1 gap-2 sm:grid-cols-2" > {DRIVER_OPTIONS.map((option) => { - const IconComponent = option.icon; return ( - + {option.label} @@ -305,27 +411,114 @@ export function AddProviderInstanceDialog({
    -