diff --git a/.gitattributes b/.gitattributes index 24860868b59bc..ab74efd46bf7f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,7 +3,8 @@ # Batch files need CRLF for cmd.exe to parse them reliably. *.cmd text eol=crlf *.bat text eol=crlf -# GitHub's and Expo's GraphQL schemas and the operations graphqlgen writes from them. +# GitHub's, Linear's and Expo's GraphQL schemas and the operations graphqlgen writes from them. packages/source-control-github/schema/** linguist-generated +packages/issue-tracker-linear/schema/** linguist-generated apps/server/schema/** linguist-generated **/*.graphql.ts linguist-generated diff --git a/.github/actions/drop-checkout-credentials/action.yml b/.github/actions/drop-checkout-credentials/action.yml new file mode 100644 index 0000000000000..f9a60340e1fe5 --- /dev/null +++ b/.github/actions/drop-checkout-credentials/action.yml @@ -0,0 +1,38 @@ +name: Drop checkout credentials +description: Removes the token actions/checkout leaves behind, so later steps can run dependency and build scripts. + +# checkout keeps the token in a file under RUNNER_TEMP that .git/config includes, so +# both go. `persist-credentials: false` fails in this repo: its cleanup runs `git +# submodule foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules). +runs: + using: composite + steps: + - name: Drop checkout credentials + shell: bash + run: | + # Status 1 means no match; any other failure stops the step. + lookup() { + local status=0 + git -C "$dir" config --local "$@" || status=$? + if [ "$status" -gt 1 ]; then exit "$status"; fi + } + for dir in . .trusted; do + [ -e "$dir/.git" ] || continue + lookup --get-regexp '^includeif\..*\.path$' | while read -r key file; do + rm -f "$file" + git -C "$dir" config --local --unset-all "$key" + done + lookup --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do + git -C "$dir" config --local --unset-all "$key" + done + remaining="$(lookup --get-regexp 'extraheader|includeif')" + if [ -n "$remaining" ]; then + echo "::error::checkout credentials are still configured in $dir" + exit 1 + fi + done + rm -f "$RUNNER_TEMP"/git-credentials-*.config + if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then + echo "::error::a checkout credential file is still present" + exit 1 + fi diff --git a/.github/actions/eas-local-build/action.yml b/.github/actions/eas-local-build/action.yml new file mode 100644 index 0000000000000..847c8e0117492 --- /dev/null +++ b/.github/actions/eas-local-build/action.yml @@ -0,0 +1,188 @@ +name: EAS local build +description: Installs the toolchain and mobile dependencies, then runs `eas build --local` on this runner. + +inputs: + platform: + description: android or ios + required: true + profile: + description: eas.json build profile + required: true + environment: + description: EAS environment to pull, preview or production + required: true + expo-token: + description: Expo token for that environment + required: true + output: + description: Path the build artifact is written to + required: true + cache: + description: "false for untrusted code: no sticky disk and no EAS cache, so nothing it writes reaches trusted builds" + default: "true" + sourcemaps-r2: + description: R2 credentials for the eas-build-on-success source map upload; EAS secrets don't reach local builds + default: "" + +runs: + using: composite + steps: + - name: Prepare Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + env: + CACHE_NAME: ${{ inputs.environment == 'production' && 'store' || 'preview' }} + run: | + cache="$HOME/.cache/t3-android-$CACHE_NAME" + { + echo "GRADLE_USER_HOME=$cache/gradle" + echo "CCACHE_DIR=$cache/ccache" + echo "CCACHE_MAXSIZE=5G" + # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. + echo "CCACHE_COMPILERCHECK=%compiler% -v" + echo "pnpm_config_store_dir=$cache/pnpm-store" + # eas build --local copies the project here. A fixed path keeps + # ccache keys stable, and the same disk as the store lets pnpm hardlink. + echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" + echo "CCACHE_BASEDIR=$cache/eas-build" + # CMake (3.17+) reads these, and AGP passes Gradle's environment through. + echo "CMAKE_C_COMPILER_LAUNCHER=ccache" + echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" + } >> "$GITHUB_ENV" + + - name: Mount Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 + with: + key: ${{ github.repository }}-android-${{ inputs.environment == 'production' && 'store' || 'preview' }}-build + path: ~/.cache/t3-android-${{ inputs.environment == 'production' && 'store' || 'preview' }} + + - name: Configure Gradle and ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" + rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" + # No daemon: nothing should hold the sticky disk open when it is committed. + printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" + sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources + sudo apt-get update -qq && sudo apt-get install -y -qq ccache + ccache --zero-stats + + # Matches the EAS build image in eas.json. + - name: Select Xcode 27.1 + if: inputs.platform == 'ios' + shell: bash + run: | + xcode=/Applications/Xcode_27.1.app + if [ ! -d "$xcode" ]; then + ls -d /Applications/Xcode*.app + echo "::error::Xcode 27.1 is not on this runner." + exit 1 + fi + sudo xcode-select -s "$xcode/Contents/Developer" + xcodebuild -version + echo "- Xcode: \`$(basename "$xcode")\`" >> "$GITHUB_STEP_SUMMARY" + + # EAS's credentials step fails to import the distribution certificate without it. + - name: Install Apple WWDR G3 intermediate + if: inputs.platform == 'ios' + shell: bash + run: | + curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer + sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true + security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep labl + + - name: Setup Node + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - name: Enable corepack + shell: bash + run: | + npm install --global corepack@latest + corepack enable + pnpm --version + + # EAS commands load app.config.ts, whose plugins must resolve. Keep install + # scripts: some download native assets that the build's fingerprint check hashes. + - name: Install mobile dependencies + shell: bash + run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... + + - name: Setup Java + if: inputs.platform == 'android' + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + with: + distribution: temurin + java-version: 17 + + - name: Setup EAS + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + with: + eas-version: latest + eas-cache: ${{ inputs.cache }} + token: ${{ inputs.expo-token }} + # npm, not pnpm: this only installs eas-cli into the action's own + # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's + # ignored build script (no allowBuilds config outside the repo). + packager: npm + + - name: Build tools + if: inputs.platform == 'ios' + shell: bash + run: | + command -v pod || sudo gem install cocoapods --no-document + command -v fastlane || brew install fastlane + pod --version + fastlane --version | tail -1 + + # EAS commands skip dotenv, and the Android fingerprint hashes this file. + - name: Pull ${{ inputs.environment }} environment variables + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + ENVIRONMENT: ${{ inputs.environment }} + PLATFORM: ${{ inputs.platform }} + run: | + eas env:pull "$ENVIRONMENT" --non-interactive + node --input-type=module <<'NODE' + import { appendFileSync, readFileSync } from "node:fs"; + import { parseEnv } from "node:util"; + const env = parseEnv(readFileSync(".env.local", "utf8")); + const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; + if (!googleServicesFile && process.env.PLATFORM === "android") { + throw new Error(`T3CODE_ANDROID_GOOGLE_SERVICES_FILE is missing from the ${process.env.ENVIRONMENT} environment`); + } + if (googleServicesFile) { + appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); + } + NODE + + - name: Build + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + MOBILE_SOURCEMAPS_R2: ${{ inputs.sourcemaps-r2 }} + PLATFORM: ${{ inputs.platform }} + PROFILE: ${{ inputs.profile }} + OUTPUT: ${{ inputs.output }} + run: | + if [ "$PLATFORM" = "ios" ]; then + # A real path: /var -> /private/var symlinks break the expo-widgets bundle step. + export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" + fi + eas build --local --platform "$PLATFORM" --profile "$PROFILE" --non-interactive --output "$OUTPUT" + + - name: Report ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + { + echo '```' + ccache --show-stats + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/actions/record-build-tag/action.yml b/.github/actions/record-build-tag/action.yml new file mode 100644 index 0000000000000..2086d004b295c --- /dev/null +++ b/.github/actions/record-build-tag/action.yml @@ -0,0 +1,57 @@ +name: Record build tag +description: Pushes the tag that tells later runs a build for this fingerprint exists. + +inputs: + tag: + description: Tag name, without refs/tags/ + required: true + message: + description: Annotated tag message; empty makes a lightweight tag + default: "" + replace: + description: "true replaces an existing tag; otherwise an existing tag counts as recorded" + default: "false" + token: + description: Token with contents write + required: true + +runs: + using: composite + steps: + - name: Record build tag + shell: bash + env: + TAG: ${{ inputs.tag }} + MESSAGE: ${{ inputs.message }} + REPLACE: ${{ inputs.replace }} + GH_TOKEN: ${{ inputs.token }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). + for attempt in 1 2 3; do + if refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then + old="$(printf '%s\n' "$refs" | while read -r sha ref; do + if [ "$ref" = "refs/tags/$TAG" ]; then echo "$sha"; fi + done)" + if [ -n "$old" ] && [ "$REPLACE" != "true" ]; then + echo "$TAG exists." + exit 0 + fi + if [ -n "$MESSAGE" ]; then + git tag -f -a "$TAG" -m "$MESSAGE" + else + git tag -f "$TAG" + fi + # An empty lease means the tag must not exist yet. + if git push --force-with-lease="refs/tags/$TAG:$old" "$remote" "refs/tags/$TAG"; then + exit 0 + fi + fi + if [ "$attempt" = 3 ]; then + echo "::error::Could not push $TAG." + exit 1 + fi + sleep $((attempt * 15)) + done diff --git a/AGENTS.md b/AGENTS.md index da3bc4a35b81d..19601500285a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,7 @@ The most common defect in this repo is a change that works on the path you teste - **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow. - **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug. - **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real. +- **Languages.** User-facing text ships in every locale: translate new keys in `apps/{web,mobile}/src/i18n/translations` after `vp run i18n:generate` (`vp run i18n:check` gates it) and in `apps/marketing/src/i18n`. - **Docs.** Check whether the change makes existing guidance inaccurate. Apply the [documentation rules](#documentation) before adding anything. ## Dev servers diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 97554fd823205..0daa6f14cf5c4 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.9", + "version": "0.1.10", "private": true, "type": "module", "main": "dist-electron/boot.cjs", diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index faeeb58ab71fb..21d3381032042 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -55,6 +56,7 @@ import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts"; import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts"; import * as DesktopIpc from "../ipc/DesktopIpc.ts"; @@ -73,6 +75,180 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as MacPermissions from "../permissions/MacPermissions.ts"; import * as PreviewManager from "../preview/Manager.ts"; +interface StubbedDesktop { + readonly localEnvironmentEnabled: boolean; + readonly environment: Partial; + readonly fileSystem: Layer.Layer; + readonly record: (event: string) => Effect.Effect; + readonly windowStarted: Deferred.Deferred; + readonly registerLinuxUrlHandler: Effect.Effect; + readonly backends?: ReadonlyArray<{ readonly stop: () => Effect.Effect }>; + readonly flushRendererHistory?: Effect.Effect; + readonly tokenRequested?: Deferred.Deferred; +} + +const runStubbedDesktop = (stub: StubbedDesktop) => + Effect.gen(function* () { + const quitting = yield* Ref.make(false); + const runApp = DesktopApp.program + .pipe( + Effect.provide(NodeCrypto.layer), + Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { + resolveUserDataPath: Effect.succeed("/isolated/userdata"), + configure: stub.record("identity"), + } as DesktopAppIdentity.DesktopAppIdentity["Service"]), + Effect.provideService(ElectronApp.ElectronApp, { + setPath: () => Effect.void, + whenReady: stub.record("ready"), + } as unknown as ElectronApp.ElectronApp["Service"]), + Effect.provideService(ElectronDialog.ElectronDialog, { + showErrorBox: () => Effect.die("unexpected fatal startup error"), + } as unknown as ElectronDialog.ElectronDialog["Service"]), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + platform: "linux", + isDevelopment: false, + isPackaged: true, + stateDir: "/isolated/userdata", + configuredBackendPort: Option.some(3773), + defaultDesktopSettings: { serverExposureMode: "local-only" }, + ...stub.environment, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { + linux: null, + linuxPasswordStoreCommandLine: "basic", + }), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), + updates: Stream.empty, + }), + Effect.provideService(DesktopAppSettings.DesktopAppSettings, { + load: Effect.void, + get: Effect.succeed({ + localEnvironmentEnabled: stub.localEnvironmentEnabled, + serverExposureMode: "local-only", + }), + } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), + Effect.provideService(DesktopLifecycle.DesktopLifecycle, { + register: Effect.void, + relaunch: () => Effect.void, + }), + Effect.provideService(DesktopClerk.DesktopClerk, { + configure: Effect.void, + } as DesktopClerk.DesktopClerk["Service"]), + Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { + selectedStorageBackend: Effect.succeedNone, + } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), + Effect.provideService(PreviewPasskeys.PreviewPasskeys, { + configure: Effect.void, + } as PreviewPasskeys.PreviewPasskeys["Service"]), + Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { + configure: stub.record("menu"), + }), + Effect.provideService(DesktopUpdates.DesktopUpdates, { + configure: Effect.void, + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { + register: stub.registerLinuxUrlHandler, + }), + ) + .pipe( + Effect.provideService(ElectronProtocol.ElectronProtocol, { + registerDesktopProtocol: () => Effect.void, + } as unknown as ElectronProtocol.ElectronProtocol["Service"]), + Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { + load: () => Effect.void, + } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), + Effect.provideService(DesktopSnapShot.DesktopSnapShot, { + initialize: Effect.void, + } as DesktopSnapShot.DesktopSnapShot["Service"]), + Effect.provideService(DesktopState.DesktopState, { + quitting, + } as DesktopState.DesktopState["Service"]), + Effect.provideService(DesktopWindow.DesktopWindow, { + ensureMain: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + createMainIfBackendReady: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + } as unknown as DesktopWindow.DesktopWindow["Service"]), + Effect.provideService(DesktopBackendPool.DesktopBackendPool, { + primary: Effect.succeed({ + start: stub.record("backend"), + currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), + }), + list: Effect.succeed(stub.backends ?? []), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), + Effect.provideService(DesktopServerExposure.DesktopServerExposure, { + configureFromSettings: () => Effect.succeed({ mode: "local-only" }), + backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), + } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), + Effect.provideService(DesktopWslBackend.DesktopWslBackend, { + reconcile: Effect.void, + } as DesktopWslBackend.DesktopWslBackend["Service"]), + Effect.provideService(DesktopAppActivation.DesktopAppActivation, { + start: Effect.void, + } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), + Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { + shutdown: stub.flushRendererHistory ?? Effect.void, + } as DesktopRendererHistory.DesktopRendererHistory["Service"]), + ); + return yield* runApp.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BrowserImport.BrowserImport, {}), + Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), + Layer.mock(CoilUpdateDelivery.CoilUpdateDelivery, {}), + Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), + Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), + Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), + Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), + Layer.mock(DesktopIpc.DesktopIpc, {}), + Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { + getBearerToken: stub + .record("token") + .pipe( + Effect.andThen( + stub.tokenRequested + ? Deferred.succeed(stub.tokenRequested, undefined) + : Effect.void, + ), + Effect.as("token"), + ), + }), + Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), + Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), + Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), + Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), + Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), + Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), + Layer.mock(ElectronMenu.ElectronMenu, {}), + Layer.mock(ElectronShell.ElectronShell, {}), + Layer.mock(ElectronTheme.ElectronTheme, {}), + Layer.mock(ElectronWindow.ElectronWindow, {}), + Layer.mock(MacPermissions.MacPermissions, {}), + Layer.mock(PreviewManager.PreviewManager, { + isBrowserPartition: () => { + throw new Error("unexpected browser partition lookup"); + }, + }), + stub.fileSystem, + Layer.mock(NetService.NetService, {}), + Path.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected HTTP request")), + ), + ), + ), + Effect.forkScoped, + ); + }); + it.effect.each([false, true])( "stops backends together before flushing history and cancels Linux registration, stop defect=%s", (stopDefect) => @@ -86,179 +262,42 @@ it.effect.each([false, true])( const releaseStops = yield* Deferred.make(); const historyStarted = yield* Deferred.make(); const releaseHistory = yield* Deferred.make(); - const quitting = yield* Ref.make(false); const tokenRequested = yield* Deferred.make(); const events: string[] = []; - const record = (event: string) => - Effect.sync(() => { - events.push(event); - }); - const runApp = DesktopApp.program - .pipe( - Effect.provide(NodeCrypto.layer), - Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { - resolveUserDataPath: Effect.succeed("/isolated/userdata"), - configure: record("identity"), - } as DesktopAppIdentity.DesktopAppIdentity["Service"]), - Effect.provideService(ElectronApp.ElectronApp, { - setPath: () => Effect.void, - whenReady: record("ready"), - } as unknown as ElectronApp.ElectronApp["Service"]), - Effect.provideService(ElectronDialog.ElectronDialog, { - showErrorBox: () => Effect.die("unexpected fatal startup error"), - } as unknown as ElectronDialog.ElectronDialog["Service"]), - Effect.provideService(DesktopEnvironment.DesktopEnvironment, { - platform: "linux", - isDevelopment: false, - isPackaged: true, - stateDir: "/isolated/userdata", - configuredBackendPort: Option.some(3773), - defaultDesktopSettings: { serverExposureMode: "local-only" }, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { - linux: null, - linuxPasswordStoreCommandLine: "basic", - }), - Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { - installIntoProcess: Effect.succeed(true), - awaitDiscovery: Effect.succeed(true), - awaitUserShellDiscovery: Effect.succeed(true), - updates: Stream.empty, + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: true, + environment: {}, + fileSystem: FileSystem.layerNoop({}), + record: (event) => + Effect.sync(() => { + events.push(event); }), - Effect.provideService(DesktopAppSettings.DesktopAppSettings, { - load: Effect.void, - get: Effect.succeed({ - localEnvironmentEnabled: true, - serverExposureMode: "local-only", - }), - } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), - Effect.provideService(DesktopLifecycle.DesktopLifecycle, { - register: Effect.void, - relaunch: () => Effect.void, - }), - Effect.provideService(DesktopClerk.DesktopClerk, { - configure: Effect.void, - } as DesktopClerk.DesktopClerk["Service"]), - Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { - selectedStorageBackend: Effect.succeedNone, - } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), - Effect.provideService(PreviewPasskeys.PreviewPasskeys, { - configure: Effect.void, - } as PreviewPasskeys.PreviewPasskeys["Service"]), - Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { - configure: record("menu"), - }), - Effect.provideService(DesktopUpdates.DesktopUpdates, { - configure: Effect.void, - } as unknown as DesktopUpdates.DesktopUpdates["Service"]), - Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { - register: Deferred.succeed(registrationStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRegistration)), - Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), - ), - }), - ) - .pipe( - Effect.provideService(ElectronProtocol.ElectronProtocol, { - registerDesktopProtocol: () => Effect.void, - } as unknown as ElectronProtocol.ElectronProtocol["Service"]), - Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { - load: () => Effect.void, - } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), - Effect.provideService(DesktopSnapShot.DesktopSnapShot, { - initialize: Effect.void, - } as DesktopSnapShot.DesktopSnapShot["Service"]), - Effect.provideService(DesktopState.DesktopState, { - quitting, - } as DesktopState.DesktopState["Service"]), - Effect.provideService(DesktopWindow.DesktopWindow, { - ensureMain: record("window").pipe( - Effect.andThen(Deferred.succeed(windowStarted, undefined)), - ), - } as unknown as DesktopWindow.DesktopWindow["Service"]), - Effect.provideService(DesktopBackendPool.DesktopBackendPool, { - primary: Effect.succeed({ - start: record("backend"), - currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), - }), - list: Effect.succeed([ - { - stop: () => - Deferred.succeed(firstStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), - ), - }, - { - stop: () => - Deferred.succeed(secondStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - ), - }, - ]), - } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), - Effect.provideService(DesktopServerExposure.DesktopServerExposure, { - configureFromSettings: () => Effect.succeed({ mode: "local-only" }), - backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), - } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), - Effect.provideService(DesktopWslBackend.DesktopWslBackend, { - reconcile: Effect.void, - } as DesktopWslBackend.DesktopWslBackend["Service"]), - Effect.provideService(DesktopAppActivation.DesktopAppActivation, { - start: Effect.void, - } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), - Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { - shutdown: Deferred.succeed(historyStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseHistory)), - Effect.asVoid, - ), - } as DesktopRendererHistory.DesktopRendererHistory["Service"]), - ); - const app = yield* runApp.pipe( - Effect.provide( - Layer.mergeAll( - Layer.mock(BrowserImport.BrowserImport, {}), - Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), - Layer.mock(CoilUpdateDelivery.CoilUpdateDelivery, {}), - Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), - Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), - Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), - Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), - Layer.mock(DesktopIpc.DesktopIpc, {}), - Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { - getBearerToken: record("token").pipe( - Effect.andThen(Deferred.succeed(tokenRequested, undefined)), - Effect.as("token"), + windowStarted, + tokenRequested, + registerLinuxUrlHandler: Deferred.succeed(registrationStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRegistration)), + Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), + ), + backends: [ + { + stop: () => + Deferred.succeed(firstStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), ), - }), - Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), - Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), - Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), - Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), - Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), - Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), - Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), - Layer.mock(ElectronMenu.ElectronMenu, {}), - Layer.mock(ElectronShell.ElectronShell, {}), - Layer.mock(ElectronTheme.ElectronTheme, {}), - Layer.mock(ElectronWindow.ElectronWindow, {}), - Layer.mock(MacPermissions.MacPermissions, {}), - Layer.mock(PreviewManager.PreviewManager, { - isBrowserPartition: () => { - throw new Error("unexpected browser partition lookup"); - }, - }), - FileSystem.layerNoop({}), - Layer.mock(NetService.NetService, {}), - Path.layer, - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("unexpected HTTP request")), - ), - ), + }, + { + stop: () => + Deferred.succeed(secondStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + ), + }, + ], + flushRendererHistory: Deferred.succeed(historyStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseHistory)), + Effect.asVoid, ), - Effect.forkScoped, - ); + }); yield* Deferred.await(registrationStarted); yield* Deferred.await(windowStarted); yield* Deferred.await(tokenRequested); @@ -285,3 +324,53 @@ it.effect.each([false, true])( assert.isTrue(yield* Deferred.isDone(registrationStopped)); }).pipe(Effect.provide(DesktopShutdown.layer)), ); + +it.effect("points a stale t3 launcher at the updated AppImage with Local environment off", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); + const launcher = DesktopCliShim.launcherPath({ + path, + baseDir, + platform: "linux", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); + const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString( + launcher, + DesktopCliShim.renderCliShim({ + target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, + shimPath: launcher, + t3Home: baseDir, + }), + ); + yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); + const windowStarted = yield* Deferred.make(); + + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: false, + environment: { + path, + baseDir, + serverRoot: path.join(baseDir, "resources", "app.asar"), + appImagePath: Option.some(updatedAppImage), + }, + fileSystem: Layer.succeed(FileSystem.FileSystem, fs), + record: () => Effect.void, + windowStarted, + registerLinuxUrlHandler: Effect.void, + }); + yield* Deferred.await(windowStarted); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + + const content = yield* fs.readFileString(launcher); + assert.include( + content, + `app='${updatedAppImage}'`, + "startup left the t3 launcher pointing at the removed AppImage", + ); + }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), +); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index f69bf965d0058..56fe979cf8c67 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -15,6 +15,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopClerk from "./DesktopClerk.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; @@ -301,6 +302,8 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool ); if (!settings.localEnvironmentEnabled) { + // The backend config refreshes the launcher when the local environment runs; an update may move the app. + yield* DesktopCliShim.install; if (!(yield* Ref.get(state.quitting))) { yield* desktopWindow.createMainIfBackendReady; } diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index ab47026875ab3..9aa43109e5a63 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -29,6 +29,7 @@ const layerShellEnvironment = (prepared = true) => installIntoProcess: Effect.succeed(prepared), awaitDiscovery: Effect.succeed(prepared), awaitUserShellDiscovery: Effect.succeed(prepared), + discoveryFinished: Effect.succeed(true), updates: Stream.empty, }); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 7f06ca4b77e9d..336ce72d54730 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -1,3 +1,4 @@ +import { startFileDrag } from "./methods/fileDrag.ts"; import * as Effect from "effect/Effect"; import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; @@ -112,6 +113,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(startFileDrag); yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 43f2e3b5b6151..030ccc175fb6f 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -149,3 +149,5 @@ export const COIL_UPDATE_STATE_CHANNEL = "coil:update-state"; export const COIL_UPDATE_GET_STATE_CHANNEL = "coil:update-get-state"; export const COIL_UPDATE_RESTART_CHANNEL = "coil:update-restart"; export const COIL_UPDATE_DISMISS_CHANNEL = "coil:update-dismiss"; + +export const START_FILE_DRAG_CHANNEL = "desktop:start-file-drag"; diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts new file mode 100644 index 0000000000000..7e140f9db5445 --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -0,0 +1,55 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { vi } from "vite-plus/test"; + +const { startDrag, getFileIcon } = vi.hoisted(() => ({ + startDrag: vi.fn(), + getFileIcon: vi.fn(async () => "file-icon"), +})); +vi.mock("electron", () => ({ app: { getFileIcon } })); + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import { startFileDrag } from "./fileDrag.ts"; + +it.effect("only drags existing absolute paths from the host environment and app window", () => + Effect.gen(function* () { + startDrag.mockClear(); + getFileIcon.mockClear(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const filePath = path.join(stateDir, "file with spaces.txt"); + yield* fs.writeFileString(filePath, "file"); + yield* fs.writeFileString(path.join(stateDir, "environment-id"), "host\n"); + const run = (environmentId: string, target: string, platform = "darwin", sender = 1) => + startFileDrag.handler({ environmentId, path: target }, { sender: { id: sender } }).pipe( + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + path, + stateDir, + platform, + } as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ webContents: { id: 1, startDrag } }), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + ); + assert.isFalse(yield* run("remote", filePath)); + assert.isFalse(yield* run("host", "relative.txt")); + assert.isFalse(yield* run("host", `${filePath}:12`)); + assert.isFalse(yield* run("host", filePath, "linux")); + assert.isFalse(yield* run("host", filePath, "darwin", 2)); + assert.strictEqual(startDrag.mock.calls.length, 0); + assert.isTrue(yield* run("host", filePath)); + assert.isTrue(yield* run("host", filePath, "win32")); + assert.deepEqual(startDrag.mock.calls, [ + [{ file: filePath, icon: "file-icon" }], + [{ file: filePath, icon: "file-icon" }], + ]); + yield* fs.remove(path.join(stateDir, "environment-id")); + assert.isFalse(yield* run("host", filePath)); + assert.strictEqual(startDrag.mock.calls.length, 2); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts new file mode 100644 index 0000000000000..227849c5935be --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -0,0 +1,37 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Electron from "electron"; + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import { makeIpcMethod } from "../DesktopIpc.ts"; +import { getHostEnvironmentId } from "./localEnvironment.ts"; + +export const startFileDrag = makeIpcMethod({ + channel: IpcChannels.START_FILE_DRAG_CHANNEL, + payload: Schema.Struct({ environmentId: Schema.String, path: Schema.String }), + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.fileDrag.start")(function* (input, event) { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin" && environment.platform !== "win32") return false; + if (!environment.path.isAbsolute(input.path)) return false; + const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); + if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; + const window = yield* (yield* ElectronWindow.ElectronWindow).main; + if (Option.isNone(window) || event?.sender.id !== window.value.webContents.id) return false; + const fs = yield* FileSystem.FileSystem; + if (!(yield* fs.exists(input.path))) return false; + return yield* Effect.promise(async () => { + try { + const icon = await Electron.app.getFileIcon(input.path, { size: "normal" }); + window.value.webContents.startDrag({ file: input.path, icon }); + return true; + } catch { + return false; + } + }); + }), +}); diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index de202529c4113..b256025eff844 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -10,6 +10,7 @@ import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -26,6 +27,7 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; @@ -235,6 +237,7 @@ describe("installRelayTelemetryEnabled", () => { const relayTelemetryEnabled = ( env: NodeJS.ProcessEnv, policy?: Parameters[0], + loginShellEnv: NodeJS.ProcessEnv = {}, ) => Effect.gen(function* () { const listeners = new Map(); @@ -244,21 +247,47 @@ describe("installRelayTelemetryEnabled", () => { removeAllListeners: (channel) => void listeners.delete(channel), on: (channel, listener) => void listeners.set(channel, listener), }; + let discoveryFinished = false; + const ask = () => { + const event = { returnValue: undefined as unknown }; + listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); + return event.returnValue; + }; yield* installRelayTelemetryEnabled().pipe( Effect.provideService(HostProcess.Environment, env), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.sync(() => discoveryFinished), + updates: Stream.empty, + }), Effect.provide( Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)), ), ); - const event = { returnValue: undefined as unknown }; - listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); - return event.returnValue; + const beforeDiscovery = ask(); + // The login shell's values land in the process env after startup has installed handlers. + Object.assign(env, loginShellEnv); + discoveryFinished = true; + return { beforeDiscovery, afterDiscovery: ask() }; }).pipe(Effect.scoped); it.effect("reads the desktop host opt-out before returning the renderer policy", () => Effect.gen(function* () { - assert.isFalse(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" })); - assert.isTrue(yield* relayTelemetryEnabled({})); + assert.deepEqual(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }), { + beforeDiscovery: false, + afterDiscovery: false, + }); + // Undecided until the login shell is read, so the renderer asks again instead of opting out. + assert.deepEqual(yield* relayTelemetryEnabled({}), { + beforeDiscovery: null, + afterDiscovery: true, + }); + assert.deepEqual( + yield* relayTelemetryEnabled({}, undefined, { T3CODE_TELEMETRY_ENABLED: "false" }), + { beforeDiscovery: null, afterDiscovery: false }, + ); }), ); @@ -269,14 +298,14 @@ describe("installRelayTelemetryEnabled", () => { organization: "Example Corp", limits, }); - assert.isFalse(yield* relayTelemetryEnabled({}, policy({ telemetry: false }))); - assert.isTrue(yield* relayTelemetryEnabled({}, policy({ webhookTasks: false }))); + const after = function* (...args: Parameters) { + return (yield* relayTelemetryEnabled(...args)).afterDiscovery; + }; + assert.isFalse(yield* after({}, policy({ telemetry: false }))); + assert.isTrue(yield* after({}, policy({ webhookTasks: false }))); // A policy that cannot be read fails closed. assert.isFalse( - yield* relayTelemetryEnabled( - {}, - new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" }), - ), + yield* after({}, new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })), ); }), ); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 38887ec71d906..2545cb9dc5390 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -34,6 +34,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopPrimaryPaste from "../../app/DesktopPrimaryPaste.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronApp from "../../electron/ElectronApp.ts"; @@ -82,22 +83,28 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ /** * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read, - * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. + * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. Until the login + * shell's environment (which may opt out) is known, answer null so the renderer asks again. */ export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")( function* () { const ipc = yield* DesktopIpc.DesktopIpc; - const enabled = - isRelayTracingEnabled(yield* HostProcess.Environment) && - (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( - Effect.map((found) => found?.document.limits?.telemetry !== false), - Effect.orElseSucceed(() => false), - )); + const env = yield* HostProcess.Environment; + const policyAllows = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( + Effect.map((found) => found?.document.limits?.telemetry !== false), + Effect.orElseSucceed(() => false), + ); + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; yield* ipc.handleSync( DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL, - result: Schema.Boolean, - handler: () => Effect.succeed(enabled), + result: Schema.NullOr(Schema.Boolean), + handler: () => + shellEnvironment.discoveryFinished.pipe( + Effect.map((known) => + !policyAllows || !isRelayTracingEnabled(env) ? false : known ? true : null, + ), + ), }), ); }, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 22b4a326efe56..23075152c1942 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -16,14 +16,11 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Electron from "electron"; import * as NetService from "@t3tools/shared/Net"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel"; -import serverPackageJson from "../../server/package.json" with { type: "json" }; import * as DesktopIpc from "./ipc/DesktopIpc.ts"; import * as ElectronApp from "./electron/ElectronApp.ts"; @@ -110,24 +107,15 @@ const layerDesktopEnvironment = Layer.unwrap( }), ); -const resolveDesktopSshCliRunner = ( - environment: DesktopEnvironment.DesktopEnvironment["Service"], -): RemoteT3RunnerOptions => { - const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); - if (environment.isDevelopment && devRemoteEntryPath !== undefined) { - return { - nodeScriptPath: devRemoteEntryPath, - nodeEngineRange: serverPackageJson.engines.node, - }; - } - return { archiveVersion: environment.appVersion }; -}; - const layerDesktopSshEnvironment = Layer.unwrap( Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; + const env = yield* HostProcess.Environment; return DesktopSshEnvironment.layer({ - resolveCliRunner: Effect.succeed(resolveDesktopSshCliRunner(environment)), + // Per connect: the login shell's environment is installed after this layer is built. + resolveCliRunner: Effect.sync(() => + DesktopSshEnvironment.resolveDesktopSshCliRunner(environment, env), + ), resolveLauncherId: yield* Effect.cached( DesktopSshEnvironment.readOrCreateLauncherId( environment.path.join(environment.stateDir, "ssh-launcher-id"), diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 18dc0c373008f..588ec90eb8ace 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -111,8 +111,10 @@ contextBridge.exposeInMainWorld("desktopBridge", { } return result as ReturnType; }, - getRelayTelemetryEnabled: () => - ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true, + getRelayTelemetryEnabled: () => { + const enabled = ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL); + return enabled === null ? null : enabled === true; + }, getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL), @@ -255,6 +257,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url), cancelProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url), + startFileDrag: (input) => ipcRenderer.invoke(IpcChannels.START_FILE_DRAG_CHANNEL, input), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url), checkSystemPermission: (pane: string) => diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 7808682dfd82b..f082020a5dec1 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -355,6 +355,7 @@ describe("DesktopShellEnvironment", () => { NODE_EXTRA_CA_CERTS: "/cached/ca.pem", SSL_CERT_FILE: "/cached/cert.pem", SSL_CERT_DIR: "/cached/certs", + T3CODE_TELEMETRY_ENABLED: "false", SSH_AUTH_SOCK: "/stale.sock", NODE_OPTIONS: "--bad", }, @@ -394,6 +395,7 @@ describe("DesktopShellEnvironment", () => { assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem"); assert.equal(env.SSL_CERT_FILE, ""); assert.equal(env.SSL_CERT_DIR, "/cached/certs"); + assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false"); assert.equal(env.SSH_AUTH_SOCK, "/current.sock"); assert.isUndefined(env.NODE_OPTIONS); assert.equal(yield* fs.readFileString(cachePath), contents); @@ -711,6 +713,8 @@ describe("DesktopShellEnvironment", () => { Effect.gen(function* () { assert.isTrue(yield* service.awaitDiscovery); assert.equal(env.PATH, "/usr/bin"); + // The user's shell may still opt out of telemetry, so discovery has not settled. + assert.isFalse(yield* service.discoveryFinished); // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await. const published = yield* service.updates.pipe( Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"), diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index f2a92069f066b..6d84b87e6fcc6 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -93,6 +93,8 @@ export class DesktopShellEnvironment extends Context.Service< readonly awaitDiscovery: Effect.Effect; /** Whether the user's own login shell, not a fallback, gave the PATH a new terminal gets. */ readonly awaitUserShellDiscovery: Effect.Effect; + /** Whether discovery has settled (the user's shell answered or retries ran out), without waiting. */ + readonly discoveryFinished: Effect.Effect; readonly updates: Stream.Stream; } >()("@t3tools/desktop/shell/DesktopShellEnvironment") {} @@ -122,6 +124,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", ] as const; @@ -548,6 +551,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "JAVA_HOME", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { config.env[name] = shellEnvironment[name]; @@ -651,6 +655,7 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", + "T3CODE_TELEMETRY_ENABLED", ] as const; /** @public */ @@ -672,6 +677,7 @@ export const make = Effect.gen(function* () { const changes = yield* PubSub.unbounded(); const latest = yield* Ref.make>(Option.none()); const discovered = yield* Deferred.make(); + const settledDiscovery = yield* Deferred.make(); const publish = Effect.fn("desktop.shellEnvironment.publish")(function* ( patch: ShellEnvironmentPatch, discovered = false, @@ -741,6 +747,7 @@ export const make = Effect.gen(function* () { ), ), ), + Effect.onExit(() => Deferred.succeed(settledDiscovery, undefined)), ); const installIntoProcess = yield* Effect.cached( Effect.gen(function* () { @@ -796,6 +803,7 @@ export const make = Effect.gen(function* () { Effect.andThen(Deferred.await(discovered)), Effect.map(({ fromUserShell }) => fromUserShell), ), + discoveryFinished: Deferred.isDone(settledDiscovery), updates, }); }); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts new file mode 100644 index 0000000000000..b94958a633156 --- /dev/null +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts @@ -0,0 +1,47 @@ +import * as NodePath from "@effect/platform-node/NodePath"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as DesktopConfig from "../app/DesktopConfig.ts"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { resolveDesktopSshCliRunner } from "./DesktopSshEnvironment.ts"; + +const packagedEnvironment = DesktopEnvironment.DesktopEnvironment.pipe( + Effect.provide( + DesktopEnvironment.layer({ + dirname: "/Applications/T3 Code.app/Contents/Resources/app.asar/dist-electron", + homeDirectory: "/Users/alice", + platform: "darwin", + processArch: "arm64", + appVersion: "0.0.22", + appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar", + isPackaged: true, + resourcesPath: "/Applications/T3 Code.app/Contents/Resources", + runningUnderArm64Translation: false, + }).pipe( + Layer.provide( + Layer.mergeAll(NodeServices.layer, NodePath.layerPosix, DesktopConfig.layerTest({})), + ), + ), + ), +); + +describe("resolveDesktopSshCliRunner", () => { + it.effect("downloads the remote runner from the release mirror", () => + Effect.gen(function* () { + const environment = yield* packagedEnvironment; + + const runner = resolveDesktopSshCliRunner(environment, { + [CLI_RELEASE_BASE_URL_ENV]: "https://mirror.example.com/t3code", + }); + + assert.deepStrictEqual(runner, { + archiveVersion: "0.0.22", + releaseBaseUrl: "https://mirror.example.com/t3code", + }); + }), + ); +}); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 0693c16cc15fd..fd749b663cd2d 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -3,6 +3,7 @@ import type { DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentTarget, } from "@t3tools/contracts"; +import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as NetService from "@t3tools/shared/Net"; import * as SshAuth from "@t3tools/ssh/auth"; import { resolveSshTarget } from "@t3tools/ssh/command"; @@ -27,6 +28,10 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as Option from "effect/Option"; +import serverPackageJson from "../../../server/package.json" with { type: "json" }; + +import type * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts"; @@ -74,6 +79,24 @@ export interface DesktopSshEnvironmentLayerOptions { readonly resolveLauncherId?: Effect.Effect; } +export const resolveDesktopSshCliRunner = ( + environment: DesktopEnvironment.DesktopEnvironment["Service"], + env: NodeJS.ProcessEnv, +): SshTunnel.RemoteT3RunnerOptions => { + const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); + if (environment.isDevelopment && devRemoteEntryPath !== undefined) { + return { + nodeScriptPath: devRemoteEntryPath, + nodeEngineRange: serverPackageJson.engines.node, + }; + } + const releaseBaseUrl = env[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined; + return { + archiveVersion: environment.appVersion, + ...(releaseBaseUrl === undefined ? {} : { releaseBaseUrl }), + }; +}; + // Remote servers record this ID as their owner, so it has to outlive restarts, // updates and edits to a saved connection. Without a stored one there is none. export const readOrCreateLauncherId = Effect.fn("desktop.ssh.readOrCreateLauncherId")( diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts index e2bfabe32762c..3b0582e8131b7 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts @@ -93,6 +93,7 @@ describe("DesktopTelemetryPublisher", () => { installIntoProcess: Effect.succeed(true), awaitDiscovery: Effect.succeed(true), awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), updates: Stream.make({ version: 1, type: "shellEnvironment", diff --git a/apps/mobile/assets/icons/issue.png b/apps/mobile/assets/icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/assets/icons/issue.png differ diff --git a/apps/mobile/assets/icons/issue@2x.png b/apps/mobile/assets/icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/assets/icons/issue@2x.png differ diff --git a/apps/mobile/assets/icons/issue@3x.png b/apps/mobile/assets/icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/assets/icons/issue@3x.png differ diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index 9367ade408e95..756c69e52176b 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -8,6 +8,8 @@ import "react-native-gesture-handler"; import { LogBox } from "react-native"; import { featureFlags } from "react-native-screens"; +// Before any GT module initializes: GT validates locales with Intl APIs that Hermes lacks. +import "./src/i18n/intl-polyfills"; import App from "./src/App"; // Enables iOS FormSheet sizing for nested native stacks in non-fitToContents sheets. diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 736f7cd3019f0..1208f3176935d 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -126,7 +126,7 @@ class T3WorkspaceNavigationView( private val onTabSelected by EventDispatcher() private val onNewThread by EventDispatcher() private val onOverlayChange by EventDispatcher() - var tabs by mutableStateOf(listOf("threads", "pullRequests", "usage", "settings")) + var tabs by mutableStateOf(listOf("threads", "pullRequests", "issues", "usage", "settings")) var selectedTab by mutableStateOf("threads") var rail by mutableStateOf(false) var floating by mutableStateOf(false) @@ -415,6 +415,7 @@ class T3WorkspaceNavigationView( private fun tabTitle(tab: String) = when (tab) { "threads" -> "Chats" "pullRequests" -> "Pulls" + "issues" -> "Issues" "usage" -> "Usage" else -> "Settings" } @@ -427,6 +428,7 @@ class T3WorkspaceNavigationView( when (tab) { "threads" -> R.drawable.t3_chats "pullRequests" -> R.drawable.t3_pull_requests + "issues" -> R.drawable.t3_issues "usage" -> R.drawable.t3_usage else -> R.drawable.t3_settings } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml new file mode 100644 index 0000000000000..14de69947215f --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec index c32f88b0dacb3..ed5fd7f091dba 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec @@ -15,6 +15,6 @@ Pod::Spec.new do |s| s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', } - s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png'] } + s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png', 'Resources/Icons/issue*.png'] } s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}' end diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index 78fd2ec1fe379..9df738d37fa67 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -40,7 +40,7 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private let composeButton = UIButton(type: .system) private lazy var tabBarTrailing = tabBar.trailingAnchor.constraint(equalTo: trailingAnchor) private var itemsByTab: [String: UITabBarItem] = [:] - var tabs = ["threads", "pullRequests", "usage", "settings"] { + var tabs = ["threads", "pullRequests", "issues", "usage", "settings"] { didSet { if tabs != oldValue { updateItems() } } } var selectedTab = "threads" { didSet { updateSelection() } } @@ -109,10 +109,11 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private func prepareItems() { let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:)) let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let labels = ["threads": "Chats", "pullRequests": "PRs", "usage": "Usage", "settings": "Settings"] + let labels = ["threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "usage": "Usage", "settings": "Settings"] + let issueIcon = UIImage(named: "issue", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"] for (tab, label) in labels { - let icon = tab == "pullRequests" ? pullRequestIcon : UIImage(systemName: symbols[tab] ?? "circle") + let icon = tab == "pullRequests" ? pullRequestIcon : tab == "issues" ? issueIcon : UIImage(systemName: symbols[tab] ?? "circle") let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0) item.accessibilityLabel = label item.accessibilityIdentifier = "workspace-tab-\(tab)" diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png new file mode 100644 index 0000000000000..1e55bbd87a57f Binary files /dev/null and b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png differ diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml new file mode 100644 index 0000000000000..8125e99ad560e --- /dev/null +++ b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml @@ -0,0 +1,4 @@ + + diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index b2ad65cf05374..7b81d0880a401 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -37,6 +37,11 @@ import { PullRequestReviewersScreen } from "./features/pull-requests/PullRequest import { PullRequestLabelsScreen } from "./features/pull-requests/PullRequestLabelsScreen"; import { PullRequestEditScreen } from "./features/pull-requests/PullRequestEditScreen"; import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequestFilterSearchScreen"; +import { IssueAssigneesScreen } from "./features/issues/IssueAssigneesScreen"; +import { IssueEditScreen } from "./features/issues/IssueEditScreen"; +import { IssueLabelsScreen } from "./features/issues/IssueLabelsScreen"; +import { IssueFilterSearchScreen } from "./features/issues/IssueFilterSearchScreen"; +import { IssueRouteScreen } from "./features/issues/IssueRouteScreen"; import { RenderErrorBoundary, RenderFailureView, @@ -94,6 +99,10 @@ import { SettingsDiagnosticsRouteScreen } from "./features/diagnostics/SettingsD import { SettingsProviderAccountsRouteScreen } from "./features/settings/SettingsProviderAccountsRouteScreen"; import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen"; import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen"; +import { + SettingsIssueTrackerRouteScreen, + SettingsSourceControlProviderRouteScreen, +} from "./features/settings/SettingsSourceControlDetailRouteScreens"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; import { SettingsLanguageRouteScreen } from "./features/settings/SettingsLanguageRouteScreen"; @@ -186,7 +195,15 @@ const SETTINGS_SCREENS = { SettingsEnvironmentSourceControl: createNativeStackScreen({ screen: SettingsEnvironmentSourceControlRouteScreen, linking: "settings/source-control", - options: settingsPage("Source control"), + options: settingsPage("Source control & issues"), + }), + SettingsSourceControlProvider: createNativeStackScreen({ + screen: SettingsSourceControlProviderRouteScreen, + options: settingsPage("Provider"), + }), + SettingsIssueTracker: createNativeStackScreen({ + screen: SettingsIssueTrackerRouteScreen, + options: settingsPage("Issue tracker"), }), SettingsEnvironmentAgentBehavior: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, @@ -552,6 +569,27 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: PullRequestEditScreen, options: sheetRoute({ detent: 0.75, androidFit: true }), }), + Issue: createNativeStackScreen({ + screen: IssueRouteScreen, + linking: "issues/:environmentId/:projectId/:tracker/:scope/:issueKey", + options: pageRoute({ duoMinimize: "never" }), + }), + IssueEdit: createNativeStackScreen({ + screen: IssueEditScreen, + options: sheetRoute({ detent: 0.75, androidFit: true }), + }), + IssueLabels: createNativeStackScreen({ + screen: IssueLabelsScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueAssignees: createNativeStackScreen({ + screen: IssueAssigneesScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueFilterSearch: createNativeStackScreen({ + screen: IssueFilterSearchScreen, + options: SEARCH_SHEET_ROUTE, + }), Thread: createNativeStackScreen({ screen: ThreadRouteScreen, linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] }, diff --git a/apps/mobile/src/components/ComposerSurface.tsx b/apps/mobile/src/components/ComposerSurface.tsx new file mode 100644 index 0000000000000..7cabdfd5faa92 --- /dev/null +++ b/apps/mobile/src/components/ComposerSurface.tsx @@ -0,0 +1,283 @@ +import { useState, type ReactNode } from "react"; +import { I18nManager, Platform, type ViewStyle } from "react-native"; +import Animated, { + FadeIn, + type LayoutAnimationFunction, + ReduceMotion, + useAnimatedStyle, + useDerivedValue, + useSharedValue, + withTiming, +} from "react-native-reanimated"; + +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout"; +import { useSidebarWorkspaceTabs } from "../features/layout/workspace/useSystemWorkspaceTabBar"; +import { useAndroidFloatingTabs } from "../features/settings/appearance/AppearancePreferencesProvider"; +import { compactEditorInsets } from "../features/threads/compactEditorInsets"; +import { + useDeviceType, + useDuoBottomBarInset, + useNativeLayoutMetrics, +} from "../native/native-layout-metrics"; +import type { ScaledTextRole } from "../features/settings/appearance/useScaledTextRole"; +import { MOBILE_TYPOGRAPHY } from "../lib/typography"; +import { useUniwindTheme } from "../lib/useUniwindTheme"; +import { GlassSurface } from "./ui/GlassSurface"; + +const COLLAPSED_EDITOR_DEFAULT_INSET = 6; +// iOS puts line-height slack above glyphs. DM Sans's lowercase midline is +// descender (0.31em) + half x-height (0.504em) above the line bottom. +const LOWERCASE_MIDLINE_EM = 0.562; + +function lowercaseMidline(text: ScaledTextRole): number { + return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize; +} + +function collapsedEditorInset(text: ScaledTextRole): number { + const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body); + return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift)); +} + +const EXPANDED_EDITOR_INSET = 14; +// Room under the expanded editor for the toolbar row. +const EXPANDED_EDITOR_BOTTOM = 52; + +export function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) { + const [contentSize, setContentSize] = useState({ width: 0, height: 0 }); + const [compactWidth, setCompactWidth] = useState(0); + const contentHeight = contentSize.height; + const rowWidth = useSharedValue(0); + const editorX = useSharedValue(0); + const editorWidth = useSharedValue(0); + const inset = + Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text); + const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset); + const height = Math.max( + minimum, + Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset), + ); + // A line that fits the expanded editor may still overflow its compact slot. + // Compare its measured width too so widening cannot trigger a collapse loop. + const isExpanded = + value.length > 0 && + (contentHeight > text.lineHeight * 1.5 || + (compactWidth > 0 && contentSize.width > compactWidth)); + const compactRowHeight = Math.max(44, minimum); + const compactBottom = (compactRowHeight - minimum) / 2; + const isRTL = I18nManager.isRTL; + const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM; + const expansion = useDerivedValue(() => { + const target = isExpanded ? 1 : 0; + return animate + ? withTiming(target, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : target; + }); + const editorStyle = useAnimatedStyle(() => { + const compactInsets = compactEditorInsets({ + slotX: editorX.value, + slotWidth: editorWidth.value, + rowWidth: rowWidth.value, + isRTL, + }); + const progress = expansion.value; + // Hanging from the row top lets the text ride the growing edge and ignore the stale + // height measured while it still wrapped in the compact slot. Layout props only: + // Reanimated applies transforms frames ahead of layout, which tore the text from its frame. + return { + position: "absolute", + overflow: "hidden", + // The compact slot is unknown until its first layout, so the editor would draw over the + button. + opacity: isExpanded || editorWidth.value > 0 ? 1 : 0, + height, + top: compactBottom * (1 - progress), + left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress, + // Snapping the far edge keeps the line from rewrapping while the near edge moves. + right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right, + }; + }); + const containerStyle = useAnimatedStyle(() => ({ + height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value, + })); + return { + isExpanded, + containerStyle, + // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted. + // An entering animation hides it from its first frame, which a shared-value opacity cannot. + toolbarControlsEntering: + animate && isExpanded + ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2) + .duration(COMPOSER_TRANSITION_DURATION_MS / 2) + .reduceMotion(ReduceMotion.System) + : undefined, + editorStyle, + onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => { + rowWidth.set(event.nativeEvent.layout.width); + }, + onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => { + // The expanded toolbar gives this slot to the model control. Keep the + // compact geometry for the return transition, rather than recording zero. + if (!isExpanded) { + editorX.set(event.nativeEvent.layout.x); + editorWidth.set(event.nativeEvent.layout.width); + setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8)); + } + }, + editorProps: { + singleLineCentered: !isExpanded, + scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4, + contentInsetVertical: inset, + onContentSizeChange: (size: { width: number; height: number }) => { + setContentSize(size); + }, + style: { flex: 1 }, + }, + }; +} + +export const COMPOSER_TRANSITION_DURATION_MS = 220; +// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar. +const composerHeightTransition: LayoutAnimationFunction = (values) => { + "worklet"; + const timing = { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }; + return { + initialValues: { + originX: values.targetOriginX, + originY: values.currentOriginY, + width: values.targetWidth, + height: values.currentHeight, + }, + animations: { + originX: values.targetOriginX, + originY: withTiming(values.targetOriginY, timing), + width: values.targetWidth, + height: withTiming(values.targetHeight, timing), + }, + }; +}; +const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition; +// Share of the one-row composer the draft keeps; a long model name truncates first. +export const INLINE_EDITOR_MIN_WIDTH = "40%"; +const INLINE_EDITOR_HEIGHT = 36; + +const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface); + +export function ComposerSurface(props: { + readonly children: ReactNode; + readonly style: ViewStyle; + readonly animateLayout?: boolean; +}) { + const colors = useUniwindTheme(); + const targetBorderRadius = + typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0; + const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android"; + const animatedBorderRadius = useDerivedValue(() => + shouldAnimate + ? withTiming(targetBorderRadius, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : targetBorderRadius, + ); + const borderCurve = props.style.borderCurve; + const animatedShapeStyle = useAnimatedStyle(() => ({ + borderRadius: animatedBorderRadius.value, + ...(borderCurve ? { borderCurve } : {}), + })); + const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined; + + // Animate every native frame or glass and content jump to final height inside the clip. + return ( + + + {null} + + + {props.children} + + + ); +} + +/** Space below the composer pill, inside the bottom inset it is given. */ +export const COMPOSER_BOTTOM_GUTTER = 6; + +/** Control size and pill shape: larger beside a sidebar tab picker and on iPad. */ +export function useComposerChrome() { + const { layout } = useAdaptiveWorkspaceLayout(); + const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView; + const sidebarWorkspaceTabs = useSidebarWorkspaceTabs(); + const deviceType = useDeviceType(); + const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad"; + return { + usesLargeControls, + controlSize: usesLargeControls ? ("large" as const) : ("regular" as const), + borderRadius: usesLargeControls ? 31 : 27, + paddingVertical: usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2, + }; +} + +/** + * The inset below a composer pinned to the bottom of a page. Fixed while the keyboard animates: + * changing it at keyboardDidHide makes the composer land low, then jump back above the safe area. + */ +export function useComposerBottomInset() { + const insets = useSafeAreaInsets(); + const windowMetrics = useNativeLayoutMetrics(); + const { layout } = useAdaptiveWorkspaceLayout(); + const bottomBarInset = useDuoBottomBarInset(); + const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker"; + // A pushed screen temporarily inherits the outgoing tab bar's safe area. + // Use the window edge so hiding that bar cannot move the composer mid-push. + const bottomSafeArea = + Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom; + // The pill already adds its own gutter; iPad and Duo align its edge with the native bar. + const alignedBottomInset = + bottomBarInset ?? + (Platform.OS === "ios" && Platform.isPad + ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0) + : undefined); + // The Duo's floating sidebar pill ends three points below the composer's usual gutter. + return Math.max( + 0, + (alignedBottomInset !== undefined + ? alignedBottomInset - COMPOSER_BOTTOM_GUTTER + : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0), + ); +} + +/** The editor's text style: the composer's scaled role in the theme's foreground color. */ +export function useComposerTextStyle(text: ScaledTextRole) { + return { ...text, color: useUniwindTheme()["--color-foreground"] }; +} diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index 4a5a16298b956..5333af3ea577a 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -1,6 +1,7 @@ import type { Icon } from "@tabler/icons-react-native/types"; /* Package-root imports eagerly register the entire Tabler icon set in Metro. */ import IconAdjustmentsHorizontal from "@tabler/icons-react-native/IconAdjustmentsHorizontal"; +import IconAlarm from "@tabler/icons-react-native/IconAlarm"; import IconAlignLeft from "@tabler/icons-react-native/IconAlignLeft"; import IconAlertCircle from "@tabler/icons-react-native/IconAlertCircle"; import IconAlertTriangle from "@tabler/icons-react-native/IconAlertTriangle"; @@ -149,6 +150,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, "arrow.branch": IconGitBranch, "arrow.left": IconArrowLeft, "arrow.right": IconArrowRight, @@ -189,6 +191,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "circle.inset.filled": IconCircleDot, "circle.dashed.inset.filled": IconCircleDot, "calendar.badge.clock": IconCalendarClock, + alarm: IconAlarm, clock: IconClock, timer: IconClock, "face.smiling": IconMoodPlus, @@ -302,6 +305,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon @@ -313,6 +317,7 @@ const SF_ICON_LOOKUP: Partial< | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsx index 146a9ccb305e7..896765db5d233 100644 --- a/apps/mobile/src/components/ui/AppSymbol.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.tsx @@ -4,6 +4,7 @@ import IconGitCommit from "@tabler/icons-react-native/IconGitCommit"; import IconGitPullRequestClosed from "@tabler/icons-react-native/IconGitPullRequestClosed"; import IconGitPullRequestDraft from "@tabler/icons-react-native/IconGitPullRequestDraft"; import type { SFSymbol } from "expo-symbols"; +import IconCircleDot from "@tabler/icons-react-native/IconCircleDot"; import IconGitPullRequest from "@tabler/icons-react-native/IconGitPullRequest"; import IconFileDiff from "@tabler/icons-react-native/IconFileDiff"; import IconRobot from "@tabler/icons-react-native/IconRobot"; @@ -23,6 +24,7 @@ const CUSTOM_ICONS = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, robot: IconRobot, }; diff --git a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx index 3913eaa47557b..db5cf357a900a 100644 --- a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx +++ b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx @@ -74,11 +74,11 @@ function ConfiguredConnectOnboardingRouteScreen() { contentInsetAdjustmentBehavior="automatic" showsVerticalScrollIndicator={false} className="flex-1" - contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }} contentContainerStyle={{ gap: 16, paddingHorizontal: 20, paddingTop: 16, + paddingBottom: Math.max(insets.bottom, 18) + 18, }} refreshControl={} > diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx index 22a266c8db9ac..b0d78ef3acbce 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx @@ -47,7 +47,21 @@ vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children })); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, - AppTextInput: () => null, + AppTextInput: ({ + accessibilityLabel, + value, + onChangeText, + }: { + accessibilityLabel: string; + value: string; + onChangeText: (value: string) => void; + }) => ( + onChangeText(event.currentTarget.value)} + /> + ), })); vi.mock("../../components/ui/FrostedCutout", () => ({ FrostedCutout: () => null })); vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); @@ -104,3 +118,40 @@ it("does not show another feature's error as a pairing failure", () => { // Leaving the form must not wipe an error that belongs to another screen. expect(harness.pendingConnectionError).toBe("Could not send the message."); }); + +it("splits a pasted pairing link and preserves the code during address edits", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + vi.stubGlobal("__DEV__", false); + harness.pendingConnectionError = null; + const container = document.createElement("div"); + const root = createRoot(container); + + try { + act(() => root.render()); + const address = container.querySelector('input[aria-label="Address"]')!; + const code = container.querySelector('input[aria-label="Code"]')!; + const enter = (input: HTMLInputElement, value: string) => { + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + value, + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + }; + + enter(code, "manual-code"); + enter(address, " http://100.82.53.91:3773/pair#token=test-pairing-code\n"); + expect(address.value).toBe("http://100.82.53.91:3773"); + expect(code.value).toBe("test-pairing-code"); + + enter(code, "replacement-code"); + for (const value of ["", "100.82.53.92:3773", "http://100.82.53.92:3773/"]) { + enter(address, value); + expect(address.value).toBe(value); + expect(code.value).toBe("replacement-code"); + } + } finally { + act(() => root.unmount()); + } +}); diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index 80f2ecc77c02d..44d2da810ca16 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -96,7 +96,13 @@ function PairingForm({ }; const handleHostChange = (value: string) => { - setHostInput(value); + const pairing = parsePairingUrl(value); + if (pairing.code) { + setHostInput(pairing.host); + setCodeInput(pairing.code); + } else { + setHostInput(value); + } clearError(); }; @@ -196,10 +202,10 @@ function PairingForm({ keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false} className="flex-1" - contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }} contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 4, + paddingBottom: Math.max(insets.bottom, 18) + 18, }} > diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index c2946c59ed065..2200829346143 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -707,6 +707,12 @@ export function HomeScreen(props: HomeScreenProps) { detail={`Looking for "${props.searchQuery}" in messages.`} variant={Platform.OS === "android" ? "plain" : undefined} /> + ) : hasSearchQuery && threadSearch.failed ? ( + ) : hasSearchQuery ? ( ) { + const navigation = useNavigation(); + const target = issueTarget(route.params); + const detail = useEnvironmentQuery(issueEnvironment.detail(target)).data; + const access = useIssueAccess(route.params, detail); + const result = useEnvironmentQuery(issueEnvironment.candidates(target)); + const update = useAtomCommand(issueEnvironment.update, { reportFailure: false }); + const [query, setQuery] = useState(""); + // The atom carries a closed sheet's picks to the next one; this sheet's own live here. + const [stored, setStored] = useAtom(issueAssigneePicksFamily(issueParamsKey(route.params))); + // Picks against an older read are dropped once, when the sheet opens. + const [picks, setPicks] = useState(() => + detail ? issuePicksFor(stored, detail, false) : noIssuePicks(), + ); + const own = detail ? issuePicksFor(picks, detail, true) : noIssuePicks(); + // What was last sent is read from the atom, so a write that fails while this sheet is open is + // sent again when it closes. + const current = { ...own, written: stored.basis === detail ? stored.written : null }; + const draft = current.draft; + const allowed = access?.assignees === true; + const held = (candidate: IssueAssigneeCandidate) => + detail ? issueAssigneeHeld(detail, candidate) : false; + const needle = query.trim().toLowerCase(); + const candidates = (result.data?.assignees ?? []).filter((candidate) => + `${candidate.login} ${candidate.name ?? ""}`.toLowerCase().includes(needle), + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed + useEffect( + () => + navigation.addListener("beforeRemove", () => { + if (!detail) return; + const assignees = issueWriteAfterPicks( + issueAssigneesAfterPicks(detail, draft), + detail.assignees.map((actor) => actor.login), + current.written, + ); + if (assignees === null) return; + const sent = { ...current, written: assignees }; + setStored(sent); + void update({ ...target, input: { ...target.input, assignees } }).then((response) => { + const failure = issueCommandError(response); + if (failure === null) return refreshIssueLists(target.environmentId); + // Picks made after this write was sent are kept. + setStored((latest) => issuePicksAfterFailedWrite(latest, sent)); + Dialog.alert("Couldn't change assignees", failure); + }); + }), + [navigation, detail, draft, current, setStored, update, target], + ); + return ( + ({ + key: candidate.id, + title: candidate.login, + ...(candidate.name ? { subtitle: candidate.name } : {}), + leading: , + // Sent when the sheet closes; a failure puts the tracker's answer back. + selected: isSelected(draft, candidate.id, held(candidate)), + }))} + allowed={allowed} + notice={ + detail && !allowed + ? (access?.blocked ?? "Changing assignees needs triage access on this tracker.") + : null + } + pending={result.isPending && !result.data} + loadError={result.data ? null : result.error} + onRetry={result.refresh} + truncated={result.data?.truncated === true} + onToggle={(id) => { + const candidate = candidates.find((entry) => entry.id === id); + if (candidate) { + setPicks({ ...current, draft: toggleSelection(draft, id, candidate, held(candidate)) }); + } + }} + /> + ); +} diff --git a/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx new file mode 100644 index 0000000000000..e4d859e2e5d71 --- /dev/null +++ b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx @@ -0,0 +1,120 @@ +import { LegendList } from "@legendapp/list/react-native"; +import type { ReactNode } from "react"; +import { Platform, View } from "react-native"; + +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { EmptyState } from "../../components/ui/EmptyState"; +import { SelectionRow } from "../../components/ui/SelectionRow"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { PullRequestSearchSheet } from "../pull-requests/PullRequestSearchSheet"; + +interface Candidate { + readonly key: string; + readonly title: string; + readonly subtitle?: string; + readonly leading: ReactNode; + readonly selected: boolean; +} + +/** The searchable checklist behind the label and assignee pickers. */ +export function IssueCandidatesSheet(props: { + readonly title: string; + readonly noun: "labels" | "people"; + readonly query: string; + readonly onQueryChange: (query: string) => void; + readonly candidates: ReadonlyArray; + readonly allowed: boolean; + readonly notice: string | null; + readonly pending: boolean; + readonly loadError: string | null; + readonly onRetry: () => void; + readonly truncated: boolean; + readonly onToggle: (key: string) => void; +}) { + const searching = props.query.trim().length > 0; + return ( + + {({ paddingBottom }) => ( + candidate.key} + extraData={props.candidates} + estimatedItemSize={64} + recycleItems + className="flex-1" + contentInsetAdjustmentBehavior="automatic" + automaticallyAdjustKeyboardInsets={Platform.OS === "ios"} + keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"} + keyboardShouldPersistTaps="handled" + showsVerticalScrollIndicator={false} + contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }} + ListHeaderComponent={ + props.notice ? ( + + {props.notice} + {props.loadError && props.candidates.length > 0 ? ( + + + + + + + + ); +} diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index be674b66520d2..b99591c92b112 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -6,6 +6,7 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell import { DEFAULT_CLIENT_SETTINGS, EnvironmentId, + type LocalApi, ProjectId, ThreadId, type ScopedThreadRef, @@ -25,6 +26,7 @@ import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/en import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; +import { readLocalApi } from "../localApi"; import type { Project } from "../types"; import Sidebar from "./Sidebar"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; @@ -42,6 +44,7 @@ vi.mock("../hooks/useThreadRouteTarget", { spy: true }); vi.mock("./sidebar/SidebarThreadRow", { spy: true }); vi.mock("../state/session", { spy: true }); vi.mock("../state/use-orchestration-command", { spy: true }); +vi.mock("../localApi", { spy: true }); vi.mock(import("../state/server"), async (original) => { const { Atom } = await import("effect/reactivity"); const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings"); @@ -261,6 +264,45 @@ describe("sidebar thread rename", () => { ); }); +describe("sidebar thread menu", () => { + it("tells the menu whether the keyboard opened it", async () => { + const activeProject = project("active"); + const thread = threadShell(activeProject.id, 0); + const threadRef = { environmentId: activeProject.environmentId, threadId: thread.id }; + const show = vi.fn().mockResolvedValue(null); + vi.mocked(readLocalApi).mockReturnValue({ contextMenu: { show } } as unknown as LocalApi); + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue([thread]); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef: threadRef, + }); + await using screen = await render( + + + , + ); + const row = screen.getByText("Thread 0").first(); + await expect.element(row).toBeInTheDocument(); + row.element().closest("[data-sidebar-row]")!.focus(); + await userEvent.keyboard("{Shift>}{F10}{/Shift}"); + await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(1)); + expect(show.mock.lastCall?.[2]).toBe("keyboard"); + await userEvent.click(row, { button: "right" }); + await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(2)); + expect(show.mock.lastCall?.[2]).toBe("mouse"); + }); +}); + describe("sidebar settled pagination", () => { it("keeps the viewport in place when showing more settled threads", async () => { using stack = new DisposableStack(); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 3cb77464473b4..4a76a689fa21f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -55,6 +55,7 @@ import { } from "@t3tools/client-runtime/environment"; import { AuthOrchestrationOperateScope, + type ContextMenuSource, ProjectId, type ScopedThreadRef, type ThreadId, @@ -1250,7 +1251,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve void handleNewThread(scopeProjectRef(group.environmentId, group.id)); }); const handleProjectFolderContextMenu = useStableCallback( - (group: SidebarProjectSnapshot, position: { x: number; y: number }) => { + ( + group: SidebarProjectSnapshot, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => { const api = readLocalApi(); if (!api) return; void (async () => { @@ -1269,6 +1274,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve { id: "project-settings", label: "Project settings", icon: "settings" }, ], position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2283,7 +2289,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleMultiSelectContextMenu = useStableCallback( - async (position: { x: number; y: number }) => { + async (position: { x: number; y: number }, source: ContextMenuSource) => { const api = readLocalApi(); if (!api) return; const selectedThreadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys]; @@ -2381,6 +2387,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, ], position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -2534,7 +2541,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleDraftContextMenu = useStableCallback( - (draftId: DraftId, position: { x: number; y: number }) => { + (draftId: DraftId, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); const session = useComposerDraftStore.getState().getDraftSession(draftId); @@ -2556,6 +2563,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve hasProject: projectGroup != null, }), position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2585,14 +2593,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleThreadContextMenu = useStableCallback( - (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { + (threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); if (!api) return; const threadKey = scopedThreadKey(threadRef); const selectionState = useThreadSelectionStore.getState(); if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { - await handleMultiSelectContextMenu(position); + await handleMultiSelectContextMenu(position, source); return; } const thread = threadByKeyRef.current.get(threadKey); @@ -2659,6 +2667,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve snoozePresets, }), position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -3265,7 +3274,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve role="status" className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground" > - {threadSearch.isPending ? "Searching thread messages…" : "No threads found"} + {threadSearch.isPending + ? "Searching thread messages…" + : threadSearch.failed + ? "Couldn't search thread messages" + : "No threads found"}

) ) : null} diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index a7b7da0a6b53b..5217b068f9a35 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -8,7 +8,7 @@ import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; -import { BackgroundThreadContext } from "./chat/backgroundThread"; +import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -229,7 +229,9 @@ export function ThreadRouteView({ className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh" inert={background} > - {view} + + {view} + {background ? null : redirect} ); diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index f9990ea7d0c45..7632d01b5f907 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -208,6 +208,8 @@ vi.mock("../hooks/useSettings", async () => { return { useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) => select(DEFAULT_CLIENT_SETTINGS), + ensureClientSettingsHydrated: async () => {}, + getClientSettings: () => DEFAULT_CLIENT_SETTINGS, }; }); diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index 570c44fb1fb3c..76247ad2ccde8 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -114,24 +114,27 @@ export function AssistantCitationCommentEditor({ ) : null}
- - + {/* Wrap as a pair so the recording pill never pushes Save alone onto a new row under Cancel. */} +
+ + +
); diff --git a/apps/web/src/components/chat/AssistantCitationSource.tsx b/apps/web/src/components/chat/AssistantCitationSource.tsx index cf2e950e96abd..1df13bdda1f7d 100644 --- a/apps/web/src/components/chat/AssistantCitationSource.tsx +++ b/apps/web/src/components/chat/AssistantCitationSource.tsx @@ -204,6 +204,14 @@ function observeAssistantCitationSource({ if (rect.bottom <= scrollRect.top || rect.top >= scrollRect.bottom) return; activation.scrolled = true; request.onComplete(); + // Screen readers follow focus, not scroll; leave someone already typing alone. + const active = root.ownerDocument.activeElement; + if ( + !(active instanceof HTMLElement) || + !(active.isContentEditable || active.matches("input, textarea, select")) + ) { + root.focus({ preventScroll: true }); + } if (!range) { toastManager.add({ type: "warning", @@ -359,6 +367,8 @@ export function AssistantCitationSource({ return (
{ - const preview = buildExpandedImagePreview(composerImages, imageId); + const preview = buildExpandedImagePreview( + composerImages, + imageId, + copyComposerSnapshotStable, + ); if (preview) onExpandImage(preview); }, openFile: setPreviewFileId, @@ -1045,6 +1055,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const backgroundThread = use(BackgroundThreadContext); + const hiddenThread = use(HiddenThreadContext); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to keydown, window blur and the desktop paste-as-text event to arm plain-text paste useEffect(() => { // A background composer listens on its own form, so it never hears the main composer's keys. @@ -1333,7 +1344,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [record]; + return [ + record.kind === "image" && attachment.type === "image" && attachment.source + ? { ...record, source: attachment.source } + : record, + ]; }), ]; if (records.length === 0) return null; @@ -1345,6 +1360,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (fragment) rememberCopiedComposerAttachments(environmentId, copiedFiles); return fragment; }; + const copyComposerSnapshot = async (imageId: string) => { + const image = composerImages.find((candidate) => candidate.id === imageId); + if (!image) throw new Error("Snapshot is no longer available."); + const contextId = toKindScopedComposerContextId("image", image.id); + const fragment = buildContextClipboardFragment([contextId]); + if (!fragment || !image.previewUrl) throw new Error("The snapshot is not ready to copy."); + await copySnapshot( + image.previewUrl, + formatComposerContextReference({ kind: "image", contextId, label: image.name }), + fragment, + ); + }; + const copyComposerSnapshotStable = useStableCallback(copyComposerSnapshot); const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); const { loadThreadTranscript, @@ -1822,6 +1850,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) projectName, ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, disabled: dictationDisabled, + label: activeThread?.title ?? null, + presented: !hiddenThread, + // A question's answer lives only in this composer, so only the thread draft outlives it. + persistentDraft: questionAttachmentTarget + ? undefined + : { + readStoredText: () => readComposerDraftPrompt(composerDraftTarget), + commitStoredText: (text) => { + const live = resolveLiveComposerDraftTarget(composerDraftTarget); + if (live !== null) setComposerDraftPrompt(live, text); + }, + // The route, not the draft target: a queued-message edit has a draft id but no route. + open: () => + void (routeKind === "draft" && typeof composerDraftTarget === "string" + ? navigate({ + to: "/draft/$draftId", + params: buildDraftThreadRouteParams(composerDraftTarget), + }) + : navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(routeThreadRef), + })), + }, readDraft: () => { const snapshot = readComposerSnapshot(); return { @@ -2415,6 +2466,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) allImages={composerImages} resolvedTheme={resolvedTheme} onExpandImage={onExpandImage} + onCopySnapshot={copyComposerSnapshotStable} onShowMore={expandMobileComposer} /> ) : null; @@ -2489,6 +2541,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // An open question owns the space above the composer. Only a machine problem, // which is why an answer could not go through, stays beside it. const replyTo = composerDraft?.replyTo ?? null; + const draftRunsLocally = composerRunsDraftLocally({ + text: prompt, + holdsOnlyText: + composerImages.length + composerFiles.length === 0 && + composerSendState.sendableTerminalContexts.length === 0 && + composerPreviewAnnotations.length === 0 && + composerReviewComments.length === 0 && + composerThreadContexts.length === 0 && + composerEnvironmentContexts.length === 0 && + replyTo === null, + sideChat: props.sideChatAvailable === true || (props.sideChatDisabledReason ?? null) !== null, + usageLimits: props.onUsageLimitsCommand !== undefined, + codexFeedback: selectedProvider === "codex" && multipleModelSelections === null, + freshSession: props.onFreshSession !== undefined, + }); const replyBannerItems: readonly ComposerBannerStackItem[] = replyTo ? [ { @@ -2744,9 +2811,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { files, folders } = splitTransferredFiles(event.clipboardData); const plainText = event.clipboardData.getData("text/plain"); const bypassAutoAttachment = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); + const pastedContext = + !isLiteralPendingAnswer && + (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; if ( folders.length > 0 || - (activeThreadId && + (!pastedContext && + activeThreadId && files.length > 0 && shouldHandleComposerAttachmentPaste({ files, plainText })) ) { @@ -2759,7 +2830,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return; } - if ((readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0) return; + if (pastedContext) return; if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } @@ -3299,6 +3370,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentId={environmentId} attachmentDraftTarget={attachmentDraftTarget} canOperateThread={canOperateThread} + onCopySnapshot={copyComposerSnapshotStable} onExpandImage={onExpandImage} onFileOpen={onFileOpen} onRemoveImage={removeComposerImage} @@ -3737,11 +3809,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) compact={isComposerPrimaryActionsCompact} canOperateThread={canOperateThread} pendingAction={pendingPrimaryAction} - // A side-chat command starts a side chat; it never queues or steers the turn. - isRunning={ - (phase === "running" || phase === "connecting") && - !(props.sideChatAvailable === true && parseSideChatCommand(prompt) !== null) - } + isRunning={(phase === "running" || phase === "connecting") && !draftRunsLocally} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} followUpBehavior={followUpBehavior} @@ -3787,6 +3855,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) finishShortcutLabel={dictationShortcutLabel} cancelShortcutLabel="Esc" level={speechInput.level} + recordingStartedAt={speechInput.recordingStartedAt} disabled={dictationDisabled} onStart={() => void speechInput.start()} onStop={() => void speechInput.stop()} diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index ca98b4d2f6c79..59115804e4972 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -149,6 +149,7 @@ export function ComposerAttachmentMediaRow({ attachmentDraftTarget, canOperateThread, onExpandImage, + onCopySnapshot, onFileOpen, onRemoveImage, onRemoveFile, @@ -167,6 +168,7 @@ export function ComposerAttachmentMediaRow({ readonly environmentId: EnvironmentId; readonly attachmentDraftTarget: ScopedThreadRef | DraftId; readonly canOperateThread: boolean; + readonly onCopySnapshot: (imageId: string) => Promise; readonly onExpandImage: (preview: ExpandedImagePreview) => void; readonly onFileOpen: (attachment: ChatFileAttachment) => void; readonly onRemoveImage: (imageId: string) => void; @@ -224,7 +226,7 @@ export function ComposerAttachmentMediaRow({ aria-label={`Preview ${image.name}`} disabled={!ready} onClick={() => { - const preview = buildExpandedImagePreview(images, image.id); + const preview = buildExpandedImagePreview(images, image.id, onCopySnapshot); if (!preview) return; onExpandImage(preview); }} @@ -254,6 +256,7 @@ export function ComposerAttachmentMediaRow({ {source?.kind === "snap-shot" ? ( onCopySnapshot(ready.id) : undefined} className={cn( upload?.status === "uploading" && "bottom-4", upload?.status === "failed" && "bottom-8", @@ -586,11 +589,13 @@ export function ComposerRestingImagePreviews({ allImages, resolvedTheme, onExpandImage, + onCopySnapshot, onShowMore, }: { readonly images: ReadonlyArray; readonly allImages: ReadonlyArray; readonly resolvedTheme: "light" | "dark"; + readonly onCopySnapshot: (imageId: string) => Promise; readonly onExpandImage: (preview: ExpandedImagePreview) => void; readonly onShowMore: () => void; }) { @@ -606,7 +611,7 @@ export function ComposerRestingImagePreviews({ aria-label={`Preview ${image.name}`} onPointerDown={(event) => event.preventDefault()} onClick={() => { - const preview = buildExpandedImagePreview(allImages, image.id); + const preview = buildExpandedImagePreview(allImages, image.id, onCopySnapshot); if (preview) onExpandImage(preview); }} > diff --git a/apps/web/src/components/chat/ComposerSpeechButton.tsx b/apps/web/src/components/chat/ComposerSpeechButton.tsx index ca9ef2a278ad6..9f7eb4f37ab74 100644 --- a/apps/web/src/components/chat/ComposerSpeechButton.tsx +++ b/apps/web/src/components/chat/ComposerSpeechButton.tsx @@ -43,18 +43,25 @@ function formatElapsed(seconds: number) { return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; } -function RecordingStatus(props: { level: number; recordingLimitSeconds?: number | undefined }) { - const [elapsedSeconds, setElapsedSeconds] = useState(0); +function RecordingStatus(props: { + level: number; + recordingStartedAt?: number | null | undefined; + recordingLimitSeconds?: number | undefined; +}) { + const { recordingStartedAt } = props; + const [elapsedSeconds, setElapsedSeconds] = useState(() => + recordingStartedAt ? Math.max(0, Math.floor((Date.now() - recordingStartedAt) / 1_000)) : 0, + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the timer displaying the native recording duration useEffect(() => { - const startedAt = Date.now(); + const startedAt = recordingStartedAt ?? Date.now(); const timer = window.setInterval( () => setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1_000)), 250, ); return () => window.clearInterval(timer); - }, []); + }, [recordingStartedAt]); return ( <> @@ -125,6 +132,7 @@ export function ComposerSpeechRecordingPill(props: { finishShortcutLabel?: string | null; cancelShortcutLabel?: string | null; level: number; + recordingStartedAt?: number | null | undefined; recordingLimitSeconds?: number | undefined; /** Compact matches the `xs` buttons beside text-field editors. */ size?: "default" | "compact"; @@ -181,6 +189,7 @@ export function ComposerSpeechRecordingPill(props: { {recording ? ( ) : ( diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 2d70c5f2ef1dc..a539994d01862 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -18,6 +18,7 @@ import { MediaVideoPlayer } from "../media/MediaVideoPlayer"; import { isContextMenuOpen } from "../../contextMenuFallback"; import { SnapShotAccessibilityData, + SnapShotCopyButton, SnapShotContentsButton, snapShotAccessibilityDetails, } from "./SnapShotAttachmentDetails"; @@ -277,6 +278,11 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ ) : item.source ? ( ) : null} + {item.onCopySnapshot && ( +
+ +
+ )}
diff --git a/apps/web/src/components/chat/ExpandedImagePreview.tsx b/apps/web/src/components/chat/ExpandedImagePreview.tsx index 0eec6753f8e96..ddd2990000119 100644 --- a/apps/web/src/components/chat/ExpandedImagePreview.tsx +++ b/apps/web/src/components/chat/ExpandedImagePreview.tsx @@ -27,6 +27,7 @@ export interface ExpandedImageItem { /** Revoke this owned object URL; other blob URLs belong to the timeline. */ ownsSrc?: boolean; source?: SnapShotSource; + onCopySnapshot?: (() => Promise) | undefined; autoPlay?: boolean; originalUrl?: string; srcFragment?: string; @@ -162,6 +163,7 @@ export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => export function buildExpandedImagePreview( images: ReadonlyArray, selectedImageId: string, + onCopySnapshot?: (id: string) => Promise, ): ExpandedImagePreview | null { const selected = images.find((image) => image.id === selectedImageId); if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) { @@ -202,7 +204,12 @@ export function buildExpandedImagePreview( src: image.src, name: image.name, mimeType: image.mimeType, - ...(image.source?.kind === "snap-shot" ? { source: image.source } : {}), + ...(image.source?.kind === "snap-shot" + ? { + source: image.source, + onCopySnapshot: onCopySnapshot ? () => onCopySnapshot(image.id) : undefined, + } + : {}), })), index: selectedIndex, }; diff --git a/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx b/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx new file mode 100644 index 0000000000000..3bc724fe1962a --- /dev/null +++ b/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx @@ -0,0 +1,52 @@ +import { useVoiceTranscriptionDestination } from "../../speech/useEnvironmentSpeechInput"; +import { + useRetainedVoiceInputSession, + useVoiceInputSessionActivity, + useVoiceInputSessionSnapshot, + useVoiceOwnerPresented, +} from "../../speech/voiceInputSession"; +import { Button } from "../ui/button"; +import { ComposerSpeechRecordingPill } from "./ComposerSpeechButton"; + +/** + * Keeps the chosen destination's dictation alive across navigation and, while the draft it + * records into is off screen, shows it so it can be finished, cancelled, or returned to. + */ +export function GlobalVoiceInputIndicator({ hidden = false }: { hidden?: boolean }) { + const { prepared, grantId, cloudProvider, cloudModel } = useVoiceTranscriptionDestination(); + const session = useRetainedVoiceInputSession({ prepared, grantId, cloudProvider, cloudModel }); + const { state, target, recordingStartedAt } = useVoiceInputSessionSnapshot(session); + const presented = useVoiceOwnerPresented(target?.ownerKey ?? null); + const { level } = useVoiceInputSessionActivity( + hidden || presented ? null : session, + target?.ownerKey ?? null, + ); + if (hidden || !session || !target || state.phase === "idle" || presented) return null; + + return ( +
+
+ + void session.start(target)} + onStop={() => void session.stop()} + onCancel={() => session.cancel()} + onSkipPostProcessing={() => session.skipPostProcessing()} + /> +
+
+ ); +} diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 5d0238fb1f3af..53e575bd5bc99 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -1,3 +1,4 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; import { useAssetUrlState } from "../../assets/assetUrls"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { @@ -42,6 +43,7 @@ interface MarkdownFileLinkProps { threadRef?: ScopedThreadRef | undefined; onOpen?: (() => Promise>) | undefined; onOpenInPanel: (panelPath: string, line: number | undefined) => void; + resolveDragPath: () => Promise; resolveCopyPaths: () => Promise>; openInEditorMenuLabel: string; onOpenInBrowser?: (() => Promise>) | undefined; @@ -73,7 +75,9 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ onReveal, revealLabel, resolveCopyPaths, + resolveDragPath, }: MarkdownFileLinkProps) { + const nativeDrag = useNativeFileDrag(environmentId, resolveDragPath); const handleOpenInEditor = () => { if (!onOpen) { return; @@ -328,6 +332,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ render={ hasPrimaryAction ? ( } @@ -362,6 +367,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ ) : ( } @@ -418,6 +424,7 @@ function areMarkdownFileLinkPropsEqual( previous.onOpenMedia === next.onOpenMedia && previous.onReveal === next.onReveal && previous.resolveCopyPaths === next.resolveCopyPaths && + previous.resolveDragPath === next.resolveDragPath && previous.revealLabel === next.revealLabel ); } diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 448e6f90a8ed0..013d478127b47 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -49,6 +49,8 @@ import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; import { TimelineRowCtx } from "./timelineRowContext"; import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; +import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; import { toastManager } from "../ui/toast"; import type { CitedHistory } from "./citationProcedure"; @@ -865,6 +867,30 @@ describe("MessagesTimeline messages", () => { expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined(); }); + it("shows the spaces typed at the start of user lines, where find also matches them", async () => { + const source = "Plan\n Step one\n\tDetail"; + await using screen = await renderTimeline([ + message(source), + message(source, { role: "assistant" }, "assistant-1"), + ]); + const [user, assistant] = screen.container.querySelectorAll( + "[data-timeline-row-kind=message]", + ); + expect(user?.querySelector("[data-user-message-body]")?.innerText).toBe(source); + expect(assistant?.querySelector(".chat-markdown")?.innerText).toBe( + "Plan Step one Detail", + ); + const query = " Step one"; + const indexed = searchableMessageSegments({ role: "user", text: source, streaming: false }); + const ranges = collectThreadFindRanges(screen.container, query); + expect(ranges.map(({ rowId, range }) => [rowId, range.toString()])).toEqual([ + [user?.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id"), query], + ]); + expect( + indexed?.reduce((count, segment) => count + countThreadSearchOccurrences(segment, query), 0), + ).toBe(ranges.length); + }); + it("keeps single tildes in user paths literal without changing double tildes or assistant text", async () => { const source = "Install the skill as ~/folder-a/skills/x, then follow the guide (~/folder-a/guide.md)."; @@ -1254,6 +1280,21 @@ describe("MessagesTimeline citations", () => { ); }); + it("moves focus to the cited response so screen readers follow it", async () => { + await using _screen = await renderTimeline( + [ + message("A question", {}, "question"), + message("the cited answer", { role: "assistant" }, "cited"), + ], + { citationRequest: CITATION_REQUEST, citationHistory: { _tag: "found" } }, + ); + await vi.waitFor(() => { + const cited = document.querySelector("[data-citation-highlighted]"); + expect(cited?.textContent).toContain("the cited answer"); + expect(cited?.contains(document.activeElement)).toBe(true); + }); + }); + it("opens the superseded attempt that folds the cited response", async () => { const runId = RunId.make("run-steered"); const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({ @@ -2083,7 +2124,7 @@ it("renders automatic compaction as one live divider that finishes with its reas await expect .element( screen.getByRole("separator", { - name: "Context automatically compacted before cache expiry 899K → 19K tokens", + name: "Auto-compacted before cache expiry 899K → 19K tokens", }), ) .toBeVisible(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 1cd8066dbcd32..f834c7cc355b9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -686,7 +686,7 @@ describe("deriveMessagesTimelineRows", () => { active: true, label: "Compacting before the cache expires…", }, - "Context automatically compacted before cache expiry", + "Auto-compacted before cache expiry", ], ["onReturn", { kind: "working", compacting: true }, "Context compacted before sending"], [undefined, { kind: "context-compaction", active: true }, undefined], diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index e9a884fde6a17..87bacfd7ca2a2 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -548,13 +548,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { const flatModels = (() => { const out: ModelPickerItem[] = []; + const seenKeys = new Set(); for (const [instanceId, models] of modelOptionsByInstance) { const entry = entryByInstanceId.get(instanceId); if (!entry) { continue; } for (const model of models) { + const key = modelPickerModelKey(instanceId, model.slug); if ( + seenKeys.has(key) || !shouldIncludeModelPickerOption({ entry, option: model, @@ -564,6 +567,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ) { continue; } + seenKeys.add(key); out.push({ slug: model.slug, name: model.name, diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index da9d7d50a5396..cc246a1f9967c 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -232,7 +232,7 @@ describe("open in editor announcement", () => { using _timers = fakeTimers(); const regions = () => [...document.querySelectorAll('body > [aria-live="polite"]')]; const spoken = async () => { - await act(async () => vi.runAllTimers()); + await act(async () => vi.advanceTimersByTime(250)); return regions() .map((region) => region.textContent) .join(""); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx index bf196f52542c2..06bb36a34c07f 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx @@ -4,6 +4,7 @@ import { ProviderInstanceId, type ModelSelection, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -176,6 +177,73 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo await expect.element(search).not.toBeInTheDocument(); }); +it("lists a model reported twice by one provider once, with contiguous jump shortcuts", async () => { + const instanceId = ProviderInstanceId.make("claude"); + const entries = deriveProviderInstanceEntries([ + { + instanceId, + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }, + ]); + const options = new Map([ + [ + instanceId, + ["a", "b", "c", "c", "d", "d"].map((slug) => ({ + slug, + name: `Model ${slug.toUpperCase()}`, + })), + ], + ]); + const keybindings = compileResolvedKeybindingsConfig( + ([1, 2, 3, 4, 5, 6] as const).map((index) => ({ + key: `mod+${index}`, + command: `modelPicker.jump.${index}` as const, + when: "modelPickerOpen", + })), + ); + + await using screen = await render( + {}} + />, + ); + await screen.getByRole("button", { name: "Choose model" }).click(); + await expect.element(page.getByRole("option", { name: /Model A/ })).toBeVisible(); + await vi.waitFor(() => + expect( + page + .getByRole("option") + .elements() + .map((row) => [ + row.textContent?.match(/Model [A-Z]/)?.[0], + row.querySelector("kbd")?.textContent?.slice(-1), + ]), + ).toEqual([ + ["Model A", "1"], + ["Model B", "2"], + ["Model C", "3"], + ["Model D", "4"], + ]), + ); +}); + it("opens on the active provider when every favorite belongs to a disabled provider", async () => { const entries = deriveProviderInstanceEntries( ["Codex", "Claude"].map((name) => ({ diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx index 8781327b5e8ad..4f4daf7c798b4 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx @@ -1,11 +1,18 @@ import { RegistryContext } from "@effect/atom-react"; import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads"; -import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { + CommandId, + EnvironmentId, + MessageId, + OrchestrationV2DispatchCommandError, + ThreadId, +} from "@t3tools/contracts"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { formatComposerContextReference, toComposerContextId, } from "@t3tools/shared/composerContextReferences"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity"; @@ -16,6 +23,7 @@ import { page } from "vite-plus/test/browser"; const state = vi.hoisted(() => ({ threadState: null as unknown as Atom.Writable>, workflow: null as unknown, + commandResult: undefined as unknown, })); vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({ @@ -66,7 +74,7 @@ vi.mock(import("../../state/threads"), async (importOriginal) => { vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({ ...(await importOriginal()), - useAtomCommand: (() => async () => undefined) as never, + useAtomCommand: (() => async () => state.commandResult) as never, })); vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({ @@ -80,12 +88,14 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/th import { act, render as renderUi } from "../../../test/render"; import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures"; +import { ToastProvider } from "../ui/toast"; import { QueuedRunsControl } from "./QueuedRunsControl"; import { ExpandedImageDialog } from "./ExpandedImageDialog"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; function setup() { state.workflow = null; + state.commandResult = undefined; } const baseProps = { @@ -399,3 +409,37 @@ it("does not re-render while assistant text streams into the thread", async () = await act(() => registry.set(state.threadState, thread("Hello there", true))); expect(renders).toBeGreaterThan(settled); }); + +it("tells the user why Send now was rejected", async () => { + setup(); + const reason = "Target run run:active is stopping and cannot be steered."; + state.workflow = { + activeRun: { id: "run:active" }, + canPromoteToSteer: true, + queuedRuns: [ + { + run: { id: "run:queued", userMessageId: "message:queued" }, + text: "Follow up", + attachments: [], + }, + ], + }; + state.commandResult = AsyncResult.failure( + Cause.fail( + new OrchestrationV2DispatchCommandError({ + commandId: CommandId.make("command:promote"), + commandType: "queued-message.promote-to-steer", + message: reason, + detail: reason, + }), + ), + ); + await using _screen = await renderUi( + + + , + ); + + await page.getByRole("button", { name: "Send now" }).click(); + await vi.waitFor(() => expect(page.getByText(reason).element()).toBeVisible()); +}); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index 8972bf468448b..49cbc8f050eea 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -1,4 +1,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { @@ -34,6 +38,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { isImageAttachment, type ChatImageAttachment, type ChatMessage } from "../../types"; import { cn } from "~/lib/utils"; import { Button, InlineButton } from "../ui/button"; +import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { TimestampFormat } from "@t3tools/contracts/settings"; import { GuestMessageName } from "./guestMessageStyle"; @@ -168,19 +173,27 @@ export function QueuedRunsControl({ if (!canSendRun(freshContext) || steerInFlightRef.current) return; steerInFlightRef.current = true; setBusyRunId(queuedRunId); - if (workflow?.canSendNow) { - await resume({ - environmentId: props.environmentId, - input: { threadId: props.threadId, runId: queuedRunId }, - }); - } else if (activeRun !== null) { - await promote({ - environmentId: props.environmentId, - input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, - }); - } + const result = workflow?.canSendNow + ? await resume({ + environmentId: props.environmentId, + input: { threadId: props.threadId, runId: queuedRunId }, + }) + : activeRun !== null + ? await promote({ + environmentId: props.environmentId, + input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, + }) + : null; steerInFlightRef.current = false; setBusyRunId(null); + if (result?._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Could not send queued message", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } }; useImperativeHandle(ref, () => ({ diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 5ba6985e19d21..6b8de5aca8ecc 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -1,6 +1,7 @@ import type { EditorId, EnvironmentId, + IssueTrackerKind, PreviewAnnotationPayload, ProjectId, ResolvedKeybindingsConfig, @@ -19,6 +20,7 @@ import { PersistentThreadTerminalPanel, type PersistentThreadTerminalPanelProps, } from "../PersistentThreadTerminals"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; import { pullRequestPanelContext } from "../pullRequest/pullRequestDetail.logic"; import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; import { PullRequestDetailGhost } from "../pullRequest/PullRequestGhosts"; @@ -77,6 +79,7 @@ export function RightPanelSurfaceContent(props: { readonly onCloseSurface: (surface: RightPanelSurface) => void; readonly terminal: RightPanelTerminalProps; readonly pullRequest: RightPanelPullRequestProps; + readonly issuesSupported: boolean; readonly files: RightPanelFileProps; readonly sideChatParentPanel: SideChatParentPanel; }) { @@ -171,6 +174,40 @@ export function RightPanelSurfaceContent(props: { /> ); } + case "issue": + if (!props.pullRequest.capabilityKnown) return ; + if (!props.issuesSupported) { + return ( + + ); + } + return ( + { + useRightPanelStore.getState().openPullRequest(threadRef, { + projectId: reference.projectId, + repository: reference.repository, + number: reference.number, + ...(reference.host ? { host: reference.host } : {}), + }); + }} + /> + ); case "pull-requests": return ; case "side-chat": diff --git a/apps/web/src/components/chat/SkillInlineText.tsx b/apps/web/src/components/chat/SkillInlineText.tsx index d2489e6ce2993..2691b8dafbb41 100644 --- a/apps/web/src/components/chat/SkillInlineText.tsx +++ b/apps/web/src/components/chat/SkillInlineText.tsx @@ -8,6 +8,7 @@ import { useRightPanelStore } from "~/rightPanelStore"; import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip"; import { ContextChipPopover } from "../contextChipParts"; import { Button } from "../ui/button"; +import { PopoverClose } from "../ui/popover"; import { ModelMentionChip } from "./ModelMentionChip"; function SkillInlineText(props: { @@ -135,9 +136,12 @@ export function SkillChipPopover(props: {

{props.label}

{props.description || "No description is available for this skill."}

{props.onViewInstructions ? ( - + ) : null} diff --git a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx index 07f16c8794e98..826b335469d09 100644 --- a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx +++ b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx @@ -1,6 +1,6 @@ import type { SnapShotSource } from "@t3tools/contracts"; -import { ImageIcon, TextIcon } from "lucide-react"; -import { Suspense } from "react"; +import { CheckIcon, CopyIcon, ImageIcon, TextIcon } from "lucide-react"; +import { Suspense, useRef, useState } from "react"; import { useRenderedAppearance } from "../../hooks/useTheme"; import { cn } from "../../lib/utils"; @@ -8,6 +8,10 @@ import { RenderErrorBoundary } from "../RenderErrorBoundary"; import { Button } from "../ui/button"; import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + ANCHORED_COPY_TOAST_TIMEOUT_MS, + showAnchoredCopyErrorToast, +} from "../ui/anchoredCopyToast"; import { HighlightedTokens } from "./HighlightedTokens"; export const SNAP_SHOT_ATTACHMENT_FRAME_CLASS = @@ -71,14 +75,64 @@ function snapShotIncludesAccessibility(source: SnapShotSource): boolean { return Boolean(source.accessibility || source.accessibleText?.trim()); } +export function SnapShotCopyButton({ + onCopy, + side = "top", +}: { + onCopy: () => Promise; + side?: "top" | "right" | "bottom" | "left"; +}) { + const ref = useRef(null); + const [copied, setCopied] = useState(false); + + return ( + + { + event.stopPropagation(); + void onCopy().then( + () => { + setCopied(true); + setTimeout(() => setCopied(false), ANCHORED_COPY_TOAST_TIMEOUT_MS); + }, + (error: unknown) => + showAnchoredCopyErrorToast( + ref, + error instanceof Error ? error : new Error(String(error)), + ), + ); + }} + size="xs" + variant="ghost-muted" + /> + } + > + {copied ? ( + + Copy snapshot + + ); +} + export function SnapShotContentsButton({ source, className, side = "top", + onCopySnapshot, }: { source: SnapShotSource; className?: string; side?: "top" | "right" | "bottom" | "left"; + onCopySnapshot?: (() => Promise) | undefined; }) { const includesAccessibility = snapShotIncludesAccessibility(source); const ContentsIcon = includesAccessibility ? TextIcon : ImageIcon; @@ -111,7 +165,14 @@ export function SnapShotContentsButton({
- Accessibility data +
+ Accessibility data + {onCopySnapshot && ( +
+ +
+ )} +
{accessibilityDetails ? ( Promise) | undefined; className?: string; }) { return ( @@ -157,7 +220,11 @@ export function SnapShotAttachmentDetails({
{source.appName} - +
{source.windowTitle || "Captured window"} diff --git a/apps/web/src/components/chat/SubagentTooltipContent.tsx b/apps/web/src/components/chat/SubagentTooltipContent.tsx index 50b50273ba965..d89bea79080da 100644 --- a/apps/web/src/components/chat/SubagentTooltipContent.tsx +++ b/apps/web/src/components/chat/SubagentTooltipContent.tsx @@ -129,7 +129,7 @@ export function SubagentTooltipContent(props: { showBadge={showInstanceBadge && entry?.accentColor !== undefined} badgeContent="none" badgeClassName="h-2 min-w-2 px-0" - iconClassName="size-3 shrink-0 grayscale opacity-60" + iconClassName="size-3 shrink-0 opacity-60" /> ) : ( diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx new file mode 100644 index 0000000000000..b529cd6afe6a1 --- /dev/null +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -0,0 +1,43 @@ +import { threadIssueKeyOf, type ThreadIssueLink } from "@t3tools/contracts"; +import type { MouseEvent as ReactMouseEvent } from "react"; + +import { cn } from "~/lib/utils"; + +import { IssueGlyph } from "../issue/issuePresentation"; +import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_LABEL_CLASS, +} from "./threadDetailsPanelStyles"; + +/** + * The thread details panel's issue rows, one per linked issue, beside the pull request rows. A + * row names the issue as it was when linked and opens it in the right panel, which reads its + * live state. + */ +export function ThreadDetailsIssueRows({ + links, + onOpenLink, +}: { + links: ReadonlyArray; + onOpenLink: (event: ReactMouseEvent, link: ThreadIssueLink) => void; +}) { + if (links.length === 0) return null; + return ( + <> + {links.map((link) => ( + onOpenLink(event, link)} + > + + + {link.displayKey}: {link.title} + + + ))} + + ); +} diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index f2f41be10f958..1c3fa1a3899fc 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerKind, ProjectId, SourceControlProviderKind, ThreadId, @@ -119,6 +120,7 @@ import { act, render as renderUi } from "../../../test/render"; import { useComposerDraftStore } from "~/composerDraftStore"; import { useUiStateStore } from "~/uiStateStore"; import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow"; +import { ThreadDetailsIssueRows } from "./ThreadDetailsIssueRows"; import { ThreadDetailsThreadPrRows } from "./ThreadDetailsPrRows"; const threadRef: ScopedThreadRef = { @@ -173,7 +175,6 @@ it("merges with the last selected merge method", async () => { status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} />, ); @@ -202,7 +203,6 @@ it("requires a new merge click after passing checks become pending and pass agai status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} /> ); @@ -266,7 +266,6 @@ it("adds the failing checks to a given composer instead of opening a new thread" status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} composerTarget={threadRef} />, @@ -333,3 +332,66 @@ it.each([ `using ${expected}`, ); }); + +it("names a linked pull request row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + state.projects = [repositoryProject]; + state.pullRequests = [ + { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + linkedAt: "2026-10-30T00:00:00.000Z", + snapshot: null, + stack: null, + }, + ]; + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Test PR"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/pull request/i); + expect(name).toContain("#1"); + expect(name).toContain("Test PR"); +}); + +it("names a linked issue row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Sidebar flickers on resize"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/issue/i); + expect(name).toContain("#123"); + expect(name).toContain("Sidebar flickers on resize"); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index acf9629a10347..c067632980156 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -94,7 +94,6 @@ export function ThreadDetailsPrRow({ status, project, label, - openAriaLabel, onOpen, onActed, onStopWatching, @@ -107,7 +106,6 @@ export function ThreadDetailsPrRow({ status: PrStatusIndicator | null; project: EnvironmentProject | null; label: string; - openAriaLabel: string; onOpen: (event: ReactMouseEvent) => void; onActed?: () => void; onStopWatching?: (() => void) | undefined; @@ -265,6 +263,15 @@ export function ThreadDetailsPrRow({ ); + const stateLabel = ( + statePresentation ?? + (pr ? resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }) : null) + )?.label.toLowerCase(); + const title = (detail?.title ?? pr?.title)?.trim(); + const openAriaLabel = `${capitalizeTerm(terminology.singular)} #${number}${ + stateLabel ? `, ${stateLabel}` : "" + }${title ? `: ${title}` : ""}`; + const rowTooltip = detail === null || statePresentation === null ? ( diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx index 65f796341d3fe..31ea6c6865a4c 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx @@ -71,7 +71,6 @@ function ThreadDetailsPrLinkRow({ status={prStatusIndicator(pr, linked?.sourceControlProvider)} project={project} label={`#${link.number}${link.snapshot === null ? "" : `: ${link.snapshot.title}`}`} - openAriaLabel={link.url} onOpen={onOpen} onStopWatching={onStopWatching} composerTarget={composerTarget} @@ -207,7 +206,6 @@ export function ThreadDetailsThreadPrRows({ status={displayed.status} project={rowProject} label={`#${number}${pr?.title.trim() ? `: ${pr.title}` : ""}`} - openAriaLabel={url} onOpen={(event) => openPrLink(event, url)} composerTarget={composerTarget} {...(onActed ? { onActed } : {})} diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx index 3a32ec20400d9..c6234895025ec 100644 --- a/apps/web/src/components/chat/TimelineMinimap.tsx +++ b/apps/web/src/components/chat/TimelineMinimap.tsx @@ -186,7 +186,6 @@ export function TimelineMinimap({ onMouseDown={(event) => event.preventDefault()} type="button" > -
{items.map((item, index) => { const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`; const activeDistance = diff --git a/apps/web/src/components/chat/TimelineRowParts.tsx b/apps/web/src/components/chat/TimelineRowParts.tsx index 549b9c7a422f9..c881b845dd21a 100644 --- a/apps/web/src/components/chat/TimelineRowParts.tsx +++ b/apps/web/src/components/chat/TimelineRowParts.tsx @@ -41,14 +41,22 @@ export function TimelineRowTimestamp({ ); } -export function ActivityShimmerOverlay({ children }: { children: ReactNode }) { +export function ActivityShimmerOverlay({ + children, + className, +}: { + children: ReactNode; + className?: string; +}) { return ( - {children} + + {children} + ); diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 3fee2134c3f58..7cd57ed18c0c1 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,3 +1,4 @@ +import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; import { @@ -102,7 +103,7 @@ const MEDIA_EDGE_CLASS_NAME = "relative after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit] after:ring-1 after:ring-inset after:ring-black/9 dark:after:ring-white/12"; const BUBBLE_CHIP_CLASS_NAME = - "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]"; + "[&_[data-slot=context-chip]]:[--context-chip-message-ink:var(--context-chip-message)]"; function UserFileCard({ file, @@ -597,6 +598,25 @@ function UserTimelineRow({ row }: { row: Extract { + const image = userImages.find((candidate) => candidate.id === id); + const record = resolvedContext.records + .map(asKnownContextRecord) + .find((candidate) => candidate?.kind === "image" && candidate.attachmentId === id); + if (!image?.previewUrl || record?.kind !== "image") + throw new Error("Snapshot is no longer available."); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: ctx.activeThreadEnvironmentId, messageId: row.message.id }, + records: [{ ...record, ...(image.source ? { source: image.source } : {}) }], + }); + if (!fragment) throw new Error("The snapshot is too large to copy."); + await copySnapshotToClipboard( + image.previewUrl, + formatComposerContextReference(record), + fragment, + ); + }; const onBodyCopyCapture = (event: React.ClipboardEvent) => { if (resolvedContext.records.length === 0 || !event.clipboardData) return; const selection = window.getSelection(); @@ -661,7 +681,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(userImages, image.id); + const preview = buildExpandedImagePreview(userImages, image.id, copySnapshot); if (preview) onImageExpand(preview); }} onOpenFile={onFileOpen} @@ -737,7 +757,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(regularImages, image.id); + const preview = buildExpandedImagePreview(regularImages, image.id, copySnapshot); if (!preview) return; ctx.onImageExpand(preview); }} @@ -772,7 +792,10 @@ function UserTimelineRow({ row }: { row: Extract )} {image.previewUrl && image.source?.kind === "snap-shot" ? ( - + copySnapshot(image.id)} + /> ) : null}
))} diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx index 39801a908b952..e345472b1f972 100644 --- a/apps/web/src/components/chat/UserMessageContextChips.tsx +++ b/apps/web/src/components/chat/UserMessageContextChips.tsx @@ -1,3 +1,5 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isSvgAttachment } from "@t3tools/shared/image"; import { useRenderedAppearance } from "../../hooks/useTheme"; @@ -68,11 +70,15 @@ function UserMessageMentionChip(props: { copyMarkdown: string; }) { const ctx = use(TimelineRowCtx); + const nativeDrag = useNativeFileDrag(ctx.activeThreadEnvironmentId, () => + resolvePathLinkTarget(props.record.path, ctx.workspaceRoot ?? ""), + ); return ( } aria-label={`Preview ${props.record.path}`} diff --git a/apps/web/src/components/chat/backgroundThread.ts b/apps/web/src/components/chat/backgroundThread.ts index b3dfee09a663c..e402bc5e62165 100644 --- a/apps/web/src/components/chat/backgroundThread.ts +++ b/apps/web/src/components/chat/backgroundThread.ts @@ -5,3 +5,6 @@ import { createContext } from "react"; * parent's panel; its global shortcuts and listeners stand down. */ export const BackgroundThreadContext = createContext(false); + +/** True only for a thread kept mounted out of sight under Settings or Usage. */ +export const HiddenThreadContext = createContext(false); diff --git a/apps/web/src/components/chat/copySnapshot.test.ts b/apps/web/src/components/chat/copySnapshot.test.ts new file mode 100644 index 0000000000000..9ac7080f7b0f7 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.test.ts @@ -0,0 +1,75 @@ +import { ComposerContextId, EnvironmentId } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + decodeComposerContextClipboardHtml, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { expect, it } from "vite-plus/test"; + +import { copySnapshot } from "./copySnapshot"; + +it.each([false, true])( + "preserves image bytes and snapshot metadata, custom format rejected: %s", + async (rejectCustom) => { + class Item { + constructor(readonly data: Record>) {} + } + let clipboard: Item | undefined; + const write = async ([item]: Item[]) => { + if (rejectCustom && item?.data[COMPOSER_CONTEXT_CLIPBOARD_MIME]) + throw new Error("Unsupported format"); + clipboard = item; + await Promise.all(Object.values(item!.data)); + }; + const originals = { + navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"), + ClipboardItem: Object.getOwnPropertyDescriptor(globalThis, "ClipboardItem"), + }; + using _globals = { + [Symbol.dispose]() { + for (const key of ["navigator", "ClipboardItem"] as const) { + const descriptor = originals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; + Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { clipboard: { write } }, + }); + Object.defineProperty(globalThis, "ClipboardItem", { configurable: true, value: Item }); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: EnvironmentId.make("snapshot-source") }, + records: [ + { + version: 1, + kind: "image", + contextId: ComposerContextId.make("image_snapshot"), + label: "Snapshot", + attachmentId: "snapshot", + name: "snapshot.png", + mimeType: "image/png", + sizeBytes: 3, + source: { + kind: "snap-shot", + capturedAt: "2026-01-01T00:00:00.000Z", + appName: "Finder", + windowTitle: "Downloads", + accessibleText: "Downloads", + }, + }, + ], + })!; + const image = "data:image/png;base64,AQID"; + await copySnapshot(image, "Snapshot", fragment); + const png = await clipboard!.data["image/png"]!; + expect(png.type).toBe("image/png"); + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual([1, 2, 3]); + expect( + decodeComposerContextClipboardHtml(await (await clipboard!.data["text/html"]!).text()), + ).toEqual(JSON.parse(fragment)); + expect(await (await clipboard!.data["text/plain"]!).text()).toBe("Snapshot"); + }, +); diff --git a/apps/web/src/components/chat/copySnapshot.ts b/apps/web/src/components/chat/copySnapshot.ts new file mode 100644 index 0000000000000..118121e753647 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.ts @@ -0,0 +1,33 @@ +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextClipboardHtml, +} from "@t3tools/shared/composerContextClipboard"; + +import { readMediaPng } from "../media/mediaContent"; + +export async function copySnapshot(src: string, text: string, fragment: string): Promise { + if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") { + throw new Error("Snapshot copying requires a secure browser connection."); + } + const formats = { + "image/png": readMediaPng(src), + "text/plain": new Blob([text], { type: "text/plain" }), + "text/html": new Blob([encodeComposerContextClipboardHtml(text, fragment)], { + type: "text/html", + }), + }; + // Start writing within the click gesture, before the image fetch or decode completes. + try { + await navigator.clipboard.write([ + new ClipboardItem({ + ...formats, + [COMPOSER_CONTEXT_CLIPBOARD_MIME]: new Blob([fragment], { + type: COMPOSER_CONTEXT_CLIPBOARD_MIME, + }), + }), + ]); + } catch { + // HTML carries the same snapshot metadata when custom clipboard formats are unsupported. + await navigator.clipboard.write([new ClipboardItem(formats)]); + } +} diff --git a/apps/web/src/components/chat/markdownFragments.ts b/apps/web/src/components/chat/markdownFragments.ts index 90a419039053e..9acacb8c65fe2 100644 --- a/apps/web/src/components/chat/markdownFragments.ts +++ b/apps/web/src/components/chat/markdownFragments.ts @@ -68,7 +68,7 @@ type HeadingHastNode = { children?: HeadingHastNode[]; }; -function githubHeadingSlug(text: string): string { +export function githubHeadingSlug(text: string): string { return text .trim() .toLowerCase() diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx index 2574f25fc0431..38ecff7666508 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx @@ -5,16 +5,25 @@ import { } from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; import ReactMarkdown from "react-markdown"; +import remarkMath from "remark-math"; +import type { PluggableList } from "unified"; import { describe, expect, it } from "vite-plus/test"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; +import { rehypeHeadingIds } from "./markdownFragments"; + +const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. -const html = (source: string) => +const renderMarkdown = (source: string, math = false) => renderToStaticMarkup( {source} , @@ -22,9 +31,27 @@ const html = (source: string) => .replace(/>\s+<") .trim(); +const html = (source: string) => renderMarkdown(source); + +const punctuatedHeadings = ["Step 1: Install", "Done:", "apps/web", "Fix (web)", "What's next?"]; + describe("splitMarkdownBlocks", () => { it.each([ "# Title\n\nFirst paragraph with `code` and **bold**.\n\nSecond [link](https://example.com).", + "## Step 1: Install\n\n## Step 1: Install\n\n[second](#step-1-install-1)", + "## /home/a/b.ts\n\n## home/a/b.ts", + "## see https://x.com/a\n\n## see httpsxcoma", + "## Done:\n\n## Done", + "## `Setup`\n\n## Setup", + "## a ` x ` b\n\n## a x b", + "# Setup\n\n# $$ Setup $$\n\n[second](#setup-1)", + "# Setup\n\n# Setup\n\n[Second setup](#setup-1)", + "\ufeff# Setup\n\n# Setup\n\n[second](#setup-1)", + "> Setup\n> ===\n\n> Setup\n> ===", + "# onetwo\n\none\ntwo\n===", + "# Setup\n\n# Setup\n\n[second](#setup-1)", + "# Setup\n\npara\n\n- a\n\n ```\n b\nx\n\nSetup\n===\n", + "Setup\n===\n\n> ## **Setup**\n\n- # [Setup](https://example.com)\n\n```sh\n# Setup\n```", "- one\n- two\n\n- loose three\n\n continued\n\nAfter the list.", "1. first\n\n2. second\n\nText\n\n3) restarted", "```ts\nconst a = 1;\n\n\nconst b = 2;\n```\n\nafter\n\n~~~\nx\n\n~~~~\n\ny\n~~~\n\nend", @@ -39,18 +66,29 @@ describe("splitMarkdownBlocks", () => { ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => { for (let end = 0; end <= text.length; end++) { const source = text.slice(0, end); - const blocks = splitMarkdownBlocks(source); - expect(blocks?.join("")).toBe(source); - expect(blocks!.map(html).join("")).toBe(html(source)); + const blocks = splitMarkdownBlocks(source) ?? [source]; + expect(blocks.join("")).toBe(source); + expect(blocks.map(html).join("")).toBe(html(source)); + expect(blocks.map((block) => renderMarkdown(block, true)).join("")).toBe( + renderMarkdown(source, true), + ); } }); + it.each(punctuatedHeadings)("keeps splitting headings with prose punctuation: %s", (heading) => { + expect(splitMarkdownBlocks(`## ${heading}\n\nNext paragraph.`)).toEqual([ + `## ${heading}\n\n`, + "Next paragraph.", + ]); + }); + it("splits only between closed blocks", () => { expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([ "a\n\n", "```\nb\n\nc\n```\n\n- d\n\n- e\n\n", "f", ]); + expect(splitMarkdownBlocks("a\n\n---\n\nb")).toEqual(["a\n\n", "---\n\n", "b"]); }); it.each([ diff --git a/apps/web/src/components/chat/markdownStreamBlocks.ts b/apps/web/src/components/chat/markdownStreamBlocks.ts index 107d5d0143c72..36decaa301838 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.ts +++ b/apps/web/src/components/chat/markdownStreamBlocks.ts @@ -1,3 +1,5 @@ +import { githubHeadingSlug } from "./markdownFragments"; + // Definitions, footnotes, raw HTML, container directives and display math can tie blocks together. const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m; // A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span. @@ -7,13 +9,22 @@ const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/; // Claude insight fences render as one callout, so they stay in one block until the closing rule. const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; +// An ATX heading, also inside a list item or blockquote; group 1 is its text. +const ATX_HEADING_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*#{1,6}(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/; +// Setext headings may span a paragraph and containers, so leave their parsing to the renderer. +const SETEXT_UNDERLINE_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*(?:=+|-+)[ \t]*$/; /** * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it - * would inside the whole text. Returns null when the text uses syntax that spans blocks. + * would inside the whole text. Returns null when the text uses syntax that spans blocks, such as + * headings with the same slug, whose ids are numbered across the whole text. */ export function splitMarkdownBlocks(text: string): string[] | null { - if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null; + // remark-parse strips a leading BOM before recognizing the first heading. + if (text.startsWith("\ufeff") || text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) + return null; const blocks: string[] = []; let blockStart = 0; let lineStart = 0; @@ -21,11 +32,35 @@ export function splitMarkdownBlocks(text: string): string[] | null { let fenceIndent = 0; let afterBlankLine = false; let insightIndent: string | null = null; + const headingKeys = new Set(); + const needsWholeHeading = (headingText: string | undefined) => { + if (headingText === undefined) return false; + // Inline syntax and path/directive colons need the renderer before their slug is known. + if (/[`*_~[\]<&\\!$]|:(?!\s|$)/.test(headingText)) return true; + const key = githubHeadingSlug(headingText); + if (!key) return false; + if (headingKeys.has(key)) return true; + headingKeys.add(key); + return false; + }; + const headingNeedsWholeDocument = (line: string, mayUnderline = true) => + (mayUnderline && SETEXT_UNDERLINE_PATTERN.test(line)) || + needsWholeHeading(ATX_HEADING_PATTERN.exec(line)?.[1]); + // Only a line right after paragraph text can underline it; elsewhere "---" is a thematic break. + let afterContentLine = false; for (const line of text.split("\n")) { const opener = FENCE_PATTERN.exec(line)?.[1]; + const mayUnderline = afterContentLine; + afterContentLine = false; if (fence !== null) { // A line left of an indented fence may end the list item holding it, which isn't tracked. - if (/\S/.test(line.slice(0, fenceIndent))) break; + if (/\S/.test(line.slice(0, fenceIndent))) { + const rest = text.slice(lineStart).split("\n"); + for (const restLine of rest) { + if (headingNeedsWholeDocument(restLine)) return null; + } + break; + } if ( opener && opener[0] === fence[0] && @@ -40,6 +75,8 @@ export function splitMarkdownBlocks(text: string): string[] | null { } else if (line.trim() === "") { afterBlankLine = true; } else { + if (headingNeedsWholeDocument(line, mayUnderline)) return null; + afterContentLine = opener === undefined; if ( afterBlankLine && insightIndent === null && diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index e2bf9676b8b6d..d48e965895ddd 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -48,6 +48,7 @@ function deferred() { it.each([ { kind: "file", edit: "delete" }, { kind: "image", edit: "delete" }, + { kind: "image", edit: "retain" }, { kind: "file", edit: "undo" }, { kind: "file", edit: "retain" }, { kind: "file", edit: "switch" }, @@ -124,7 +125,17 @@ it.each([ const attachment = ( kind === "file" ? { ...attachmentFields, kind: "file" as const } - : { ...attachmentFields, kind: "image" as const } + : { + ...attachmentFields, + kind: "image" as const, + source: { + kind: "snap-shot" as const, + appName: "Finder", + windowTitle: "Downloads", + capturedAt: "2026-01-01T00:00:00.000Z", + accessibleText: "Downloads", + }, + } ) satisfies ComposerContextRecord; const annotation = { version: 1, @@ -182,6 +193,10 @@ it.each([ const draft = store.getComposerDraft(target)!; expect(draft.prompt).toBe(promptRef.current); const attachments = kind === "file" ? draft.files : draft.images; + if (kind === "image" && edit === "retain") + expect(draft.images[0]?.source).toEqual( + attachment.kind === "image" ? attachment.source : undefined, + ); expect(attachments.map((file) => file.name)).toEqual( edit === "undo" || edit === "retain" || diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 0cc66d6a71d19..265278faec747 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -246,6 +246,7 @@ export function useComposerContextImport(input: { sizeBytes: file.size, previewUrl: URL.createObjectURL(file), file, + ...(record.source ? { source: record.source } : {}), }, ], { diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx index b4ddb847d0824..1a6e2b038832c 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx @@ -108,6 +108,7 @@ function setup() { enabled: true, }, connection: { phase: "connected", error: null, traceId: null }, + refusedRouteIds: [], serverConfig: null, }, ]), diff --git a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx index cc3640fc2a166..40c84cc69fde6 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx @@ -1,11 +1,15 @@ -import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; +import { + FILE_PREVIEW_SCROLL_SCRIPT, + injectHtmlRenderBootstrap, + readFilePreviewScroll, +} from "@t3tools/shared/htmlRender"; import { describe, expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; -import { HtmlRenderDocument } from "./BrowserDocumentFrame"; +import { BrowserDocumentFrame, HtmlRenderDocument } from "./BrowserDocumentFrame"; const sizeChanged = (height: number) => ({ jsonrpc: "2.0", @@ -219,3 +223,98 @@ it("keeps the first and last selected card rings inside the fitted renderer fram expect(bounds.scrollWidth).toBeLessThanOrEqual(bounds.viewportWidth); } }); + +describe("BrowserDocumentFrame", () => { + it("keeps a page on screen until its next revision has loaded", async () => { + using pages = (() => { + const urls = ["first", "second", "third"].map((name) => + URL.createObjectURL(new Blob([`

${name}

`], { type: "text/html" })), + ); + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) }; + })(); + const [first, second, third] = pages.urls as [string, string, string]; + const frame = (revision: string, src: string) => ( +
+ +
+ ); + await using screen = await render(frame("1", first)); + const srcs = () => Array.from(screen.container.querySelectorAll("iframe"), (f) => f.src); + const onScreen = () => { + const box = screen.container.getBoundingClientRect(); + const hit = document.elementFromPoint(box.left + box.width / 2, box.top + 10); + return hit instanceof HTMLIFrameElement ? hit.src : null; + }; + await vi.waitFor(() => expect(onScreen()).toBe(first)); + + // The incoming frame cannot have loaded when it is inserted, so the current page must cover it. + const atInsertion = new Promise((resolve) => { + const observer = new MutationObserver(() => { + if (!srcs().includes(second)) return; + observer.disconnect(); + resolve(onScreen()); + }); + observer.observe(screen.container, { childList: true, subtree: true }); + }); + await screen.rerender(frame("2", second)); + expect(await atInsertion).toBe(first); + await vi.waitFor(() => expect(srcs()).toEqual([second])); + expect(onScreen()).toBe(second); + + await screen.rerender(frame("3", third)); + await screen.rerender(frame("2", second)); + expect(srcs(), "returning to the shown revision kept the pending frame").toEqual([second]); + await screen.rerender(frame("3", third)); + await vi.waitFor(() => expect(onScreen()).toBe(third)); + }); + + it("opens the next revision where the reader left the page", async () => { + // The first page scrolls itself, as a reader would; the second is served without scrolling. + const tall = '
report
'; + using pages = (() => { + const urls = [ + `${tall}`, + tall, + ].map((body) => + URL.createObjectURL(new Blob([body + FILE_PREVIEW_SCROLL_SCRIPT], { type: "text/html" })), + ); + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) }; + })(); + const [first, second] = pages.urls as [string, string]; + const reports: Array<{ source: MessageEventSource | null; y: number }> = []; + const onMessage = (event: MessageEvent) => { + const scroll = readFilePreviewScroll(event.data); + if (scroll !== undefined) reports.push({ source: event.source, y: scroll.y }); + }; + window.addEventListener("message", onMessage); + using _listener = { [Symbol.dispose]: () => window.removeEventListener("message", onMessage) }; + const frame = (revision: string, src: string) => ( +
+ +
+ ); + await using screen = await render(frame("1", first)); + const iframes = () => Array.from(screen.container.querySelectorAll("iframe")); + await vi.waitFor(() => expect(reports.map((report) => report.y)).toContain(1200)); + + await screen.rerender(frame("2", second)); + await vi.waitFor(() => expect(iframes().map((element) => element.src)).toEqual([second])); + const shown = iframes()[0]!.contentWindow; + expect( + reports.filter((report) => report.source === shown).map((report) => report.y), + "the next revision was uncovered before it took the reader's position", + ).toContain(1200); + }); +}); diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index 4dba7607f81c0..bfa699cf252b4 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -7,6 +7,10 @@ import { THREAD_JUMP_KEYBINDING_COMMANDS, } from "@t3tools/contracts"; import { + type FilePreviewScroll, + filePreviewRestoreScrollMessage, + isFilePreviewScrollRestored, + readFilePreviewScroll, type HtmlRenderShortcut, htmlRenderShortcutsMessage, htmlRenderThemeFragment, @@ -157,21 +161,119 @@ export function BrowserDocumentFrame(props: { className="min-h-0 flex-1" /> ) : ( - + ); } -// URL renewals must not discard form input or scroll; a new key mounts a fresh document. -function FileDocument(props: { readonly src: string; readonly title: string }) { - const [src] = useState(props.src); +interface FileDocumentRevision { + readonly key: string; + readonly src: string; +} + +interface FileDocumentFrames { + readonly shown: FileDocumentRevision; + readonly next: FileDocumentRevision | null; +} + +// Identity, not key, so a late load from a replaced frame cannot uncover a newer unloaded one. +const showRevision = + (next: FileDocumentRevision) => + (current: FileDocumentFrames): FileDocumentFrames => + current.next === next ? { shown: next, next: null } : current; + +// A page whose load never fires (a stalled subresource) must not pin the previous revision. +const FILE_DOCUMENT_SWAP_TIMEOUT_MS = 5_000; + +// URL renewals keep a revision's first URL, so they do not discard form input or scroll. A new +// revision loads beneath the page on screen, takes its scroll position and replaces it once +// painted, so no blank frame shows and the reader keeps their place. +function FileDocument(props: { + readonly documentKey: string; + readonly src: string; + readonly title: string; +}) { + const [frames, setFrames] = useState(() => ({ + shown: { key: props.documentKey, src: props.src }, + next: null, + })); + if ((frames.next ?? frames.shown).key !== props.documentKey) { + setFrames({ + shown: frames.shown, + next: + frames.shown.key === props.documentKey ? null : { key: props.documentKey, src: props.src }, + }); + } + const { next } = frames; + const shownFrame = useRef(null); + const nextFrame = useRef(null); + // The page reports its scroll position (see FILE_PREVIEW_SCROLL_SCRIPT); the next revision + // scrolls there before it is uncovered. + const scroll = useRef(null); + // Two frames let the browser paint the incoming page before it is uncovered. + const reveal = (revision: FileDocumentRevision) => + requestAnimationFrame(() => requestAnimationFrame(() => setFrames(showRevision(revision)))); + const onFrameMessage = useEffectEvent((event: MessageEvent) => { + const position = readFilePreviewScroll(event.data); + if (position !== undefined) { + if (event.source === shownFrame.current?.contentWindow) scroll.current = position; + } else if ( + next !== null && + event.source === nextFrame.current?.contentWindow && + isFilePreviewScrollRestored(event.data) + ) { + reveal(next); + } + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for the frames' scroll reports + useEffect(() => { + const onMessage = (event: MessageEvent) => onFrameMessage(event); + window.addEventListener("message", onMessage); + return () => window.removeEventListener("message", onMessage); + }, []); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- swaps in a revision whose load event never arrives + useEffect(() => { + if (next === null) return; + const timer = setTimeout(() => setFrames(showRevision(next)), FILE_DOCUMENT_SWAP_TIMEOUT_MS); + return () => clearTimeout(timer); + }, [next]); + // The shown frame stays last so it paints on top and is never moved, which would reload it. return ( -