Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
269e5a8f89 | ||
|
|
b11bb00094 | ||
|
|
ac3dc22a5e | ||
|
|
63b64f489c | ||
|
|
d17635201c | ||
|
|
08bebb2472 | ||
|
|
0ac8024a02 | ||
|
|
c86ed345a4 | ||
|
|
cf23cc1dd1 | ||
|
|
7177ae1264 | ||
|
|
20a1f53ae2 | ||
|
|
a0cdebce7e | ||
|
|
c14c9088e3 | ||
|
|
798c458954 | ||
|
|
ea57e97d58 | ||
|
|
92d2b60789 | ||
|
|
7778a1cea7 | ||
|
|
dad0889766 | ||
|
|
b9cc8d6ef1 | ||
|
|
0e0040832c | ||
|
|
cd8b9fc8b3 | ||
|
|
fa6073e2e1 | ||
|
|
4eb1b57933 | ||
|
|
4414f922fe | ||
|
|
6e42231cb1 | ||
|
|
bdf5aed665 | ||
|
|
0b62e2eb11 | ||
|
|
f9727d0853 | ||
|
|
d8e0ba3ea0 | ||
|
|
32e7844837 | ||
|
|
482d56233d | ||
|
|
6009720844 | ||
|
|
e26e55f389 | ||
|
|
4ac094fef6 | ||
|
|
a7e43b2281 | ||
|
|
cabc93bad3 | ||
|
|
5cda815626 | ||
|
|
32d17d3db5 | ||
|
|
6d35a87c5d | ||
|
|
dac514e6b6 | ||
|
|
96b4071cdb | ||
|
|
4ca3ff5191 | ||
|
|
6d33dd25ca | ||
|
|
c2132ee7dd | ||
|
|
7bf0a2ce15 | ||
|
|
2f774f8e80 | ||
|
|
73d8597e01 | ||
|
|
30fa9443d6 | ||
|
|
cc92acf77b | ||
|
|
57aa76ac14 | ||
|
|
3b864044c6 | ||
|
|
b452303639 | ||
|
|
706c819cf3 | ||
|
|
1467717c12 | ||
|
|
1603df97f5 | ||
|
|
2c33e9f28c | ||
|
|
89c752c2b8 | ||
|
|
967193f737 | ||
|
|
e15026a12a | ||
|
|
5df6529caa | ||
|
|
3a12575b05 | ||
|
|
272e355ee9 | ||
|
|
e201350381 | ||
|
|
361df65ffb | ||
|
|
fc23be8184 | ||
|
|
c529c610e3 | ||
|
|
54a555c71b | ||
|
|
323ad3614f | ||
|
|
353acd9a27 | ||
|
|
d6e3326426 | ||
|
|
fb9764b8cb | ||
|
|
6a295b93ea | ||
|
|
9f19b4f06c | ||
|
|
84e1a91cab | ||
|
|
170f3201e7 | ||
|
|
9711e6c879 | ||
|
|
42450d51f1 | ||
|
|
5ba299d715 | ||
|
|
7fcc993eae | ||
|
|
6821946ccc | ||
|
|
12259adb5d | ||
|
|
c7f7e8c38d | ||
|
|
1161529645 | ||
|
|
9d38de8628 | ||
|
|
9198a64c3d | ||
|
|
d62855cd7d | ||
|
|
c7539b92f5 | ||
|
|
b7ff82862e | ||
|
|
dbb184bb8a | ||
|
|
acc41f4742 | ||
|
|
6b6a9c4081 | ||
|
|
ae922761c3 | ||
|
|
0425b5510d | ||
|
|
0de927dfc6 | ||
|
|
e39cfb89f8 | ||
|
|
b14e89f11a | ||
|
|
96073b6bac | ||
|
|
bf75071f40 | ||
|
|
a1d2f75253 | ||
|
|
6d1d513032 | ||
|
|
ff03673ff8 | ||
|
|
1b440329f4 | ||
|
|
85f570a413 | ||
|
|
26f3c80250 | ||
|
|
ca835c2508 | ||
|
|
7979036cd1 | ||
|
|
2ea043e73b | ||
|
|
9316b57f9f | ||
|
|
d9c39e4d30 | ||
|
|
f3957fd473 | ||
|
|
59e9c647b7 | ||
|
|
5e5ad3c7a7 | ||
|
|
2769c2e42d | ||
|
|
334265e87b | ||
|
|
969e8ea4fa | ||
|
|
7eefb2eb1d | ||
|
|
3bc8508de8 | ||
|
|
355eb2dade | ||
|
|
d138a0bc31 | ||
|
|
11fa703852 | ||
|
|
d53e02b981 | ||
|
|
6e6bcd8450 | ||
|
|
6164a937ae | ||
|
|
c01b90a8fd | ||
|
|
047eb4e29a | ||
|
|
9c916d6caa | ||
|
|
35bc0902ae | ||
|
|
fa9bcbc053 | ||
|
|
a15194f649 | ||
|
|
2b623b54ff | ||
|
|
308dd659da |
No files matched your search
@@ -0,0 +1,72 @@
|
||||
---
|
||||
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Cursor Cloud specific instructions
|
||||
|
||||
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
|
||||
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
|
||||
|
||||
## Toolchain
|
||||
|
||||
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
|
||||
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
|
||||
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
|
||||
|
||||
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
|
||||
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
|
||||
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
|
||||
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
|
||||
`vp check --fix` before committing.
|
||||
|
||||
## Running the web app
|
||||
|
||||
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
|
||||
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
|
||||
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
|
||||
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
|
||||
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
|
||||
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
|
||||
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
|
||||
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
|
||||
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
|
||||
Without one installed the UI loads but no agent can run. Claude Code
|
||||
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
|
||||
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
|
||||
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
|
||||
server to pick up a newly installed provider CLI immediately.
|
||||
|
||||
## Android native builds (apps/mobile)
|
||||
|
||||
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
|
||||
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
|
||||
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
|
||||
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
|
||||
Gradle auto-downloads any additional pinned SDK packages on demand.
|
||||
|
||||
- Generate the native project first: from `apps/mobile`,
|
||||
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
|
||||
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
|
||||
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
|
||||
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
|
||||
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
|
||||
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
|
||||
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
|
||||
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
|
||||
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
|
||||
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
|
||||
Android Studio bundles is what is installed.
|
||||
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
|
||||
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
|
||||
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
|
||||
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
|
||||
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
|
||||
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
|
||||
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
|
||||
scope for environment setup.
|
||||
|
||||
## Known flaky tests (unrelated to setup)
|
||||
|
||||
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
|
||||
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
|
||||
@@ -57,7 +57,10 @@ jobs:
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
packager: pnpm
|
||||
# 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: Pull preview environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
name: Mobile EAS Production
|
||||
|
||||
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
|
||||
# Under the fingerprint runtime-version policy the fingerprint must be computed
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "build (+ auto-submit to TestFlight) or update (OTA)"
|
||||
required: true
|
||||
type: choice
|
||||
default: build
|
||||
options:
|
||||
- build
|
||||
- update
|
||||
platform:
|
||||
description: "Target platform"
|
||||
required: true
|
||||
type: choice
|
||||
default: ios
|
||||
options:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.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: Pull production environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
@@ -0,0 +1,246 @@
|
||||
# Plan: Thread Lineage And Lazy Context Transfer
|
||||
|
||||
## Summary
|
||||
|
||||
Implement the shared backend foundation for forking, provider handoff, merge-back, and future subagents without forcing provider selection at fork time. The first slice should create cheap app-level fork lineage and defer expensive context materialization until a run starts and the target provider is known.
|
||||
|
||||
Architecture reference: `docs/orchestration-v2/thread-lineage-and-context-transfer.md`.
|
||||
|
||||
## Goals
|
||||
|
||||
- Support user-created fork threads for exploration.
|
||||
- Keep fork creation provider-neutral and cheap.
|
||||
- Reuse the same source-point/context-transfer model for provider switching, merge-back, and future subagents.
|
||||
- Prefer native same-provider fork at first dispatch when available.
|
||||
- Fall back to portable context only when native transfer is unavailable or target provider differs.
|
||||
- Keep all behavior replayable through V2 events/projections.
|
||||
|
||||
## Non-Goals For First Slice
|
||||
|
||||
- Full portable context generation quality.
|
||||
- Cross-provider adapter implementation beyond the data/runtime hook.
|
||||
- Merge-back UI.
|
||||
- Native or custom subagent orchestration.
|
||||
- Forking from actively streaming provider state.
|
||||
- Backward compatibility with old dev databases.
|
||||
|
||||
## Core Data Model
|
||||
|
||||
Add schema/contracts for:
|
||||
|
||||
```ts
|
||||
type ContextTransferType =
|
||||
| "fork"
|
||||
| "provider_handoff"
|
||||
| "merge_back"
|
||||
| "subagent_spawn"
|
||||
| "subagent_result";
|
||||
|
||||
type ContextSourcePoint = {
|
||||
threadId: ThreadId;
|
||||
runId?: RunId;
|
||||
checkpointId?: CheckpointId;
|
||||
turnItemId?: TurnItemId;
|
||||
providerThreadRef?: NativeThreadRef;
|
||||
providerTurnRef?: NativeTurnRef;
|
||||
};
|
||||
|
||||
type ContextTransferStatus =
|
||||
| "pending"
|
||||
| "resolved_native"
|
||||
| "resolved_portable"
|
||||
| "failed"
|
||||
| "consumed"
|
||||
| "superseded";
|
||||
```
|
||||
|
||||
Persist:
|
||||
|
||||
- `orchestration_v2_projection_context_transfers`
|
||||
- optional later portable handoff payload columns/table if the existing context handoff projection is not enough
|
||||
|
||||
For the first slice, `ContextTransfer` is required. Materialized `ContextHandoff` payloads can be deferred until portable context is implemented.
|
||||
|
||||
## Events
|
||||
|
||||
Add V2 events:
|
||||
|
||||
- `context-transfer.created`
|
||||
- `context-transfer.updated`
|
||||
- possibly `context-handoff.created` later
|
||||
|
||||
Do not emit provider-native fork details as app identity. Native fork refs belong in the transfer resolution payload and provider thread refs.
|
||||
|
||||
## Commands
|
||||
|
||||
Add:
|
||||
|
||||
```ts
|
||||
type ThreadForkCommand = {
|
||||
type: "thread.fork";
|
||||
commandId: CommandId;
|
||||
sourceThreadId: ThreadId;
|
||||
targetThreadId: ThreadId;
|
||||
sourcePoint:
|
||||
| { type: "latest_stable" }
|
||||
| { type: "run"; runId: RunId }
|
||||
| { type: "checkpoint"; checkpointId: CheckpointId };
|
||||
title?: string;
|
||||
createdAt: string;
|
||||
};
|
||||
```
|
||||
|
||||
First-slice policy:
|
||||
|
||||
- `latest_stable` resolves to latest completed run checkpoint.
|
||||
- explicit completed run/checkpoint is accepted.
|
||||
- active run source is rejected or resolved to latest stable checkpoint; choose one policy and test it.
|
||||
- target thread starts idle.
|
||||
- no provider session/thread is created by `thread.fork`.
|
||||
|
||||
## Runtime Hook
|
||||
|
||||
Add a provider-neutral start-context resolver used by run startup:
|
||||
|
||||
```ts
|
||||
resolveStartContext({
|
||||
threadId,
|
||||
runId,
|
||||
provider,
|
||||
modelSelection,
|
||||
userMessage,
|
||||
}): Effect<StartContextResolution, StartContextResolutionError>
|
||||
```
|
||||
|
||||
Resolution order:
|
||||
|
||||
1. No pending transfer targeting the thread/run: normal run start.
|
||||
2. Pending fork transfer and same provider with native fork support: resolve native fork.
|
||||
3. Pending transfer requiring portable context: return explicit unsupported/stub result in first slice, or build minimal portable context if cheap.
|
||||
4. Failed resolution: fail command before provider side effects.
|
||||
|
||||
The resolver should be called before provider thread creation/startTurn so the adapter can decide whether to create, resume, or native-fork provider state.
|
||||
|
||||
## Codex Native Fork Path
|
||||
|
||||
Investigate the app-server native fork API in `effect-codex-app-server` and Codex docs/probes.
|
||||
|
||||
Implementation target:
|
||||
|
||||
- use native fork only when source provider is Codex and source native refs are strong;
|
||||
- create or bind a new `ProviderThread` for the forked native thread;
|
||||
- when the source point is an earlier completed Codex provider turn, fork the latest native thread first and then rollback the forked native thread by later terminal provider turns;
|
||||
- mark `ContextTransfer.status = resolved_native` and then `consumed` when the first run starts;
|
||||
- preserve source app thread lineage separately from native thread refs.
|
||||
|
||||
If native API details are not clean, land the data model and resolver first with native fork marked unsupported, then add Codex native fork in a follow-up.
|
||||
|
||||
## Portable Context Fallback
|
||||
|
||||
The first slice should define the fallback boundary even if it does not fully implement high-quality summarization.
|
||||
|
||||
Minimum viable fallback:
|
||||
|
||||
- detect cross-provider fork/handoff need;
|
||||
- create failed/unsupported transfer resolution with a clear command error, or
|
||||
- generate a deterministic minimal context handoff from app projection if we want a usable MVP.
|
||||
|
||||
Do not silently concatenate hidden summaries into the user message without a `ContextTransfer`/`ContextHandoff` record.
|
||||
|
||||
## Merge-Back Preparation
|
||||
|
||||
Do not implement merge-back in the first slice, but keep model support:
|
||||
|
||||
- `ContextTransfer.type = "merge_back"`
|
||||
- `basePoint` on transfer
|
||||
- source thread may differ from target thread
|
||||
|
||||
The later merge-back command should create a transfer from fork latest stable point back to source thread and consume it with the next user message.
|
||||
|
||||
## Subagent Preparation
|
||||
|
||||
Do not implement subagents in this slice, but keep model support:
|
||||
|
||||
- `createdBy: "agent"`
|
||||
- `type: "subagent_spawn"` and `"subagent_result"`
|
||||
- source/target thread relationship fields
|
||||
|
||||
Native subagent ingestion can later map provider-native child refs into the same graph. Cross-provider app-owned subagents can later create child app threads using the same transfer primitive.
|
||||
|
||||
## Projection And Debugger
|
||||
|
||||
Backend projection first:
|
||||
|
||||
- expose thread lineage in thread projection;
|
||||
- expose context transfers in debug projection;
|
||||
- expose transfer status and resolution strategy.
|
||||
|
||||
Debugger after backend:
|
||||
|
||||
- fork button/control from stable source point;
|
||||
- show thread lineage/source point;
|
||||
- show pending/resolved/failed transfers;
|
||||
- show native vs portable resolution.
|
||||
|
||||
Do not build debugger controls before the backend projection is authoritative.
|
||||
|
||||
## Tests
|
||||
|
||||
Use `bun run test`, not `bun test`.
|
||||
|
||||
Required backend tests:
|
||||
|
||||
- `thread.fork` from latest completed checkpoint creates target thread and pending transfer.
|
||||
- fork command is idempotent through command receipts.
|
||||
- fork does not create provider session/thread eagerly.
|
||||
- first run on same-provider fork invokes native resolution path when capability exists.
|
||||
- unsupported native fork falls back or fails according to explicit policy.
|
||||
- active-run fork policy is deterministic.
|
||||
- replay/recovery preserves target thread lineage and pending transfer.
|
||||
|
||||
Add test provider layers only at external service boundaries. Do not mock core orchestration policy.
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Add contract schemas and ids for context transfers/source points.
|
||||
2. Add migration/projection table for context transfers.
|
||||
3. Add event store/projection handling for transfer events.
|
||||
4. Add `thread.fork` command policy and orchestrator path.
|
||||
5. Add tests for cheap idle fork creation and recovery.
|
||||
6. Add start-context resolver interface.
|
||||
7. Wire resolver into run startup with no-op behavior.
|
||||
8. Add Codex native fork capability investigation and adapter path.
|
||||
9. Add tests for same-provider native fork resolution.
|
||||
10. Add debug projection surface after backend behavior is stable.
|
||||
|
||||
## Validation
|
||||
|
||||
Before considering the slice complete:
|
||||
|
||||
- `bun fmt`
|
||||
- `bun lint`
|
||||
- `bun typecheck`
|
||||
- targeted backend tests with `bun run test`
|
||||
|
||||
If backend code changes are included, tests must cover the new orchestration behavior before the task is considered done.
|
||||
|
||||
## Implementation Status
|
||||
|
||||
Implemented in this slice:
|
||||
|
||||
- context transfer ids, schemas, JSON codecs, events, and projection storage
|
||||
- app-thread lineage on thread creation and fork creation
|
||||
- `thread.fork` command using `latest_stable`, explicit run, or explicit checkpoint source points
|
||||
- cheap idle fork creation with no eager provider session/thread/run
|
||||
- Codex same-provider native `thread/fork` resolution on first target dispatch
|
||||
- Codex native fork-from-earlier-run resolution with `thread/fork` plus fork-local `thread/rollback`
|
||||
- transfer status progression through `pending`, `resolved_native`, and `consumed`
|
||||
- command receipt idempotency for duplicate fork commands
|
||||
- replay-backed integration coverage for lazy fork creation and native Codex fork consumption
|
||||
|
||||
Explicitly deferred:
|
||||
|
||||
- portable `ContextHandoff` materialization for cross-provider forks/provider handoff
|
||||
- merge-back command/runtime
|
||||
- subagent spawn/result runtime
|
||||
- debugger controls for creating/inspecting transfers
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,958 @@
|
||||
{
|
||||
"sessionSummaries": [
|
||||
{
|
||||
"sessionKey": "GLOBAL",
|
||||
"summary": "Global cross-thread audit of the v2 orchestrator DB (43,378 events across 63 streams, 6,286 turn items, 60 threads, 206 runs). Core invariants are healthy: event streams have zero version gaps/duplicates and no occurred_at regressions >5s; turn-item ordinals have zero collisions and are 100% consistent with orchestration_v2_turn_item_positions; no nativeItemRef duplicates; outbox (463 rows) and command receipts (580) are fully succeeded/accepted; all 12 failed runs surfaced exactly one user-visible error item; no items/runs stuck beyond the one currently-live run (started 17:03Z, audit ran 17:07Z). Findings are edge-case lineage danglers, generic error strings that discard the underlying cause, sessions left 'ready' after detach, and 13 old local_bash tasks projected as empty-prompt subagents.",
|
||||
"stats": "43,378 events / 63 streams (0 version gaps, 0 dupes, 0 time regressions >5s); 6,286 turn items (6,042 completed, 243 failed, 2 interrupted, 1 running=live); 206 runs (188 completed, 12 failed, 4 cancelled, 1 interrupted, 1 running=live); 212 provider_turns; 19 provider_sessions (3 ready, 16 stopped); 40 subagents (38 completed, 2 failed); outbox 463 rows all 'succeeded'; receipts 580 all 'accepted'; 12 error items total. Loss sample: 258 native tool_use ids in latest 71e29ba5 log \u2192 all accounted for (254 direct items, 3 Agent spawns as subagent items, 1 in-flight run)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "a5a643b2-codex-heya",
|
||||
"summary": "Small 4-run codex smoke session (\"heya\") on 2026-06-28 04:52-05:22 UTC, plus one delegated Claude task child thread. Core pipeline is healthy: all 19 main-thread items + 3 child items are projected with verbatim text, ordinals match turn_item_positions exactly, lineage (run/node/provider_turn refs, subagent -> child thread -> context-transfer -> handoff) fully resolves, and all runs/turns/nodes/items are terminal. Two real problems: the codex-native collab subagent spawned in run 3 left zero trace in ingested events (its wait tool call, web search, and final \"Hello.\" message are lost), and the run-4 delegated Claude task that failed with a 401 auth error is recorded as status \"completed\" everywhere because the adapter ignores is_error on subtype \"success\" results.",
|
||||
"stats": "Main thread: 138 events, 19 projected items (19 distinct item ids in turn-item.updated events), 4 runs / 4 attempts / 4 provider turns, all completed. Child delegated-task thread: 27 events, 3 items, 1 run completed. Native log: 798 lines, 4 turn/start requests but 5 native turns (extra = codex-native subagent thread 019f0c93-d260), 22 item/completed across 2 native threads, 5 reasoning items (all empty summaries), 1 native error (401 auth, is_error:true result)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "a61e9269-codex",
|
||||
"summary": "Short two-turn Codex session (\"hey\" then \"spawn a subagent and say hello\") that spawned one provider-native subagent thread. Pipeline health is very good: every user-visible native item (2 user messages, 2 assistant messages, webSearch, subAgentActivity, child assistant message) is ingested and projected with exact untruncated text; lineage is fully consistent (subagent item childThreadId -> child thread, forkedFrom points back to parent provider-thread/turn, provider_turns map to run_attempts); all runs/turns/nodes/items terminal completed matching the native turn/completed events; ordinals match orchestration_v2_turn_item_positions with no collisions or duplicates and projection order matches native emission order. Only gaps: an (empty) reasoning item and token-usage/rate-limit notifications are dropped by the adapter, which has no handlers for them.",
|
||||
"stats": "Native (decoded, deduped): main thread 2 userMessage, 2 agentMessage, 1 subAgentActivity, 1 webSearch, 1 empty reasoning; child thread 1 agentMessage; 3 native turns all turn/completed; 0 native errors, 2 dev-feature warnings. Ingested: 74 events on main stream (versions 0-73, monotonic), 12 on child stream. Projected: 9 turn_items main (incl 2 synthetic checkpoints + workspace-preparation) + 1 child; 2 runs completed, 2 attempts completed, 3 provider_turns completed, 8 nodes completed; positions table matches item ordinals exactly, no duplicates."
|
||||
},
|
||||
{
|
||||
"sessionKey": "20296b49-grok-tasks",
|
||||
"summary": "Short grok session (2026-06-29 21:46-21:48): user said \"yoo\", then \"spawn some subagents\"; grok ran 3 parallel Task subagents (git state, architecture docs, mobile connection changes) as child threads and summarized. Pipeline health is good: all runs/attempts/provider-turns completed, provider session stopped, lineage intact, no ordinal collisions, no duplicates, no truncation (subagent item result lengths 3721/6274/2647 exactly match child assistant_message lengths). The children's 1319-2711 events vs 2 projected items is EXPECTED: each child has exactly 2 distinct item ids (prompt + result) and the event volume is per-token streaming re-upserts of the result item, not lost items.",
|
||||
"stats": "Main thread: 300 events, 14 turn_items, 2 runs (both completed), 2 run_attempts, 2 provider_turns (completed), 9 subagent.updated events -> 3 subagent rows (completed). Children: 3 threads, 5717 events (1319/2711/1687), 2 items each (6 total, all completed), 6 position rows. Native log: 3702 lines (3694 protocol \u2014 payloads redacted to byteLength/itemCount, 8 request), 2 session/prompt \"failed\" (errorTag Interrupt), no other errors. Integrity: 0 bad run/node/turn/parent refs, 0 ordinal collisions, 0 nativeItemRef dupes, 0 timestamp regressions."
|
||||
},
|
||||
{
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"summary": "Short cursor (glm-5.2) session \"Hello therw!\" with 2 user turns and zero assistant output. The 7-line native log is genuine: the backend child process fatally crashed (Node error originating in @cursor/sdk/dist/esm/index.js) ~0.3s after run 1's run.started, killing the provider mid-turn; a startup reconcile then cancelled run 1. Run 2 (\"what did you just say\") resumed the agent but agent.send rejected 4ms after run.start and was projected as a failed run with only a generic error string; the process crashed again with the same @cursor/sdk fatal error 29s later. Projection internals (ordinals, positions, statuses, lineage forward-links) are consistent and all state is terminal \u2014 the problems are crash handling and error fidelity, not ingestion mechanics.",
|
||||
"stats": "47 events on stream 721fc23c-... (seq 6271-6340, versions 0-46); 7 native log lines (all protocol/decoded, 0 assistant/tool output); 4 turn items (2 user_message, 1 command_execution \"Workspace ready\", 1 error); 2 runs (ordinal 1 cancelled, ordinal 2 failed); 2 messages (both user); 1 provider_turn (cancelled); 0 subagents/handoffs/transfers; 2 backend-child process crashes; 2 startup reconciles."
|
||||
},
|
||||
{
|
||||
"sessionKey": "48663fb7-cursor",
|
||||
"summary": "Thread 48663fb7 is a single \"hello\" message sent to the cursor provider (glm-5.2) at 2026-06-29T21:49:07Z. The provider session opened and acked run.started at 21:49:09.097Z, then the server restarted; a startup runtime-reconcile at 21:49:10.775Z cancelled the run/attempt/provider-turn, idled the provider thread, and stopped the session. Pipeline health is good: no native output was lost (the provider emitted nothing after run.started), lineage and ordinals are consistent, and nothing is stuck in a non-terminal state. The only gap is that the user got no assistant response and no explanation of why the run was cancelled.",
|
||||
"stats": "Native log: 4 decoded protocol lines (agent.open/agent.opened/run.start/run.started), 0 provider output items, 0 errors. Events: 28 (stream_version 0-27, seq 6318-6346 excl. 6340). Projections: 1 run (cancelled), 1 attempt (cancelled), 1 provider_turn (cancelled), 1 node (cancelled), 2 turn_items (both completed), 1 message, 0 subagents, 0 child threads. Provider session: stopped; provider thread: idle."
|
||||
},
|
||||
{
|
||||
"sessionKey": "3029dc85-opencode",
|
||||
"summary": "Opencode chat session \"Hey!\" (2026-06-29 22:02-22:16, idle-reaped 22:46): 7 user turns spawning 5 native opencode subagent sessions, 2 cross-provider delegated claudeAgent tasks (results handed back via context-transfer/handoff), and 3 top-level threads (codex/grok/claude). Pipeline health is very good: all 9 runs/7 attempts/12 provider turns completed, every distinct item id in events has exactly one projection, ordinals match event arrival order with zero collisions or duplicates, lineage (run/node/provider-turn/subagent->child-thread) fully resolves, and the provider session was cleanly stopped after the 30-min idle window. Main issues found are debuggability gaps rather than data loss: the one failed tool call projected no error message (file_search items structurally cannot carry one), file_search outputs are never projected, a placeholder \"pending\" provider_thread row lingers, and the native log itself is payload-redacted so content-level verification is impossible.",
|
||||
"stats": "Native log: 17,198 lines (15,542 part deltas, 723 part updates, 204 message updates, 7 promptAsync, 5 session.created, 12 session.idle; 0 error lines). Events: main 3,335 (1,047 turn-item.updated over 50 distinct items), opencode children 1051/1107/559/241/209, delegated-task children 94/34. Projected items: main 50, opencode children 185, delegated children 23 \u2014 every distinct event item id has exactly one projection (50/90/41/39/8/7 match 1:1). Runs: 7 main + 2 delegated, all completed; 7 attempts completed; 12 provider_turns completed; sessions stopped. 1 failed item (file_search), 0 stuck items, 0 ordinal collisions, 0 dangling run/node/turn/thread refs, 0 nativeItemRef dupes, positions table fully consistent."
|
||||
},
|
||||
{
|
||||
"sessionKey": "9f8d616d-opencode",
|
||||
"summary": "Single-turn opencode session ('hey' -> greeting reply) on 2026-06-29: 1 run, 1 provider turn, ~5s of activity, then 30min of heartbeats until the idle reaper stopped the session. The 100-events/5-items ratio is benign: 25 of the 33 turn-item.updated events are streaming updates of one reasoning part. No data loss, no duplicates, no ordering violations, no errors in the native log, and all runs/turns/items are terminal. Only minor findings: the pending-vs-resolved provider-thread dual-row pattern leaves run/attempt/turn pointing at a different provider_thread_id than the items, and the resolved provider-thread row lingered 'active' for ~20h after session stop before being marked idle.",
|
||||
"stats": "Native log: 273 lines (180 heartbeats, 32 file.watcher, 31 part deltas, 7 part updates, 6 message updates, 1 session.idle, 0 errors). Ingested: 100 events (stream_version 0-99 contiguous, 100 distinct event_ids), incl. 33 turn-item.updated over exactly 5 distinct items. Projected: 5 turn_items (ordinals 1000001-1000005, positions table matches 1:1), 2 messages, 1 run + 1 attempt + 1 provider_turn (all completed), 3 nodes completed, 2 checkpoints, 0 subagents/children, provider_session stopped."
|
||||
},
|
||||
{
|
||||
"sessionKey": "1156181e-delegated-task",
|
||||
"summary": "MCP delegated task \"hello-opus-48\" sent one user prompt (\"Say hello briefly and stop.\") to claudeAgent (claude-opus-4-8). The API call never succeeded: the SDK logged two api_retry events with error_status 401 (authentication_failed) and then emitted a synthetic assistant message \"Failed to authenticate. API Error: 401 Invalid authentication credentials\" plus a result with subtype \"success\" but is_error:true / api_error_status:401. Ingestion and projection are structurally clean (all 3 items projected, ordinals consistent, lineage valid, nothing stuck), but the run/attempt/provider-turn were all recorded as \"completed\" with no failure info, so the delegated task looks successful despite executing zero tokens.",
|
||||
"stats": "Native log: 10 decoded lines (1 query.open, 1 prompt.offer, 5 system incl. 2x api_retry 401, 1 synthetic assistant msg, 1 result is_error:true). Events: 30 (stream_version 0-29, sequences 116-168). Projections: 1 run, 1 attempt, 1 provider_turn, 2 messages, 3 turn_items (user_message, assistant_message, checkpoint), 0 child threads/subagents. Errors seen: 401 authentication_failed x3."
|
||||
},
|
||||
{
|
||||
"sessionKey": "6d618dc4-mcp-group",
|
||||
"summary": "MCP-driven fan-out session: 2 claudeAgent delegated-task threads plus 3 parallel MCP threads (codex :0, grok :1, claudeAgent :2), all single-run. Pipeline health is good overall: all 122 items verified against native logs with exact tool-call counts (19/19 on :2, 1/1 and 16/16 on the delegated tasks), ordinals fully consistent with turn_item_positions, zero lineage orphans, no duplicates, and the codex 400 model error was ingested verbatim and surfaced as a user-visible failed error item. Main defects found: the claudeAgent adapter (as of the code that ran, fc23be8184) concatenates intra-turn assistant text segments without separators into one end-of-turn item, destroying segment boundaries and native interleaving; and the three claudeAgent provider sessions were never idle-reaped, staying 'ready' for ~21 hours until a simultaneous shutdown sweep.",
|
||||
"stats": "5 threads, 1842 ingested events (34/94/22/1587/105), 122 projected items (4/19/2/75/22), 5 runs (4 completed, 1 failed), 5 provider turns, 5 provider sessions (all stopped). Native: mcp log 3763 lines (grok 3158 / claude 499 / codex 106), delegated log 495 lines. 1 provider error (codex 400), 0 orphan run/node/provider_turn/parent references, 0 ordinal collisions, 0 nativeItemRef dupes, positions match 122/122."
|
||||
},
|
||||
{
|
||||
"sessionKey": "5dcea72d-grok-subagent",
|
||||
"summary": "Two-run grok session (\"spawn a subagent\"): run 1 asked the user clarifying questions (xai-question), spawned a background explore subagent; run 2 fetched its output via a blocking TaskOutput tool call and summarized it. Main-thread projections are complete and consistent (16 items, all completed, positions/ordinals match, no dupes, all terminal states correct, no backwards timestamps). The main problem is the subagent child thread: it froze at spawn time with a placeholder result, and the subagent's entire live transcript (116 tool calls over 74.9s) was never ingested \u2014 the real output survives only inside a parent-thread tool item.",
|
||||
"stats": "Native log: 7028 lines, 3501 decoded incoming + 8 decoded outgoing protocol msgs, 10 request events (2 session/prompt terminations logged failed/Interrupt); payload contents are redacted (shape-only). Ingested: 257 events on main thread + 8 on child thread. Projected: 16 turn_items main + 2 child; 2 runs / 2 attempts / 2 provider_turns all completed; provider session stopped; provider thread idle; 1 subagent row (completed). 0 tool failures / rate limits observed."
|
||||
},
|
||||
{
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks",
|
||||
"summary": "Dev session on scheduled tasks: run 1 on codex, then a provider handoff to claudeAgent for runs 2-10 (8 completed, run 9 user-cancelled, run 10 failed 2s after query.open with no SDK response). Pipeline health is very good: zero lost native content in the claudeAgent portion, lineage fully intact, ordering matches native emission exactly, no duplicates, and nothing stuck non-terminal (session stopped, provider threads idle, 0 running items). The only real defect found is that run 10's failure was persisted with a hardcoded generic message, making it undebuggable from the DB.",
|
||||
"stats": "Main thread: 1707 events, 363 items (169 codex run-1 + 194 claude), 69 messages, 10 runs, 10 provider turns (8 completed/1 cancelled/1 failed). 15 child threads: 2 Explore subagents (95+245 events, 20+50 items) + 13 bash-task threads (7-9 events, 2 items each); all child items completed. Native log 5336 lines (2 files, runs 2-10 only). Cross-checks: 156/156 main tool_use ids accounted for (154 toolu items + 2 Agent calls projected as task subagent items), 64/64 subagent tool_use ids, assistant text preserved exactly (27311 chars log = 27311 chars items), 94 thinking blocks all natively empty (SDK sends thinking_delta with empty text), 5/5 is_error tool_results projected as failed, 1 api_retry (recovered), 14 task_notifications + 1 task_updated-only completion (bqu8waxt3) all reconciled; 0 ordinal collisions, 0 position mismatches, 0 orphan lineage refs. All backgrounded-bash tasks completed within their runs, so cross-run/wakeup paths were not exercised in this session."
|
||||
},
|
||||
{
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"summary": "Long claudeAgent coding session (PR #3638 scheduled-tasks work, 20:56-23:43 UTC on 2026-07-01) with 16 runs, 2 Task subagents, and heavy post-turn wakeup activity via task notifications. The persisted portion of the pipeline is healthy \u2014 lineage, ordinals/positions, ordering vs native emission, terminal states, and text fidelity all check out \u2014 but roughly 40% of the provider's actual output (10 full post-turn wakeup turns: 16 assistant messages and ~84 tool calls, including real git pushes) was never ingested at all, this being one of the threads on which that gap was originally diagnosed. Two error-handling gaps stand out: a 401 auth failure projected as a completed run, and run 10's failure persisted only as 'Claude Agent SDK query failed.' with no root cause recorded anywhere.",
|
||||
"stats": "Native log: 8088 lines (all protocol/decoded): 25 results, 594 assistant msgs (68 distinct main-thread text msgs, 122 with thinking), 371 unique tool_use (307 main / 64 child), 49 task_notification, 4 rate_limit (all 'allowed'), 3 query.open, 1 query.close. Ingested: 1546 events on main stream. Projected: 16 runs (15 completed, 1 failed), 16 provider_turns, 308 main items + 70 child items = 378 (positions table matches 378, no collisions/dupes), 68 messages, 2 subagents (both completed, child threads linked). Coverage gap: 84 tool calls + 16 assistant texts in log with no projection (all in wakeup windows); 0 items stuck running/streaming."
|
||||
},
|
||||
{
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"summary": "Long mixed-provider session (13 claudeAgent runs, then a clean claudeAgent\u2192cursor provider handoff at run 14, then 3 failed cursor runs) with two claudeAgent subagent child threads. Core pipeline health is good: ordering/positions are perfectly consistent, no duplicates, no stuck non-terminal items/nodes/messages, sampled long assistant text survives un-truncated, and handoff lineage (context-transfer consumed \u2192 handoff ready \u2192 run 14, thread.provider-switched) is fully intact. The big defect is the known 'invisible post-turn turns' problem: three post-run wakeup turns (10 and 17 native turns' worth of tool calls, including a GitHub comment being posted) produced zero events and zero projections. Secondary issues: 529-Overloaded turns (runs 11-13) projected as completed despite native is_error:true, and cursor run failures persisted with only a generic 'Provider turn failed.' string.",
|
||||
"stats": "Events: 6482 (main) + 165 + 255 (two subagent child threads). Items: 695 main + 34 + 52 child; positions table matches 695/695 with zero ordinal collisions, zero duplicate nativeItemRefs. Runs: 17 total \u2014 13 claudeAgent completed, 1 cursor completed (14), 3 cursor failed (15/16/17; 15 had a superseded steering_restart attempt). 2 subagents, both completed and linked to child threads. Tool-call coverage: cursor run 15 window 51/51 projected; claudeAgent era 529 native tool_use ids, all projected except 42 post-turn-wakeup calls (lost) and 2 Agent spawns (correctly represented as subagent items). Nodes: 751, all terminal. Errors seen natively: 3 is_error results (529 Overloaded), 1 error_during_execution, 1 model_refusal_fallback, 29 api_retry, 3 cursor run status:error."
|
||||
},
|
||||
{
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns",
|
||||
"summary": "Two-run cursor session (composer-2.5, fastMode) where the user asked why cursor turns fail; run 1 completed a full debugging pass, run 2 hung silently for 440s and failed \u2014 reproducing the very bug being investigated. The ingestion/projection pipeline itself is in excellent health: all 123 native tool calls plus reasoning/assistant text project 1:1 with exact character counts (3664/3664 assistant, 3382/3382 thinking), ordering matches native emission exactly, positions table is consistent (150/150, 0 ordinal mismatches or dupes), lineage refs all resolve, no stuck states (run/attempt/turn/node all 'failed' for run 2, session 'stopped' after agent.close), and timestamps are monotonic. The one substantive problem is error-handling fidelity: the run 2 failure is projected only as failure {message:\"Provider turn failed.\", code:null}, because CursorAdapterV2 reads a non-existent result.error and never surfaces the Cursor SDK's real error_code (an authentication error), dropping even the requestId/durationMs present in the decoded payload.",
|
||||
"stats": "Native log: 1920 decoded protocol lines, 2 native runs (run-1cbebefe finished; run-f4d64e64 status error), 123 distinct tool calls (87 shell / 18 read / 14 grep / 4 glob; 118 natively completed), 17 thinking blocks, 3664 assistant chars, 3382 thinking chars. Ingested: 906 orchestration_events for the stream. Projected: 150 turn items (2 user_message, 5 assistant_message, 17 reasoning, 88 command_execution, 36 file_search, 1 checkpoint, 1 error), 2 runs (1 completed / 1 failed), 2 run attempts, 2 provider turns, 7 messages, 0 subagents/child threads. 1 provider failure seen (generic)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "8ee00dcc-cursor-spacing",
|
||||
"summary": "Single-run Cursor (composer-2.5, fastMode) session: user asked to remove extra spacing on the mobile Threads/Home screen; the agent searched, read files, made 3 edits to HomeScreen.tsx, and summarized. The pipeline is essentially clean: every native item (33 tool calls, 10 thinking segments, 3 assistant messages, 1 user message) maps 1:1 to projected turn_items with exact content fidelity, ordinals are contiguous and match native emission order, all statuses reached terminal states, and no errors occurred in the native log. Only minor gaps found: token usage from the native turn-ended/run.completed is not ingested anywhere, and run_attempt.provider_turn_id is never backfilled.",
|
||||
"stats": "Native log: 665 lines (all stage=decoded), 659 interaction.update (33 tool-call-started + 33 tool-call-completed, 10 thinking-completed, 94 text-delta, 107 thinking-delta, 377 token-delta, 3 partial-tool-call, 1 turn-ended, 1 step-completed) + run.start/started/completed + agent.open/opened/close. Events: 415 (stream versions 0-414 contiguous; 194 turn-item.updated, 194 node.updated). Projections: 49 turn_items (1 user_message, 1 workspace-prep command_execution, 3 assistant_message, 10 reasoning, 29 file_search, 3 file_change, 1 tool command_execution, 1 checkpoint), 49 positions, 1 run (completed), 1 attempt (completed), 1 provider_turn (completed), 4 messages. Zero errors in native log."
|
||||
},
|
||||
{
|
||||
"sessionKey": "codex-no-native-logs",
|
||||
"summary": "Four sibling codex threads multiplexed onto the shared codex app-server session ('provider-session:provider-instance:codex:shared'). The missing native logs are explained: the codex protocol logger is bound to the threadId that opened the shared session (71e29ba5, whose own codex native thread is 019f1b50), so all four threads' traffic went to 71e29ba5's log file and was mostly rotated away by that thread's heavy claude traffic. Events-to-projections consistency is excellent: all 11 runs and provider turns terminal (10 completed, 1 user-interrupted with proper interrupt request/result items), zero lineage violations, zero ordinal collisions or duplicates, projection order matches native start order (verified against the surviving log window for c878541b runs 4-6), and message text verified byte-exact (1733/1733 chars). Only gaps: codex reasoning items (empty-content in this session) and one contextCompaction item are not projected at all.",
|
||||
"stats": "4 sibling codex threads (not parent/child; 0 subagent rows), 1797 events total (1077/468/222/30), 11 runs (10 completed, 1 interrupted), 440 turn_items (117 assistant_message, 264 command_execution incl. 20 failed, 18 file_change, 8 dynamic_tool, 12 user_message, 11 checkpoint, 2 interrupt items), 129 messages sampled on c878541b (61 assistant/7 user = item counts). 0 lineage violations, 0 ordinal collisions, 0 native-ref dupes, 0 non-terminal items/runs/turns/nodes. Native log survives only for c878541b runs 4-6 (16:00-16:44Z window)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"summary": "Largest session in the store: the wakeup/blur dev thread, started on codex (runs 1-55), provider-switched to claudeAgent via a ready context handoff (runs 56-122), spawning 7 claude subagent child threads; still live during the audit (run 122 completed mid-audit at 17:13:36Z). In-run ingestion is very healthy: ordinals/positions are perfectly consistent across main + child threads with zero collisions or dangling lineage refs, projection order exactly matches native emission (run 121 verified item-by-item), no duplicates, no stuck items/turns/streaming messages, and all failed runs and user-interrupted subagents are surfaced with error/failed items. The two significant problems are both loss-of-data outside run windows: 76 completed claudeAgent tool calls plus assistant text from post-turn task_notification wakeup turns were never ingested (the known invisible-post-turn-turns bug this thread was used to develop the fix for \u2014 no provider_wakeup runs exist here), and a 30-minute codex-era ingestion gap (16:10-16:40 Jul 1) lost 119 command/fileChange items with only assistant text later backfilled at a single flattened timestamp.",
|
||||
"stats": "Main thread: 14259 events (seq 13799-43607, still live during audit), 3390 projected turn_items (922 assistant_message, 1658 command_execution, 345 file_change, 144 dynamic_tool, 26 web_search, 7 subagent, 4 error, 169 user_message, 117 checkpoint, 1 handoff), 1091 messages, 122 runs = 122 provider_turns (117 completed / 4 failed / 1 cancelled, statuses exactly aligned). 7 subagent child threads (not 9): 79-260 events and 17-53 items each, 214 child items total. Native logs cover only 2026-07-01T16:00:59Z onward (~50k lines, 11 files; earlier rotations deleted). Claude era: 1130 native toolu ids vs 1045 projected (76 lost in wakeup gaps, 7 Agent-remapped, 2 in-flight). Codex era (in-log): 450 native call ids, 119 unprojected. 4 native error_during_execution, 2 orchestrator transport failures, 1 user cancel, 2 user-interrupted subagents."
|
||||
}
|
||||
],
|
||||
"confirmed": [
|
||||
{
|
||||
"title": "Codex-native collab subagent (run 3) entirely missing from events and projections",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "User prompt run 3 was 'spawn a subagent'. Native log a5a643b2-...log shows: item/completed subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq (kind 'started', agentThreadId 019f0c93-d260-7740-a477-0c0d19e8b299, agentPath /root/hello_agent) at 2026-06-28T04:54:02.530Z; collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX (tool 'wait', inProgress 04:54:04.013Z -> completed 04:54:14.015Z); and on child native thread 019f0c93-d260: webSearch ws_08e14d73aa33777f016a40a8f75cd0819ba433374351c23d4f (query 'Codex OpenAI latest docs'), reasoning rs_08e14..., agentMessage msg_08e14d73aa33777f016a40a8fd816c819bbd856f295f6ce730 (text 'Hello.', completed 04:54:23, child turn 019f0c93-d421 completed 04:54:23.777Z -- AFTER parent run 3 finalized 04:54:15.874Z). SQL: 0 rows in orchestration_events for LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%', '%call_9wPxyaS7ueh1MXl7XJt6zysq%', '%ws_08e14d73%', '%msg_08e14d73%', '%019f0c93-d260%'; orchestration_v2_projection_subagents has only the run-4 delegate-task row. Run 3 projected only user_message + 2 assistant messages + checkpoint; the parent assistant text ('Subagent spawned as /root/hello_agent. It hasn't returned within the short wait window yet.') is the only user-visible trace. Note: current CodexAdapterV2.ts (registerSubagentActivity/registerSubagentThreads, lines ~2815/2986; commits 3b864044c6 2026-06-28 'Adopt userdata-v2 and subagent activity mapping' and 57aa76ac14 2026-06-29) now maps these item types, so the session likely ran a pre-fix build -- but the historical data is unrecoverable and the child agent's post-run-completion output (arrived 8s after parent turn completed) remains a late-arrival hazard.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE payload_json LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%' OR payload_json LIKE '%019f0c93-d260%'\" # returns 0; vs grep -c 'subAgentActivity\\|collabAgentToolCall' ~/.t3/userdata-v2/logs/provider/a5a643b2-6ca8-4250-9c54-ddefe7d55565.log",
|
||||
"sessionKey": "a5a643b2-codex-heya",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Every evidence point reproduces: the native log contains subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq, collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX, and 29 child-thread (019f0c93-d260) lines including agentMessage msg_08e14d73 (\"Hello.\") at 04:54:23.755Z, while orchestration_events and all projections return 0 rows for every identifier; run 3 projected only user_message + 2 assistant messages + checkpoint, and the subagents table has only the run-4 delegate-task row. The child output also arrived 8s after run 3's projected completed_at (04:54:15.874Z), matching the late-arrival claim. So the data loss is real and unrecoverable. Severity adjusted to medium because the session predates fix commit 3b864044c6 (2026-06-28 17:58 PDT, ~20h after the session) and current CodexAdapterV2.ts (lines 2815/2986-2998) now maps both item types, so recurrence for these types is addressed; only the historical loss and an unverified late-arrival hazard remain."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Backend child process fatally crashed twice on @cursor/sdk, killing run 1 mid-turn with no user-visible error",
|
||||
"category": "error-handling",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "server-child.log (~/.t3/userdata-v2/logs/server-child.log): stderr fatal-error dump referencing 'file:///Applications/T3 Code (Alpha).app/.../node_modules/@cursor/sdk/dist/esm/index.js:1' at 2026-06-29T21:48:20.166Z (0.33s after native run.started run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 at 21:48:19.834Z) and again at 21:49:09.455Z (followed by 'Node.js v24.15.0' crash footer). Server restart at 21:48:21.35 logged 'V2 orchestration recovery completed { terminalizedRuns: 1, stoppedSessions: 2 }'. Reconcile events seq 6294-6299 (command:runtime-reconcile:startup...21:48:21.501Z) set run:thread:721fc23c...:ordinal:1, its attempt, and provider-turn run-9d9ff525 to 'cancelled'. Run 1 has no error/cancelled turn item \u2014 user asked 'Hello therw!' and got only the 'Workspace ready' item; the cancellation is silent (run status is the only signal). No assistant content was lost in the log sense (crash preceded any deltas), but the turn was killed by a server bug, not a user cancel, and is projected indistinguishably from a user cancellation.",
|
||||
"repro": "grep -n 'cursor/sdk\\|terminalizedRuns' ~/.t3/userdata-v2/logs/server-child.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT event_type,occurred_at FROM orchestration_events WHERE stream_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND event_id LIKE '%runtime-reconcile%'\"",
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Every cited artifact reproduces: the @cursor/sdk fatal stderr dump at 21:48:20.166Z (0.33s after native run.started run-9d9ff525), a second fatal crash at 21:49:09.455Z with Node.js footer and child exit code=1, the recovery log 'terminalizedRuns: 1, stoppedSessions: 2', reconcile events seq 6294-6299 setting run 1/attempt/node/provider-turn to 'cancelled', and no error or cancelled turn item on run 1 (only user_message + workspace item). ProviderRuntimeRecoveryService.ts intentionally marks interrupted runs 'cancelled' and never persists its 'server restarted' detail string user-visibly, so the crash-induced kill is projected identically to a user cancel with zero debuggable trace \u2014 a real gap, though the terminalization itself is designed behavior. Downgraded to medium because recovery worked cleanly (nothing stuck, no assistant content lost since the crash preceded any deltas), and the finding slightly overstates impact: run 2's failure WAS surfaced with a visible provider_error item; only run 1 died silently."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "401 authentication failure recorded as fully successful run \u2014 is_error on SDK result ignored",
|
||||
"category": "error-handling",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log 2026-06-28T05:22:33.360Z: result payload has subtype:\"success\" but is_error:true, api_error_status:401, result:\"Failed to authenticate. API Error: 401 Invalid authentication credentials\", usage all zeros; preceded by two api_retry events (05:22:31.612Z, 05:22:32.312Z, error_status 401 authentication_failed). Projections: run run:...ordinal:1 status=completed (event seq 146, run.updated stream_version 27), run_attempt ...attempt:1 status=completed (seq 139), provider_turn ...attempt%3A1 status=completed (seq 138), assistant turn-item turn-item:provider:claudeAgent:native-item:03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc status=completed. No failure/error field anywhere in any payload_json; the only trace of the error is the synthetic assistant message text (which did survive verbatim, so it is user-visible as ordinary assistant text, not as an error state). Root cause: terminalStatusFromResult in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:1652 returns \"completed\" whenever message.subtype === \"success\" and the failure branch at ~line 3254 only fires for non-success subtypes; is_error/api_error_status are never checked (only tool-result is_error at lines 1498-1500). An MCP delegate_task caller polling run status sees success for a task that never executed.",
|
||||
"repro": "grep 'api_error_status' ~/.t3/userdata-v2/logs/provider/thread-delegated-task-command-3amcp-3a1156181e-e188-4fe4-8cc5-a294003ebfed-3adel.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE thread_id LIKE '%1156181e%';\"",
|
||||
"sessionKey": "1156181e-delegated-task",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Every evidence point reproduces: the native log at 2026-06-28T05:22:33.360Z shows a result with subtype \"success\" but is_error:true, api_error_status:401, zero usage, preceded by two api_retry 401 authentication_failed events (05:22:31.612Z, 05:22:32.312Z); projections show run (seq 146), run_attempt (seq 139), provider_turn (seq 138) and assistant turn-item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc all status=completed with no failure field in any payload_json. The code claim is accurate: terminalStatusFromResult (ClaudeAdapterV2.ts:1658) returns \"completed\" for any subtype===\"success\" and the failure branch at ~3254 only fires for non-success subtypes, while the SDK's SDKResultSuccess type explicitly exposes is_error and api_error_status (sdk.d.ts:2739-2740) \u2014 so this is an ignored error signal, not an SDK ambiguity or intentional design. Severity high stands because this thread is a delegated MCP task whose caller consumes run status programmatically; an auth failure that executed zero turns is reported as a fully successful run, with the only trace being ordinary assistant text."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Subagent live transcript and final output never projected to its child thread",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child thread 'thread:provider:grok:native-thread:019f1b5f-efdb-7da0-acd7-1a31b3fe00bc%3Atask%3Acall-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has only 8 events (sequences 14437-14451, last stream_version 7 at 2026-07-01T01:52:10.705Z) and 2 turn_items, both timestamped at spawn (01:52:10). Its assistant_message item 'turn-item:provider:grok:native-item:call-cdbbacb3-...-1%3Aresult' contains only the bootstrap text 'Subagent started in background... Use get_command_or_subagent_output ... to wait for results.' Yet the task actually ran 01:52:10Z-01:53:25Z with tool_calls=116 (per TaskOutput result in parent item turn-item:provider:grok:native-item:019f1b5f...%3Atool%3Acall-5ca8a4be-6fc8-4924-909c-b198de7dcbc8-2). Native log shows 811 decoded incoming ACP messages between 01:52:14 and 01:52:59 (gap between run 1 Interrupt at 01:52:13.249 and run 2 start at 01:52:59.9) with ZERO orchestration_events ingested for any session stream in that window \u2014 the subagent's streamed activity was dropped, likely because AcpAdapterV2's subagent context (context.subagents / subagentsBySessionId / pendingSubagentNotifications in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts ~line 559) is per-active-turn and turn 1 had already finalized. The 15,053-char final output is preserved un-truncated ONLY inside the parent's turn-2 dynamic_tool item; a user opening the child thread 'Explore codebase structure and architecture' sees none of the subagent's work.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE occurred_at>'2026-07-01T01:52:13.4' AND occurred_at<'2026-07-01T01:52:59' AND (stream_id LIKE '%5dcea72d%' OR stream_id LIKE 'thread:provider:grok:native-thread:019f1b5f%');\" -- returns 0, vs grep of the log showing 811 decoded incoming messages in the same window",
|
||||
"sessionKey": "5dcea72d-grok-subagent",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "All evidence reproduces: child thread has only 8 spawn-time events (seq 14437-14451, all 01:52:10Z) and its result item contains only bootstrap text; 0 orchestration_events exist in the 01:52:13.4-01:52:59 gap despite continuous decoded incoming traffic in the log; run 1 prompt failed with errorTag Interrupt at 01:52:13.249Z and the subagent ran to 01:53:25Z (116 tool_calls per parent TaskOutput item). Code intent confirms this is a bug, not design: AcpAdapterV2's emitSubagentAssistant/projectSubagentNotification/pendingSubagentNotifications (lines 845-882, 1447-1461) are built to stream subagent text into the child thread, but the per-turn context's finalized guard plus run 2's empty subagentsBySessionId map dropped everything; the subagent projection row is also frozen at spawn (completed_at 01:52:10.702Z, result=bootstrap text). Downgraded to medium because the full 15,053-char final output is preserved un-truncated and user-visible in the parent's turn-2 dynamic_tool item, and even happy-path design only projects assistant text chunks (not tool calls) to the child thread \u2014 the loss is the child-thread transcript and an accurate subagent row, not the final answer."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "10 post-turn wakeup turns entirely unpersisted (16 assistant messages + 84 tool calls lost)",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Native log has 25 result messages but only 16 runs exist. 10 results have no corresponding run/message/item: 21:19:42 ('CodeRabbit's final pass came back clean'), 22:14:37, 22:19:27, 22:25:18, 22:32:25, 22:38:55 (review-fix 'Rounds 3-7' incl. real git pushes 'a3c87931a2', 'cb28a0842f', 'c435bec111', '57ca73e655', 'd851eb7b9c'), 23:12:04, 23:17:19, 23:32:05 ('Round 11 pushed c19ceca8a5'), 23:41:55 ('Converged. PR #3638 is fully green'). Diff of tool_use ids in log vs nativeItemRef in projections: 86 missing (84 after excluding 2 Agent ids that are represented as task-id subagent items) \u2014 all timestamped inside wakeup windows (21:19, 22:13-22:38, 22:59:24-32, 23:11:24-34, 23:16-23:23, 23:29-23:31, 23:41). 16 native assistant text messages missing (uuids incl. 6299b5cf-7941-4355-8063-eb9d60d7216f @21:19:41, d226f500-43a0-489e-a1bd-888747c56495 @22:38:54, 093e91b9-0d5b-4ad9-a7a9-2ef06c4c2021 @23:41:52). Zero orchestration_events on the stream between 22:10:30 and 22:48:00 except one provider-session.updated (stopped) at 22:41:50.039Z. No run/message has inputIntent provider_wakeup; all 16 user messages have creationSource=web. This is the documented 'invisible post-turn turns' issue diagnosed on this exact thread (fix implemented later on branch t3code/codex-turn-mapping); this session's data predates the fix.",
|
||||
"repro": "SELECT COUNT(*) FROM orchestration_events WHERE stream_id='47763f5e-76c1-4d67-8037-442a280f1514' AND occurred_at>'2026-07-01T22:10:30' AND occurred_at<'2026-07-01T22:48:00'; -- =1 (session stop only), while the native log shows 5 full result turns in that window: grep '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 | grep 'T22:[123]'",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Every evidence point reproduces: 25 decoded result messages in the native log vs 16 projected runs, with the exact 10 cited orphan results unmatched by any run completed_at; the repro SQL returns 1 (only a provider-session stop at 22:41:50.039Z) for a window where the log shows 5 full turns; 86 top-level tool_use ids (371 in log vs 285 projected across all threads) are missing, all timestamped in the orphan-turn windows; cited assistant texts/uuids exist in the log but in zero projection rows; and no run/message carries provider_wakeup intent. This is real, substantial user-facing data loss (whole review-fix rounds with real git pushes invisible), matching the documented pre-fix \"invisible post-turn turns\" issue on this exact thread \u2014 known issue, but the lost session data is not backfilled by the fix, so high severity stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Invisible post-turn wakeup turns: 42 native tool calls + final assistant messages never ingested or projected",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Three windows where the claudeAgent SDK kept working after the orchestrator closed the run: 23:31:27-23:36:48 (16 calls: Bash/Read/Edit/TaskCreate/TaskUpdate, after run 5 completed 23:30:07), 00:16:13-00:17:13 (9 calls, after run 6 completed 00:16:09), 00:33:32-00:37:24 (16 calls incl. mcp__t3-code__preview_* tools, after run 7 completed 00:33:22). Native results confirm full turns: [2026-07-02T00:17:51.602Z] subtype success num_turns:10 and [00:37:39.534Z] num_turns:17. Zero rows in orchestration_events for e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD (Bash 00:17:05.797Z); zero main-stream events between 00:16:10 and 00:21:50. The wakeup turn's final assistant text 'Done \u2014 comment posted: https://github.com/pingdotgg/t3code/pull/2829#issuecomment-4861082710' (log.2, 00:17:4x) has 0 events and 0 turn_items \u2014 the agent posted a GitHub comment with no user-visible record. This is the diagnosed 'invisible post-turn turns' issue; the fix (turn.wakeup / ProviderWakeupService / attach_wakeup) is on this branch but this session ran on the pre-fix build (this thread is itself the diagnosis session, title 'check in on this thread: 47763f5e...').",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%toolu_012dzkuS4eoKeRiAaQ3icFpD%'\" -- returns 0; grep toolu_012dzkuS4eoKeRiAaQ3icFpD ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2 shows the Bash tool_use",
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Re-ran the full evidence trail: run 5/6/7 completion timestamps match, all 9 window-2 tool ids (e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD) and 33 window-1/3 ids have zero rows in orchestration_events, zero main-stream events exist in all three gap windows, and the final assistant text with the posted GitHub comment URL (issuecomment-4861082710) has 0 events and 0 turn_items despite 4 native log occurrences with a success result (num_turns:10 at 00:17:51.602Z). Minor correction: 5 ids the finding attributed to window 1 belong to run 6 and were ingested, but the total lost count is still exactly 42. The session ran on the pre-fix build (the fix lives uncommitted on this branch), so whole turns including a real-world side effect were permanently lost with no user-visible record \u2014 real lost-data, correctly flagged as a known issue, severity stays high."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Cursor turn failure projected with only generic 'Provider turn failed.' \u2014 real error detail (auth error) never captured",
|
||||
"category": "error-handling",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run 2 (native run-f4d64e64-0af6-42bc-8813-5b6ce53a328d) failed: native log line [2026-07-02T02:35:28.424Z] run.completed result {status:\"error\", requestId:\"beca30c7-7e90-481b-abf7-fdab84b3c48d\", durationMs:440732} \u2014 no error field in the decoded payload, and zero interaction.updates for the entire 440s turn (only run.started at 02:28:07.973Z then silence). Projected error item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...run-f4d64e64... (event seq 38493, occurred_at 2026-07-02T02:35:28.524Z) carries failure {class:\"provider_error\", message:\"Provider turn failed.\", code:null, retryable:null} \u2014 requestId and durationMs from the native payload are dropped too. Cause: CursorAdapterV2.ts:2165-2168 maps `cause: (result as { readonly error?: unknown }).error` which is undefined on the SDK RunResult, falling back to DEFAULT_PROVIDER_FAILURE_MESSAGE. The session's own in-turn diagnosis (final assistant item ...assistant%3Arun-1cbebefe...%3A5) confirmed the real cause lives only in the Cursor SDK store runs.error_code (\"Authentication error If you are logged in, try logging out and back in.\") which T3 never reads. The failure IS surfaced user-visibly (error item status failed, run/attempt/provider-turn all 'failed'), but with zero debuggable detail \u2014 this exact gap forced the user to spawn this debugging thread, and then recurred on the thread itself (run ordinal 2).",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND type='error';\" ; grep 'run.completed' ~/.t3/userdata-v2/logs/provider/c9e72a05-4c87-4dd5-b1b6-83834cc73afe.log | tail -1",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Fully reproduced: the projected error item for run-f4d64e64 carries only {\"message\":\"Provider turn failed.\",\"code\":null}, while the native log's run.completed (02:35:28.424Z, status \"error\", requestId beca30c7, durationMs 440732) confirms no detail was captured and requestId/durationMs were dropped. The cited code (CursorAdapterV2.ts:2165-2168) reads (result as {error?: unknown}).error, but @cursor/[email protected]'s RunResult type has no error field whatsoever \u2014 the fallback is guaranteed dead-code behavior for EVERY failed Cursor turn, and the SDK's public store API does expose RunRecord.errorCode (\"Authentication error...\") which T3 never reads. The failure is surfaced user-visibly with correct terminal states (so nothing is swallowed), but the projection retains zero debuggable detail for a systematic, provider-wide failure path, which matches the audit's explicit error-handling criterion; severity high stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Shared codex session native logs written to opener thread's file, not the active thread's \u2014 no log file ever created for these threads",
|
||||
"category": "other",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All four threads bind provider_session_id 'provider-session:provider-instance:codex:shared'. Their codex app-server protocol traffic appears in 71e29ba5-654b-4f67-b363-ad400e5bd016.log.6/.9/.10 (e.g. 019f1b62-f532 = c878541b's nativeThreadRef: 4768 hits in .log.10, 2828 in .log.9), interleaved with that thread's own claudeAgent and codex (019f1b50-4248) traffic. Cause: in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts, codexAppServerClientFactoryFromSettingsLayer.open builds makeCodexAppServerProtocolLogger({ nativeEventLogger, threadId: input.threadId, ... }) once per app-server process; EventNdjsonLogger.write routes to `${threadSegment}.log` from that frozen threadId, so every thread multiplexed onto the shared session logs under the opener's file. No file named c878541b-*/de5f191a-*/68f7595b-*/af66fc2c-* was ever created.",
|
||||
"repro": "grep -l '019f1b62-f532' ~/.t3/userdata-v2/logs/provider/*.log* # hits only 71e29ba5-654b-...log.{6,9,10}, never a file named after the audited threads",
|
||||
"sessionKey": "codex-no-native-logs",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Fully reproduced: all four threads bind provider-session:provider-instance:codex:shared; c878541b's nativeThreadRef 019f1b62-f532 appears exactly 4768x in 71e29ba5.log.10 and 2828x in .log.9 (interleaved with 71e29ba5's own codex ref 019f1b50-4248), and no log file named after any of the four threads exists. Code confirms the cause: CodexAdapterV2.ts line 1136 freezes input.threadId into makeCodexAppServerProtocolLogger at app-server open, so every multiplexed thread's protocol traffic routes to the opener's `${threadSegment}.log` \u2014 defeating EventNdjsonLogger's per-write threadId routing, so this is a misrouting bug, not intent. Downgraded to medium because ingestion/projections for these threads are intact (observability-only defect), though rotation under the busy opener file has permanently deleted 3 of 4 threads' protocol history."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Invisible post-turn wakeup turns (claudeAgent): 76 completed tool calls + assistant text never ingested or projected",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "1130 unique toolu_ ids in decoded native logs vs 1045 projected nativeItemRef ids. Of the 85 unmatched, 7 are Agent spawns (projected under task:<hash>:subagent ids, fine) and 2 are stream-only in-flight blocks; the remaining 76 (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) ALL fall in gaps between run windows \u2014 0 fall inside any run. Example: run 56 completed 2026-07-01T22:18:57.958Z (result subtype=success 22:18:57.333Z); at 22:20:52.374Z 'system task_notification bk7bmoyti' re-woke the session, assistant emitted text 'The build failed \u2014 let me see the actual error.' (22:20:58.275Z) then Bash toolu_011YH7oQm6yGVjWTfxwQ1QsH (22:20:59, tool_result 22:21:00) etc. \u2014 none exist in orchestration_events or turn_items (LIKE search for that text returns 0). This thread has ZERO wakeup runs/messages (0 messages with inputIntent provider_wakeup / creationSource other than agent|provider,user|web), while 367 provider_wakeup events exist elsewhere in the DB (first at 2026-07-01T22:47:41) \u2014 this is the thread on which the fix was being developed (memory: diagnosed 2026-07-01 on threads 47763f5e & 71e29ba5).",
|
||||
"repro": "comm -23 /tmp/native_toolu.txt /tmp/proj_toolu.txt (native ids from grep -h '\"stage\":\"decoded\"' ~/.t3/userdata-v2/logs/provider/71e29ba5-654b-4f67-b363-ad400e5bd016.log* | grep -o 'toolu_[A-Za-z0-9]*' vs SELECT json_extract(payload_json,'$.nativeItemRef.nativeId') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%71e29ba5%')",
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Re-ran the full evidence trail: 85 genuine claudeAgent tool_use ids in decoded native logs have no projection; after excluding 7 Agent spawns (verified projected as task:<hash> items) and 2 stream-only in-flight blocks, exactly 76 completed tool calls (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) all fall in gaps between run windows (0 inside any of the 127 runs). The cited example reproduces: assistant text 'The build failed...' at 2026-07-01T22:20:58.275Z between run 56 (ended 22:18:57.958Z) and run 57 (started 22:22:38.734Z), with 0 matching rows in orchestration_events; the thread has 0 provider_wakeup events/messages while 367 exist elsewhere. This is the documented known issue the branch fixes, but for this session the provider-emitted tool calls, results, and assistant text are unrecoverably absent from ingestion and projections, with losses continuing into 2026-07-02 \u2014 real high-severity lost data, correctly flagged knownIssue=true."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Provider failures persist only generic error strings; underlying cause is unrecoverable from the DB",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "4 claudeAgent error items say only 'Claude Agent SDK query failed.' (class transport_error, code null) \u2014 e.g. run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:10 failed 2026-07-01T22:48:38 with zero native-log traffic in that minute, so the real exception exists nowhere. Root cause: ClaudeAgentSdkQueryRunnerError.message getter in apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:280 hardcodes the string and discards `cause`. Similarly 4 cursor items say 'Provider turn failed.' (code null) while the native run.completed carried status:'error' plus requestId d1cd7f44-91fb-45ce-bdd3-86e9b5cc8e3e and durationMs 2434335 that were dropped. Counter-example showing it can be done right: codex errors keep full detail ('stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)' and the full 400 invalid_request_error body for gpt-5.3-codex).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT thread_id, json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE type='error';\"",
|
||||
"sessionKey": "GLOBAL",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced the SQL: all 4 claudeAgent error items persist only 'Claude Agent SDK query failed.' (code/retryable null) and no richer detail exists in any orchestration_events row for those failures; the root cause is confirmed at ClaudeAdapterV2.ts:279-281 where the message getter hardcodes the string while the Schema.Defect cause field is discarded by makeProviderFailure (real exception goes only to Effect.logWarning). This is not intentional: ProviderFailure.ts has redaction/4096-char bounding built to persist real error text, and codex failures do persist full detail. Minor correction: the '47763f5e had zero native-log traffic at 22:48' claim is false (8 lines exist in .log.1, outgoing query.open/prompt.offer at 22:48:38.086), and the cursor generic message is partly upstream (native run.completed carried no error message, only requestId d1cd7f44/durationMs which were dropped) \u2014 but the core finding stands, so severity stays medium."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Delegated Claude task failed with 401 auth error but all statuses say 'completed' (is_error ignored on success-subtype result)",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child native log thread-delegated-task-command-3amcp-3a1156181e-...log (2026-06-28T05:22:33Z) shows SDK result {\"type\":\"result\",\"subtype\":\"success\",\"is_error\":true,\"result\":\"Failed to authenticate. API Error: 401 Invalid authentication credentials\"}. Projections: child run run:thread:thread%3Adelegated-task%3Acommand%253Amcp%253A1156181e-...:ordinal:1 status=completed; provider_turn status=completed; subagent row node:delegated-task:command%3Amcp%3A1156181e-...%3Ahello-opus-48 status='completed' with result='Failed to authenticate...'; delegate_task tool item call_qV0wnlB5N6Osa6CPxTGN1Ajh output.status='completed'. Root cause in current code: ClaudeAdapterV2.ts terminalStatusFromResult (~line 1658) returns 'completed' whenever message.subtype==='success' without checking is_error, and the result handler (~line 3254) only attaches a ProviderFailure when subtype!=='success'. Mitigating: the error text IS preserved and user-visible (child assistant item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc text = the 401 message; parent's final assistant message msg_...9bb460 explains the failure), so nothing was swallowed -- but status semantics are wrong for anything filtering on failed tasks.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.result') FROM orchestration_v2_projection_subagents WHERE subagent_id LIKE '%hello-opus-48%'\" # completed | Failed to authenticate. API Error: 401 ...",
|
||||
"sessionKey": "a5a643b2-codex-heya",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Re-ran every evidence step: the child native log shows SDK result subtype=\"success\" with is_error=true and api_error_status=401 (zero tokens, \"Failed to authenticate. API Error: 401...\"), yet the child run, provider_turn, subagent row, and the parent's delegate_task item (call_qV0wnlB5N6Osa6CPxTGN1Ajh, output.status=\"completed\") all report completed. Source confirms the cause: ClaudeAdapterV2.ts terminalStatusFromResult (line 1658) returns \"completed\" on subtype===\"success\" without checking is_error, and the result handler (lines 3250-3263) only attaches a ProviderFailure when subtype!==\"success\" \u2014 is_error is checked only for tool results, so this is an oversight, not intent. Medium stands: the error text is preserved and user-visible, but status semantics are wrong end-to-end for anything filtering on failed delegated tasks."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Streaming deltas persisted as full-row event pairs cause ~2800x event amplification on child result items",
|
||||
"category": "other",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child thread ...composer_call_kFjs8 accumulated 2711 events (1352 turn-item.updated + 1352 message.updated + overhead) to stream a single 6274-char result; the 3 children total 5702 turn-item/message events for ~12.6KB of final text. This one 2-minute session wrote 6017 rows to orchestration_events (43k total table), i.e. each streaming delta is persisted as a full-row upsert event for both the turn item and its message. Not a correctness bug (final projections are correct) but a storage/replay-cost anomaly.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT event_type, COUNT(*) FROM orchestration_events WHERE stream_id LIKE 'thread:provider:grok:native-thread:019f1558%' GROUP BY 1;\"",
|
||||
"sessionKey": "20296b49-grok-tasks",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Evidence reproduces exactly: 1352 turn-item.updated + 1352 message.updated events on the single kFjs8 result item with monotonically growing text (4 -> 6274 chars, sequences 2160-4862), and the session totals exactly 6017 event rows. Code confirms the mechanism: AcpAdapterV2.emitSubagentAssistant emits a full-row message+turn-item event pair per agent_message_chunk and ProviderEventIngestor persists each pair durably with no coalescing, throttling, or event-log pruning (ProjectionMaintenance only rebuilds projections by replaying the full log). Quantified: 18.0 MB of payload_json for ~12.6 KB of final subagent text (~1400x, quadratic in output length), 15.5% of the entire event table from one 2-minute session. Final projections are correct so severity stays medium, but the unbounded quadratic storage/replay cost is a real, unmitigated pipeline anomaly, not intended behavior or a misreading."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Run 2 failure projected with generic wrapper message; actual cause dropped from projection and depth-elided in server log",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Error turn item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...ordinal%25253A2... (ordinal 2000002, status failed, 21:48:40.703Z) persists failure = {class:'provider_error', message:'Failed to start run run:thread:721fc23c-2cf3-42bf-9d84-edd94359dca9:ordinal:2 on cursor provider thread provider-thread:provider:cursor:native-thread:pending%3A...', code:null, retryable:null}. That string is ProviderAdapterTurnStartError's message getter (apps/server/src/orchestration-v2/ProviderAdapter.ts:291); RunExecutionService.ts:830 builds the failure via makeProviderFailure({cause: Cause.squash(cause)}) so the tagged error's wrapped `cause` (the real agent.send rejection from CursorAgentSdk runnerError 'run.start') never reaches the projection. The only other record, server-child.log line 89 at 21:48:40.703Z, printed the cause as \"{ _id: 'Cause', failures: [ [Object] ] }\" \u2014 depth-elided. The underlying reason run 2 failed 4ms after run.start is now unrecoverable. Positive: the failure WAS surfaced user-visibly as an error item and run/attempt/node all show 'failed'.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND type='error'\" ; grep -n '721fc23c' ~/.t3/userdata-v2/logs/server-child.log",
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "All cited evidence reproduces: the projected error item and its source event (orchestration_events sequence 6314) both persist only ProviderAdapterTurnStartError's generic message getter (ProviderAdapter.ts:280-293); RunExecutionService.ts:~831 feeds Cause.squash(cause) into makeProviderFailure, which (ProviderFailure.ts:90-113) reads only .message/.code and never unwraps the nested cause defect that CursorAdapterV2.ts:2203 attaches. server-child.log line 89 depth-elides the cause as \"[ [Object] ]\" and the native provider log ends at the outgoing run.start (21:48:40.699Z) with no error event, so the real reason run 2 failed is unrecoverable from any persisted artifact. The failure was surfaced user-visibly with correct terminal statuses, so medium (not high) is the honest severity \u2014 this is a debuggability gap, not silent loss."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Native provider log never records failure frames \u2014 cursor SDK send errors and process death are invisible in the ground-truth log",
|
||||
"category": "other",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log 721fc23c-2cf3-42bf-9d84-edd94359dca9.log ends at [2026-06-29T21:48:40.699Z] with outgoing run.start 'what did you just say' and no incoming frame, though the turn failed at 21:48:40.703Z. In Adapters/CursorAgentSdk.ts send(), the log writes cover outgoing run.start and incoming run.started/interaction.update/run.completed only; when agent.send rejects, Effect.tryPromise raises runnerError(cause,'run.start') with no protocol log write. Similarly run 1 shows run.started at 21:48:19.834Z and then nothing \u2014 no error, no lifecycle/exit record \u2014 because the process crash killed the logger too. Result: the 'ground truth' log cannot explain either failed turn, which is exactly why this session looked suspicious (7 lines vs 47 events).",
|
||||
"repro": "cat ~/.t3/userdata-v2/logs/provider/721fc23c-2cf3-42bf-9d84-edd94359dca9.log | tail -2 ; grep -n 'runnerError(cause, \"run.start\")' apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts",
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "low",
|
||||
"reasoning": "Evidence reproduces fully: the native log ends at 21:48:40.699Z with the outgoing run.start and no failure frame while events 6313-6315 record the run failing at 21:48:40.703Z, and CursorAgentSdk.ts's error paths (runnerError catches at lines 408/440; run.completed logged via success-only Effect.tap) confirm no error-frame logging exists \u2014 indeed no adapter has an error/lifecycle log kind at all. However, the pipeline did not swallow anything: the failure was ingested and user-surfaced as turn-item 6314 (type error, status failed) with correct terminal statuses, and the raw cause is logged to the server application log (CursorAdapterV2.ts:2188 logWarning with cause), so this is an observability gap in the debug/protocol log (compounded by the generic projected message with code:null) rather than a data-loss or projection bug. Run 1's \"process crash\" explanation is unproven (DB shows cancelled, lastError null), so I downgrade to low: real, design-wide log-scope limitation worth fixing, but errors remain debuggable and user-visible through other channels."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Failed tool item drops the provider error message (file_search projection has no error/output field)",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child thread ses_0ea978228: turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc (ordinal 87) went running->failed at 2026-06-29T22:04:02.915Z (events seq 8284 -> 8286 on stream thread:provider:opencode:native-thread:ses_0ea978228ffeVM6qpFUgGn62Vl). Final payload contains only {status:'failed', type:'file_search', pattern:'/Users/julius/Development/Work/codething-mvp/CLAUDE.md'} \u2014 no error text at all. Root cause in OpenCodeAdapterV2.ts: toolOutput() (line 659) returns part.state.error for status 'error', but the file_search branch (~line 1376) only maps 'pattern'; output/error is only attached for dynamic_tool. The contract (packages/contracts/src/orchestrationV2.ts line 841) also has no output/error field on file_search items, so the failure reason is unrecoverable from projections. Failure IS user-visible via status=failed, but not debuggable.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE turn_item_id='turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc';\"",
|
||||
"sessionKey": "3029dc85-opencode",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced the exact projection payload (failed file_search item prt_f15692f30001qL66As1xsUCQXc, ordinal 87, no error text) and the running->failed transition at events seq 8284->8286. Source confirms the mechanism: OpenCodeAdapterV2.ts toolOutput() (line 659) extracts part.state.error, but the file_search branch (lines 1376-1383) only maps pattern \u2014 output/error is attached only for command_execution/dynamic_tool \u2014 and the contract's file_search schema (orchestrationV2.ts line 841) has no field to hold it. The native log is additionally redacted (protocol payloads logged as fieldCount summaries only), so the error message is unrecoverable anywhere; failure is visible via status=failed but not debuggable, so medium stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Claude assistant text segments merged without separator into a single end-of-turn item, losing interleaving",
|
||||
"category": "lost-data",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Thread :2 native log has 5 assistant text blocks with distinct SDK uuids (341420a1 len 95 @22:09:54, 78f308a1 len 37 @22:09:58, 26b0aa8d len 90 @22:10:11, 31c4bfa0 len 73 @22:11:40, bfa7a134 len 10347 @22:13:07), interleaved with 19 tool calls. Projection has ONE assistant_message item turn-item:provider:claudeAgent:native-item:bfa7a134-04d5-4434-bb14-66927497fb91, ordinal 1000021 (after all tools), text length 10642 = exact sum, joined with no whitespace: '...read all the files thoroughly.I'll read all files in the directory.Let me gather context...'. The 4 intermediate uuids have ZERO orchestration_events (only seq 11544-11546 reference bfa7a134, all at 22:13:07). Root cause in code that ran (git fc23be8184 ClaudeAdapterV2.ts:2815): `context.assistant.text += assistantText.text` with single emission at result time; current worktree code (emitAssistantTextArtifacts per message.uuid) already emits per-segment items, so this appears fixed for future runs.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.text'),80,150) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:2' AND type='assistant_message';\"",
|
||||
"sessionKey": "6d618dc4-mcp-group",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "low",
|
||||
"reasoning": "Reproduced every claim: native log has 5 assistant text blocks (lens 95/37/90/73/10347 at 22:09:54\u201322:13:07) but the projection has one assistant_message item (native ref bfa7a134, ordinal 1000021 after all 19 tools) of length 10642 = exact sum, joined with no separator (\"thoroughly.I'll read all files in the directory.Let me gather context\"); the 4 intermediate uuids have zero orchestration_events while bfa7a134 has seq 11544\u201311547. Historical code (fc23be8184 ClaudeAdapterV2.ts:2815 `context.assistant.text +=`) caused it; current worktree emitAssistantTextArtifacts emits per-nativeItemId, so it is fixed going forward. Real for this session's data, but downgraded to low because no text content was lost (only interleaving/segmentation) and the fix already landed."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Subagent projection marked completed at spawn with placeholder result (lifecycle wrong by ~75s)",
|
||||
"category": "other",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "orchestration_v2_projection_subagents row 'node:provider:grok:native-item:call-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has status=completed, started_at=2026-07-01T01:52:10.677Z, completed_at=2026-07-01T01:52:10.702Z and result='Subagent started in background...\\nUse get_command_or_subagent_output...' \u2014 but the task's real lifetime was 01:52:10Z to 01:53:25Z (duration_secs 74.874 per the TaskOutput payload). The parent 'subagent' turn_item (ordinal 1000007) mirrors the same premature completedAt and placeholder result. Cause visible in AcpAdapterV2.emitSubagent (~lines 1047-1060): when the spawn tool returns 'started in background', taskStatus is non-running and update.result (the bootstrap text) is adopted as assistantText/result; nothing later updates it when the background task actually finishes.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, completed_at, substr(json_extract(payload_json,'$.result'),1,60) FROM orchestration_v2_projection_subagents WHERE thread_id='5dcea72d-15e1-4ded-922b-0b00c587de6c';\"",
|
||||
"sessionKey": "5dcea72d-grok-subagent",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced end-to-end: projection row 'node:provider:grok:native-item:call-cdbbacb3-...-1' has status=completed, completed_at=2026-07-01T01:52:10.702Z with result='Subagent started in background...' while the TaskOutput payload (event seq 14622, 01:53:28.477Z, item call-5ca8a4be-...) shows the task actually ran 01:52:10Z-01:53:25Z (duration_secs 74.874); only 3 subagent.updated events exist, all at spawn time, so nothing ever corrects it. Code confirms the cause: extractXAiAcpSubagentUpdate (XAiAcpExtension.ts:86-91) maps the spawn tool's completed status straight to subagent status with no background-spawn detection, and AcpAdapterV2.ts:1047-1053 adopts the bootstrap text as assistantText/result; the later TaskOutput tool call is projected as an unrelated dynamic_tool item and never routed back to the subagent, and the child thread's only assistant message is also the placeholder. Severity stays medium: the real 15.5KB output survives user-visibly in the separate dynamic_tool item, but the subagent card's lifecycle, result, and child-thread transcript are wrong, and this Grok/ACP path is not covered by the claudeAgent backgrounded-task known issue."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Run 10 terminal failure persisted with only a generic error message",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run run:thread:7f1dfff1-...:ordinal:10 failed at 2026-07-01T20:47:58.607Z. The projected error item (turn-item:provider:claudeAgent:native-item:terminal-failure%3A...ordinal%25253A10..., event seq 25810) has failure {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null, retryable:null}. run-attempt payload (seq 25811) carries no error detail either. Native log ends at 20:47:58.429Z with outgoing query.open + prompt.offer (user text \".\") and zero incoming SDK messages, so the DB retains no clue what actually failed. Root cause in code: ClaudeAdapterV2.ts:279-280 \u2014 ClaudeAgentSdkQueryRunnerError.message hardcodes \"Claude Agent SDK query failed.\" and the underlying `cause` defect is never propagated into the projected failure. The failure IS user-visible (error item + run failed), but is undebuggable after the fact.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='7f1dfff1-4cbb-450b-8514-764d11c903e1' AND type='error';\"",
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Re-ran the repro: the error turn-item (event seq 25810) and run-attempt (seq 25811) for run ordinal 10 persist only {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null}, and the native log truly ends at 20:47:58.429Z with outgoing query.open/prompt.offer and no incoming SDK data, so no error detail exists anywhere in DB or provider log. Code confirms the mechanism: ClaudeAgentSdkQueryRunnerError.message is hardcoded at ClaudeAdapterV2.ts:279-280 and makeProviderFailure (ProviderFailure.ts:97-100) reads exactly that getter, dropping the Schema.Defect cause; the real cause only reaches an ephemeral Effect.logWarning. Other adapters (e.g. OpenCodeAdapterV2.ts:2202) propagate real detail, so this is an unintended gap, not design \u2014 finding stands at medium since the failure is user-visible but undebuggable after the fact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "401 authentication error result projected as successful run + plain assistant message",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native result at 2026-07-01T20:56:54.878Z has is_error=true with result 'Failed to authenticate. API Error: 401 Invalid authentication credentials'. Run run:thread:47763f5e-...:ordinal:1 is projected status='completed' (completed_at 20:56:54.916Z) and its provider_turn completed. The error text is user-visible only as a normal assistant_message (turn-item:provider:claudeAgent:native-item:94ed662f-814a-43d7-aad3-92e479b9dfe8, status=completed, type=assistant_message) \u2014 no error item, no failed status, so the run reads as a success.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE run_id='run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:1';\" vs grep -m1 '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 (is_error:true)",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced fully: native result at 20:56:54.878Z has subtype \"success\" with is_error:true and api_error_status:401, yet run ordinal:1 and its provider_turn are projected status=completed, and the error text survives only as a plain completed assistant_message item (94ed662f, itself the SDK's synthetic \"<synthetic>\"-model assistant message). Code confirms this is a gap, not intent: terminalStatusFromResult in ClaudeAdapterV2.ts only inspects message.subtype and the failure payload is attached only for non-\"success\" subtypes; is_error/api_error_status on result messages are never checked. The error text is user-visible via the SDK's synthetic message, but the run's structured status misreports failure as success and the 401 detail is not persisted, so medium severity stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Run 10 failure persisted with generic message only \u2014 no root cause anywhere",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run ordinal:10 failed in 0.5s (requested 22:48:37.674Z, completed 22:48:38.293Z). The only error record is the error turn-item terminal-failure...ordinal%25253A10 with failure {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}. The native log contains no error detail either \u2014 line 6324 (.log.1) shows the outgoing query.open at 22:48:38.086Z using create-style param sessionId:'b896a082-a480-416f-8ffd-c42845e71993' (after the session was closed at 22:41:50), then nothing incoming; the retry run 11 at 22:48:55.300Z used resume:'b896a082...' and succeeded. The actual SDK failure reason was never captured, and the failed open plausibly stems from reopening with sessionId instead of resume. Related: the query.close at 22:41:50 came ~31.8 min after run 9 completed (22:10:01) despite native wakeup activity through 22:38:55 \u2014 consistent with the known idle-session-reaper-vs-wakeup issue.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='error';\" and sed -n '6323,6327p' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Fully reproduced: run ordinal:10 failed in ~0.6s and the only persisted failure anywhere (turn-item event seq 29464) is the generic {class:transport_error, message:'Claude Agent SDK query failed.'}; the native log (.log.1 lines 6324-6325) shows query.open at 22:48:38.086Z with create-style sessionId after the 22:41:50 query.close, no incoming lines, then a successful resume-based retry at 22:48:55. The genericness is by construction: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:279-281) hardcodes its .message getter, defeating makeProviderFailure's cause.message extraction (ProviderFailure.ts), whose redaction/4096-char bounding shows real messages were intended to flow through. Even the fallback Effect.logWarning (server-child.log:457) collapsed the cause to '[Object]', so the root cause is unrecoverable from every persisted artifact \u2014 a real error-handling gap, though user-visibly surfaced and recovered by retry, so medium stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Runs 11-13 projected as 'completed' although native result had is_error:true (API 529 Overloaded)",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native results in log.2: [2026-07-02T00:51:30.884Z], [00:55:19.085Z], [01:00:28.143Z] all 'subtype':'success','is_error':true,'num_turns':1 (preceded by 29 api_retry 'overloaded' events and one model_refusal_fallback at 00:51:30.857Z). Projections: runs ordinal 11/12/13 status 'completed', provider_turns 'completed'. The only user-visible signal is that the SDK emitted the error text as an assistant message (turn-item:provider:claudeAgent:native-item:9c0cead6-f253-44c8-8cc7-3c95b58a326e, run 13, text 'API Error: 529 Overloaded...'; run 11 item text 'API Error: Overloaded'). Run/attempt/turn statuses do not reflect the failure, so downstream logic treating these runs as successful is wrong.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT run_id,status FROM orchestration_v2_projection_runs WHERE run_id LIKE '%ea84f015%ordinal:1_' \" vs grep '\"is_error\":true' ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2",
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Evidence fully reproduces: log.2 has three decoded results with subtype 'success' but is_error:true (00:51:30.884Z 'API Error: Overloaded', 00:55:19.085Z api_error_status:529, 01:00:28.143Z), while runs ordinal 11/12/13 and their provider_turns project as 'completed' with matching completed_at timestamps, and the only trace is the error text projected as a completed assistant_message (item 9c0cead6-... on run 13). Code confirms the gap: terminalStatusFromResult in ClaudeAdapterV2.ts returns 'completed' for any subtype==='success' and attaches a failure payload only for non-success subtypes, even though the SDK's SDKResultSuccess type explicitly carries is_error and api_error_status \u2014 the signal is typed and available but ignored, so this is a real mapping bug, not intended behavior. Severity stays medium: the error is user-visible as assistant text, but structured run/attempt/turn statuses misreport success and the 529 detail is not queryable, which misleads any downstream logic."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Native ground truth for most of the session destroyed by rotation of the opener thread's log",
|
||||
"category": "lost-data",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Because codex traffic shares 71e29ba5's high-churn log (10 files x 10MB), the oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z. Everything earlier is deleted: c878541b runs 1-3 (01:54-15:58Z), all of de5f191a runs 1-3 (07:42-15:49Z), all of 68f7595b (05:53-05:56Z) and af66fc2c incl. its interrupted run (05:52-05:53Z). Only c878541b runs 4-6 (16:00-16:44Z) retain native logs. Consequence of the finding above; debuggability loss only \u2014 projections for the lost window exist and are internally consistent.",
|
||||
"repro": "for f in ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log*; do head -1 \"$f\" | cut -c2-25; done # earliest = 2026-07-01T16:00:59.024Z",
|
||||
"sessionKey": "codex-no-native-logs",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "low",
|
||||
"reasoning": "Evidence fully reproduces: oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z; DB run windows confirm c878541b runs 1-3, all of de5f191a/68f7595b/af66fc2c predate it; native item ids from c878541b run 1 (msg_024da2f2..., call_z8cGFhrA...) appear in zero log files while run 4's msg_0e493c0caf68... appears 82x in .log.10, and no dedicated logs exist for the codex threads because CodexAdapterV2's protocol logger is keyed to the shared session's opener thread. Downgraded to low: the loss is a by-design consequence of intentional bounded rotation (10x10MB in EventNdjsonLogger.ts), the durable pipeline record (events + projections) for the lost window is intact and consistent, and the actual defect (codex traffic sharing a high-churn foreign thread's rotation budget) is the parent finding this one merely derives from."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Terminal-failure error items carry only generic message ('Claude Agent SDK query failed.'), underlying cause not preserved",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 4 failed runs (37, 54 codex; 89, 119 claudeAgent) DO get a user-visible type='error' item (good surfacing), but payload is generic: run 119 item failure = {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}, title 'Provider error'. The native log at both claude failure sites (2026-07-02T04:47:07.200Z and 16:45:25.921Z) shows only outgoing query.open/prompt.offer with no captured error line, so neither projection nor provider log retains the actual failure reason \u2014 undebuggable after the fact.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure'), json_extract(payload_json,'$.title') FROM orchestration_v2_projection_turn_items WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND type='error'\"",
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced fully: claudeAgent failed runs 89/119 project only {class:'transport_error', message:'Claude Agent SDK query failed.', code:null} (event seq 43072), and the provider log at both failure sites (04:47:07.200Z log.2:790, 16:45:25.921Z log:3026) shows only outgoing query.open/prompt.offer with no error line. Source confirms the mechanism: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:280) hardcodes its message getter while the real error lives in its cause Defect, which makeProviderFailure (ProviderFailure.ts:90) never unwraps \u2014 defeating the redaction/bounding machinery built to carry real messages (codex failures on this same thread DO carry specific messages, proving intent). The adapter's Effect.logWarning with the full cause was not found in any retained server trace log, so the failure reason is genuinely lost; medium severity stands since errors are surfaced but undebuggable."
|
||||
}
|
||||
}
|
||||
],
|
||||
"refuted": [
|
||||
{
|
||||
"title": "Orchestrator ingestion gap 16:10-16:40 Jul 1 (codex era): 119 native command/fileChange items lost; assistant messages backfilled with flattened timestamps",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Zero orchestration_events for the stream between 2026-07-01T16:10:19 (run 50 completed) and 16:40:12 (run 51 requested), yet the native codex log shows substantive work in that window and around it: item/started fileChange items and commandExecutions incl. 'vp test .../OrchestratorReplayFixtures', 'vp check', 'git add apps/server/src/orchestration-v2/Adapters/Claude...' (call_0j3Wjk1K3an2l1CpCRgYBp8b 16:43:43) and 'git push origin t3code/codex-turn-mapping' (call_Hc9NQMOiQ9wo3by6RnzGbShQ 16:43:50), all with source 'unifiedExecStartup' on native thread 019f1b62-f532-79e2-9553-af817911965c. 119 of 450 native call_ ids have no projected turn_item (comm diff), all first seen 16:01-16:43 Jul 1. When run 51 started, 13 assistant messages (message:provider:codex:native-item:msg_*) were backfilled with IDENTICAL created_at 2026-07-01T16:40:14.821Z describing that missing work, but 0 turn_items have startedAt in 16:11-16:40. Text recovered, tool/file items and real timestamps lost. Mechanism (server down/restart vs codex turn-mapping bug) not fully determinable because logs older than 16:00:59Z were rotated away; loss itself is certain.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND occurred_at BETWEEN '2026-07-01T16:11' AND '2026-07-01T16:39'\" -> 0; SELECT count(*) FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at='2026-07-01T16:40:14.821Z' -> 13",
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"verdict": {
|
||||
"isReal": false,
|
||||
"reasoning": "The \"lost\" work belongs to a different session: the codex provider session is shared, so this thread's log contains other threads' traffic. All gap-window log lines (1322 decoded events, 16:11-16:39) carry threadId 019f1b62-f532-..., which per orchestration_v2_projection_provider_threads is owned by thread c878541b-a832-..., not 71e29ba5 (whose codex nativeThreadRef is 019f1b50-4248-...). Exactly 119 call_ ids in the log belong to 019f1b62 and ALL 119 (including the cited call_0j3Wjk1K3an2l1CpCRgYBp8b and call_Hc9NQMOiQ9wo3by6RnzGbShQ) are projected on thread c878541b; all 62 call_ ids on this thread's own native id are projected on 71e29ba5 (comm diff = 0 both ways). The zero-event window is genuine idle time between run 50 (completed 16:10:19) and run 51 (requested 16:40:12), and the 13 messages at created_at 16:40:14.821Z are run 51's live-streamed assistant messages (e.g. msg_00c4d1e6... streamed at 16:48:38 on threadId 019f1b50) \u2014 every one of the 55 codex runs shows the same pattern of assistant messages sharing created_at = run start, so this is systematic projection behavior, not backfill of lost work."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "All thinking/reasoning blocks dropped for main thread (122 native thinking messages, 0 reasoning items)",
|
||||
"category": "lost-data",
|
||||
"severity": "medium",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains 122 distinct main-thread assistant messages with thinking content blocks plus 646 'thinking_tokens' system events, but the main thread has zero projected reasoning turn-items (the only 2 'reasoning' items in the session are subagent-progress placeholders on the child threads, e.g. turn-item:...task%3Aac08aa451ed54d3f6%3Aprogress). ClaudeAdapterV2.ts only extracts part.type==='text' blocks (line 730: content.flatMap((part) => (part.type === \"text\" ? [part.text] : []))). May be an intentional product choice for claudeAgent, but it means no reasoning is ever visible/persisted for this provider.",
|
||||
"repro": "cat log.1 log | jq 'select(.event.payload.type==\"assistant\" and .event.payload.parent_tool_use_id==null) | select([.event.payload.message.content[]?|select(.type==\"thinking\")]|length>0) | .event.payload.uuid' | sort -u | wc -l # 122, vs SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='reasoning'; -- 0",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": false,
|
||||
"reasoning": "The counts reproduce (155 native thinking blocks, 0 projected reasoning items), but inspection of the actual block contents refutes the lost-data claim: every final thinking block in the native log is {\"thinking\":\"\",\"signature\":\"...\"} and all 593 thinking_delta stream events are {\"thinking\":\"\",\"estimated_tokens\":N} \u2014 the Claude Agent SDK redacted all thinking text at the source for claude-fable-5, so there was never any reasoning content to project. ClaudeAdapterV2.ts:730 extracting only text parts drops nothing user-visible here; projecting these blocks would produce 155 empty reasoning items. The 646 'thinking_tokens' system events are token telemetry, not content."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Failed cursor runs 15/16/17 keep only a generic 'Provider turn failed.' with code:null \u2014 no diagnostic detail persisted",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Error items exist and are user-visible (turn-item:provider:cursor:native-item:terminal-failure%3A...run-abf255cf / run-ceb09abc / run-f5fe7fcf, status failed, ordinals 15000098/16000002/17000002) but failure = {class:'provider_error', message:'Provider turn failed.', code:null, retryable:null}; run and run_attempt payloads contain no error field at all. Native run.completed results (log: 02:05:24.474Z, 02:16:37.138Z, 02:19:07.097Z) carry status:'error' with no message either \u2014 so cursor itself gave nothing \u2014 but available context (result.status, requestId d1cd7f44/55687657/6de8f367, durationMs 2434335/1223/657) was dropped. Run 15 did 40 min of work then errored; runs 16/17 ('continue') died in ~1s each with only 'Provider error' shown.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='ea84f015-e597-4f79-9557-d39b5a895fba' AND type='error'\"",
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"verdict": {
|
||||
"isReal": false,
|
||||
"reasoning": "The evidence reproduces (three failed cursor runs projected with the generic 'Provider turn failed.' failure), but the native log shows cursor's run.completed results carried status:'error' with NO error/message/code field at all, so there was no provider diagnostic to persist. The code path is intentional: CursorAdapterV2 forwards result.error as cause, and makeProviderFailure (ProviderFailure.ts) extracts message/code when supplied, falling back to the tested DEFAULT_PROVIDER_FAILURE_MESSAGE \u2014 including an explicit test asserting arbitrary cause objects are deliberately not serialized. The 'dropped context' claim largely fails: result.status is persisted as failed on item/run/provider_turn, and durationMs is recoverable from the persisted provider_turn startedAt/completedAt (01:24:50.203Z\u219202:05:24.475Z \u2248 2434335ms); only cursor's requestId is unpersisted, which the ProviderFailure contract intentionally omits and which remains in the provider log. This is an upstream cursor SDK limitation plus a possible enhancement (persist requestId), not a pipeline discrepancy.",
|
||||
"adjustedSeverity": "low"
|
||||
}
|
||||
}
|
||||
],
|
||||
"lowUnverified": [
|
||||
{
|
||||
"title": "Interrupt-result turn item references an interrupt-request parent that was never emitted",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "turn_item 'turn-item:run:run%3Athread%3Aea84f015-e597-4f79-9557-d39b5a895fba%3Aordinal%3A15:signal:interrupt-result' (event seq 34176, 2026-07-02T01:24:49.393Z) has parent_item_id '...:signal:interrupt-request' with no matching row/event. Contrast thread af66fc2c-73cd-4c30-bea5-66932ecdba29 where both request (seq 20000) and result (seq 20003) were emitted. Code: makeInterruptResultTurnItem in apps/server/src/orchestration-v2/RunExecutionService.ts (line ~874) unconditionally derives parentItemId from the request id without ensuring that item was emitted; the request emission lives on a separate path in Orchestrator.ts:4422.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, parent_item_id FROM orchestration_v2_projection_turn_items ti WHERE parent_item_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_turn_items p WHERE p.turn_item_id=ti.parent_item_id);\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "Synthesized terminal-failure error item references a provider_turn_id that was never projected",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "turn_item 'turn-item:provider:cursor:native-item:terminal-failure%3A...' on thread 721fc23c-2cf3-42bf-9d84-edd94359dca9 (updated 2026-06-29T21:48:40.703Z) carries providerTurnId 'provider-turn:provider:cursor:native-turn:failed%3Arun-attempt%3A...ordinal%253A2%3Aattempt%3A1' which has no row in orchestration_v2_projection_provider_turns. The run failed 4ms after the outgoing run.start ('what did you just say', log 2026-06-29T21:48:40.699Z) with no incoming response; the synthetic 'failed' turn id was minted for the failure item but the turn itself never projected.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items ti WHERE ti.provider_turn_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_provider_turns p WHERE p.provider_turn_id=ti.provider_turn_id);\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "provider_sessions stay status='ready' after provider-session.detached (projection ignores detach)",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Session provider-session:...claudeAgent:thread:47763f5e...:1c70abe8-4ecb-... got provider-session.detached event seq 31344 (2026-07-01T23:44:29.976Z, reason 'Thread archived.') and session ...ea84f015...:21ed85a2-... got detached seq 32566 (2026-07-02T01:03:00.273Z), yet both projection rows still show status='ready' with stale updated_at (22:48:37 / 22:12:31 \u2014 predating even later provider-session.updated events like seq 31274 at 23:42:43). The 16 'stopped' sessions were transitioned via updated events; detach alone leaves rows 'ready' indefinitely on archived threads.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT s.provider_session_id, s.status, s.updated_at FROM orchestration_v2_projection_provider_sessions s WHERE s.status='ready' AND EXISTS (SELECT 1 FROM orchestration_events e WHERE e.event_type='provider-session.detached' AND e.payload_json LIKE '%'||s.provider_session_id||'%');\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "13 backgrounded local_bash tasks projected as subagents with empty prompts and synthetic child threads",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Thread 7f1dfff1-4cbb-450b-8514-764d11c903e1 run 2 (2026-07-01T15:51): tasks bw28jiyac, bzmkw8629, bnkw62tp7, etc. are task_type 'local_bash' in the native log (task_started has only a 'description' like 'vp run --filter @t3tools/web typecheck...', no prompt), yet each got a subagent row (prompt length 0), a child thread, and a user_message prompt item with text ''. Newer local_agent tasks (a-prefixed 16-hex ids) capture full prompts (1.9k-4.3k chars). Predates the backgrounded-Bash redesign on t3code/codex-turn-mapping where local_bash stays a running Bash item completed cross-run; these are stale artifacts of the old mapping, not current behavior.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE type='user_message' AND coalesce(json_extract(payload_json,'$.text'),'')='';\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "Cursor stream stall: abandoned partial-tool-call finalized as 'completed'; provider retry duplicated assistant text",
|
||||
"category": "duplicate",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Thread ea84f015 run 15: partial-tool-call toolu_01HgLigck78NC9MSVyjitDXe (edit) at log 2026-07-02T01:54:20.622Z never received tool-call-started/completed (stream stalled 6.5 min, cursor retried at 02:00:47 with new callId toolu_01NkWmCzHTn5ofjtYi4NkhsJ); the abandoned call's item 'turn-item:provider:cursor:native-item:toolu_01HgLigck78NC9MSVyjitDXe' (type file_change) was finalized status='completed' at run end (02:05:24.475Z) though the edit never executed. The retry also re-emitted identical assistant text ('Now the `WorkGroupSection` filter and the `SimpleWorkEntryRow` indicator.') producing items ...abf255cf...%3A6 (ordinal 15000077) and %3A7 (15000079) with duplicate visible text \u2014 faithful to two native text-delta emissions (log 01:54:19.813Z and 02:00:47.715Z), so provider-side, but rendered twice to the user.",
|
||||
"repro": "grep -a 'SimpleWorkEntryRow\\` indicator' ~/.t3/userdata-v2/logs/provider/ea84f015-e597-4f79-9557-d39b5a895fba.log | cut -c1-30",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "provider_turn status has no 'waiting' literal during ScheduleWakeup sleep loops",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Known issue per assignment; currently only 1 provider_turn 'running' (thread 71e29ba5, started 2026-07-02T17:03:04.470Z \u2014 genuinely live at audit time 17:07Z), so no stale instance observed in this pass, but the schema/status distribution confirms no 'waiting' state exists (statuses seen: cancelled/completed/failed/interrupted/running).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, count(*) FROM orchestration_v2_projection_provider_turns GROUP BY status;\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "Codex reasoning items never ingested (no content lost in this session: all summaries empty)",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains 5 reasoning item/completed events (e.g. rs_0cfa4cea83165175016a40a8e17de08199a84ec646c88a40cd run 2, rs_0cfa4cea...8c48/9052/9329 run 4), all with summary: []. SQL: 0 orchestration_events on stream a5a643b2-... with payload LIKE '%native-item:rs_%', and 0 turn_items of reasoning type with a codex provider_thread anywhere in the DB (172 reasoning items exist for other providers). CodexAdapterV2.ts has no reasoning item mapping (grep hits only 'reasoningEffort' config). With empty summaries nothing user-visible was lost here, and dropping empty reasoning may be intentional, but non-empty reasoning summaries would be silently dropped.",
|
||||
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/a5a643b2-6ca8-4250-9c54-ddefe7d55565.log | jq -c 'select(.event.stage==\"decoded\") | .event.payload | select(.method==\"item/completed\" and .params.item.type==\"reasoning\")' | wc -l # 5, vs sqlite count 0",
|
||||
"sessionKey": "a5a643b2-codex-heya"
|
||||
},
|
||||
{
|
||||
"title": "Codex reasoning items are silently dropped by CodexAdapterV2 (no handler for item type \"reasoning\")",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log emits item/started + item/completed for reasoning item rs_056ea93bc8adc0f3016a42c0594d788194ad4afb537a0a0b16 at 2026-06-29T18:58:33.314Z/33.340Z (turn 019f14bf-4440-7bb0-9655-7194b384e690), but zero rows in orchestration_events reference it and no turn_item exists. Code confirms: CodexAdapterV2.ts item/started (line 2802) and item/completed (line 2875) handlers cover userMessage, subAgentActivity, commandExecution, mcpToolCall/dynamicToolCall, fileChange, webSearch, plan, collabAgentToolCall, agentMessage \u2014 no \"reasoning\" branch and no item/reasoning delta handler, despite capabilities declaring streamsReasoning: true (line 139). In THIS session the item had empty summary/content so no user-visible text was lost, hence severity low \u2014 but any non-empty reasoning summary would vanish.",
|
||||
"repro": "grep 'rs_056ea93bc8adc0f3' ~/.t3/userdata-v2/logs/provider/a61e9269-0180-4f4c-988a-aca00b240469.log ; sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%rs_056ea93bc8adc0f3%'\" -- returns 0",
|
||||
"sessionKey": "a61e9269-codex"
|
||||
},
|
||||
{
|
||||
"title": "thread/tokenUsage/updated and account/rateLimits/updated notifications never ingested; runs have no usage data",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains 5 thread/tokenUsage/updated and 5 account/rateLimits/updated decoded notifications; CodexAdapterV2.ts registers no handler for either (only item/agentMessage/delta, item/plan/delta, turn/plan/updated, turn/started, item/started, item/completed, turn/completed at lines 2693-3395). Runs projection payload has usage:null for both run:thread:a61e9269-0180-4f4c-988a-aca00b240469:ordinal:1 and :2, and no orchestration_events row carries token usage. May be intentional scope, but per-turn token accounting from the provider is discarded.",
|
||||
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/a61e9269-0180-4f4c-988a-aca00b240469.log | jq -r 'select(.event.stage==\"decoded\") | .event.payload.method' | grep -c tokenUsage",
|
||||
"sessionKey": "a61e9269-codex"
|
||||
},
|
||||
{
|
||||
"title": "Child task threads projecting only 2 items is intended, not data loss",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Each child stream (e.g. ...composer_call_kFjs8) has exactly 2 distinct turn-item ids across its 2711 events: ...%3Aprompt (user_message, 1 event) and ...%3Aresult (assistant_message, 1352 events growing text 4->6274 chars). Grok's ACP Task envelope only exposes rawInput.prompt plus streamed output text (apps/server/src/provider/acp/XAiAcpExtension.ts extractXAiAcpSubagentUpdate / xAiTaskOutputText), and the child's intermediate narration is contained in the streamed result text ('I'll read the connection files...'). Parent subagent items' result lengths (3721/6274/2647) exactly equal child assistant_message text lengths \u2014 nothing truncated.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.id'), COUNT(*), MAX(length(json_extract(payload_json,'$.text'))) FROM orchestration_events WHERE stream_id LIKE '%composer_call_kFjs8' AND event_type='turn-item.updated' GROUP BY 1;\"",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Every successful grok turn logs session/prompt as failed with errorTag Interrupt",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log events ec0b4762-8c1d-41c9-b4b3-2687da09d40b (2026-06-29T21:46:13.448Z) and 5a4a5b58-40ad-4f71-b2de-6e703e0c9173 (21:47:37.827Z): payload {method:'session/prompt',status:'failed',errorTag:'Interrupt'} \u2014 yet both runs completed successfully (run ordinal 1 completedAt 21:46:13.476Z, ordinal 2 completedAt 21:47:38.686Z). Cause: XAiAcpExtension races the direct prompt request against the private _x.ai/session/prompt_complete fallback; the losing fiber is interrupted and logged as a failed request. Correctly NOT surfaced as a user-visible error (nothing to surface), but the 'failed' log entries are misleading noise for future debugging.",
|
||||
"repro": "grep '\"status\":\"failed\"' ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Grok native log redacts all payload content, limiting ground-truth audits",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 3694 protocol lines in ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log carry only shape summaries, e.g. payload {valueType:'string',byteLength:165} or {valueType:'array',itemCount:1} \u2014 no message text, tool names, or ids. Content-level loss/truncation verification against the provider is impossible from this log; verification here relied on internal consistency (event max text length == projection text length). If other providers' logs contain full JSON, grok's redaction is an inconsistency worth knowing about.",
|
||||
"repro": "grep -c 'byteLength' ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Child task thread items carry null run_id/provider_thread_id/provider_turn_id",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 6 child items have runId=null, providerThreadId=null, providerTurnId=null (e.g. turn-item ...composer_call_Olv1X%3Aprompt payload: runId:null, nodeId:'node:...%3Achild-root', creationSource:'provider'); child threads have zero run.created / provider-turn events. node_id resolves (child-root nodes exist) and the subagents projection links parent node -> child_thread_id, so navigation works via subagents rather than runs. Appears intentional for provider-native task children (no orchestrator run exists), but any consumer that groups items by run_id will see these as orphans.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, run_id, provider_turn_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:grok:native-thread:019f1558%';\"",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "run_attempts.provider_turn_id is never populated (null for all 207 attempts DB-wide) \u2014 back-link from attempt to provider turn missing",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "This session: run-attempt:run:run%3Athread%3A721fc23c...%3Aordinal%3A1:attempt:1 has providerTurnId:null although provider-turn:provider:cursor:native-turn:run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 references that exact runAttemptId (forward link intact, nativeTurnRef strong). Global check: SELECT provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1 shows every row (completed 188, failed 12, cancelled 4, interrupted 1, running 1, superseded 1) has NULL \u2014 the column/payload field exists but nothing ever writes it. Forward resolution via provider_turns.run_attempt_id works, so impact is limited to reverse-lookup ergonomics; may be intentional but the schema advertises the field.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1,2\"",
|
||||
"sessionKey": "721fc23c-cursor"
|
||||
},
|
||||
{
|
||||
"title": "Run orphaned by server restart is cancelled with no user-visible or persisted reason; user's message got no response",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log ends at run.started 2026-06-29T21:49:09.097Z (runId run-f062e5d9-534a-48a8-8214-48fea97bc268) with zero assistant output. Events seq 6341-6346 (command:runtime-reconcile:startup:48663fb7-...:2026-06-29T21:49:10.775Z) set run:thread:48663fb7-...:ordinal:1, its attempt, and provider-turn:provider:cursor:native-turn:run-f062e5d9-... to status 'cancelled' with no reason field in any payload, indistinguishable from a user cancel. No error/system turn_item was emitted, so the timeline shows only the user 'hello' and 'Workspace ready' with nothing explaining the missing reply. Source: ProviderRuntimeRecoveryService.ts:107 builds detail 'Cancelled because the server restarted before the provider work completed.' but attaches it only to runtime-request payloads and outbox effect cancellations (lines 291/316), never to run/attempt/turn/item rows \u2014 intentional code path, but a debuggability/UX gap.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, payload_json FROM orchestration_events WHERE stream_id='48663fb7-fbd6-4be2-ad14-d8163282c069' AND command_id LIKE 'command:runtime-reconcile:%'\" \u2014 note status 'cancelled' payloads contain no reason; and grep -c NTIVE ~/.t3/userdata-v2/logs/provider/48663fb7-fbd6-4be2-ad14-d8163282c069.log shows only 4 lines with no assistant output.",
|
||||
"sessionKey": "48663fb7-cursor"
|
||||
},
|
||||
{
|
||||
"title": "file_search items never carry results (read/grep/glob outputs dropped) despite contract supporting them",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 117 file_search items across the 5 opencode child threads have results=NULL (contract OrchestrationV2FileSearchResult array at orchestrationV2.ts:843 is never populated by OpenCodeAdapterV2 \u2014 its file_search branch emits only 'pattern'). Example: prt_f15688536002X4CTVKyjMIxGfL (ses_0ea978228, ordinal 3) has only pattern '/Users/julius/Development/Work/codething-mvp'. Tool outputs (file contents read, matches found) exist in opencode's part.state.output but are discarded for this item type. Likely intentional UI minimalism, but it is provider-emitted content with no projection.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*), SUM(json_extract(payload_json,'$.results') IS NOT NULL) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:opencode:native-thread:ses_%' AND type='file_search';\" -- returns 117|0",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Placeholder 'pending' provider_thread row persists alongside the real one; orchestrator-synthesized items split across the two",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Main thread has TWO provider_thread rows: provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A3029dc85...%3Aordinal%3A1 (status idle, first/last run ordinals 1-7) and the real provider-thread:provider:opencode:native-thread:ses_0ea983868ffens4ayJQLKgPE6J (idle, 1-7). 20 items (7 user_message, 7 checkpoint, 3 thread_created, 2 delegated subagent, 1 command_execution) still reference the pending placeholder while all native items reference ses_0ea983868 \u2014 e.g. thread_created item turn-item:created-thread:...126456a2...%3A0 has providerThreadId '...pending%3Arun%3A...ordinal%3A1' but providerTurnId pointing at the real session ses_0ea983868. Lineage is queryable but split; the placeholder was never collapsed after the native session id was learned.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id, status, first_run_ordinal, last_run_ordinal FROM orchestration_v2_projection_provider_threads WHERE thread_id='3029dc85-93b7-43c5-8993-1beff41b1c98';\"",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Single occurred_at inversion on main stream (checkpoint capture vs concurrent subagent-result handoff)",
|
||||
"category": "ordering",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Stream 3029dc85...: stream_version 1868 (sequence 10004, checkpoint.captured, occurred_at 2026-06-29T22:09:54.344Z, checkpoint root:name:5 for run 5) was appended AFTER stream_versions 1863-1867 (sequences 9881-9885, delegated subagent d43de13f completion + context-handoff/transfer, occurred_at 22:09:54.779Z) \u2014 occurred_at goes backwards by 435ms. Benign concurrency between run-5 completion checkpointing and the delegated claudeAgent subagent result handoff landing; projection ordinals unaffected (0 ordinal inversions vs first-seen event order across all 6 threads).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT stream_version, sequence, event_type, occurred_at FROM (SELECT stream_version, sequence, event_type, occurred_at, LAG(occurred_at) OVER (ORDER BY stream_version) prev FROM orchestration_events WHERE stream_id='3029dc85-93b7-43c5-8993-1beff41b1c98') WHERE occurred_at < prev;\"",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Native provider log payloads are fully redacted (valueType/fieldCount only), preventing content-level loss auditing",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Every one of the 17,198 log lines in 3029dc85-93b7-43c5-8993-1beff41b1c98.log(.1) has kind='protocol' with inner payload reduced to {valueType:'object', fieldCount:N} \u2014 e.g. message.part.updated lines carry no part id, text, or error. Only method-level counts are auditable (15,542 message.part.delta, 723 message.part.updated, 204 message.updated, 7 session.promptAsync, 5 session.created, 12 session.idle). Method counts DO reconcile with projections (7 promptAsync = 7 runs; 5 session.created = 5 child threads; 12 session.idle = 7 main turns + 5 child turns), but text truncation and the actual error string of the failed file_search cannot be verified against the wire. If these logs are meant to be 'ground truth', the opencode SSE logger is not recording decoded payloads.",
|
||||
"repro": "grep -h '\"message.part.updated\"' ~/.t3/userdata-v2/logs/provider/3029dc85-93b7-43c5-8993-1beff41b1c98.log.1 | head -1",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Split provider-thread identity: run/attempt/provider_turn reference the pending-keyed provider-thread row while turn items and threads.active_provider_thread_id reference the ses_-keyed row",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Two rows in orchestration_v2_projection_provider_threads for the same native session: 'provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A9f8d616d-...%3Aordinal%3A1' and 'provider-thread:provider:opencode:native-thread:ses_0ea7ea5deffe0eNd8RbfyTfgAw' (both idle, same provider_session_id, and the pending row's payload has nativeThreadRef.nativeId=ses_0ea7ea5deffe0eNd8RbfyTfgAw strength strong). projection_runs.provider_thread_id, run_attempts.provider_thread_id and provider_turns.provider_thread_id all point at the pending-keyed row, while the two provider-part turn_items (prt_f158168eb001r0Ubqqry5Z31Q1, prt_f158169d0002CgOsT8eNRkPGI3) and threads.active_provider_thread_id point at the ses_-keyed row. Notably provider_turns row provider-turn:...ses_0ea7ea5deffe0eNd8RbfyTfgAw%3Aattempt... encodes ses_ in its own id but its provider_thread_id column is the pending row. Pending id minted in Orchestrator.ts (`nativeThreadId: \\`pending:${runId}\\``, lines 2384/2772); the pending row is resolved via nativeThreadRef rather than rebinding downstream rows, so joins on provider_thread_id split the turn across two ids.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id FROM orchestration_v2_projection_provider_turns WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3'; SELECT DISTINCT provider_thread_id FROM orchestration_v2_projection_turn_items WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3';\"",
|
||||
"sessionKey": "9f8d616d-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Real provider-thread row stayed status 'active' for ~20h after the provider session stopped",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "provider-session.updated seq 13792 marks session stopped at 2026-06-29T23:00:38.028Z (idle reaper ~30min after last activity 22:30:30; last native log line heartbeat 2026-06-29T23:00:27.024Z). The pending-keyed provider-thread went idle at turn completion (seq 13783, 22:30:30.877Z), but the ses_0ea7ea5deffe0eNd8RbfyTfgAw provider-thread's last status update before shutdown was 'active' (seq 13779, 22:30:30.876Z) and it was only flipped to idle by seq 13797 at 2026-06-30T18:59:15.308Z, ~20h later (presumably on next app start). During that window the projection showed an active provider-thread bound to a stopped session. Eventually reconciled; final state is consistent.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.id'), json_extract(payload_json,'$.status') FROM orchestration_events WHERE stream_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3' AND event_type IN ('provider-thread.updated','provider-session.updated') ORDER BY sequence\"",
|
||||
"sessionKey": "9f8d616d-opencode"
|
||||
},
|
||||
{
|
||||
"title": "OpenCode native log payloads are redacted to shape summaries, preventing content-level ground-truth verification",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Every one of the 273 lines in 9f8d616d-86ee-4560-bd52-2387d6adb1c3.log is kind 'protocol' (opencode-sdk.sse) with payload reduced to e.g. {\"payload\":{\"valueType\":\"object\",\"fieldCount\":3}} \u2014 no message text, part ids, or tool args (contrast with claude logs which carry full decoded JSON). Only method names/counts are auditable: 31 message.part.delta, 7 message.part.updated, 6 message.updated, 1 session.idle, 0 session.error. Projected content was spot-checked instead and looks sensible and un-truncated (user 'hey'; reasoning 'The user is just saying \"hey\" - a casual greeting...'; assistant 'Hey! What can I help you with?').",
|
||||
"repro": "sed -E 's/^\\[[^]]+\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/9f8d616d-86ee-4560-bd52-2387d6adb1c3.log | jq -r '[.event.payload.direction,.event.payload.method]|@tsv' | sort | uniq -c",
|
||||
"sessionKey": "9f8d616d-opencode"
|
||||
},
|
||||
{
|
||||
"title": "run_attempt.provider_turn_id never populated (null on all 207 attempts DB-wide)",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "run-attempt row run-attempt:...ordinal%3A1:attempt:1 has providerTurnId:null in payload_json and empty provider_turn_id column, while the provider_turn row correctly back-references runAttemptId. DB-wide: SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts \u2192 207|0. Forward lineage attempt\u2192turn is only recoverable by scanning provider_turns; may be intentional (reverse-only linkage) but the column exists and is never filled.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts;\"",
|
||||
"sessionKey": "1156181e-delegated-task"
|
||||
},
|
||||
{
|
||||
"title": "Provider session stayed 'running' ~25h after turn ended; only reconciled to 'stopped' at server shutdown",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": true,
|
||||
"evidence": "Turn completed 2026-06-28T05:22:33.360Z (last native log line); no further session events until sequence 168 provider-session.updated at 2026-06-29T06:33:36.481Z via command:runtime-reconcile:shutdown, which set status=stopped. No provider-session.detached was ever emitted for this thread. Related to the known idle-session-reaper/session-lifecycle area; state is correct now, so no data impact, but the projection reported a live session for a day for a one-shot delegated task.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, occurred_at FROM orchestration_events WHERE stream_id LIKE '%1156181e%' AND event_type LIKE 'provider-session%' ORDER BY sequence;\"",
|
||||
"sessionKey": "1156181e-delegated-task"
|
||||
},
|
||||
{
|
||||
"title": "claudeAgent provider sessions never idle-reaped; stayed 'ready' ~21 hours until simultaneous shutdown sweep",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "codex session stopped 2026-06-29T22:39:55 (seq 13789, 30 min after its 22:09:55 failure) and grok stopped 22:41:44 (seq 13790, 30 min after 22:11:44 completion) \u2014 idle reaper working. But all 3 claudeAgent sessions (last activity 22:08:48 / 22:09:50 / 22:13:07 on 6/29) only transitioned ready->stopped at 2026-06-30T18:59:15.286/.289/.291 (seq 13793-13795), simultaneously, ~21h later \u2014 a shutdown sweep, not the 30-min reaper. Native logs show no claude activity after 22:13, so either processes lingered or projections misreported 'ready' for a day. Inverse of the known 'reaper kills long sleeps' issue: reaper never fired for claudeAgent.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.status') FROM orchestration_events WHERE event_type LIKE 'provider-session%' AND stream_id LIKE '%6d618dc4%' ORDER BY sequence;\"",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Codex model-rejection error fully preserved and user-visible (works as intended)",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log 22:09:55.424 method 'error' / turn/completed status failed with message 'The gpt-5.3-codex model is not supported when using Codex with a ChatGPT account' (400 invalid_request_error). Projection: turn_item turn-item:provider:codex:native-item:terminal-failure%3A...019f156e-851a... type=error status=failed carries the verbatim JSON error in failure.message; run/run_attempt/provider_turn all 'failed'. No swallowing \u2014 this is a positive verification, listed for completeness.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE turn_item_id LIKE '%terminal-failure%019f156e-851a%';\"",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Grok session/prompt request ends with errorTag 'Interrupt' at the instant the turn completes",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "low",
|
||||
"knownIssue": false,
|
||||
"evidence": "Log 2026-06-29T22:11:44.909Z: {method:'session/prompt',status:'failed',errorTag:'Interrupt'} while provider_turn 019f156e-797f...:turn:1 completedAt 22:11:44.910 status=completed and the 6663-char assistant report is fully projected (item ordinal 1000074). Likely adapter-initiated interrupt cleanup after observing turn completion (grok capabilities: supportsSteeringByInterruptRestart=true); no data lost, but a native 'failed' prompt request maps to a 'completed' turn, which could confuse future debugging.",
|
||||
"repro": "grep '\"method\":\"session/prompt\",\"status\":\"failed\"' ~/.t3/userdata-v2/logs/provider/thread-mcp-6d618dc4-25fd-453b-9193-fd22a6739d1f-126456a2-f1ff-4098-a0a0-fde04bb1.log",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Grok file_search/read items persist only pattern + fileName echo, no tool output; grok native log fully redacted",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "low",
|
||||
"knownIssue": false,
|
||||
"evidence": "49 file_search items on thread :1 store e.g. pattern='pnpm-workspace.yaml', results=[{'fileName':'pnpm-workspace.yaml'}] (item turn-item:provider:grok:native-item:...call-e4489e09-...-1, ordinal 1000004) \u2014 the file content the tool returned is not kept, unlike claudeAgent command items which keep full stdout envelopes. Additionally the grok log redacts all decoded payloads to shape summaries ({'valueType':'array','itemCount':1}), so native-vs-projection content verification is impossible for grok; command_execution and reasoning items do carry real content, so this may be an intentional thin mapping for read-style tools.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.pattern'), json_extract(payload_json,'$.results') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:1' AND type='file_search' LIMIT 5;\"",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Both session/prompt requests logged as failed with errorTag=Interrupt despite runs completing",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log request events: session/prompt started 01:51:45.517 -> failed errorTag=Interrupt at 01:52:13.249; session/prompt started 01:53:00.071 -> failed errorTag=Interrupt at 01:53:37.665. These timestamps exactly equal provider_turn completed_at values (turn 1: 01:52:13.249, turn 2: 01:53:37.665), and both runs/turns/items project as completed with full assistant content, so this appears to be intentional adapter teardown (interrupting the pending ACP prompt fiber once the turn result is reached; grok sets interruptPromptOnCancel:false in GrokAdapterV2.ts line 90/641). No content was lost and no spurious failure surfaced, but the log-level 'failed' status for successful turns will mislead debugging.",
|
||||
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/5dcea72d-15e1-4ded-922b-0b00c587de6c.log | jq -c 'select(.event.kind==\"request\" and .event.payload.method==\"session/prompt\")'",
|
||||
"sessionKey": "5dcea72d-grok-subagent"
|
||||
},
|
||||
{
|
||||
"title": "run_attempts.provider_turn_id never populated (reverse link only)",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Both attempts for this session (run-attempt:run:run%3Athread%3A5dcea72d...ordinal%3A1:attempt:1 and ...ordinal%3A2:attempt:1) have provider_turn_id NULL in both the column and payload_json; DB-wide, 0 of all rows in orchestration_v2_projection_run_attempts have a non-NULL provider_turn_id. Lineage is still resolvable via orchestration_v2_projection_provider_turns.run_attempt_id (both turns correctly reference their attempts), so this may be an intentionally unused column, but the forward link is dead.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_v2_projection_run_attempts WHERE provider_turn_id IS NOT NULL;\"",
|
||||
"sessionKey": "5dcea72d-grok-subagent"
|
||||
},
|
||||
{
|
||||
"title": "Backgrounded-bash child threads have empty-text prompt user_message items",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 13 backgrounded-bash child threads project a user_message item task%3A<id>%3Aprompt with text:\"\" (e.g. turn-item:provider:claudeAgent:native-item:task%3Abw28jiyac%3Aprompt, startedAt 2026-07-01T15:51:26.160Z), even though the native task_started event carried description \"vp run --filter @t3tools/web typecheck 2>&1 | tail...\". The command is still user-visible via the main-thread subagent item title, so impact is cosmetic (empty bubble if the child thread is opened).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%7f1dfff1%' AND type='user_message' AND json_extract(payload_json,'$.text')='';\"",
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Codex run 1 (169 items) has no surviving native log to verify against",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run ordinal 1 (codex, 2026-07-01T01:45:03Z\u201302:01:10Z, 169 items incl. 10 failed command_executions) predates the oldest surviving log rotation: 7f1dfff1-...log.1 first line is 2026-07-01T15:48:00.224Z (run 2). The codex portion of the log was rotated away, so item-level loss/ordering for run 1 could not be ground-truthed; its events/projections are internally consistent (contiguous ordinals 1000001-1000169, all terminal).",
|
||||
"repro": "head -1 ~/.t3/userdata-v2/logs/provider/7f1dfff1-4cbb-450b-8514-764d11c903e1.log.1",
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Provider session projection stuck at status 'ready' after detach/archive",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "provider-session.detached event at 2026-07-01T23:44:29.976Z (reason 'Thread archived.') for provider-session:...:1c70abe8-4ecb-43f8-8ee6-9ce19beddcfe, but the orchestration_v2_projection_provider_sessions row still shows status='ready' with updated_at=2026-07-01T22:48:37.724Z and thread_id still bound. The event stream also shows the session flip stopped\u2192ready correctly at 22:41:50/22:48:37, so the projection simply never reflects the final detached/terminated state.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, updated_at FROM orchestration_v2_projection_provider_sessions WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514';\"",
|
||||
"sessionKey": "47763f5e-claude-fable"
|
||||
},
|
||||
{
|
||||
"title": "Detached claudeAgent provider session left in status 'ready' forever after handoff",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Event seq 32566 provider-session.detached at 2026-07-02T01:03:00.273Z (reason 'Provider or model selection changed.') for provider-session:provider-instance:claudeAgent:thread:ea84f015-...:21ed85a2-2ed1-4bd8-94be-1e5affe1aa72, but the orchestration_v2_projection_provider_sessions row still shows status='ready' \u2014 no stopped update was ever emitted. The replacement cursor session was correctly moved to 'stopped' at 02:49:07 (seq 38639).",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT provider_session_id,status FROM orchestration_v2_projection_provider_sessions WHERE provider_session_id LIKE '%ea84f015%'\"",
|
||||
"sessionKey": "ea84f015-cursor-handoff"
|
||||
},
|
||||
{
|
||||
"title": "Subagent child-thread items have null run_id / provider_thread_id / provider_turn_id",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 34 items of child thread ...a4bd1db1834cb086a and 52 items of ...ab96794f302d5fd03 have runId:null, providerThreadId:null, providerTurnId:null (e.g. turn-item:provider:claudeAgent:native-item:toolu_01L5SAT2nkGMce3gWf3qFFqJ). Lineage back to the parent exists only via orchestration_v2_projection_subagents (child_thread_id set, run_id = parent runs ordinal 2 and 5, both completed) and the two parent subagent turn items (task%3Aa4bd1db1834cb086a%3Asubagent / task%3Aab96794f302d5fd03%3Asubagent). Likely by design (child threads have no runs of their own), but items cannot be joined to any run/turn directly.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:claudeAgent%ea84f015%' AND run_id IS NULL\"",
|
||||
"sessionKey": "ea84f015-cursor-handoff"
|
||||
},
|
||||
{
|
||||
"title": "error_during_execution result during run 5 coincides with steering message \u2014 absorbed without any projected trace",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "log.3 line 677 [2026-07-01T23:13:24.083Z] result subtype error_during_execution, is_error:true, duration_api_ms 2473149, session 44cbb4c7. A user steering message was ingested 50ms earlier (seq 30447 message.updated 23:13:24.031Z, message 513621d3-5a03-46e1-8fd7-cc4de4b417f1, run 5), so this looks like the intentional interrupt-for-steering path; run 5 continued and completed at 23:30:07 with items after 23:13. No event records the aborted query, which is acceptable if intentional but leaves no audit trail of the abort.",
|
||||
"repro": "grep -n error_during_execution ~/.t3/userdata-v2/logs/provider/ea84f015-e597-4f79-9557-d39b5a895fba.log.3",
|
||||
"sessionKey": "ea84f015-cursor-handoff"
|
||||
},
|
||||
{
|
||||
"title": "5 tool calls that never returned natively were auto-marked 'completed' (with no results) at turn end",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log has 123 distinct tool-call-started but only 118 tool-call-completed; the 5 without completion (tool_e1f3ce39... glob, tool_fd1ba594..., tool_e2f6262c..., tool_840aeaa9... grep, tool_671d1b53... read) are all projected as status 'completed' with completedAt forced to the turn-end timestamp 2026-07-02T02:25:57.991Z and no results payload (e.g. turn-item:provider:cursor:native-item:tool_e1f3ce39-4604-4ced-8039-bbd5e75946b ends with pattern:'**/*' and no results field). This is the intentional finalizeTurn flush (CursorAdapterV2.ts:1886-1889 emitToolArtifacts({completed:true})), but 'completed' misrepresents tools whose results never arrived; something like 'interrupted' or an explicit no-result marker would be more truthful. Minor: cursor itself abandoned these calls, so no user-visible content was lost.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.completedAt') FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_e1f3ce39-4604-4ced-8039-bbd5e75946b';\"",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns"
|
||||
},
|
||||
{
|
||||
"title": "Run 2 was a 7.3-minute silent hang before failing \u2014 nothing projected during the window (faithful to provider, but no progress/heartbeat signal exists)",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log: run.started for run-f4d64e64 at 02:28:07.973Z, next event is run.completed status 'error' at 02:35:28.424Z \u2014 zero interaction.updates in between. Ingested events for the stream in that window: 0 (SELECT COUNT(*) ... occurred_at BETWEEN '02:28:09' AND '02:35:28' returns 0). The pipeline mirrors the provider exactly (nothing lost), but the projection offers no signal distinguishing 'model working' from 'SDK dead due to auth error' during those 440s; the user just saw a running turn that eventually failed generically.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE stream_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND occurred_at > '2026-07-02T02:28:09' AND occurred_at < '2026-07-02T02:35:28';\"",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns"
|
||||
},
|
||||
{
|
||||
"title": "Native 'read' tool calls are projected as type 'file_search'",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "18 native 'read' tool calls (e.g. tool_671d1b53-bb49-46ef-94de-8f682391c93 reading a file path) are projected as type 'file_search' with the file path as 'pattern'. Intentional per CursorAdapterV2.ts:1203-1219 (glob/grep/read/ls/readLints/semSearch all map to file_search), so the content is preserved, but the item type flattens semantically distinct operations (file reads rendered as searches). Cosmetic fidelity note only.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT type FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_671d1b53-bb49-46ef-94de-8f682391c93';\"",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns"
|
||||
},
|
||||
{
|
||||
"title": "Token usage from turn-ended/run.completed is dropped by the ingestion pipeline",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log line 663 (2026-07-02T07:08:07.565Z) turn-ended carries usage {inputTokens:596379, outputTokens:6430, cacheReadTokens:522080}; line 664 run.completed repeats it with totalTokens:1124889. No event for stream_id=8ee00dcc-fa04-4fe7-9920-cd3432d45415 contains 'usage' or 'Tokens' (query returned 0 rows), and neither the run nor provider_turn projection payloads have a usage field. grep for 'usage' in apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts, ProviderEventIngestor.ts and ProviderAdapter.ts returns nothing \u2014 the v2 contract simply doesn't model usage, so this looks like a pipeline-wide design gap rather than a session bug, but users lose per-turn token/cost data.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND payload_json LIKE '%Tokens%';\" (returns 0) vs grep -c 'inputTokens' ~/.t3/userdata-v2/logs/provider/8ee00dcc-fa04-4fe7-9920-cd3432d45415.log (returns 2)",
|
||||
"sessionKey": "8ee00dcc-cursor-spacing"
|
||||
},
|
||||
{
|
||||
"title": "run_attempt.provider_turn_id never backfilled (forward link missing; reverse link intact)",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "orchestration_v2_projection_run_attempts row run-attempt:run:run%3Athread%3A8ee00dcc-fa04-4fe7-9920-cd3432d45415%3Aordinal%3A1:attempt:1 has provider_turn_id='' and payload providerTurnId:null even after completion, while orchestration_v2_projection_provider_turns row provider-turn:provider:cursor:native-turn:run-ee800ef2-cd0e-45bd-9481-65fd5cfdae67 correctly points back via run_attempt_id to that attempt. Lineage is resolvable only in one direction (turn->attempt).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT a.attempt_id, a.provider_turn_id, t.provider_turn_id FROM orchestration_v2_projection_run_attempts a JOIN orchestration_v2_projection_provider_turns t ON t.run_attempt_id=a.attempt_id WHERE a.thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415';\"",
|
||||
"sessionKey": "8ee00dcc-cursor-spacing"
|
||||
},
|
||||
{
|
||||
"title": "file_change diffStr has malformed diff headers (a//abs/path, b//abs/path)",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "turn-item:provider:cursor:native-item:tool_fee434e5-6388-483d-82f1-9e6c6ab418c (ordinal 1000042) payload diffStr begins '--- a//Users/julius/.t3/worktrees/codething-mvp/t3code-3cba2658/apps/mobile/src/features/home/HomeScreen.tsx' \u2014 absolute path concatenated after 'a/' yields double slash and a non-standard diff header; same for the other two file_change items (tool_361abe3b, tool_b586252d). Diff hunk content itself is intact (additions:2 deletions:1 recorded). Cosmetic, but breaks strict unified-diff parsers.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.diffStr'),1,80) FROM orchestration_v2_projection_turn_items WHERE thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND type='file_change';\"",
|
||||
"sessionKey": "8ee00dcc-cursor-spacing"
|
||||
},
|
||||
{
|
||||
"title": "Codex 'reasoning' items are silently dropped (no adapter handler, no projection)",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Surviving log window shows 45 item/started + 45 item/completed reasoning items for native thread 019f1b62-f532 (c878541b runs 4-6), but the projection has 0 reasoning-type turn_items for any of the four threads (types present: assistant_message, command_execution, file_change, user_message, checkpoint, dynamic_tool, run_interrupt_*). CodexAdapterV2.ts item/started / item/completed handlers dispatch on userMessage/commandExecution/mcpToolCall/dynamicToolCall/fileChange/webSearch/plan/collabAgentToolCall/subAgentActivity and fall through for 'reasoning' despite capabilities streamsReasoning:true (line 139). Mitigating: every observed reasoning item had empty summary/content (e.g. rs_0e493c0caf681939016a4539c1c0988193b7174c9c067dfdb2, summary:[], content:[]), so no user-visible text was actually lost in this session.",
|
||||
"repro": "cat ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log.10 | grep '\"decoded\"' | grep '\"item/completed\"' | grep '019f1b62' | grep -c '\"reasoning\"' vs SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='c878541b-a832-4757-a254-5550e3f6c2d1' AND type LIKE '%reason%';",
|
||||
"sessionKey": "codex-no-native-logs"
|
||||
},
|
||||
{
|
||||
"title": "contextCompaction native item has no projection representation",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log shows item/completed contextCompaction id ad331e6d-f971-46a9-a04a-c70a1b86894f on turn 019f1e69-826e-7de2-9200-b6852ff53138 (c878541b run 4, ~16:00-16:05Z); no turn_item, node, or event for it exists (payload_json LIKE '%ompaction%' matches only incidental message text). Users cannot see that context was compacted mid-run. Native item carries only an id (no content), so the informational loss is small.",
|
||||
"repro": "grep 'contextCompaction' ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log.10 | grep 019f1b62",
|
||||
"sessionKey": "codex-no-native-logs"
|
||||
},
|
||||
{
|
||||
"title": "Run 119 marked failed while its native query kept running; retry run 120 adopted the result, leaving a duplicated user message",
|
||||
"category": "duplicate",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run 119 failed at 2026-07-02T16:45:26.143Z (transport_error, ~1.5s after requested_at 16:45:24.618Z), but the native log shows query.open + prompt.offer at 16:45:25.921Z proceeding to SessionStart:resume (16:45:41) and a successful result at 16:47:00.764Z. Retry run 120 (requested 16:45:36.222Z) completed at 16:47:01.354Z with that assistant message (message:provider:claudeAgent:native-item:693d3576-4e56-4c10-9b0f-90ff9825f663, 3190 chars, intact). Two user messages with identical text exist: 9b135da3-dd1b-4a9a-90bc-ee4166bce48d (run 119) and 0f1b1078-74cb-4488-9626-e1ddbe933a9a (run 120) \u2014 timeline shows the prompt twice (plus the error item). Content preserved; cosmetic/duplication issue only.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT message_id, run_id, created_at FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at BETWEEN '2026-07-02T16:45' AND '2026-07-02T16:46'\"",
|
||||
"sessionKey": "71e29ba5-claude-mega"
|
||||
},
|
||||
{
|
||||
"title": "4 native error_during_execution results silently recovered in-adapter with no projection trace",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native results with subtype=error_during_execution/is_error=true at 2026-07-02T01:34:23.046Z, 02:29:30.034Z, 05:08:27.090Z, 17:03:10.206Z fall inside runs 73/80/95/122 \u2014 all completed with a single run attempt and no error item/event. At 01:34:23 the error coincides with an outgoing prompt.offer (mid-stream steering) followed immediately by system init and continued streaming, so the adapter's transparent re-query is likely intentional; but the transient error is invisible to projections (debug info only in provider log).",
|
||||
"repro": "grep -h '\"subtype\":\"error_during_execution\"' ~/.t3/userdata-v2/logs/provider/71e29ba5*.log* | grep '\"stage\":\"decoded\"'",
|
||||
"sessionKey": "71e29ba5-claude-mega"
|
||||
},
|
||||
{
|
||||
"title": "Session has 7 subagent child threads, not 9 as briefed; all 7 fully linked and consistent",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains exactly 7 top-level Agent tool_use spawns (toolu_01CtiEb3..., 01CrTuja..., 01TiUmm..., 01W2SNA..., 01RjCn6..., 017H3QK..., 018VQWh...); projections have 7 type='subagent' items, 7 orchestration_v2_projection_subagents rows all with non-null child_thread_id resolving to existing thread rows, and 7 child-thread event streams (79-260 events each) with items on the correct thread ids (0 items with mismatched threadId). The 2 failed subagents (task%3Aafbafdde..., task%3Aa0e0b5f3..., completed_at 2026-07-02T08:34:33.868Z) match native '[Request interrupted by user for tool use]' is_error tool_results for toolu_017H3QKcEb9FrecsT4tyzg1M / toolu_018VQWhHKSAP1cFkZwZGRGe5 at 08:34:33.867Z \u2014 correct failure surfacing, not a bug.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_subagents WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016'\"",
|
||||
"sessionKey": "71e29ba5-claude-mega"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
# Plan: Orchestration V2 Session Audit Remediation
|
||||
|
||||
## Summary
|
||||
|
||||
A full audit of every v2 orchestrator session in `~/.t3/userdata-v2` (2026-07-02, 18 session
|
||||
groups, ~43k events, ~6.3k projected turn items, all 5 providers) compared native provider logs
|
||||
against ingested events and item projections. Core mechanics are healthy — zero stream_version
|
||||
gaps, zero ordinal collisions, positions table 100% consistent, no duplicate `nativeItemRef`s,
|
||||
no stuck non-terminal state — but 23 verified discrepancies cluster into the workstreams below.
|
||||
|
||||
Every finding was adversarially re-verified against the raw DB/logs and the adapter source.
|
||||
Repro commands are inline. File/line references are as of branch `t3code/codex-turn-mapping`
|
||||
on the audit date; expect drift.
|
||||
|
||||
Status legend: `[ ]` todo · `[~]` in progress · `[x]` done
|
||||
|
||||
## Tracking checklist
|
||||
|
||||
> **Restructure note (2026-07-04):** the PR stack was reorganized to combine with
|
||||
> mwolson's parallel work. Shared continuation plumbing (C0, ea57e97d58) now lives
|
||||
> directly on `t3code/codex-turn-mapping`; Claude session-continuity fixes including
|
||||
> our #1/#15 (+ fixtures `claude_result_is_error`, `claude_idle_resume`,
|
||||
> `advance_clock` step) live in PR #3860; grok/ACP lifecycle (superset of plan #7)
|
||||
> lives in PR #3578; this branch (PR #3677) keeps the remaining audit fixes:
|
||||
> #2 #3 #4 #5 #9 #10 #11 #12. Our turn.wakeup implementation was dropped in favor
|
||||
> of the C0 continuation design.
|
||||
|
||||
|
||||
- [x] 1. Honor `is_error` on Claude SDK results — MOVED to PR #3860 (with fixture claude_result_is_error)
|
||||
- [x] 2. Preserve real failure causes in projected errors (Claude adapter + ProviderFailure)
|
||||
- [x] 3. Preserve cursor failure detail (requestId, durationMs; SDK exposes no error text yet)
|
||||
- [x] 4. Log failure/lifecycle frames in native provider logs (claude + cursor runners)
|
||||
- [x] 5. Surface provider-process crashes / reconcile cancellations to the user
|
||||
- [x] 6. Ingest codex-native collab subagents — already implemented upstream (verified 2026-07-04 on #3908's branch: registerSubagentActivity/registerSubagentThreads handle subAgentActivity + collabAgentToolCall, and the subagent_v2 fixtures replay the exact a5a643b2 loss scenario incl. post-settle child completion, asserting the child's "Hello." result)
|
||||
- [ ] 7. Fix grok/ACP background subagent lifecycle + transcript projection
|
||||
- [x] 8. Invisible post-turn wakeup turns — SUPERSEDED by C0/#3860's provider-continuation design (our turn.wakeup implementation dropped in the restructure)
|
||||
- [x] 9. Route shared-codex-session native logs to the correct thread's file
|
||||
- [x] 10. Coalesce streaming-delta event persistence (~2800x amplification)
|
||||
- [x] 11. Assistant text segments merged without separator (fixed in worktree — add regression fixture)
|
||||
- [x] 12. OpenCode `file_search` items drop error/output
|
||||
- [ ] 13. Low-severity backlog (see section)
|
||||
- [ ] 14. Cursor SDK unhandled `write EPIPE` crashes the backend child (recurring, post-SDK-bump)
|
||||
|
||||
---
|
||||
|
||||
## 1. `is_error: true` on Claude SDK results ignored — failed runs recorded as completed
|
||||
|
||||
**Severity: high.** The Claude Agent SDK emits terminal `result` messages with
|
||||
`subtype: "success"` but `is_error: true` for API-level failures. The adapter only branches on
|
||||
subtype, so the run, run_attempt, provider_turn, and (for delegated tasks) the subagent row and
|
||||
the parent's `delegate_task` item all read `completed`.
|
||||
|
||||
Observed in four independent places:
|
||||
|
||||
- Delegated task `hello-opus-48` (thread `1156181e`): 401 auth failure, zero token usage,
|
||||
everything projected `completed`.
|
||||
- Same 401 in a5a643b2's run-4 delegated child — parent `delegate_task` item output.status
|
||||
`completed`.
|
||||
- Thread `47763f5e` run 1: 401 result projected as a completed run; error text survives only as
|
||||
a plain completed `assistant_message` (the SDK's synthetic `<synthetic>`-model message) — no
|
||||
error item, so the run reads as a success.
|
||||
- Thread `ea84f015` runs 11–13: `API Error: 529 Overloaded` (29 `api_retry` events preceding),
|
||||
all three runs `completed`.
|
||||
|
||||
**Root cause:** `ClaudeAdapterV2.ts` — `terminalStatusFromResult` (~line 1652) returns
|
||||
`"completed"` whenever `message.subtype === "success"`; the failure branch (~line 3254) only
|
||||
fires for non-success subtypes. `is_error` / `api_error_status` are never consulted.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. In `terminalStatusFromResult` (and the result handler), treat `subtype === "success" &&
|
||||
is_error === true` as a failure.
|
||||
2. Build a `ProviderFailure` from the result: `message` = the `result` text (e.g. `Failed to
|
||||
authenticate. API Error: 401 ...`), `code` = `api_error_status` when present, plausibly
|
||||
`retryable: true` for 429/529.
|
||||
3. Ensure a terminal-failure error item is emitted (not just the synthetic assistant message)
|
||||
and delegated-task subagent rows go to `failed`.
|
||||
4. Testkit: extend `ClaudeAdapterV2.testkit.ts` + replay fixtures with an
|
||||
`is_error`-on-success-subtype result.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT status FROM orchestration_v2_projection_runs WHERE thread_id LIKE '%1156181e%';" # completed
|
||||
grep 'api_error_status' ~/.t3/userdata-v2/logs/provider/thread-delegated-task-command-3amcp-3a1156181e-*.log
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 2. Terminal failures persist only generic strings — root cause unrecoverable from DB
|
||||
|
||||
**Severity: high (systemic).** Every claudeAgent failed run in the DB persists exactly
|
||||
`{class: "transport_error", message: "Claude Agent SDK query failed.", code: null,
|
||||
retryable: null}` (threads 47763f5e run 10, 7f1dfff1 run 10, 71e29ba5 runs 89/119). The native
|
||||
log at those failure sites shows only the outgoing `query.open`/`prompt.offer` with nothing
|
||||
incoming — so after the fact, **no record of the actual failure exists anywhere**. The same
|
||||
pattern hit cursor (issue 3) — while codex proves it can be done right: codex failures keep the
|
||||
full upstream error body.
|
||||
|
||||
**Root causes:**
|
||||
|
||||
- `ClaudeAdapterV2.ts:279-281` — `ClaudeAgentSdkQueryRunnerError.message` getter hardcodes the
|
||||
string; the wrapped `cause` defect is discarded.
|
||||
- `ProviderFailure.ts:90-113` — `makeProviderFailure` reads only `.message`/`.code` off the
|
||||
squashed cause and never unwraps nested causes of tagged wrapper errors.
|
||||
- `RunExecutionService.ts:~830` — feeds `Cause.squash(cause)` into `makeProviderFailure`, so a
|
||||
tagged error's inner cause never reaches the projection. The server log printed the cause
|
||||
depth-elided (`failures: [ [Object] ]`), destroying the last copy.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Give wrapper errors (`ClaudeAgentSdkQueryRunnerError`, `ProviderAdapterTurnStartError` at
|
||||
`ProviderAdapter.ts:~291`) a message that includes `String(cause)` (or a `detail` field).
|
||||
2. In `makeProviderFailure`, walk the cause chain (`Cause.prettyErrors` / unwrap `.cause`) and
|
||||
persist a structured `detail` (message chain + code) on the failure payload; contracts change
|
||||
in `packages/contracts/src/orchestrationV2.ts` if the failure schema needs a `detail` field.
|
||||
3. Fix the server-log print to use full-depth inspection for causes.
|
||||
4. Side note from 47763f5e run 10: the failed `query.open` reused a **create-style `sessionId`
|
||||
param after the session had been closed** (retry with `resume:` succeeded) — check
|
||||
`ProviderSessionManager`/adapter open-vs-resume selection for closed sessions while fixing.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT thread_id, json_extract(payload_json,'$.failure.message') \
|
||||
FROM orchestration_v2_projection_turn_items WHERE type='error';"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 3. Cursor failure detail dropped (requestId, durationMs, SDK error_code)
|
||||
|
||||
**Severity: high.** Thread `c9e72a05` (the "why are cursor turns failing" session): run 2 failed
|
||||
after a 440s silent turn; native `run.completed` carried `status:"error"`,
|
||||
`requestId:"beca30c7-..."`, `durationMs:440732`. Projection kept only
|
||||
`{message: "Provider turn failed.", code: null}` — requestId and duration dropped. The real
|
||||
cause ("Authentication error. If you are logged in, try logging out and back in.") lives only in
|
||||
the Cursor SDK's local store (`runs.error_code`), which T3 never reads.
|
||||
|
||||
**Root cause:** `CursorAdapterV2.ts:2165-2168` maps `cause: (result as {error?: unknown}).error`
|
||||
— that field does not exist on the SDK `RunResult`, so it always falls back to
|
||||
`DEFAULT_PROVIDER_FAILURE_MESSAGE`.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Map what the result actually carries: persist `requestId` and `durationMs` on the failure
|
||||
payload (code field is a natural home for requestId).
|
||||
2. On `status === "error"`, query the Cursor SDK store for `runs.error_code` /
|
||||
error message for that run id and attach it.
|
||||
3. Note: verify against current SDK shape — the audit also found (refuted-as-intentional) cases
|
||||
where cursor's `run.completed` genuinely carries no detail; the fix is "persist everything
|
||||
present", not "invent detail".
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items \
|
||||
WHERE thread_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND type='error';"
|
||||
grep 'run.completed' ~/.t3/userdata-v2/logs/provider/c9e72a05-*.log | tail -1
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 4. Native provider logs never record failure/lifecycle frames
|
||||
|
||||
**Severity: medium.** The "ground truth" logs cannot explain failed turns. In `721fc23c` the
|
||||
log ends with an outgoing `run.start` and no trace of the `agent.send` rejection 4ms later, nor
|
||||
of the provider child process fatally crashing (twice, `@cursor/sdk` Node error — visible only
|
||||
in `server-child.log`). No adapter has an error/lifecycle log kind at all.
|
||||
|
||||
**Root cause:** e.g. `CursorAgentSdk.ts` `send()` — log writes cover outgoing `run.start` and
|
||||
incoming frames only; `runnerError(cause, "run.start")` paths (lines ~408/440) write nothing.
|
||||
Process exit is not logged to the per-thread native log either.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Add an `error`/`lifecycle` kind to the native event logger contract and write a frame on:
|
||||
adapter send/open rejections, runner errors, provider process spawn/exit (with exit code),
|
||||
and turn-abort paths — across all adapters (cursor, claude, codex, ACP, opencode).
|
||||
2. Keep payloads small (message + code + native run/turn id), no secrets.
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 5. Provider crashes / reconcile cancellations are silent to the user
|
||||
|
||||
**Severity: high.** In `721fc23c` the cursor backend crashed mid-turn; startup reconcile
|
||||
cancelled run 1. In `48663fb7` a server restart orphaned the run; reconcile cancelled it. In
|
||||
both cases the user asked something, got **no response, no error item, and no explanation** —
|
||||
a reconcile-cancelled run is projected indistinguishably from a user cancellation.
|
||||
|
||||
**Root cause:** the startup runtime-reconcile (`command:runtime-reconcile:startup...`)
|
||||
terminalizes runs/attempts/turns to `cancelled` but emits no user-visible item and no reason.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. When reconcile terminalizes a run it did not start, emit an error (or `interrupted`) turn
|
||||
item with a reason: e.g. "Provider process exited unexpectedly" / "Run was interrupted by an
|
||||
app restart".
|
||||
2. Record the cancellation reason on the run payload (`cancelReason: "runtime_reconcile" |
|
||||
"user" | ...`) so UI and debugging can distinguish.
|
||||
3. Optional: auto-offer retry in UI for reconcile-cancelled runs.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT event_type, occurred_at FROM orchestration_events \
|
||||
WHERE stream_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND event_id LIKE '%runtime-reconcile%';"
|
||||
grep -n 'cursor/sdk\|terminalizedRuns' ~/.t3/userdata-v2/logs/server-child.log
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 6. Codex-native collab subagents entirely missing from events and projections
|
||||
|
||||
**Severity: high (lost data).** In `a5a643b2` run 3 ("spawn a subagent"), codex spawned a
|
||||
native collab subagent: `subAgentActivity` item, `collabAgentToolCall` (`wait`), and a child
|
||||
native thread (`019f0c93-d260`) with webSearch, reasoning, and a final `agentMessage`
|
||||
("Hello."). **Zero** of it was ingested — no events, no items, no subagent row, no child
|
||||
thread. The child also completed *after* the parent turn finalized, so late-arriving child
|
||||
items need routing even post-turn.
|
||||
|
||||
**Root cause:** `CodexAdapterV2.ts` has no handlers for `subAgentActivity` /
|
||||
`collabAgentToolCall` item types, and events on non-primary native threads of the shared
|
||||
app-server session are not attributed to any T3 thread.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Handle `subAgentActivity`: create a subagent projection row + child provider thread (mirror
|
||||
of what `a61e9269`'s newer session shape already does — that session projected
|
||||
`subAgentActivity` fine, so check what differs: likely experimental collab API vs newer
|
||||
subagent API).
|
||||
2. Handle `collabAgentToolCall` as a tool item on the parent.
|
||||
3. Route child-native-thread items to the child T3 thread, including after the parent turn
|
||||
completed (same routing-loosening pattern used for owned-provider-thread updates in the
|
||||
wakeup work).
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT COUNT(*) FROM orchestration_events WHERE payload_json LIKE '%019f0c93-d260%';" # 0
|
||||
grep -c 'subAgentActivity\|collabAgentToolCall' ~/.t3/userdata-v2/logs/provider/a5a643b2-*.log # >0
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 7. Grok/ACP background subagent: wrong lifecycle + transcript never projected
|
||||
|
||||
**Severity: high (lost data) + medium (lifecycle).** Thread `5dcea72d` ("spawn a subagent"):
|
||||
|
||||
- The subagent row and parent `subagent` item were marked `completed` at spawn time
|
||||
(01:52:10) with the placeholder result "Subagent started in background..." — the task
|
||||
actually ran 75s (116 tool calls, per the later `TaskOutput` payload).
|
||||
- The child thread got only its 2 spawn-time items; the live transcript (811 decoded incoming
|
||||
ACP messages between runs) produced **zero** ingested events. The subagent's real final
|
||||
output never reached the child thread.
|
||||
|
||||
**Root cause:** `AcpAdapterV2.ts` `emitSubagent` (~lines 1047-1060) adopts the spawn tool's
|
||||
bootstrap text as the result and a non-running taskStatus as terminal; session notifications
|
||||
arriving **between runs** (no active turn) are dropped rather than buffered/routed to the
|
||||
subagent's child thread.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Keep the subagent `running` until a terminal task status; update result/completedAt from
|
||||
`TaskOutput` (or task-completion notification) when it arrives.
|
||||
2. Route/buffer ACP session notifications for background tasks outside active turns to the
|
||||
child thread (reuse the wakeup-buffer pattern from ClaudeAdapterV2 if applicable to ACP).
|
||||
3. Related low finding: child-thread items carry null `run_id`/`provider_thread_id`/
|
||||
`provider_turn_id` — populate lineage when projecting child items.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT status, completed_at, substr(json_extract(payload_json,'$.result'),1,60) \
|
||||
FROM orchestration_v2_projection_subagents WHERE thread_id='5dcea72d-15e1-4ded-922b-0b00c587de6c';"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 8. Invisible post-turn wakeup turns (known — fix on this branch)
|
||||
|
||||
**Severity: high (lost data), known issue.** The audit quantified the pre-fix damage:
|
||||
|
||||
- `47763f5e`: 10 whole wakeup turns unpersisted — 16 assistant messages + 84 tool calls,
|
||||
including 5 real git pushes and the final "Converged. PR #3638 is fully green".
|
||||
- `ea84f015`: 42 tool calls + final assistant messages across 3 windows — including a GitHub
|
||||
comment posted with no user-visible record (`pull/2829#issuecomment-4861082710`).
|
||||
- `71e29ba5`: 76 completed tool calls (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup), all falling
|
||||
in gaps between run windows, zero inside any run.
|
||||
|
||||
The fix (`turn.wakeup` / `ProviderWakeupService` / `attach_wakeup` / backgrounded-bash
|
||||
adoption) is implemented on `t3code/codex-turn-mapping`; these sessions ran on pre-fix builds.
|
||||
First `provider_wakeup` events in the DB appear 2026-07-01T22:47:41 — post-fix threads persist
|
||||
wakeups.
|
||||
|
||||
**Remaining work:**
|
||||
|
||||
- [x] Core fix implemented (this branch, replay fixture `claude_provider_wakeup`)
|
||||
- [ ] Sanity-check the three audit scenarios against the fixture set (task-notification wakeup,
|
||||
ScheduleWakeup sleep-loop, backgrounded Bash completion) — the audit evidence makes good
|
||||
additional fixture material
|
||||
- [ ] Known follow-ups (from memory): idle session reaper vs long sleeps; superseded-wakeup
|
||||
buffer only replays task bookkeeping; provider_turn has no `waiting` status literal
|
||||
|
||||
## 9. Shared codex session logs written to opener thread's file
|
||||
|
||||
**Severity: medium.** Four codex threads (`c878541b`, `de5f191a`, `68f7595b`, `af66fc2c`) have
|
||||
**no native log file at all** — their app-server traffic was written into
|
||||
`71e29ba5-...log.*` because that thread opened the shared codex app-server session.
|
||||
Consequence: rotation of the busy opener's log (10 files × 10MB) **destroyed the native ground
|
||||
truth** for most of those threads' runs; it also produced a false "ingestion gap" signal during
|
||||
the audit (another thread's traffic interleaved in 71e29ba5's log).
|
||||
|
||||
**Root cause:** `CodexAdapterV2.ts:~1136` — `codexAppServerClientFactoryFromSettingsLayer.open`
|
||||
builds `makeCodexAppServerProtocolLogger({ threadId: input.threadId })` once per app-server
|
||||
process; `EventNdjsonLogger.write` routes to `${threadSegment}.log` from that frozen threadId.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Resolve the log target per message, not per process: maintain a native-thread-id → T3
|
||||
thread-id map (the adapter already tracks owned native threads) and route each protocol
|
||||
frame to the owning thread's log; fall back to a shared
|
||||
`codex-shared-session.log` for unattributable frames (initialize, thread/start, etc.).
|
||||
2. Consider retention bump for provider logs, since they are the only ground truth
|
||||
(`.plans/06-provider-logstream-lifecycle.md` is the related prior art).
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
grep -l '019f1b62-f532' ~/.t3/userdata-v2/logs/provider/*.log* # only 71e29ba5-*.log.{6,9,10}
|
||||
ls ~/.t3/userdata-v2/logs/provider/ | grep -c 'c878541b\|de5f191a\|68f7595b\|af66fc2c' # 0
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 10. Streaming deltas persisted as full-row event pairs (~2800x amplification)
|
||||
|
||||
**Severity: medium (cost/scale, not correctness).** Grok/ACP streams a child task's result
|
||||
per-token; each chunk is persisted as a **full-row** `turn-item.updated` + `message.updated`
|
||||
event pair. One 6,274-char result accumulated 2,704 events; a 2-minute session wrote 6,017
|
||||
rows (14% of the whole 43k-row table). Replay and projection costs scale with this.
|
||||
|
||||
**Root cause:** `AcpAdapterV2.emitSubagentAssistant` emits a full event pair per
|
||||
`agent_message_chunk`, and `ProviderEventIngestor` persists every emission.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Split live streaming from persistence: broadcast deltas to subscribers in-memory, persist
|
||||
coalesced snapshots (e.g. on item completion + every N seconds/K bytes while running).
|
||||
2. Alternatively debounce persistence per item id in the ingestor so any adapter gets the
|
||||
benefit.
|
||||
3. Check other adapters for the same pattern (claude/codex emit per-block, which is fine;
|
||||
ACP per-token is the outlier).
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT event_type, COUNT(*) FROM orchestration_events \
|
||||
WHERE stream_id LIKE 'thread:provider:grok:native-thread:019f1558%' GROUP BY 1;"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 11. Claude assistant text segments merged without separator (fixed — needs regression fixture)
|
||||
|
||||
**Severity: medium, already fixed in worktree.** In the `6d618dc4` MCP group (build
|
||||
`fc23be8184`), 5 interleaved assistant text blocks were accumulated
|
||||
(`context.assistant.text += ...`) and emitted as ONE item at end of turn — 10,642 chars joined
|
||||
with no separator, ordered after all 19 tool calls, losing interleaving. Current worktree code
|
||||
(`emitAssistantTextArtifacts` per `message.uuid`) already emits per-segment items.
|
||||
|
||||
**Remaining work:**
|
||||
|
||||
- [x] Fix (already in worktree)
|
||||
- [ ] Add a replay fixture asserting multi-segment assistant text produces one item per SDK
|
||||
uuid, interleaved with tool items at correct ordinals
|
||||
|
||||
## 12. OpenCode `file_search` items drop error/output
|
||||
|
||||
**Severity: medium.** Child session `ses_0ea978228`: a failed `file_search` item projects only
|
||||
`{status: 'failed', type: 'file_search', pattern: '...'}` — the provider's error message is
|
||||
unrecoverable. Same shape drops successful read/grep/glob outputs (low finding).
|
||||
|
||||
**Root cause:** `OpenCodeAdapterV2.ts` — `toolOutput()` (line ~659) extracts
|
||||
`part.state.error`, but the `file_search` mapping branch (~line 1376) only maps `pattern`;
|
||||
output/error only attach for `dynamic_tool`. The contract type
|
||||
(`packages/contracts/src/orchestrationV2.ts` ~line 841) has no output/error field on
|
||||
`file_search` either.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Add optional `output`/`error` to the `file_search` item contract.
|
||||
2. Map `part.state.error` (and output where present) in the opencode/ACP `file_search` branch.
|
||||
3. Grok has the same gap (`file_search`/`read` persist only pattern/fileName echo — low
|
||||
finding); fix at the shared mapping level if possible.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT payload_json FROM orchestration_v2_projection_turn_items \
|
||||
WHERE turn_item_id='turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc';"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 13. Low-severity backlog
|
||||
|
||||
Unverified (single-auditor) findings, grouped. Tick when triaged/fixed:
|
||||
|
||||
**Lineage**
|
||||
- [ ] `run_attempts.provider_turn_id` is null on ALL 207 attempts DB-wide (reverse link only) —
|
||||
populate the forward link or drop the column
|
||||
- [ ] Opencode/claude "pending"-keyed provider-thread placeholder row persists alongside the
|
||||
real `ses_`-keyed row; runs/attempts reference one, items/active_provider_thread_id the
|
||||
other (3029dc85, 9f8d616d)
|
||||
- [ ] Subagent child-thread items carry null run/provider_thread/provider_turn ids (grok,
|
||||
ea84f015)
|
||||
- [ ] Interrupt-result turn item references an interrupt-request parent item that was never
|
||||
emitted (GLOBAL)
|
||||
- [ ] Synthesized terminal-failure error item references a provider_turn_id that was never
|
||||
projected (GLOBAL)
|
||||
|
||||
**Stuck state / lifecycle**
|
||||
- [ ] Projection ignores `provider-session.detached` — sessions stay `ready`/`running` for
|
||||
~20-25h until shutdown sweep (GLOBAL, 1156181e, 6d618dc4, 47763f5e, ea84f015); also
|
||||
claudeAgent sessions are never idle-reaped
|
||||
- [ ] Provider-thread row stayed `active` ~20h after its session stopped (9f8d616d)
|
||||
- [ ] Run 119 (71e29ba5) marked failed while its native query kept running; retry run 120
|
||||
adopted the result leaving a duplicated user message — dedupe/adopt semantics on retry
|
||||
|
||||
**Dropped provider data (no user-visible loss observed yet)**
|
||||
- [ ] Codex `reasoning` items silently dropped (no adapter handler; all observed summaries were
|
||||
empty — would lose data once codex emits populated summaries)
|
||||
- [ ] Codex `thread/tokenUsage/updated` + `account/rateLimits/updated` never ingested — runs
|
||||
have no usage data; cursor `run.completed` usage also dropped (8ee00dcc)
|
||||
- [ ] Codex `contextCompaction` item has no projection representation
|
||||
- [ ] Cursor tool calls that never returned natively are auto-marked `completed` with no
|
||||
results at turn end (c9e72a05) — should be `failed`/`interrupted`
|
||||
- [ ] 4 native `error_during_execution` results silently recovered in-adapter with no
|
||||
projection trace (71e29ba5); one absorbed during a steering message (ea84f015)
|
||||
|
||||
**Cosmetic / observability**
|
||||
- [ ] Grok + opencode native logs redact payloads to shape summaries — no content-level ground
|
||||
truth for audits; consider a debug setting to log content
|
||||
- [ ] Grok logs every successful `session/prompt` as `failed` with `errorTag: Interrupt`
|
||||
- [ ] Cursor native `read` tool calls projected as type `file_search` (semantic mismatch)
|
||||
- [ ] Cursor `file_change` diffStr has malformed headers (`a//abs/path`, `b//abs/path`)
|
||||
- [ ] 13 old backgrounded `local_bash` tasks projected as subagents with empty prompts and
|
||||
synthetic child threads (GLOBAL); backgrounded-bash child threads have empty-text prompt
|
||||
user_message items (7f1dfff1)
|
||||
- [ ] Cursor 7.3-minute silent hang before failing (c9e72a05) — no progress/heartbeat signal
|
||||
exists to distinguish a hung turn from a thinking one
|
||||
|
||||
## 14. Cursor SDK unhandled `write EPIPE` crashes the backend child (recurring)
|
||||
|
||||
**Severity: high.** Added 2026-07-02 after new cursor sessions reproduced backend crashes.
|
||||
Distinct from the June-29 crash that the `@cursor/sdk` version bump addressed.
|
||||
|
||||
Three occurrences in `server-child.log`, identical signature — `Unhandled 'error' event /
|
||||
Error: write EPIPE` on a `net.Socket`, followed by the `Node.js v24.15.0` footer (process
|
||||
death):
|
||||
|
||||
- **2026-07-02T19:04:57.558Z** — stack definitively inside `@cursor/sdk/dist/esm/357.js`
|
||||
(`et.execute` → `We.execute` → `Is.execute`): a connect-RPC execute writing to a
|
||||
cursor-agent socket whose far end had closed. Context: TWO cursor sessions streaming
|
||||
concurrently (d1bfdd3d run-0294b303, 4f3381e5 run-c7e93ba0, each with its own provider
|
||||
session, plus a native subagent task thread); both streamed token-deltas until 19:04:55.5.
|
||||
- **2026-07-01T20:47:34.573Z** and **2026-07-02T04:46:20.557Z** — same signature, but stack is
|
||||
only the async write-completion frame (`WriteWrap.onWriteComplete`), so origin unproven. No
|
||||
cursor turns were active; consistent with a lingering cursor-agent connection dying idle and
|
||||
a later write hitting EPIPE.
|
||||
|
||||
**Collateral (ties into issues 2/4/5):**
|
||||
|
||||
- d1bfdd3d run 1 + 4f3381e5 run 1 silently `cancelled` by startup reconcile at 19:05:01;
|
||||
4f3381e5 has NO error item at all (issue 5).
|
||||
- d1bfdd3d run 2 (retry) failed with the generic `Failed to start run ... on cursor provider
|
||||
thread ...pending...` wrapper, cause depth-elided in the log (issue 2), and targeted the
|
||||
stale `pending`-keyed provider thread (issue 13 lineage note).
|
||||
- The two earlier EPIPE crashes explain two previously "undebuggable" audit failures: the
|
||||
restarted child killed the live claude CLI processes, so 7f1dfff1 run 10 (requested
|
||||
20:47:56, `claude-query-stream-failed` 20:47:58) and 71e29ba5 run 89 (requested 04:47:03)
|
||||
failed ~20-40s after each crash with the generic "Claude Agent SDK query failed."
|
||||
- The June-29 crash's actual error text is unknowable: the stderr dump was truncated at
|
||||
51,674 chars (log line cap) BEFORE the error message — only minified bundle source survived.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Containment: attach `error` handlers to (or wrap) the cursor SDK's sockets, and add a
|
||||
`process.on('uncaughtException'/'unhandledRejection')` policy in the backend child that
|
||||
fails the owning provider session instead of dying. Longer-term: isolate provider SDKs in
|
||||
their own child process so an SDK crash cannot kill the orchestrator.
|
||||
2. Report upstream to Cursor: SDK leaves its agent socket without an `error` listener;
|
||||
`write EPIPE` after agent-process exit is fatal to the host.
|
||||
3. Fix stderr log truncation: when capping captured child output, keep the TAIL (where Node
|
||||
prints the error + stack), not just the head.
|
||||
4. Issues 2/4/5 remain the reason this was hard to diagnose — they get us error items with
|
||||
real causes, native-log failure frames, and user-visible reconcile cancellations.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
grep -n "Unhandled 'error' event" ~/.t3/userdata-v2/logs/server-child.log # 3 hits
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT run_id,status,completed_at FROM orchestration_v2_projection_runs \
|
||||
WHERE thread_id IN ('d1bfdd3d-38cc-4ff3-ab75-8be6dc592b00','4f3381e5-89e2-45a8-bca1-bbe5d520bbba');"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## Refuted during verification (do NOT act on)
|
||||
|
||||
- 71e29ba5 "ingestion gap, 119 items lost" — traffic belonged to c878541b via the shared codex
|
||||
session (see issue 9).
|
||||
- 47763f5e "122 thinking blocks dropped" — all native thinking blocks were empty
|
||||
(`{"thinking":""}`); nothing to lose. (Reasoning ingestion is still absent, tracked as low.)
|
||||
- ea84f015 failed cursor runs 15-17 "generic error" — native results genuinely carried no
|
||||
detail; nothing to persist (but see issues 3/4 for making cursor carry detail).
|
||||
|
||||
## Validation
|
||||
|
||||
- Re-run the audit repro queries above after each fix; each issue's repro should flip.
|
||||
- Extend replay fixtures (`testkit/fixtures/`) per issue where marked; the audit evidence
|
||||
(thread ids + native log excerpts) is fixture source material.
|
||||
- Full audit data with per-finding evidence, verifier verdicts, and repro commands:
|
||||
`.plans/22-orchestration-v2-audit-findings.json`.
|
||||
@@ -12,3 +12,4 @@
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
21. `21-orchestration-v2-application-integration.md`
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
vp staged
|
||||
@@ -358,10 +358,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
ensureElectronRuntime();
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
@@ -378,13 +375,23 @@ export function resolveElectronLaunchCommand(args = []) {
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveElectronBinaryPath({
|
||||
ensureRuntime = ensureElectronRuntime,
|
||||
createRequire = NodeModule.createRequire,
|
||||
moduleUrl = import.meta.url,
|
||||
} = {}) {
|
||||
ensureRuntime();
|
||||
|
||||
const require = createRequire(moduleUrl);
|
||||
return require("electron");
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
|
||||
return {
|
||||
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
@@ -25,4 +25,24 @@ describe("electron development launcher", () => {
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
|
||||
it("repairs Electron before loading the package entrypoint", () => {
|
||||
const calls = [];
|
||||
const electronPath = resolveElectronBinaryPath({
|
||||
ensureRuntime: () => {
|
||||
calls.push("ensure");
|
||||
},
|
||||
createRequire: () => (specifier) => {
|
||||
calls.push(`require:${specifier}`);
|
||||
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
|
||||
},
|
||||
moduleUrl: import.meta.url,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
electronPath,
|
||||
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
});
|
||||
@@ -126,7 +126,7 @@ const withIdentity = <A, E, R>(
|
||||
input.legacyPathProbeError
|
||||
? Effect.fail(input.legacyPathProbeError)
|
||||
: Effect.succeed(
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha v2)"),
|
||||
),
|
||||
readFileString: () =>
|
||||
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
|
||||
@@ -147,14 +147,14 @@ describe("DesktopAppIdentity", () => {
|
||||
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const userDataPath = yield* identity.resolveUserDataPath;
|
||||
|
||||
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha)");
|
||||
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha v2)");
|
||||
}),
|
||||
{ legacyPathExists: true },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves failures while inspecting the legacy userData path", () => {
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha v2)";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
|
||||
@@ -254,7 +254,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -271,11 +271,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -291,7 +291,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -309,11 +309,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.equal(error.path, `${baseDir}/userdata-v2`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata-v2.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -398,14 +398,14 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("derives production state paths under userdata", () =>
|
||||
it.effect("derives production state paths under userdata-v2", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
@@ -88,10 +88,12 @@ describe("DesktopEnvironment", () => {
|
||||
);
|
||||
|
||||
assert.equal(environment.isDevelopment, false);
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata-v2");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata-v2/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata-v2/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata-v2/settings.json");
|
||||
assert.equal(environment.userDataDirName, "t3code-v2");
|
||||
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha v2)");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -155,9 +155,9 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata-v2");
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code-v2";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha v2)";
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
|
||||
@@ -358,7 +358,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = path.join(baseDir, "userdata", "settings.json");
|
||||
const settingsPath = path.join(baseDir, "userdata-v2", "settings.json");
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
|
||||
@@ -503,7 +503,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// config resolution lands in dev/ instead of userdata-v2/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
|
||||
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.orElseSucceed((): string | null => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
|
||||
@@ -83,7 +83,7 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2/client-settings.json`,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -403,7 +403,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const registryPath = `${baseDir}/userdata/saved-environments.json`;
|
||||
const registryPath = `${baseDir}/userdata-v2/saved-environments.json`;
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -439,7 +439,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -455,11 +455,11 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.equal(error.path, `${baseDir}/userdata-v2`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata-v2.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
|
||||
@@ -204,7 +204,7 @@ const mobileEndorsementRows = [
|
||||
<div class="harness-mark"><img src="/harnesses/cursor_light.svg" alt="" /></div>
|
||||
<div class="harness-meta">
|
||||
<div class="harness-name">Cursor</div>
|
||||
<div class="harness-tag">cursor-agent</div>
|
||||
<div class="harness-tag">@cursor/sdk</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
included:
|
||||
- ios/T3Code
|
||||
- modules/t3-composer-editor/ios
|
||||
- modules/t3-native-controls/ios
|
||||
- modules/t3-terminal/ios
|
||||
- modules/t3-review-diff/ios
|
||||
|
||||
|
||||
@@ -15,30 +15,38 @@ const VARIANT_CONFIG: Record<
|
||||
readonly appName: string;
|
||||
readonly scheme: string;
|
||||
readonly iosIcon: string;
|
||||
readonly splashIcon: string;
|
||||
readonly iosBundleIdentifier: string;
|
||||
readonly androidPackage: string;
|
||||
readonly relyingParty?: string;
|
||||
}
|
||||
> = {
|
||||
development: {
|
||||
appName: "T3 Code Dev",
|
||||
scheme: "t3code-dev",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
||||
androidPackage: "com.t3tools.t3code.dev",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
},
|
||||
preview: {
|
||||
appName: "T3 Code Preview",
|
||||
scheme: "t3code-preview",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
},
|
||||
production: {
|
||||
appName: "T3 Code",
|
||||
scheme: "t3code",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code",
|
||||
androidPackage: "com.t3tools.t3code",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -62,7 +70,11 @@ const config: ExpoConfig = {
|
||||
scheme: variant.scheme,
|
||||
version: "0.1.0",
|
||||
runtimeVersion: {
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
|
||||
// could land on a binary missing the native changes it needs and crash.
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
|
||||
},
|
||||
orientation: "portrait",
|
||||
icon: "./assets/icon.png",
|
||||
@@ -77,6 +89,14 @@ const config: ExpoConfig = {
|
||||
icon: variant.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
// Sign in with Apple, or push notification entitlements).
|
||||
appleTeamId: "ARK85ZXQ4Z",
|
||||
associatedDomains: [
|
||||
`applinks:${variant.relyingParty}`,
|
||||
`webcredentials:${variant.relyingParty}`,
|
||||
],
|
||||
infoPlist: {
|
||||
NSAppTransportSecurity: {
|
||||
NSAllowsArbitraryLoads: true,
|
||||
@@ -101,7 +121,6 @@ const config: ExpoConfig = {
|
||||
favicon: "./assets/favicon.png",
|
||||
},
|
||||
plugins: [
|
||||
"expo-router",
|
||||
"expo-font",
|
||||
"expo-secure-store",
|
||||
["@clerk/expo", { theme: "./clerk-theme.json" }],
|
||||
@@ -116,12 +135,12 @@ const config: ExpoConfig = {
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
image: "./assets/splash-icon.png",
|
||||
image: variant.splashIcon,
|
||||
resizeMode: "contain",
|
||||
backgroundColor: "#ffffff",
|
||||
imageWidth: 220,
|
||||
dark: {
|
||||
image: "./assets/splash-icon.png",
|
||||
image: variant.splashIcon,
|
||||
backgroundColor: "#0a0a0a",
|
||||
},
|
||||
},
|
||||
@@ -139,12 +158,22 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
],
|
||||
"./plugins/withIosCocoaPodsUuidCache.cjs",
|
||||
// Must be listed BEFORE expo-widgets: same-type mods run last-registered-
|
||||
// first, so registering earlier makes this plugin's mods run AFTER
|
||||
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
|
||||
// would delete the asset catalog) and its xcodeproj mod creates the widget
|
||||
// target (which must exist before the compile phase can be attached).
|
||||
"./plugins/withWidgetLogoAsset.cjs",
|
||||
[
|
||||
"expo-widgets",
|
||||
{
|
||||
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
|
||||
enablePushNotifications: true,
|
||||
// Agent activity can update many times an hour; without the
|
||||
// frequent-updates entitlement iOS throttles the update budget sooner.
|
||||
frequentUpdates: true,
|
||||
widgets: [
|
||||
{
|
||||
name: "AgentActivity",
|
||||
@@ -155,6 +184,7 @@ const config: ExpoConfig = {
|
||||
],
|
||||
},
|
||||
],
|
||||
"./plugins/withIosSceneLifecycle.cjs",
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
],
|
||||
extra: {
|
||||
@@ -166,6 +196,15 @@ const config: ExpoConfig = {
|
||||
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
|
||||
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
|
||||
},
|
||||
// Native Google sign-in credentials. @clerk/expo reads these from `extra`
|
||||
// under their exact env-var names (not nested), and its config plugin reads
|
||||
// the iOS URL scheme at prebuild to register it in Info.plist.
|
||||
// Unset values must be omitted (not null): the public manifest serializes
|
||||
// null to {}, which is truthy and would defeat Clerk's fallback checks.
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
|
||||
observability: {
|
||||
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 2.0 MiB After Width: | Height: | Size: 2.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 302 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg width="111" height="74" viewBox="7 29 111 74" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="black"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 887 B |
@@ -6,6 +6,7 @@
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "development"
|
||||
},
|
||||
@@ -14,6 +15,7 @@
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview"
|
||||
},
|
||||
@@ -22,6 +24,7 @@
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview:dev": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview",
|
||||
"MOBILE_VERSION_POLICY": "fingerprint"
|
||||
@@ -35,6 +38,7 @@
|
||||
}
|
||||
},
|
||||
"production": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "production"
|
||||
},
|
||||
@@ -46,7 +50,10 @@
|
||||
"submit": {
|
||||
"production": {
|
||||
"ios": {
|
||||
"ascAppId": "6761315631"
|
||||
"ascAppId": "6787819824"
|
||||
},
|
||||
"android": {
|
||||
"track": "internal"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
-18
@@ -199,24 +199,24 @@
|
||||
--font-bold: "DMSans_700Bold";
|
||||
|
||||
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
|
||||
--text-3xs: 10px;
|
||||
--text-3xs--line-height: 13px;
|
||||
--text-2xs: 11px;
|
||||
--text-2xs--line-height: 15px;
|
||||
--text-xs: 12px;
|
||||
--text-xs--line-height: 16px;
|
||||
--text-sm: 13px;
|
||||
--text-sm--line-height: 18px;
|
||||
--text-base: 15px;
|
||||
--text-base--line-height: 22px;
|
||||
--text-lg: 17px;
|
||||
--text-lg--line-height: 22px;
|
||||
--text-xl: 20px;
|
||||
--text-xl--line-height: 26px;
|
||||
--text-2xl: 24px;
|
||||
--text-2xl--line-height: 30px;
|
||||
--text-3xl: 28px;
|
||||
--text-3xl--line-height: 34px;
|
||||
--text-3xs: 11px;
|
||||
--text-3xs--line-height: 14px;
|
||||
--text-2xs: 12px;
|
||||
--text-2xs--line-height: 16px;
|
||||
--text-xs: 13px;
|
||||
--text-xs--line-height: 17px;
|
||||
--text-sm: 14px;
|
||||
--text-sm--line-height: 19px;
|
||||
--text-base: 16px;
|
||||
--text-base--line-height: 23px;
|
||||
--text-lg: 18px;
|
||||
--text-lg--line-height: 23px;
|
||||
--text-xl: 21px;
|
||||
--text-xl--line-height: 28px;
|
||||
--text-2xl: 26px;
|
||||
--text-2xl--line-height: 32px;
|
||||
--text-3xl: 30px;
|
||||
--text-3xl--line-height: 36px;
|
||||
}
|
||||
|
||||
/* ─── Custom utilities ──────────────────────────────────────────────── */
|
||||
|
||||
+10
-1
@@ -1,2 +1,11 @@
|
||||
import { registerRootComponent } from "expo";
|
||||
import "react-native-gesture-handler";
|
||||
import "expo-router/entry";
|
||||
import { featureFlags } from "react-native-screens";
|
||||
|
||||
import App from "./src/App";
|
||||
|
||||
// Required for react-native-screens' iOS FormSheet sizing fix when a nested
|
||||
// native stack is rendered inside a non-fitToContents formSheet.
|
||||
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
|
||||
|
||||
registerRootComponent(App);
|
||||
@@ -47,6 +47,7 @@ public class T3ComposerEditorModule: Module {
|
||||
"onComposerSelectionChange",
|
||||
"onComposerFocus",
|
||||
"onComposerBlur",
|
||||
"onComposerSubmit",
|
||||
"onComposerPasteImages",
|
||||
"onComposerContentSizeChange"
|
||||
)
|
||||
|
||||
@@ -63,6 +63,24 @@ private final class ComposerTextView: UITextView {
|
||||
|
||||
var onPasteImages: (([String]) -> Void)?
|
||||
var onAttributedMutation: (() -> Void)?
|
||||
var onSubmit: (() -> Void)?
|
||||
|
||||
override var keyCommands: [UIKeyCommand]? {
|
||||
var commands = super.keyCommands ?? []
|
||||
let submit = UIKeyCommand(
|
||||
input: "\r",
|
||||
modifierFlags: .command,
|
||||
action: #selector(submitMessage(_:))
|
||||
)
|
||||
submit.discoverabilityTitle = "Send Message"
|
||||
submit.wantsPriorityOverSystemBehavior = true
|
||||
commands.append(submit)
|
||||
return commands
|
||||
}
|
||||
|
||||
@objc private func submitMessage(_ sender: UIKeyCommand) {
|
||||
onSubmit?()
|
||||
}
|
||||
|
||||
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
||||
if action == #selector(paste(_:)) {
|
||||
@@ -299,6 +317,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
let onComposerSelectionChange = EventDispatcher()
|
||||
let onComposerFocus = EventDispatcher()
|
||||
let onComposerBlur = EventDispatcher()
|
||||
let onComposerSubmit = EventDispatcher()
|
||||
let onComposerPasteImages = EventDispatcher()
|
||||
let onComposerContentSizeChange = EventDispatcher()
|
||||
|
||||
@@ -320,6 +339,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
textView.onAttributedMutation = { [weak self] in
|
||||
self?.emitTextChange()
|
||||
}
|
||||
textView.onSubmit = { [weak self] in
|
||||
self?.onComposerSubmit([:])
|
||||
}
|
||||
addSubview(textView)
|
||||
|
||||
placeholderLabel.numberOfLines = 0
|
||||
|
||||
@@ -26,6 +26,15 @@ function nodeKey(node: MarkdownNode, index: number): string {
|
||||
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
|
||||
}
|
||||
|
||||
/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
|
||||
function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
|
||||
return Math.max(10, Math.round(textStyle.fontSize * 0.8));
|
||||
}
|
||||
|
||||
function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
|
||||
return codeBlockFontSize(textStyle) + 6;
|
||||
}
|
||||
|
||||
function nodeText(node: MarkdownNode): string {
|
||||
if (node.content !== undefined) {
|
||||
return node.content;
|
||||
@@ -161,8 +170,8 @@ function HighlightedCodeText(props: {
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
lineHeight: codeBlockLineHeight(props.textStyle),
|
||||
}}
|
||||
>
|
||||
{props.content}
|
||||
@@ -196,8 +205,8 @@ function HighlightedCodeText(props: {
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
lineHeight: codeBlockLineHeight(props.textStyle),
|
||||
}}
|
||||
>
|
||||
{keyedLines.map((line, lineIndex) => (
|
||||
@@ -264,7 +273,7 @@ function NativeCodeBlock(props: {
|
||||
flex: 1,
|
||||
color: props.textStyle.mutedColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
}}
|
||||
>
|
||||
{languageLabel}
|
||||
|
||||
@@ -32,11 +32,25 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
].join(":");
|
||||
}
|
||||
|
||||
const DEFAULT_BODY_FONT_SIZE = 15;
|
||||
const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
|
||||
|
||||
function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
|
||||
const index = Math.max(0, Math.min(5, headingLevel - 1));
|
||||
const configured = textStyle.headingFontSizes?.[index];
|
||||
if (typeof configured === "number" && Number.isFinite(configured)) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
|
||||
return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
|
||||
}
|
||||
|
||||
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
|
||||
const isFile = run.fileIcon != null;
|
||||
const isSkill = run.skillName != null;
|
||||
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
|
||||
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
|
||||
const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
|
||||
const isHeading = run.role === "heading";
|
||||
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
|
||||
const hasParagraphStyle = run.headIndent !== undefined;
|
||||
@@ -88,7 +102,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
: isHeading
|
||||
? headingFontSize
|
||||
: run.role === "code-language"
|
||||
? 11
|
||||
? Math.max(10, Math.round(textStyle.fontSize * 0.73))
|
||||
: run.code || isCodeBlock
|
||||
? Math.max(12, textStyle.fontSize - 2)
|
||||
: textStyle.fontSize,
|
||||
@@ -98,9 +112,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
: run.role === "list-break"
|
||||
? textStyle.lineHeight + (run.spacing ?? 0)
|
||||
: isHeading
|
||||
? Math.max(headingFontSize + 6, 20)
|
||||
? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
|
||||
: isCodeBlock
|
||||
? 18
|
||||
? Math.max(16, textStyle.lineHeight - 2)
|
||||
: textStyle.lineHeight,
|
||||
fontStyle: run.italic ? "italic" : "normal",
|
||||
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
|
||||
@@ -148,6 +162,9 @@ export function NativeMarkdownSelectableText(props: {
|
||||
// color-only child update can otherwise leave the previous appearance cached.
|
||||
const appearanceKey = [
|
||||
colorScheme ?? "unspecified",
|
||||
props.textStyle.fontSize,
|
||||
props.textStyle.lineHeight,
|
||||
props.textStyle.headingFontSizes?.join(","),
|
||||
props.textStyle.color,
|
||||
props.textStyle.strongColor,
|
||||
props.textStyle.mutedColor,
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface NativeMarkdownTextStyle {
|
||||
readonly fontFamily: string;
|
||||
readonly headingFontFamily: string;
|
||||
readonly boldFontFamily: string;
|
||||
readonly headingFontSizes?: ReadonlyArray<number>;
|
||||
}
|
||||
|
||||
export interface MarkdownHighlightedToken {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3HeaderButtonView: ExpoView {
|
||||
private static let size: CGFloat = 44
|
||||
private static let symbolSize: CGFloat = 18
|
||||
|
||||
private let button = UIButton(type: .system)
|
||||
private var systemImage = "circle"
|
||||
|
||||
let onTriggered = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
isAccessibilityElement = false
|
||||
button.frame = bounds
|
||||
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
|
||||
addSubview(button)
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
public override var intrinsicContentSize: CGSize {
|
||||
CGSize(width: Self.size, height: Self.size)
|
||||
}
|
||||
|
||||
public func setLabel(_ label: String) {
|
||||
button.accessibilityLabel = label
|
||||
}
|
||||
|
||||
public func setSystemImage(_ systemImage: String) {
|
||||
guard self.systemImage != systemImage else {
|
||||
return
|
||||
}
|
||||
self.systemImage = systemImage
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
private func applyConfiguration() {
|
||||
var configuration: UIButton.Configuration
|
||||
if #available(iOS 26.0, *) {
|
||||
configuration = .glass()
|
||||
configuration.cornerStyle = .capsule
|
||||
} else {
|
||||
configuration = .plain()
|
||||
}
|
||||
|
||||
configuration.baseForegroundColor = .label
|
||||
configuration.contentInsets = .zero
|
||||
configuration.image = UIImage(systemName: systemImage)
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
|
||||
pointSize: Self.symbolSize,
|
||||
weight: .regular
|
||||
)
|
||||
button.configuration = configuration
|
||||
}
|
||||
|
||||
@objc private func handlePress() {
|
||||
onTriggered()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3KeyboardCommandsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3KeyboardCommands")
|
||||
|
||||
View(T3KeyboardCommandsView.self) {
|
||||
Prop("enabledCommands") { (view: T3KeyboardCommandsView, commands: [String]) in
|
||||
view.setEnabledCommands(commands)
|
||||
}
|
||||
Events("onCommand")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public final class T3KeyboardCommandsView: ExpoView {
|
||||
let onCommand = EventDispatcher()
|
||||
private var enabledCommands = Set<String>()
|
||||
|
||||
public override var canBecomeFirstResponder: Bool { true }
|
||||
|
||||
public override var keyCommands: [UIKeyCommand]? {
|
||||
[
|
||||
enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"),
|
||||
enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"),
|
||||
enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"),
|
||||
enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"),
|
||||
enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"),
|
||||
enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"),
|
||||
enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"),
|
||||
enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
|
||||
].compactMap { $0 }
|
||||
}
|
||||
|
||||
func setEnabledCommands(_ commands: [String]) {
|
||||
enabledCommands = Set(commands)
|
||||
if isFirstResponder {
|
||||
resignFirstResponder()
|
||||
}
|
||||
reclaimFirstResponderIfAvailable()
|
||||
}
|
||||
|
||||
private func enabledCommand(
|
||||
_ identifier: String,
|
||||
input: String,
|
||||
modifiers: UIKeyModifierFlags,
|
||||
action: Selector,
|
||||
title: String
|
||||
) -> UIKeyCommand? {
|
||||
guard enabledCommands.contains(identifier) else { return nil }
|
||||
return command(input, modifiers: modifiers, action: action, title: title)
|
||||
}
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reclaimFirstResponderIfAvailable),
|
||||
name: UITextView.textDidEndEditingNotification,
|
||||
object: nil
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reclaimFirstResponderIfAvailable),
|
||||
name: UITextField.textDidEndEditingNotification,
|
||||
object: nil
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reclaimFirstResponderIfAvailable),
|
||||
name: UIApplication.didBecomeActiveNotification,
|
||||
object: nil
|
||||
)
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
public override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
reclaimFirstResponderIfAvailable()
|
||||
}
|
||||
|
||||
public override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
reclaimFirstResponderIfAvailable()
|
||||
}
|
||||
|
||||
private func command(
|
||||
_ input: String,
|
||||
modifiers: UIKeyModifierFlags,
|
||||
action: Selector,
|
||||
title: String
|
||||
) -> UIKeyCommand {
|
||||
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
|
||||
command.discoverabilityTitle = title
|
||||
command.wantsPriorityOverSystemBehavior = true
|
||||
return command
|
||||
}
|
||||
|
||||
@objc private func newTask() { emit("newTask") }
|
||||
@objc private func focusSearch() { emit("focusSearch") }
|
||||
@objc private func goBack() { emit("back") }
|
||||
@objc private func openFiles() { emit("files") }
|
||||
@objc private func openTerminal() { emit("terminal") }
|
||||
@objc private func openReview() { emit("review") }
|
||||
@objc private func handleToggleSidebar() { emit("toggleSidebar") }
|
||||
|
||||
private func emit(_ command: String) {
|
||||
onCommand(["command": command])
|
||||
}
|
||||
|
||||
@objc private func reclaimFirstResponderIfAvailable() {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, self.window?.t3FirstResponder == nil else { return }
|
||||
self.becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension UIView {
|
||||
var t3FirstResponder: UIResponder? {
|
||||
if isFirstResponder { return self }
|
||||
for subview in subviews {
|
||||
if let responder = subview.t3FirstResponder { return responder }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'T3NativeControls'
|
||||
s.version = '1.0.0'
|
||||
s.summary = 'Native UIKit controls for T3 Code mobile.'
|
||||
s.description = 'UIKit-backed controls that match native iOS navigation chrome.'
|
||||
s.author = 'T3 Tools'
|
||||
s.homepage = 'https://t3tools.com'
|
||||
s.platforms = {
|
||||
:ios => '18.0',
|
||||
}
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
}
|
||||
s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
import ExpoModulesCore
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,14 @@ public class T3ReviewDiffModule: Module {
|
||||
Name("T3ReviewDiffSurface")
|
||||
|
||||
View(T3ReviewDiffView.self) {
|
||||
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
|
||||
view.setRowsJson(rowsJson)
|
||||
}
|
||||
|
||||
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
|
||||
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
|
||||
view.setTokensPatchJson(tokensPatchJson)
|
||||
}
|
||||
|
||||
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
|
||||
view.setTokensResetKey(tokensResetKey)
|
||||
}
|
||||
|
||||
Prop("contentResetKey") { (view: T3ReviewDiffView, contentResetKey: String) in
|
||||
view.setContentResetKey(contentResetKey)
|
||||
}
|
||||
|
||||
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
|
||||
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
|
||||
}
|
||||
@@ -61,7 +53,42 @@ public class T3ReviewDiffModule: Module {
|
||||
view.setInitialRowIndex(initialRowIndex)
|
||||
}
|
||||
|
||||
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
|
||||
Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in
|
||||
view.setRefreshing(refreshing)
|
||||
}
|
||||
|
||||
Events(
|
||||
"onDebug",
|
||||
"onVisibleFileChange",
|
||||
"onToggleFile",
|
||||
"onToggleViewedFile",
|
||||
"onPressLine",
|
||||
"onToggleComment",
|
||||
"onPullToRefresh"
|
||||
)
|
||||
|
||||
AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
|
||||
view.scrollToFile(fileId, animated: animated)
|
||||
}
|
||||
|
||||
AsyncFunction("scrollToTop") { (view: T3ReviewDiffView, animated: Bool) in
|
||||
view.scrollToTop(animated: animated)
|
||||
}
|
||||
|
||||
// Large, frequently changing JSON values cannot be regular Fabric props. Expo's
|
||||
// prop adapter compares strings on the main thread before invoking a setter, which
|
||||
// makes a syntax-token patch capable of blocking a frame by itself.
|
||||
AsyncFunction("setRowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
|
||||
view.setRowsJson(rowsJson)
|
||||
}
|
||||
|
||||
AsyncFunction("setTokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
|
||||
AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
|
||||
view.setTokensPatchJson(tokensPatchJson)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
private struct ReviewDiffNativeRow: Decodable {
|
||||
private struct ReviewDiffNativeRow: Decodable, Sendable {
|
||||
let kind: String
|
||||
let id: String
|
||||
let fileId: String?
|
||||
@@ -21,18 +21,18 @@ private struct ReviewDiffNativeRow: Decodable {
|
||||
let commentSectionTitle: String?
|
||||
}
|
||||
|
||||
private struct ReviewDiffNativeWordDiffRange: Decodable {
|
||||
private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
|
||||
let start: Int
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ReviewDiffNativeToken: Decodable {
|
||||
private struct ReviewDiffNativeToken: Decodable, Sendable {
|
||||
let content: String
|
||||
let color: String?
|
||||
let fontStyle: Int?
|
||||
}
|
||||
|
||||
private struct ReviewDiffNativeTokenPatch: Decodable {
|
||||
private struct ReviewDiffNativeTokenPatch: Decodable, Sendable {
|
||||
let resetKey: String?
|
||||
let chunkIndex: Int?
|
||||
let tokensByRowId: [String: [ReviewDiffNativeToken]]?
|
||||
@@ -312,6 +312,10 @@ private struct ReviewDiffNativeStyle {
|
||||
}
|
||||
|
||||
public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
private let payloadDecodeQueue = DispatchQueue(
|
||||
label: "com.t3tools.review-diff.payload-decode",
|
||||
qos: .userInitiated
|
||||
)
|
||||
private let scrollView = UIScrollView()
|
||||
private let contentView = ReviewDiffContentView()
|
||||
private var rows: [ReviewDiffNativeRow] = []
|
||||
@@ -323,14 +327,25 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
private var lastMetricsDebugKey = ""
|
||||
private var lastVisibleRangeDebugKey = ""
|
||||
private var tokensResetKey = ""
|
||||
private var contentResetKey = ""
|
||||
private var initialRowIndex: Int?
|
||||
private var hasAppliedInitialRowIndex = false
|
||||
private var lastVisibleFileId: String?
|
||||
private var pendingScrollFileId: String?
|
||||
private var pendingScrollAnimated = false
|
||||
private var isProgrammaticScrollActive = false
|
||||
private var rowsDecodeGeneration = 0
|
||||
private var tokensDecodeGeneration = 0
|
||||
|
||||
let onDebug = EventDispatcher()
|
||||
let onVisibleFileChange = EventDispatcher()
|
||||
let onToggleFile = EventDispatcher()
|
||||
let onToggleViewedFile = EventDispatcher()
|
||||
let onPressLine = EventDispatcher()
|
||||
let onToggleComment = EventDispatcher()
|
||||
let onPullToRefresh = EventDispatcher()
|
||||
|
||||
private let pullRefreshControl = UIRefreshControl()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
@@ -345,6 +360,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
scrollView.showsVerticalScrollIndicator = true
|
||||
scrollView.showsHorizontalScrollIndicator = false
|
||||
scrollView.backgroundColor = contentView.theme.background
|
||||
pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
|
||||
scrollView.refreshControl = pullRefreshControl
|
||||
addSubview(scrollView)
|
||||
|
||||
contentView.backgroundColor = contentView.theme.background
|
||||
@@ -379,6 +396,13 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
updateViewportFrame()
|
||||
}
|
||||
|
||||
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
|
||||
// A direct gesture takes ownership from any interrupted programmatic jump.
|
||||
// Resume visible-file events immediately so the inspector follows the finger.
|
||||
isProgrammaticScrollActive = false
|
||||
contentView.isVerticalScrollActive = true
|
||||
}
|
||||
|
||||
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
|
||||
guard !decelerate else {
|
||||
return
|
||||
@@ -396,77 +420,125 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
}
|
||||
|
||||
func setRowsJson(_ rowsJson: String) {
|
||||
guard let data = rowsJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
rowsDecodeGeneration += 1
|
||||
let generation = rowsDecodeGeneration
|
||||
|
||||
do {
|
||||
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
|
||||
contentView.rows = rows
|
||||
hasAppliedInitialRowIndex = false
|
||||
emitDebug("rows-decoded", [
|
||||
"rows": rows.count,
|
||||
"firstKind": rows.first?.kind ?? "none",
|
||||
])
|
||||
updateContentMetrics()
|
||||
} catch {
|
||||
rows = []
|
||||
contentView.rows = []
|
||||
hasAppliedInitialRowIndex = false
|
||||
updateContentMetrics()
|
||||
emitDebug("rows-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
])
|
||||
payloadDecodeQueue.async { [weak self] in
|
||||
guard let data = rowsJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.rowsDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.rows = decodedRows
|
||||
self.contentView.rows = decodedRows
|
||||
self.hasAppliedInitialRowIndex = false
|
||||
self.lastVisibleFileId = nil
|
||||
self.emitDebug("rows-decoded", [
|
||||
"rows": decodedRows.count,
|
||||
"firstKind": decodedRows.first?.kind ?? "none",
|
||||
])
|
||||
self.updateContentMetrics()
|
||||
self.applyPendingScrollIfNeeded()
|
||||
}
|
||||
} catch {
|
||||
let message = error.localizedDescription
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.rowsDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.rows = []
|
||||
self.contentView.rows = []
|
||||
self.hasAppliedInitialRowIndex = false
|
||||
self.lastVisibleFileId = nil
|
||||
self.pendingScrollFileId = nil
|
||||
self.updateContentMetrics()
|
||||
self.emitDebug("rows-decode-failed", ["error": message])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensJson(_ tokensJson: String) {
|
||||
guard let data = tokensJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
tokensDecodeGeneration += 1
|
||||
let generation = tokensDecodeGeneration
|
||||
|
||||
do {
|
||||
contentView.tokensByRowId = try JSONDecoder().decode(
|
||||
[String: [ReviewDiffNativeToken]].self,
|
||||
from: data
|
||||
)
|
||||
} catch {
|
||||
contentView.tokensByRowId = [:]
|
||||
emitDebug("tokens-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
])
|
||||
payloadDecodeQueue.async { [weak self] in
|
||||
guard let data = tokensJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let decodedTokens = try JSONDecoder().decode(
|
||||
[String: [ReviewDiffNativeToken]].self,
|
||||
from: data
|
||||
)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.tokensDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.contentView.tokensByRowId = decodedTokens
|
||||
}
|
||||
} catch {
|
||||
let message = error.localizedDescription
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.tokensDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.contentView.tokensByRowId = [:]
|
||||
self.emitDebug("tokens-decode-failed", ["error": message])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensPatchJson(_ tokensPatchJson: String) {
|
||||
guard let data = tokensPatchJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
let contentResetKey = self.contentResetKey
|
||||
|
||||
do {
|
||||
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
|
||||
if let resetKey = patch.resetKey, resetKey != tokensResetKey {
|
||||
tokensResetKey = resetKey
|
||||
contentView.tokensByRowId = [:]
|
||||
}
|
||||
|
||||
let tokensByRowId = patch.tokensByRowId ?? [:]
|
||||
if tokensByRowId.isEmpty {
|
||||
payloadDecodeQueue.async { [weak self] in
|
||||
guard let data = tokensPatchJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
|
||||
contentView.mergeTokensByRowId(tokensByRowId)
|
||||
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
|
||||
emitDebug("tokens-patch-decoded", [
|
||||
"chunkIndex": chunkIndex,
|
||||
"rows": tokensByRowId.count,
|
||||
"totalRows": contentView.tokensByRowId.count,
|
||||
])
|
||||
do {
|
||||
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self else {
|
||||
return
|
||||
}
|
||||
guard contentResetKey == self.contentResetKey else {
|
||||
return
|
||||
}
|
||||
// A highlighter request from the previous file can finish after the view has
|
||||
// already reset. Never let that stale patch roll the native token state back.
|
||||
if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
|
||||
return
|
||||
}
|
||||
|
||||
let tokensByRowId = patch.tokensByRowId ?? [:]
|
||||
if tokensByRowId.isEmpty {
|
||||
return
|
||||
}
|
||||
|
||||
self.contentView.mergeTokensByRowId(tokensByRowId)
|
||||
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
|
||||
self.emitDebug("tokens-patch-decoded", [
|
||||
"chunkIndex": chunkIndex,
|
||||
"rows": tokensByRowId.count,
|
||||
"totalRows": self.contentView.tokensByRowId.count,
|
||||
])
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
let message = error.localizedDescription
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.emitDebug("tokens-patch-decode-failed", ["error": message])
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
emitDebug("tokens-patch-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,6 +554,27 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
])
|
||||
}
|
||||
|
||||
func setContentResetKey(_ contentResetKey: String) {
|
||||
guard contentResetKey != self.contentResetKey else {
|
||||
return
|
||||
}
|
||||
|
||||
self.contentResetKey = contentResetKey
|
||||
rowsDecodeGeneration += 1
|
||||
tokensDecodeGeneration += 1
|
||||
contentView.tokensByRowId = [:]
|
||||
rows = []
|
||||
contentView.rows = []
|
||||
hasAppliedInitialRowIndex = false
|
||||
pendingScrollFileId = nil
|
||||
isProgrammaticScrollActive = false
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
updateContentMetrics()
|
||||
updateViewportFrame()
|
||||
lastVisibleFileId = nil
|
||||
applyInitialRowIndexIfNeeded()
|
||||
}
|
||||
|
||||
func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {
|
||||
let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)
|
||||
let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)
|
||||
@@ -573,6 +666,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
contentView.invalidateVisibleViewport()
|
||||
contentView.setNeedsDisplay()
|
||||
applyInitialRowIndexIfNeeded()
|
||||
applyPendingScrollIfNeeded()
|
||||
emitVisibleFileIfNeeded()
|
||||
|
||||
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
|
||||
if debugKey != lastMetricsDebugKey {
|
||||
@@ -596,11 +691,41 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
}
|
||||
|
||||
private func finishVerticalScroll() {
|
||||
isProgrammaticScrollActive = false
|
||||
contentView.isVerticalScrollActive = false
|
||||
updateViewportFrame()
|
||||
emitVisibleRange(reason: "scroll-end")
|
||||
}
|
||||
|
||||
private func emitVisibleFileIfNeeded() {
|
||||
// Keep the explicit destination selected while UIKit animates through the files
|
||||
// between the old and new offsets. Emitting every intermediate header forces a
|
||||
// React render per crossing and makes the navigator visibly flash.
|
||||
guard !isProgrammaticScrollActive else {
|
||||
return
|
||||
}
|
||||
|
||||
// The top of the combined diff is the explicit "All files" destination.
|
||||
// Treat it as a first-class selection instead of immediately resolving the
|
||||
// first file header and undoing the navigator's optimistic selection.
|
||||
if scrollView.contentOffset.y <= 0.5 {
|
||||
guard lastVisibleFileId != nil else {
|
||||
return
|
||||
}
|
||||
lastVisibleFileId = nil
|
||||
onVisibleFileChange(["fileId": NSNull()])
|
||||
return
|
||||
}
|
||||
|
||||
guard let fileId = contentView.visibleFileId(atVerticalOffset: scrollView.contentOffset.y),
|
||||
fileId != lastVisibleFileId else {
|
||||
return
|
||||
}
|
||||
|
||||
lastVisibleFileId = fileId
|
||||
onVisibleFileChange(["fileId": fileId])
|
||||
}
|
||||
|
||||
private func emitVisibleRange(reason: String) {
|
||||
guard let range = contentView.currentVisibleRowRange() else {
|
||||
return
|
||||
@@ -670,6 +795,33 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
applyInitialRowIndexIfNeeded()
|
||||
}
|
||||
|
||||
func scrollToFile(_ fileId: String, animated: Bool) {
|
||||
pendingScrollFileId = fileId
|
||||
pendingScrollAnimated = animated
|
||||
applyPendingScrollIfNeeded()
|
||||
}
|
||||
|
||||
func scrollToTop(animated: Bool) {
|
||||
pendingScrollFileId = nil
|
||||
pendingScrollAnimated = false
|
||||
setVerticalContentOffset(0, animated: animated)
|
||||
}
|
||||
|
||||
@objc private func handlePullToRefresh() {
|
||||
onPullToRefresh([:])
|
||||
}
|
||||
|
||||
/// Driven from JS: set to false once the reload completes to dismiss the spinner.
|
||||
func setRefreshing(_ refreshing: Bool) {
|
||||
if refreshing {
|
||||
if !pullRefreshControl.isRefreshing {
|
||||
pullRefreshControl.beginRefreshing()
|
||||
}
|
||||
} else if pullRefreshControl.isRefreshing {
|
||||
pullRefreshControl.endRefreshing()
|
||||
}
|
||||
}
|
||||
|
||||
private func applyStyle() {
|
||||
contentView.style = ReviewDiffNativeStyle
|
||||
.resolve(stylePayload)
|
||||
@@ -686,6 +838,38 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
)
|
||||
contentView.verticalOffset = scrollView.contentOffset.y
|
||||
contentView.invalidateVisibleViewport()
|
||||
emitVisibleFileIfNeeded()
|
||||
}
|
||||
|
||||
private func applyPendingScrollIfNeeded() {
|
||||
guard let fileId = pendingScrollFileId,
|
||||
bounds.height > 0 else {
|
||||
return
|
||||
}
|
||||
|
||||
guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else {
|
||||
if !rows.isEmpty {
|
||||
pendingScrollFileId = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let animated = pendingScrollAnimated
|
||||
pendingScrollFileId = nil
|
||||
pendingScrollAnimated = false
|
||||
setVerticalContentOffset(headerOffset, animated: animated)
|
||||
}
|
||||
|
||||
private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) {
|
||||
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
|
||||
let clampedOffset = min(max(targetOffset, 0), maxOffset)
|
||||
let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5
|
||||
isProgrammaticScrollActive = shouldAnimate
|
||||
contentView.isVerticalScrollActive = shouldAnimate
|
||||
scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
|
||||
if !shouldAnimate {
|
||||
updateViewportFrame()
|
||||
}
|
||||
}
|
||||
|
||||
private func applyInitialRowIndexIfNeeded() {
|
||||
@@ -1255,6 +1439,32 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
|
||||
return rowOffsets[rowIndex]
|
||||
}
|
||||
|
||||
func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? {
|
||||
guard let firstHeaderRowIndex = fileHeaderRowIndices.first else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var lowerBound = 0
|
||||
var upperBound = fileHeaderRowIndices.count
|
||||
while lowerBound < upperBound {
|
||||
let midpoint = (lowerBound + upperBound) / 2
|
||||
let rowIndex = fileHeaderRowIndices[midpoint]
|
||||
if rowOffsets[rowIndex] <= verticalOffset + 0.5 {
|
||||
lowerBound = midpoint + 1
|
||||
} else {
|
||||
upperBound = midpoint
|
||||
}
|
||||
}
|
||||
|
||||
let rowIndex = lowerBound > 0
|
||||
? fileHeaderRowIndices[lowerBound - 1]
|
||||
: firstHeaderRowIndex
|
||||
guard rows.indices.contains(rowIndex) else {
|
||||
return nil
|
||||
}
|
||||
return resolvedFileId(for: rows[rowIndex])
|
||||
}
|
||||
|
||||
private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {
|
||||
fileHeaderRowIndices.first { rowIndex in
|
||||
rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId
|
||||
|
||||
+10
@@ -7,6 +7,12 @@ class T3TerminalModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3TerminalSurface")
|
||||
|
||||
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
|
||||
// logs so a stale native binary is distinguishable from a broken key pipeline.
|
||||
Constants(
|
||||
"hardwareKeyRevision" to 2,
|
||||
)
|
||||
|
||||
View(T3TerminalView::class) {
|
||||
Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
|
||||
view.terminalKey = terminalKey
|
||||
@@ -20,6 +26,10 @@ class T3TerminalModule : Module() {
|
||||
view.fontSize = fontSize.toFloat()
|
||||
}
|
||||
|
||||
Prop("focusRequest") { view: T3TerminalView, focusRequest: Double ->
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
+19
-2
@@ -62,6 +62,15 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
|
||||
var themeConfig: String = ""
|
||||
|
||||
var focusRequest: Double = 0.0
|
||||
set(value) {
|
||||
val previous = field
|
||||
field = value
|
||||
if (value != previous && value > 0) {
|
||||
requestKeyboardFocus()
|
||||
}
|
||||
}
|
||||
|
||||
var backgroundColorHex: String = "#24292E"
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -113,11 +122,19 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
}
|
||||
inputView.setOnKeyListener { _, keyCode, event ->
|
||||
if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false
|
||||
when (keyCode) {
|
||||
android.view.KeyEvent.KEYCODE_DEL -> {
|
||||
when {
|
||||
keyCode == android.view.KeyEvent.KEYCODE_DEL -> {
|
||||
onInput(mapOf("data" to "\u007F"))
|
||||
true
|
||||
}
|
||||
// Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...).
|
||||
event.isCtrlPressed &&
|
||||
keyCode in android.view.KeyEvent.KEYCODE_A..android.view.KeyEvent.KEYCODE_Z -> {
|
||||
onInput(
|
||||
mapOf("data" to (keyCode - android.view.KeyEvent.KEYCODE_A + 1).toChar().toString()),
|
||||
)
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,12 @@ public class T3TerminalModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3TerminalSurface")
|
||||
|
||||
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
|
||||
// logs so a stale native binary is distinguishable from a broken key pipeline.
|
||||
Constants([
|
||||
"hardwareKeyRevision": 2,
|
||||
])
|
||||
|
||||
View(T3TerminalView.self) {
|
||||
Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in
|
||||
view.terminalKey = terminalKey
|
||||
@@ -17,6 +23,10 @@ public class T3TerminalModule: Module {
|
||||
view.fontSize = CGFloat(fontSize)
|
||||
}
|
||||
|
||||
Prop("focusRequest") { (view: T3TerminalView, focusRequest: Double) in
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -22,13 +22,129 @@ private enum GhosttyRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes hardware-keyboard combos that UITextField never surfaces through its
|
||||
/// text-editing delegate (control combos, Escape, Tab, arrow keys) into the byte
|
||||
/// sequences a terminal expects.
|
||||
///
|
||||
/// Capture uses UIKeyCommand with `wantsPriorityOverSystemBehavior` rather than
|
||||
/// `pressesBegan`: while a text field is first responder, iPadOS routes hardware key
|
||||
/// events through the text-input system, which can consume presses before they reach
|
||||
/// responder press callbacks. Registered key commands are matched deterministically
|
||||
/// before that happens.
|
||||
private enum TerminalHardwareKeyEncoder {
|
||||
/// Characters that produce a control byte when combined with Ctrl.
|
||||
private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? "
|
||||
|
||||
static func makeKeyCommands(action: Selector) -> [UIKeyCommand] {
|
||||
var commands: [UIKeyCommand] = []
|
||||
|
||||
let specialInputs = [
|
||||
UIKeyCommand.inputEscape,
|
||||
UIKeyCommand.inputUpArrow,
|
||||
UIKeyCommand.inputDownArrow,
|
||||
UIKeyCommand.inputLeftArrow,
|
||||
UIKeyCommand.inputRightArrow,
|
||||
"\t",
|
||||
]
|
||||
for input in specialInputs {
|
||||
commands.append(makeCommand(input: input, modifierFlags: [], action: action))
|
||||
}
|
||||
commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action))
|
||||
|
||||
for character in controlInputs {
|
||||
commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action))
|
||||
commands.append(
|
||||
makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action)
|
||||
)
|
||||
}
|
||||
|
||||
return commands
|
||||
}
|
||||
|
||||
private static func makeCommand(
|
||||
input: String,
|
||||
modifierFlags: UIKeyModifierFlags,
|
||||
action: Selector
|
||||
) -> UIKeyCommand {
|
||||
let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action)
|
||||
command.wantsPriorityOverSystemBehavior = true
|
||||
return command
|
||||
}
|
||||
|
||||
static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? {
|
||||
switch input {
|
||||
case UIKeyCommand.inputEscape:
|
||||
return "\u{1B}"
|
||||
case UIKeyCommand.inputUpArrow:
|
||||
return "\u{1B}[A"
|
||||
case UIKeyCommand.inputDownArrow:
|
||||
return "\u{1B}[B"
|
||||
case UIKeyCommand.inputRightArrow:
|
||||
return "\u{1B}[C"
|
||||
case UIKeyCommand.inputLeftArrow:
|
||||
return "\u{1B}[D"
|
||||
case "\t":
|
||||
return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t"
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
guard modifiers.contains(.control) else { return nil }
|
||||
guard let scalar = input.lowercased().unicodeScalars.first else { return nil }
|
||||
return controlSequence(for: scalar)
|
||||
}
|
||||
|
||||
private static func controlSequence(for scalar: Unicode.Scalar) -> String? {
|
||||
switch scalar {
|
||||
case "a"..."z":
|
||||
// Ctrl+A..Z -> 0x01..0x1A (Ctrl+C = ETX, Ctrl+Z = SUB, ...).
|
||||
return UnicodeScalar(scalar.value - 96).map(String.init)
|
||||
case " ", "@":
|
||||
return "\u{00}"
|
||||
case "[":
|
||||
return "\u{1B}"
|
||||
case "\\":
|
||||
return "\u{1C}"
|
||||
case "]":
|
||||
return "\u{1D}"
|
||||
case "^":
|
||||
return "\u{1E}"
|
||||
case "_", "-":
|
||||
return "\u{1F}"
|
||||
case "?":
|
||||
return "\u{7F}"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class TerminalInputField: UITextField {
|
||||
var onDeleteBackward: (() -> Void)?
|
||||
var onInsert: ((String) -> Void)?
|
||||
|
||||
private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
|
||||
action: #selector(handleHardwareKeyCommand(_:))
|
||||
)
|
||||
|
||||
override var keyCommands: [UIKeyCommand]? {
|
||||
Self.hardwareKeyCommands
|
||||
}
|
||||
|
||||
override func deleteBackward() {
|
||||
onDeleteBackward?()
|
||||
super.deleteBackward()
|
||||
}
|
||||
|
||||
@objc
|
||||
private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
|
||||
guard let input = command.input else { return }
|
||||
guard let sequence = TerminalHardwareKeyEncoder.sequence(
|
||||
input: input,
|
||||
modifiers: command.modifierFlags
|
||||
) else { return }
|
||||
onInsert?(sequence)
|
||||
}
|
||||
}
|
||||
|
||||
private enum TerminalAppearanceScheme: String {
|
||||
@@ -108,6 +224,15 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
var focusRequest: Double = 0 {
|
||||
didSet {
|
||||
guard oldValue != focusRequest else { return }
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.requestKeyboardFocus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
|
||||
didSet {
|
||||
guard oldValue != appearanceScheme else { return }
|
||||
@@ -167,6 +292,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
inputField.onDeleteBackward = { [weak self] in
|
||||
self?.emitInput("\u{7F}")
|
||||
}
|
||||
inputField.onInsert = { [weak self] data in
|
||||
self?.emitInput(data)
|
||||
}
|
||||
|
||||
focusTapGesture.addTarget(self, action: #selector(handleViewportTap))
|
||||
terminalViewport.addGestureRecognizer(focusTapGesture)
|
||||
|
||||
+31
-20
@@ -5,7 +5,7 @@
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"dev": "expo start --clear",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --clear",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear",
|
||||
"start": "expo start",
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
"start:preview": "APP_VARIANT=preview expo start",
|
||||
@@ -43,12 +43,16 @@
|
||||
"@clerk/expo": "catalog:",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
"@expo/metro-runtime": "~56.0.15",
|
||||
"@expo/ui": "~56.0.18",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@react-native-menu/menu": "^2.0.0",
|
||||
"@react-navigation/elements": "2.9.26",
|
||||
"@react-navigation/native": "7.3.4",
|
||||
"@react-navigation/native-stack": "7.17.6",
|
||||
"@shikijs/core": "4.2.0",
|
||||
"@shikijs/engine-javascript": "4.2.0",
|
||||
"@shikijs/langs": "4.2.0",
|
||||
@@ -62,38 +66,37 @@
|
||||
"clsx": "^2.1.1",
|
||||
"diff": "8.0.3",
|
||||
"effect": "catalog:",
|
||||
"expo": "^56.0.0",
|
||||
"expo-asset": "~56.0.15",
|
||||
"expo-auth-session": "~56.0.12",
|
||||
"expo-build-properties": "~56.0.15",
|
||||
"expo-camera": "~56.0.7",
|
||||
"expo-clipboard": "~56.0.3",
|
||||
"expo-constants": "~56.0.16",
|
||||
"expo": "~56.0.12",
|
||||
"expo-asset": "~56.0.17",
|
||||
"expo-auth-session": "~56.0.14",
|
||||
"expo-build-properties": "~56.0.19",
|
||||
"expo-camera": "~56.0.8",
|
||||
"expo-clipboard": "~56.0.4",
|
||||
"expo-constants": "~56.0.18",
|
||||
"expo-crypto": "~56.0.4",
|
||||
"expo-dev-client": "~56.0.16",
|
||||
"expo-file-system": "~56.0.7",
|
||||
"expo-font": "~56.0.5",
|
||||
"expo-dev-client": "~56.0.20",
|
||||
"expo-file-system": "~56.0.8",
|
||||
"expo-font": "~56.0.7",
|
||||
"expo-glass-effect": "~56.0.4",
|
||||
"expo-haptics": "~56.0.3",
|
||||
"expo-image-picker": "~56.0.14",
|
||||
"expo-linking": "~56.0.12",
|
||||
"expo-image-picker": "~56.0.18",
|
||||
"expo-linking": "~56.0.14",
|
||||
"expo-network": "~56.0.5",
|
||||
"expo-notifications": "~56.0.14",
|
||||
"expo-notifications": "~56.0.18",
|
||||
"expo-paste-input": "^0.1.15",
|
||||
"expo-router": "~56.2.7",
|
||||
"expo-secure-store": "~56.0.4",
|
||||
"expo-splash-screen": "~56.0.10",
|
||||
"expo-symbols": "~56.0.5",
|
||||
"expo-updates": "~56.0.17",
|
||||
"expo-symbols": "~56.0.6",
|
||||
"expo-updates": "~56.0.19",
|
||||
"expo-web-browser": "~56.0.5",
|
||||
"expo-widgets": "~56.0.15",
|
||||
"expo-widgets": "~56.0.19",
|
||||
"punycode": "^2.3.1",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.7",
|
||||
"react-native-keyboard-controller": "1.21.13",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
@@ -117,5 +120,13 @@
|
||||
},
|
||||
"overrides": {
|
||||
"react-native-nitro-markdown": "file:deps/react-native-nitro-markdown-0.5.0.tgz"
|
||||
},
|
||||
"expo": {
|
||||
"autolinking": {
|
||||
"buildFromSource": [
|
||||
"react-native-screens",
|
||||
"@react-native-menu/menu"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use strict";
|
||||
|
||||
// Bundle the widget asset catalog into an app-extension (widget) target.
|
||||
//
|
||||
// expo-widgets generates the widget target without a Resources build phase, and
|
||||
// hand-adding a PBXResourcesBuildPhase does NOT get picked up — xcodebuild's
|
||||
// planner never schedules `actool` for it (verified: even a full re-plan skips
|
||||
// it). So instead we add a shell-script phase that runs `actool` directly and
|
||||
// drops the compiled Assets.car into the extension bundle. Marked
|
||||
// alwaysOutOfDate so the build system always runs it.
|
||||
//
|
||||
// Idempotent across re-runs. Returns true when it added the phase, false when
|
||||
// it was already present. Throws when the target does not exist — that means
|
||||
// this ran before expo-widgets created the target (plugin ordering bug) and
|
||||
// silently skipping would ship a widget without its assets.
|
||||
|
||||
const PHASE_NAME = "Compile Widget Assets";
|
||||
|
||||
// Compiles ExpoWidgetsTarget/Assets.xcassets into the extension's resources dir.
|
||||
// Uses only Xcode-provided build settings so it works for device + simulator.
|
||||
const ACTOOL_SCRIPT = [
|
||||
"set -e",
|
||||
'CATALOG="${SRCROOT}/ExpoWidgetsTarget/Assets.xcassets"',
|
||||
'if [ ! -d "$CATALOG" ]; then',
|
||||
' echo "error: widget asset catalog not found at $CATALOG (expo-widgets wiped it? check plugin ordering in app.config.ts)"',
|
||||
" exit 1",
|
||||
"fi",
|
||||
'DEST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"',
|
||||
'mkdir -p "$DEST"',
|
||||
'xcrun actool "$CATALOG" --compile "$DEST" --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET:-16.0}" --output-format human-readable-text',
|
||||
].join("\n");
|
||||
|
||||
function stripComments(map) {
|
||||
const out = {};
|
||||
for (const key of Object.keys(map || {})) {
|
||||
if (key.endsWith("_comment")) continue;
|
||||
out[key] = map[key];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function findByName(map, name) {
|
||||
for (const [uuid, value] of Object.entries(stripComments(map))) {
|
||||
if (value && value.name === name) return { uuid, value };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('xcode').XcodeProject} proj
|
||||
* @param {{ targetName: string }} opts
|
||||
*/
|
||||
function addWidgetAssetCatalog(proj, opts) {
|
||||
const objects = proj.hash.project.objects;
|
||||
const target = findByName(objects.PBXNativeTarget, opts.targetName);
|
||||
if (!target) {
|
||||
throw new Error(
|
||||
`addWidgetAssetCatalog: target "${opts.targetName}" not found — ` +
|
||||
"withWidgetLogoAsset must be registered before expo-widgets so its " +
|
||||
"xcodeproj mod runs after the widget target is created.",
|
||||
);
|
||||
}
|
||||
|
||||
const phases = target.value.buildPhases || [];
|
||||
const existing = objects.PBXShellScriptBuildPhase || {};
|
||||
const already = Object.entries(stripComments(existing)).some(
|
||||
([uuid, value]) =>
|
||||
value && value.name === `"${PHASE_NAME}"` && phases.some((p) => p.value === uuid),
|
||||
);
|
||||
if (already) return false;
|
||||
|
||||
const { uuid } = proj.addBuildPhase([], "PBXShellScriptBuildPhase", PHASE_NAME, target.uuid, {
|
||||
shellPath: "/bin/sh",
|
||||
shellScript: ACTOOL_SCRIPT,
|
||||
});
|
||||
// Always run: input-analysis is exactly what skipped the Resources phase.
|
||||
objects.PBXShellScriptBuildPhase[uuid].alwaysOutOfDate = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = { addWidgetAssetCatalog };
|
||||
@@ -0,0 +1,52 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const { withDangerousMod } = require("expo/config-plugins");
|
||||
|
||||
const MARKER = "# t3code: repair cached CocoaPods UUID allocation before SPM integration";
|
||||
const UUID_REPAIR = `${MARKER}
|
||||
pods_project = installer.pods_project
|
||||
existing_uuids = pods_project.objects.map(&:uuid)
|
||||
uuid_prefix = pods_project.instance_variable_get(:@uuid_prefix)[0, 6]
|
||||
sequential_uuid = /\\A#{Regexp.escape(uuid_prefix)}([0-9A-F]{7})0\\z/
|
||||
highest_index = existing_uuids.filter_map do |uuid|
|
||||
match = sequential_uuid.match(uuid)
|
||||
match && match[1].to_i(16)
|
||||
end.max || -1
|
||||
|
||||
# Pod::Project generates sequential UUIDs without collision checks because CocoaPods
|
||||
# normally creates the project in this process. EAS can restore Pods.xcodeproj from
|
||||
# cache, leaving the allocator behind the loaded objects. React Native's SPM support
|
||||
# then reuses an existing UUID and silently corrupts the project graph.
|
||||
next_index = highest_index + 1
|
||||
pods_project.instance_variable_set(:@generated_uuids, Array.new(next_index))
|
||||
pods_project.instance_variable_set(:@available_uuids, [])
|
||||
pods_project.generate_available_uuid_list(1_000)
|
||||
Pod::UI.puts "T3Code: reset CocoaPods UUID allocator at #{next_index} (#{existing_uuids.length} existing objects)"
|
||||
`;
|
||||
|
||||
module.exports = function withIosCocoaPodsUuidCache(config) {
|
||||
return withDangerousMod(config, [
|
||||
"ios",
|
||||
(nextConfig) => {
|
||||
const podfilePath = path.join(nextConfig.modRequest.platformProjectRoot, "Podfile");
|
||||
const podfile = fs.readFileSync(podfilePath, "utf8");
|
||||
|
||||
if (podfile.includes(MARKER)) {
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
const postInstallStart = "post_install do |installer|\n";
|
||||
if (!podfile.includes(postInstallStart)) {
|
||||
throw new Error("Unable to repair CocoaPods UUID allocation: post_install is missing.");
|
||||
}
|
||||
|
||||
fs.writeFileSync(
|
||||
podfilePath,
|
||||
podfile.replace(postInstallStart, `${postInstallStart}${UUID_REPAIR}`),
|
||||
"utf8",
|
||||
);
|
||||
return nextConfig;
|
||||
},
|
||||
]);
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
const { withAppDelegate, withInfoPlist } = require("expo/config-plugins");
|
||||
|
||||
const SCENE_DELEGATE = `
|
||||
|
||||
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func scene(
|
||||
_ scene: UIScene,
|
||||
willConnectTo session: UISceneSession,
|
||||
options connectionOptions: UIScene.ConnectionOptions
|
||||
) {
|
||||
guard
|
||||
let windowScene = scene as? UIWindowScene,
|
||||
let appDelegate = UIApplication.shared.delegate as? AppDelegate
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
let appWindow: UIWindow
|
||||
if let existingWindow = appDelegate.window {
|
||||
appWindow = existingWindow
|
||||
} else {
|
||||
appWindow = UIWindow(windowScene: windowScene)
|
||||
appDelegate.window = appWindow
|
||||
appDelegate.reactNativeFactory?.startReactNative(
|
||||
withModuleName: "main",
|
||||
in: appWindow,
|
||||
launchOptions: nil)
|
||||
}
|
||||
|
||||
window = appWindow
|
||||
appWindow.windowScene = windowScene
|
||||
appWindow.makeKeyAndVisible()
|
||||
|
||||
if let url = connectionOptions.urlContexts.first?.url {
|
||||
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
|
||||
}
|
||||
|
||||
if let userActivity = connectionOptions.userActivities.first {
|
||||
_ = appDelegate.application(
|
||||
UIApplication.shared,
|
||||
continue: userActivity,
|
||||
restorationHandler: { _ in })
|
||||
}
|
||||
}
|
||||
|
||||
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
|
||||
guard
|
||||
let url = URLContexts.first?.url,
|
||||
let appDelegate = UIApplication.shared.delegate as? AppDelegate
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
|
||||
}
|
||||
|
||||
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
|
||||
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
|
||||
return
|
||||
}
|
||||
|
||||
_ = appDelegate.application(
|
||||
UIApplication.shared,
|
||||
continue: userActivity,
|
||||
restorationHandler: { _ in })
|
||||
}
|
||||
}`;
|
||||
|
||||
module.exports = function withIosSceneLifecycle(config) {
|
||||
config = withInfoPlist(config, (nextConfig) => {
|
||||
nextConfig.modResults.UIApplicationSceneManifest = {
|
||||
UIApplicationSupportsMultipleScenes: false,
|
||||
UISceneConfigurations: {
|
||||
UIWindowSceneSessionRoleApplication: [
|
||||
{
|
||||
UISceneConfigurationName: "Default Configuration",
|
||||
UISceneDelegateClassName: "$(PRODUCT_MODULE_NAME).SceneDelegate",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
return nextConfig;
|
||||
});
|
||||
|
||||
return withAppDelegate(config, (nextConfig) => {
|
||||
if (nextConfig.modResults.language !== "swift") {
|
||||
throw new Error("The iOS scene lifecycle plugin requires a Swift AppDelegate.");
|
||||
}
|
||||
|
||||
if (!nextConfig.modResults.contents.includes("class SceneDelegate:")) {
|
||||
nextConfig.modResults.contents += SCENE_DELEGATE;
|
||||
}
|
||||
|
||||
return nextConfig;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
|
||||
// Ships the branded T3 mark to the Live Activity / widget extension.
|
||||
//
|
||||
// expo-widgets generates ExpoWidgetsTarget without a Resources build phase and
|
||||
// has no asset support, so this plugin (a) writes an SVG template image set into
|
||||
// the generated widget asset catalog and (b) wires that catalog into the widget
|
||||
// target with an actool build phase.
|
||||
//
|
||||
// ORDERING: must be listed BEFORE "expo-widgets" in the plugins array. Expo
|
||||
// chains same-type mods so the last-registered runs FIRST; registering this
|
||||
// plugin earlier makes its mods run AFTER expo-widgets' mods. That matters
|
||||
// twice: expo-widgets' dangerous mod rmSync's ios/ExpoWidgetsTarget/ (deleting
|
||||
// any catalog written before it), and its xcodeproj mod is what creates the
|
||||
// widget target. Listed after expo-widgets, both steps silently no-op on a
|
||||
// fresh prebuild — which is how prod build 8 shipped without the logo.
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
|
||||
const { addWidgetAssetCatalog } = require("./lib/addWidgetAssetCatalog.cjs");
|
||||
|
||||
const TARGET_NAME = "ExpoWidgetsTarget";
|
||||
const CATALOG_NAME = "Assets.xcassets";
|
||||
const IMAGE_SET = "T3Mark.imageset";
|
||||
const SVG_NAME = "T3Mark.svg";
|
||||
|
||||
const CATALOG_CONTENTS = JSON.stringify({ info: { author: "expo", version: 1 } }, null, 2) + "\n";
|
||||
const IMAGE_SET_CONTENTS =
|
||||
JSON.stringify(
|
||||
{
|
||||
images: [{ idiom: "universal", filename: SVG_NAME }],
|
||||
info: { author: "expo", version: 1 },
|
||||
properties: {
|
||||
"preserves-vector-representation": true,
|
||||
"template-rendering-intent": "template",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n";
|
||||
|
||||
function withAssetFiles(config) {
|
||||
return withDangerousMod(config, [
|
||||
"ios",
|
||||
(cfg) => {
|
||||
const source = path.join(cfg.modRequest.projectRoot, "assets", "widget", SVG_NAME);
|
||||
const catalogDir = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, CATALOG_NAME);
|
||||
const imageSetDir = path.join(catalogDir, IMAGE_SET);
|
||||
fs.mkdirSync(imageSetDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(catalogDir, "Contents.json"), CATALOG_CONTENTS);
|
||||
fs.writeFileSync(path.join(imageSetDir, "Contents.json"), IMAGE_SET_CONTENTS);
|
||||
fs.copyFileSync(source, path.join(imageSetDir, SVG_NAME));
|
||||
return cfg;
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function withAssetWiring(config) {
|
||||
return withXcodeProject(config, (cfg) => {
|
||||
addWidgetAssetCatalog(cfg.modResults, { targetName: TARGET_NAME });
|
||||
return cfg;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = function withWidgetLogoAsset(config) {
|
||||
return withAssetWiring(withAssetFiles(config));
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
|
||||
// One-off: apply the widget asset-catalog wiring to the already-generated
|
||||
// ios/ project so the current build compiles ExpoWidgetsTarget/Assets.xcassets
|
||||
// without a full `expo prebuild`. The durable equivalent lives in
|
||||
// plugins/withWidgetLogoAsset.cjs and runs on prebuild.
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
const xcodePath = require.resolve("xcode", {
|
||||
paths: [
|
||||
require.resolve("@expo/config-plugins", { paths: [require.resolve("expo/package.json")] }),
|
||||
],
|
||||
});
|
||||
const xcode = require(xcodePath);
|
||||
const { addWidgetAssetCatalog } = require("../plugins/lib/addWidgetAssetCatalog.cjs");
|
||||
|
||||
const pbxprojPath = path.join(__dirname, "..", "ios", "T3CodeDev.xcodeproj", "project.pbxproj");
|
||||
const proj = xcode.project(pbxprojPath);
|
||||
proj.parseSync();
|
||||
|
||||
const added = addWidgetAssetCatalog(proj, { targetName: "ExpoWidgetsTarget" });
|
||||
|
||||
if (added) {
|
||||
fs.writeFileSync(pbxprojPath, proj.writeSync());
|
||||
console.log("Added widget asset-compile phase to ExpoWidgetsTarget.");
|
||||
} else {
|
||||
console.log("No change: phase already present.");
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
useFonts,
|
||||
} from "@expo-google-fonts/dm-sans";
|
||||
import * as Linking from "expo-linking";
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
import { StatusBar, useColorScheme } from "react-native";
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { KeyboardProvider } from "react-native-keyboard-controller";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
|
||||
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { useEffect } from "react";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
import { useThemeColor } from "./lib/useThemeColor";
|
||||
|
||||
import "../global.css";
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
};
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
|
||||
export default function App() {
|
||||
const [fontsLoaded] = useFonts({
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
});
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
|
||||
useEffect(() => {
|
||||
if (fontsLoaded) SplashScreen.hide();
|
||||
}, [fontsLoaded]);
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<AppearancePreferencesProvider>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
<StatusBar
|
||||
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
|
||||
backgroundColor={statusBarBg}
|
||||
translucent
|
||||
/>
|
||||
{/* The navigation theme drives the NATIVE header appearance: native-stack
|
||||
forwards `dark` as the nav bar's overrideUserInterfaceStyle. Without
|
||||
this, React Navigation defaults to its light theme and every native
|
||||
header (glass buttons, title, materials) is forced light even when
|
||||
the system is in dark mode. */}
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</AppearancePreferencesProvider>
|
||||
</CloudAuthProvider>
|
||||
</RegistryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
import {
|
||||
createPathConfigForStaticNavigation,
|
||||
getPathFromState,
|
||||
NavigationState,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
} from "@react-navigation/native";
|
||||
import {
|
||||
createNativeStackNavigator,
|
||||
createNativeStackScreen,
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
|
||||
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
|
||||
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
|
||||
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
|
||||
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
|
||||
import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet";
|
||||
import { ReviewSheet } from "./features/review/ReviewSheet";
|
||||
import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen";
|
||||
import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet";
|
||||
import { GitCommitSheet } from "./features/threads/git/GitCommitSheet";
|
||||
import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";
|
||||
import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet";
|
||||
import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen";
|
||||
import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen";
|
||||
import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen";
|
||||
import { HomeRouteScreen } from "./features/home/HomeRouteScreen";
|
||||
import { AddProjectDestinationRoute } from "./features/projects/AddProjectDestinationRoute";
|
||||
import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
|
||||
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
|
||||
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
|
||||
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
|
||||
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
|
||||
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
|
||||
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
|
||||
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
|
||||
// background stay STATIC config while still adapting to appearance changes.
|
||||
const SHEET_BACKGROUND_COLOR =
|
||||
Platform.OS === "ios"
|
||||
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
|
||||
: undefined;
|
||||
|
||||
type AppScreenOptions = NativeStackNavigationOptions & {
|
||||
readonly unstable_navigationItemStyle?: "editor";
|
||||
};
|
||||
|
||||
// Shared header presets. Screens only override genuinely dynamic values (titles,
|
||||
// subtitles, toolbar items, search callbacks) via NativeStackScreenOptions.
|
||||
//
|
||||
// GLASS: transparent header over the screen's primary scroll view, with the iOS 26
|
||||
// scroll-edge blur sampling the content (Home, Thread, Files tree, settings sheet).
|
||||
const GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: Platform.OS === "ios",
|
||||
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
};
|
||||
|
||||
// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally
|
||||
// (file viewer, terminal, review) — there is nothing for glass to sample there.
|
||||
const SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
? // native-stack types this as `string`, but the native side accepts any
|
||||
// ColorValue including DynamicColorIOS.
|
||||
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: false,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
};
|
||||
|
||||
// Solid header variant for screens inside sheets (centered title, no editor style).
|
||||
const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...SOLID_HEADER_OPTIONS,
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
// Sheets read better with the iOS-default centered title (no editor style).
|
||||
unstable_navigationItemStyle: undefined,
|
||||
},
|
||||
screens: {
|
||||
Settings: createNativeStackScreen({
|
||||
screen: SettingsRouteScreen,
|
||||
linking: "",
|
||||
options: {
|
||||
title: "Settings",
|
||||
},
|
||||
}),
|
||||
SettingsEnvironments: createNativeStackScreen({
|
||||
screen: SettingsEnvironmentsRouteScreen,
|
||||
linking: "environments",
|
||||
options: {
|
||||
title: "Environments",
|
||||
},
|
||||
}),
|
||||
SettingsEnvironmentNew: createNativeStackScreen({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "environment-new",
|
||||
options: {
|
||||
title: "Add Environment",
|
||||
},
|
||||
}),
|
||||
SettingsArchive: createNativeStackScreen({
|
||||
screen: ArchivedThreadsRouteScreen,
|
||||
linking: "archive",
|
||||
options: {
|
||||
title: "Archived Threads",
|
||||
},
|
||||
}),
|
||||
SettingsAppearance: createNativeStackScreen({
|
||||
screen: SettingsAppearanceRouteScreen,
|
||||
linking: "appearance",
|
||||
options: {
|
||||
title: "Appearance",
|
||||
},
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
screen: SettingsWaitlistRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Join the waitlist",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// Thread routes live FLAT in the root stack (not in a nested navigator). A nested
|
||||
// stack means a second UINavigationController with its own UINavigationBar, which
|
||||
// breaks iOS 26's shared-header morphing between Home and Thread (each pair inside
|
||||
// one bar morphs; across two bars the whole screen slides). Flat linking paths keep
|
||||
// the same deep-link URLs the nested config produced.
|
||||
const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
|
||||
|
||||
// New-task / add-project flow: nested navigator inside the formSheet (Settings-sheet
|
||||
// pattern — a plain formSheet screen cannot render a stack header; the header and
|
||||
// in-sheet pushes come from this nested stack).
|
||||
const NewTaskSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "NewTask",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
// Sheets read better with the iOS-default centered title (no editor style).
|
||||
unstable_navigationItemStyle: undefined,
|
||||
},
|
||||
screens: {
|
||||
NewTask: createNativeStackScreen({
|
||||
screen: NewTaskRouteScreen,
|
||||
linking: "",
|
||||
options: {
|
||||
title: "Choose project",
|
||||
},
|
||||
}),
|
||||
NewTaskDraft: createNativeStackScreen({
|
||||
screen: NewTaskDraftRouteScreen,
|
||||
linking: "draft",
|
||||
// The draft composer has no scroll view for glass to sample; a solid
|
||||
// header also lays the content out below the bar (no manual inset).
|
||||
options: SHEET_SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
AddProject: createNativeStackScreen({
|
||||
screen: AddProjectSourceRoute,
|
||||
linking: "add-project",
|
||||
options: {
|
||||
title: "Add Project",
|
||||
},
|
||||
}),
|
||||
AddProjectRepository: createNativeStackScreen({
|
||||
screen: AddProjectRepositoryRoute,
|
||||
linking: "add-project/repository",
|
||||
}),
|
||||
AddProjectDestination: createNativeStackScreen({
|
||||
screen: AddProjectDestinationRoute,
|
||||
linking: "add-project/destination",
|
||||
}),
|
||||
AddProjectLocal: createNativeStackScreen({
|
||||
screen: AddProjectLocalRoute,
|
||||
linking: "add-project/local",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// Routes presented as sheets/overlays ON TOP of the workspace. They must not
|
||||
// influence the adaptive workspace layout: opening Settings over Home should
|
||||
// not flip the sidebar in or change the active thread.
|
||||
const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"ConnectOnboarding",
|
||||
"Connections",
|
||||
"ConnectionsNew",
|
||||
"GitBranches",
|
||||
"GitCommit",
|
||||
"GitConfirm",
|
||||
"GitOverview",
|
||||
"NewTaskSheet",
|
||||
"SettingsSheet",
|
||||
"ThreadReviewComment",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Pathname of the topmost NON-overlay route — the screen the workspace is
|
||||
* actually "on", regardless of any sheets floating above it.
|
||||
*/
|
||||
function workspacePathFromState(state: NavigationState): string {
|
||||
const routes = state.routes.filter((route) => !WORKSPACE_OVERLAY_ROUTES.has(route.name));
|
||||
const effectiveState =
|
||||
routes.length > 0 && routes.length !== state.routes.length
|
||||
? ({ ...state, routes, index: routes.length - 1 } as NavigationState)
|
||||
: state;
|
||||
const path = getPathFromState(effectiveState, navigationPathConfig);
|
||||
return path.startsWith("/") ? path : `/${path}`;
|
||||
}
|
||||
|
||||
function RootStackLayout(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly state: NavigationState;
|
||||
}) {
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
|
||||
useConnectOnboardingNavigation();
|
||||
// Full pathname (sheets included) for keyboard-command scoping; the
|
||||
// workspace layout only reacts to the underlying non-overlay route.
|
||||
const path = getPathFromState(props.state, navigationPathConfig);
|
||||
const pathname = path.startsWith("/") ? path : `/${path}`;
|
||||
const workspacePathname = workspacePathFromState(props.state);
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function NotFoundScreen() {
|
||||
const navigation = useNavigation();
|
||||
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
|
||||
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
|
||||
const returnHomeButtonStyle = StyleSheet.flatten([
|
||||
{
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 20,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
primaryBgStyle,
|
||||
]);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{
|
||||
flexGrow: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 16,
|
||||
paddingHorizontal: 24,
|
||||
paddingVertical: 32,
|
||||
}}
|
||||
style={[{ flex: 1 }, screenBgStyle]}
|
||||
>
|
||||
<Text className="text-3xl font-t3-bold text-foreground" selectable>
|
||||
Route not found
|
||||
</Text>
|
||||
<Pressable
|
||||
style={returnHomeButtonStyle}
|
||||
onPress={() => navigation.dispatch(StackActions.replace("Home"))}
|
||||
>
|
||||
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
|
||||
</Pressable>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
export const RootStack = createNativeStackNavigator({
|
||||
initialRouteName: "Home",
|
||||
layout: RootStackLayout,
|
||||
screenOptions: {
|
||||
headerShown: false,
|
||||
},
|
||||
screens: {
|
||||
Home: createNativeStackScreen({
|
||||
screen: HomeRouteScreen,
|
||||
linking: "",
|
||||
options: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerBackVisible: false,
|
||||
title: "Threads",
|
||||
},
|
||||
}),
|
||||
Thread: createNativeStackScreen({
|
||||
screen: ThreadRouteScreen,
|
||||
linking: THREAD_LINKING_PREFIX,
|
||||
options: GLASS_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadTerminal: createNativeStackScreen({
|
||||
screen: ThreadTerminalRouteScreen,
|
||||
linking: `${THREAD_LINKING_PREFIX}/terminal`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadReview: createNativeStackScreen({
|
||||
screen: ReviewSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/review`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadReviewComment: createNativeStackScreen({
|
||||
screen: ReviewCommentComposerSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/review-comment`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
ThreadFiles: createNativeStackScreen({
|
||||
screen: ThreadFilesTreeScreen,
|
||||
linking: `${THREAD_LINKING_PREFIX}/files`,
|
||||
options: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR }
|
||||
: undefined,
|
||||
title: "Files",
|
||||
},
|
||||
}),
|
||||
ThreadFile: createNativeStackScreen({
|
||||
screen: ThreadFileScreen,
|
||||
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
GitOverview: createNativeStackScreen({
|
||||
screen: GitOverviewSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
GitCommit: createNativeStackScreen({
|
||||
screen: GitCommitSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
GitBranches: createNativeStackScreen({
|
||||
screen: GitBranchesSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
GitConfirm: createNativeStackScreen({
|
||||
screen: GitConfirmSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.45, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
SettingsSheet: createNativeStackScreen({
|
||||
screen: SettingsSheetStack,
|
||||
linking: "settings",
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.7, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
ConnectOnboarding: createNativeStackScreen({
|
||||
screen: ConnectOnboardingRouteScreen,
|
||||
linking: "connect-onboarding",
|
||||
options: {
|
||||
// Root screenOptions hide headers; formSheets that want the native
|
||||
// title bar opt back in with the sheet header preset.
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.6, 0.95],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
Connections: createNativeStackScreen({
|
||||
screen: ConnectionsRouteScreen,
|
||||
linking: "connections",
|
||||
options: {
|
||||
title: "Environments",
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
ConnectionsNew: createNativeStackScreen({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "connections/new",
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
NewTaskSheet: createNativeStackScreen({
|
||||
screen: NewTaskSheetStack,
|
||||
linking: "new",
|
||||
// The whole new-task flow (choose project → draft → add project) shares
|
||||
// draft state via NewTaskFlowProvider. The expo-router era mounted it in
|
||||
// app/new/_layout.tsx; this layout wrapper is the native-stack equivalent.
|
||||
layout: ({ children }) => <NewTaskFlowProvider>{children}</NewTaskFlowProvider>,
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
NotFound: createNativeStackScreen({
|
||||
screen: NotFoundScreen,
|
||||
linking: "*",
|
||||
}),
|
||||
},
|
||||
});
|
||||
type RootStackType = typeof RootStack;
|
||||
|
||||
const navigationPathConfig = {
|
||||
screens: createPathConfigForStaticNavigation(RootStack) ?? {},
|
||||
};
|
||||
|
||||
declare module "@react-navigation/native" {
|
||||
interface RootNavigator extends RootStackType {}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Link } from "expo-router";
|
||||
import { Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "../components/AppText";
|
||||
|
||||
export default function NotFoundRoute() {
|
||||
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
|
||||
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{
|
||||
flexGrow: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 16,
|
||||
paddingHorizontal: 24,
|
||||
paddingVertical: 32,
|
||||
}}
|
||||
style={[{ flex: 1 }, screenBgStyle]}
|
||||
>
|
||||
<Text className="text-3xl font-t3-bold text-foreground" selectable>
|
||||
Route not found
|
||||
</Text>
|
||||
<Link href="/" asChild>
|
||||
<Pressable
|
||||
style={[
|
||||
{
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 20,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
primaryBgStyle,
|
||||
]}
|
||||
>
|
||||
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
|
||||
</Pressable>
|
||||
</Link>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
import "../../global.css";
|
||||
import {
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
useFonts,
|
||||
} from "@expo-google-fonts/dm-sans";
|
||||
import { usePathname } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback } from "react";
|
||||
import { StatusBar, useColorScheme } from "react-native";
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { KeyboardProvider } from "react-native-keyboard-controller";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { LoadingScreen } from "../components/LoadingScreen";
|
||||
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
|
||||
import {
|
||||
ClerkSettingsSheetDetentProvider,
|
||||
useClerkSettingsSheetDetent,
|
||||
} from "../features/cloud/ClerkSettingsSheetDetent";
|
||||
import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
function AppNavigator() {
|
||||
const pathname = usePathname();
|
||||
const expandedSettingsRouteIsActive =
|
||||
pathname === "/settings/archive" || pathname === "/settings/auth";
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
|
||||
<AppNavigatorContent />
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function AppNavigatorContent() {
|
||||
const { state } = useWorkspaceState();
|
||||
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
const sheetStyle = useResolveClassNames("bg-sheet");
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
|
||||
const handleSettingsTransitionEnd = useCallback(
|
||||
(event: { data: { closing: boolean } }) => {
|
||||
if (event.data.closing) {
|
||||
collapse();
|
||||
}
|
||||
},
|
||||
[collapse],
|
||||
);
|
||||
|
||||
const newTaskScreenOptions = {
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.92],
|
||||
sheetGrabberVisible: true,
|
||||
};
|
||||
|
||||
const connectionSheetScreenOptions = {
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
};
|
||||
|
||||
const settingsSheetScreenOptions = {
|
||||
...connectionSheetScreenOptions,
|
||||
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
|
||||
};
|
||||
|
||||
if (state.isLoadingConnections) {
|
||||
return <LoadingScreen message="Loading remote workspace…" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatusBar
|
||||
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
|
||||
backgroundColor={String(statusBarBg)}
|
||||
translucent
|
||||
/>
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
<Stack.Screen
|
||||
name="index"
|
||||
options={{
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="settings"
|
||||
listeners={{ transitionEnd: handleSettingsTransitionEnd }}
|
||||
options={settingsSheetScreenOptions}
|
||||
/>
|
||||
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
|
||||
<Stack.Screen name="new" options={newTaskScreenOptions} />
|
||||
<Stack.Screen
|
||||
name="threads/[environmentId]/[threadId]"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RootLayout() {
|
||||
const [fontsLoaded] = useFonts({
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
});
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
{fontsLoaded ? (
|
||||
<AppNavigator />
|
||||
) : (
|
||||
<LoadingScreen message="Loading remote workspace…" />
|
||||
)}
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</CloudAuthProvider>
|
||||
</RegistryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function ConnectionsLayout() {
|
||||
const contentStyle = useResolveClassNames("bg-sheet");
|
||||
const connSheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle,
|
||||
headerStyle: { backgroundColor: connSheetBg },
|
||||
headerTintColor: headerTint,
|
||||
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
|
||||
headerShadowVisible: false,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none" }} />
|
||||
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { buildThreadRoutePath } from "../lib/routes";
|
||||
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
|
||||
import { HomeScreen } from "../features/home/HomeScreen";
|
||||
import { HomeHeader } from "../features/home/HomeHeader";
|
||||
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
|
||||
import { useThreadListActions } from "../features/home/useThreadListActions";
|
||||
|
||||
interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
export default function HomeRouteScreen() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [listOptions, setListOptions] = useState<HomeListOptions>({
|
||||
selectedEnvironmentId: null,
|
||||
projectSortOrder:
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
});
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
Arr.sort(
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
})),
|
||||
Order.mapInput(
|
||||
Order.String,
|
||||
(environment: { readonly label: string }) => environment.label,
|
||||
),
|
||||
),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const selectedEnvironmentId = environments.some(
|
||||
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
|
||||
)
|
||||
? listOptions.selectedEnvironmentId
|
||||
: null;
|
||||
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
|
||||
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
|
||||
}, []);
|
||||
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, projectSortOrder }));
|
||||
}, []);
|
||||
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, threadSortOrder }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
|
||||
setListOptions((current) => ({ ...current, projectGroupingMode }));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenSettings={() => router.push("/settings")}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => router.push("/new")}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
/>
|
||||
|
||||
<HomeScreen
|
||||
catalogState={catalogState}
|
||||
onAddConnection={() => router.push("/connections/new")}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onOpenEnvironments={() => router.push("/settings/environments")}
|
||||
onSelectThread={(thread) => {
|
||||
router.push(buildThreadRoutePath(thread));
|
||||
}}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function NewTaskLayout() {
|
||||
const sheetStyle = useResolveClassNames("bg-sheet");
|
||||
const sheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
|
||||
return (
|
||||
<NewTaskFlowProvider>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: sheetBg },
|
||||
headerTintColor: headerTint,
|
||||
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none", title: "Choose project" }} />
|
||||
<Stack.Screen
|
||||
name="add-project/index"
|
||||
options={{ animation: "slide_from_right", title: "New project" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="add-project/repository"
|
||||
options={{ animation: "slide_from_right", title: "Repository" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="add-project/destination"
|
||||
options={{ animation: "slide_from_right", title: "Clone destination" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="add-project/local"
|
||||
options={{ animation: "slide_from_right", title: "Local folder" }}
|
||||
/>
|
||||
<Stack.Screen name="draft" options={{ animation: "slide_from_right", title: "New task" }} />
|
||||
</Stack>
|
||||
</NewTaskFlowProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectDestinationRoute() {
|
||||
return <AddProjectDestinationScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectRoute() {
|
||||
return <AddProjectSourceScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectLocalRoute() {
|
||||
return <AddProjectLocalFolderScreen />;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Stack, useLocalSearchParams } from "expo-router";
|
||||
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
|
||||
|
||||
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectRepositoryRoute() {
|
||||
const params = useLocalSearchParams<{ source?: string | string[] }>();
|
||||
const source = Array.isArray(params.source) ? params.source[0] : params.source;
|
||||
const title =
|
||||
source === "github" ||
|
||||
source === "gitlab" ||
|
||||
source === "bitbucket" ||
|
||||
source === "azure-devops"
|
||||
? addProjectRemoteSourceLabel(source)
|
||||
: "Git URL";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ title }} />
|
||||
<AddProjectRepositoryScreen />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Stack, useLocalSearchParams } from "expo-router";
|
||||
|
||||
import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen";
|
||||
|
||||
export default function NewTaskDraftRoute() {
|
||||
const params = useLocalSearchParams<{
|
||||
environmentId?: string | string[];
|
||||
projectId?: string | string[];
|
||||
title?: string | string[];
|
||||
}>();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
|
||||
}}
|
||||
/>
|
||||
<NewTaskDraftScreen
|
||||
initialProjectRef={{
|
||||
environmentId: Array.isArray(params.environmentId)
|
||||
? params.environmentId[0]
|
||||
: params.environmentId,
|
||||
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback } from "react";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function SettingsLayout() {
|
||||
const { collapse } = useClerkSettingsSheetDetent();
|
||||
const contentStyle = useResolveClassNames("bg-sheet");
|
||||
const sheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
const handleExpandedRouteTransitionEnd = useCallback(
|
||||
(event: { data: { closing: boolean } }) => {
|
||||
if (event.data.closing) {
|
||||
collapse();
|
||||
}
|
||||
},
|
||||
[collapse],
|
||||
);
|
||||
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: sheetBg },
|
||||
headerTintColor: headerTint,
|
||||
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none", title: "Settings" }} />
|
||||
<Stack.Screen
|
||||
name="environments"
|
||||
options={{ animation: "slide_from_right", title: "Environments" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="environment-new"
|
||||
options={{ animation: "slide_from_right", title: "Add Environment" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="waitlist"
|
||||
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="archive"
|
||||
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
|
||||
options={{ animation: "slide_from_right", title: "Archived Threads" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auth"
|
||||
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
|
||||
options={{ animation: "slide_from_right", title: "Sign in" }}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
|
||||
|
||||
export default ArchivedThreadsRouteScreen;
|
||||
@@ -1,33 +0,0 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { Redirect, Stack } from "expo-router";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
|
||||
|
||||
export default function SettingsAuthRouteScreen() {
|
||||
return hasCloudPublicConfig() ? (
|
||||
<ConfiguredSettingsAuthRouteScreen />
|
||||
) : (
|
||||
<Redirect href="/settings" />
|
||||
);
|
||||
}
|
||||
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ title: isSignedIn ? "Account" : "Sign in" }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from "../connections/new";
|
||||
@@ -1,107 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
export default function ThreadLayout() {
|
||||
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
|
||||
const headerBg = {
|
||||
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
<Stack.Screen
|
||||
name="index"
|
||||
options={{
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
headerTitle: "",
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="git"
|
||||
options={{
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.85],
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="git-confirm"
|
||||
options={{
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.4],
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "Files changed",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/index"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "Files",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/[...path]"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "File",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review-comment"
|
||||
options={{
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.72, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="terminal"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: { backgroundColor: "#050505" },
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFileRoute() {
|
||||
return <ThreadFileScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFilesIndexRoute() {
|
||||
return <ThreadFilesTreeScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
|
||||
|
||||
export default function GitConfirmRoute() {
|
||||
return <GitConfirmSheet />;
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function GitSheetLayout() {
|
||||
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
|
||||
const headerBg = {
|
||||
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle: sheetStyle,
|
||||
headerShown: false,
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none" }} />
|
||||
<Stack.Screen
|
||||
name="commit"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
headerShown: true,
|
||||
headerTitle: "Commit changes",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="branches"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
headerShown: true,
|
||||
headerTitle: "Branches & worktrees",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
headerShown: true,
|
||||
headerTitle: "Review changes",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
|
||||
|
||||
export default function GitBranchesRoute() {
|
||||
return <GitBranchesSheet />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
|
||||
|
||||
export default function GitCommitRoute() {
|
||||
return <GitCommitSheet />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
|
||||
|
||||
export default function GitRoute() {
|
||||
return <GitOverviewSheet />;
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { Redirect, useLocalSearchParams } from "expo-router";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
const { environmentId, threadId } = useLocalSearchParams<{
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
}>();
|
||||
|
||||
return (
|
||||
<Redirect
|
||||
href={{
|
||||
pathname: "/threads/[environmentId]/[threadId]/review",
|
||||
params: { environmentId, threadId },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
|
||||
|
||||
export default function ThreadRoute() {
|
||||
return <ThreadRouteScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet";
|
||||
|
||||
export default function ReviewCommentRoute() {
|
||||
return <ReviewCommentComposerSheet />;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
|
||||
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
return (
|
||||
<ReviewHighlighterProvider>
|
||||
<ReviewSheet />
|
||||
</ReviewHighlighterProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen";
|
||||
|
||||
export default function ThreadTerminalRoute() {
|
||||
return <ThreadTerminalRouteScreen />;
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { Ref } from "react";
|
||||
import {
|
||||
Text as RNText,
|
||||
TextInput as RNTextInput,
|
||||
@@ -21,7 +20,7 @@ export function AppText({ className, ...props }: AppTextProps) {
|
||||
|
||||
export type AppTextInputProps = RNTextInputProps & {
|
||||
readonly className?: string;
|
||||
readonly ref?: Ref<RNTextInput>;
|
||||
readonly ref?: React.Ref<RNTextInput>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -40,7 +39,7 @@ export function AppTextInput({
|
||||
<RNTextInput
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
|
||||
"min-h-13.5 rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
|
||||
className,
|
||||
)}
|
||||
placeholderTextColor={placeholderTextColor ?? placeholderColor}
|
||||
|
||||
@@ -75,7 +75,7 @@ export function ControlPill(props: {
|
||||
}
|
||||
|
||||
export function ControlPillMenu(
|
||||
props: Omit<ComponentProps<typeof MenuView>, "children" | "style" | "themeVariant"> & {
|
||||
props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> & {
|
||||
readonly children: ReactNode;
|
||||
},
|
||||
) {
|
||||
|
||||
@@ -7,11 +7,33 @@ export function EmptyState(props: {
|
||||
readonly detail: string;
|
||||
readonly actionLabel?: string;
|
||||
readonly onAction?: () => void;
|
||||
readonly variant?: "card" | "plain";
|
||||
}) {
|
||||
if (props.variant === "plain") {
|
||||
return (
|
||||
<View className="items-center px-8 py-8">
|
||||
<Text className="text-center text-xl font-t3-bold text-foreground">{props.title}</Text>
|
||||
<Text className="mt-2 text-center font-sans text-base leading-normal text-foreground-muted">
|
||||
{props.detail}
|
||||
</Text>
|
||||
{props.actionLabel && props.onAction ? (
|
||||
<Pressable
|
||||
className="mt-5 rounded-full bg-primary px-5 py-3 active:opacity-70"
|
||||
onPress={props.onAction}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
{props.actionLabel}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="rounded-[22px] border border-border bg-card p-5">
|
||||
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
|
||||
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
|
||||
<Text className="mt-2 font-sans text-sm leading-relaxed text-foreground-muted">
|
||||
{props.detail}
|
||||
</Text>
|
||||
{props.actionLabel && props.onAction ? (
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText";
|
||||
export function ErrorBanner(props: { readonly message: string }) {
|
||||
return (
|
||||
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
|
||||
<Text className="font-t3-medium text-sm leading-[18px] text-rose-700 dark:text-rose-300">
|
||||
<Text className="font-t3-medium text-sm text-rose-700 dark:text-rose-300">
|
||||
{props.message}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -92,7 +92,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
if (session === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "Sign in to T3 Cloud to connect this environment.",
|
||||
detail: "Sign in to T3 Connect to connect this environment.",
|
||||
});
|
||||
}
|
||||
const token = yield* session.readClerkToken().pipe(
|
||||
@@ -107,7 +107,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
detail: "The T3 Connect session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
|
||||
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof snapshotLoaderLayer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof connectionPlatformLayer;
|
||||
|
||||
const connectionLayer = Connection.layer.pipe(
|
||||
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -3,6 +3,10 @@ import {
|
||||
ConnectionRegistrationStore,
|
||||
ConnectionTargetStore,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
decodeOrDiscardOrchestrationCache,
|
||||
registerConnectionInCatalog,
|
||||
removeConnectionFromCatalog,
|
||||
removeCatalogValue,
|
||||
@@ -14,12 +18,7 @@ import {
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
OrchestrationShellSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -29,31 +28,16 @@ import * as SecureStore from "expo-secure-store";
|
||||
|
||||
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
thread: OrchestrationThread,
|
||||
});
|
||||
|
||||
const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
environmentId: EnvironmentId,
|
||||
snapshotReceivedAt: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
|
||||
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
|
||||
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
@@ -289,44 +273,50 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}
|
||||
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
|
||||
if (!legacyFile.exists) {
|
||||
return Option.none();
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
}),
|
||||
|
||||
return Option.none();
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
shellSnapshotFile(environmentId, "load-shell").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "save-shell");
|
||||
const stored = {
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -351,22 +341,41 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}),
|
||||
saveThread: (environmentId, thread) =>
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
threadSnapshotFile(environmentId, threadId, "load-thread").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const file = yield* threadSnapshotFile(
|
||||
environmentId,
|
||||
snapshot.projection.thread.id,
|
||||
"save-thread",
|
||||
);
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
encodeStoredThreadSnapshot({
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
threadId: snapshot.projection.thread.id,
|
||||
snapshot,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useLinkTo } from "@react-navigation/native";
|
||||
|
||||
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
|
||||
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
|
||||
|
||||
export function useAgentNotificationNavigation(): void {
|
||||
const router = useRouter();
|
||||
const linkTo = useLinkTo();
|
||||
const handledResponseIds = useRef(new Set<string>());
|
||||
|
||||
useEffect(() => {
|
||||
@@ -14,7 +14,7 @@ export function useAgentNotificationNavigation(): void {
|
||||
routeAgentNotificationResponseOnce({
|
||||
handledResponseIds: handledResponseIds.current,
|
||||
response,
|
||||
navigate: (deepLink) => router.push(deepLink as never),
|
||||
navigate: linkTo,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void {
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, [router]);
|
||||
}, [linkTo]);
|
||||
}
|
||||
@@ -2,11 +2,20 @@ import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
|
||||
|
||||
import type { Preferences } from "../../lib/storage";
|
||||
|
||||
// Development builds are Xcode-signed and receive sandbox APNs tokens;
|
||||
// preview and production builds are distribution-signed and use production
|
||||
// APNs. The relay routes each device's pushes accordingly.
|
||||
export function resolveApsEnvironment(appVariant: unknown): "sandbox" | "production" {
|
||||
return appVariant === "development" ? "sandbox" : "production";
|
||||
}
|
||||
|
||||
export function makeRelayDeviceRegistrationRequest(input: {
|
||||
readonly deviceId: string;
|
||||
readonly label: string;
|
||||
readonly iosMajorVersion: number;
|
||||
readonly appVersion?: string;
|
||||
readonly bundleId?: string;
|
||||
readonly apsEnvironment?: "sandbox" | "production";
|
||||
readonly pushToken?: string;
|
||||
readonly pushToStartToken?: string;
|
||||
readonly notificationsEnabled: boolean;
|
||||
@@ -19,6 +28,8 @@ export function makeRelayDeviceRegistrationRequest(input: {
|
||||
platform: "ios",
|
||||
iosMajorVersion: input.iosMajorVersion,
|
||||
appVersion: input.appVersion,
|
||||
...(input.bundleId ? { bundleId: input.bundleId } : {}),
|
||||
...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),
|
||||
...(input.pushToken ? { pushToken: input.pushToken } : {}),
|
||||
...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
|
||||
preferences: {
|
||||
|
||||
@@ -16,15 +16,23 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { cryptoLayer } from "../cloud/dpop";
|
||||
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
loadAgentAwarenessRegistrationRecord,
|
||||
loadOrCreateAgentAwarenessDeviceId,
|
||||
saveAgentAwarenessRegistrationRecord,
|
||||
} from "../../lib/storage";
|
||||
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
|
||||
import {
|
||||
AgentAwarenessOperationError,
|
||||
__resetAgentAwarenessRemoteRegistrationForTest,
|
||||
getAgentAwarenessRegistrationStatus,
|
||||
refreshActiveLiveActivityRemoteRegistration,
|
||||
refreshAgentAwarenessRegistration,
|
||||
normalizeAgentAwarenessRelayBaseUrl,
|
||||
registerAgentAwarenessConnection,
|
||||
registerLiveActivityPushToken,
|
||||
releaseAgentAwarenessRelayTokenProvider,
|
||||
setAgentAwarenessRelayTokenProvider,
|
||||
shouldRegisterAgentAwarenessDeviceForProvider,
|
||||
unregisterAgentAwarenessConnection,
|
||||
@@ -41,6 +49,16 @@ const backgroundRuntime = vi.hoisted(() => ({
|
||||
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
|
||||
}>,
|
||||
}));
|
||||
const appStateMock = vi.hoisted(() => ({
|
||||
listeners: [] as Array<(state: string) => void>,
|
||||
}));
|
||||
const registrationRecordStore = vi.hoisted(() => ({
|
||||
current: null as {
|
||||
readonly identity: string;
|
||||
readonly signature: string;
|
||||
readonly pushToStartToken?: string;
|
||||
} | null,
|
||||
}));
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -100,6 +118,19 @@ vi.mock("react-native", () => ({
|
||||
OS: "ios",
|
||||
Version: "18.0",
|
||||
},
|
||||
AppState: {
|
||||
addEventListener: (_event: string, listener: (state: string) => void) => {
|
||||
appStateMock.listeners.push(listener);
|
||||
return {
|
||||
remove: () => {
|
||||
const index = appStateMock.listeners.indexOf(listener);
|
||||
if (index >= 0) {
|
||||
appStateMock.listeners.splice(index, 1);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/runtime", () => ({
|
||||
@@ -114,7 +145,18 @@ vi.mock("../../lib/runtime", () => ({
|
||||
vi.mock("../../lib/storage", () => ({
|
||||
loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
|
||||
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
|
||||
loadPreferences: vi.fn(() => Promise.resolve({})),
|
||||
loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
|
||||
loadAgentAwarenessRegistrationRecord: vi.fn(() =>
|
||||
Promise.resolve(registrationRecordStore.current),
|
||||
),
|
||||
saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => {
|
||||
registrationRecordStore.current = record;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
clearAgentAwarenessRegistrationRecord: vi.fn(() => {
|
||||
registrationRecordStore.current = null;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
}));
|
||||
|
||||
function proofIat(proof: string): number {
|
||||
@@ -176,6 +218,12 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
backgroundRuntime.pending.length = 0;
|
||||
Constants.expoConfig!.extra = {};
|
||||
__resetAgentAwarenessRemoteRegistrationForTest();
|
||||
appStateMock.listeners.length = 0;
|
||||
registrationRecordStore.current = null;
|
||||
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
|
||||
vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
|
||||
vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
|
||||
widgetMocks.getInstances.mockReset();
|
||||
widgetMocks.getInstances.mockReturnValue([]);
|
||||
});
|
||||
@@ -213,6 +261,31 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("registers the app's APNs routing so the relay targets the right bundle", () => {
|
||||
expect(
|
||||
makeRelayDeviceRegistrationRequest({
|
||||
deviceId: "device-1",
|
||||
label: "Julius's iPhone",
|
||||
iosMajorVersion: 18,
|
||||
appVersion: "1.0.0",
|
||||
bundleId: "com.t3tools.t3code.preview",
|
||||
apsEnvironment: resolveApsEnvironment("preview"),
|
||||
notificationsEnabled: true,
|
||||
preferences: {},
|
||||
}),
|
||||
).toMatchObject({
|
||||
bundleId: "com.t3tools.t3code.preview",
|
||||
apsEnvironment: "production",
|
||||
});
|
||||
});
|
||||
|
||||
it("routes development builds to the APNs sandbox", () => {
|
||||
expect(resolveApsEnvironment("development")).toBe("sandbox");
|
||||
expect(resolveApsEnvironment("preview")).toBe("production");
|
||||
expect(resolveApsEnvironment("production")).toBe("production");
|
||||
expect(resolveApsEnvironment(undefined)).toBe("production");
|
||||
});
|
||||
|
||||
it("marks notification delivery disabled when APNs permission is unavailable", () => {
|
||||
expect(
|
||||
makeRelayDeviceRegistrationRequest({
|
||||
@@ -329,6 +402,53 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"re-registers active Live Activity tokens when the app returns to the foreground",
|
||||
() => {
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
activity.getPushToken.mockClear();
|
||||
|
||||
expect(appStateMock.listeners).toHaveLength(1);
|
||||
for (const listener of appStateMock.listeners) {
|
||||
listener("background");
|
||||
}
|
||||
yield* runBackgroundOperations();
|
||||
expect(activity.getPushToken).not.toHaveBeenCalled();
|
||||
|
||||
for (const listener of appStateMock.listeners) {
|
||||
listener("active");
|
||||
}
|
||||
yield* runBackgroundOperations();
|
||||
expect(activity.getPushToken).toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
},
|
||||
);
|
||||
|
||||
it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
|
||||
const end = vi.fn(() => Promise.resolve());
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
end,
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
expect(appStateMock.listeners).toHaveLength(1);
|
||||
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
|
||||
expect(end).toHaveBeenCalledWith("immediate");
|
||||
expect(appStateMock.listeners).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.effect("refreshes APNs registration for connected environments after settings changes", () => {
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
return Effect.gen(function* () {
|
||||
@@ -395,6 +515,174 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
nowEpochSeconds: proofIat(dpop),
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("marks registration failed when device registration cannot complete", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
|
||||
new Error("registration failed"),
|
||||
);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
// Drive the registration directly so the assertion does not depend on the
|
||||
// background queue draining; refreshAgentAwarenessRegistration swallows the
|
||||
// error but must record the failed status so the settings toggles cannot
|
||||
// read as enabled.
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("failed");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it("clears registration status on cloud sign-out", () => {
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
|
||||
expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("releases the provider without ending activities or clearing the registration", () => {
|
||||
const end = vi.fn(() => Promise.resolve());
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
end,
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
registrationRecordStore.current = { identity: "", signature: "sig" };
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
expect(appStateMock.listeners).toHaveLength(1);
|
||||
|
||||
releaseAgentAwarenessRelayTokenProvider();
|
||||
|
||||
expect(appStateMock.listeners).toHaveLength(0);
|
||||
expect(end).not.toHaveBeenCalled();
|
||||
expect(clearAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
|
||||
expect(registrationRecordStore.current).not.toBeNull();
|
||||
});
|
||||
|
||||
it.effect("resets a pending status to unknown when relay config is missing", () => {
|
||||
// No relay url configured: registration can neither run nor ever succeed,
|
||||
// so the status must not stick at "pending".
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("keeps a registered status when a later refresh fails", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
|
||||
// The relay still holds the accepted registration; a transient refresh
|
||||
// failure must not flip the settings toggles off.
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
|
||||
new Error("transient failure"),
|
||||
);
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("does not re-register the same account when nothing has changed", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
|
||||
expect(registrationRecordStore.current).not.toBeNull();
|
||||
|
||||
// Second attempt with an identical payload must skip the relay entirely,
|
||||
// so no new registration record is written.
|
||||
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("dedupes rapid activity-token re-registrations within the replay window", () => {
|
||||
// Fetch counts are unreliable here (the module-level relay layer captures
|
||||
// the first test's fetch), so assert on the flow's own seams: a real
|
||||
// registration attempt loads the device id, a deduped one short-circuits
|
||||
// before it.
|
||||
const fetchMock = vi.fn((request: RequestInfo | URL) => {
|
||||
const url = request instanceof Request ? request.url : String(request);
|
||||
return Promise.resolve(
|
||||
Response.json(
|
||||
url.endsWith("/v1/client/dpop-token")
|
||||
? {
|
||||
access_token: "relay-dpop-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "DPoP",
|
||||
expires_in: 300,
|
||||
scope: "mobile:registration",
|
||||
}
|
||||
: { ok: true },
|
||||
),
|
||||
);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
// Drains the sign-in refresh, which registers the activity token.
|
||||
yield* runBackgroundOperations();
|
||||
expect(activity.getPushToken).toHaveBeenCalled();
|
||||
|
||||
// A burst refresh (foreground / connection update seconds later) must
|
||||
// dedupe: it reads the token but never proceeds to a registration
|
||||
// attempt (which would load the device id first).
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockClear();
|
||||
yield* refreshActiveLiveActivityRemoteRegistration();
|
||||
expect(loadOrCreateAgentAwarenessDeviceId).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("re-registers when the stored account identity differs", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
registrationRecordStore.current = { identity: "someone-else", signature: "stale" };
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
|
||||
import { type LiveActivity } from "expo-widgets";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Platform } from "react-native";
|
||||
import { AppState, Platform } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
type RelayDeviceRegistrationRequest,
|
||||
type RelayAgentActivitySnapshotResponse,
|
||||
type RelayLiveActivityRegistrationRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
@@ -20,13 +21,16 @@ import {
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
loadAgentAwarenessDeviceId,
|
||||
loadAgentAwarenessRegistrationRecord,
|
||||
loadOrCreateAgentAwarenessDeviceId,
|
||||
loadPreferences,
|
||||
saveAgentAwarenessRegistrationRecord,
|
||||
} from "../../lib/storage";
|
||||
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
|
||||
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
|
||||
|
||||
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
|
||||
|
||||
@@ -42,6 +46,8 @@ const AgentAwarenessOperation = Schema.Literals([
|
||||
"read-live-activity-push-token",
|
||||
"load-live-activity-registration-identifier",
|
||||
"list-active-live-activities",
|
||||
"load-live-activity-prime-preferences",
|
||||
"prime-live-activity",
|
||||
]);
|
||||
|
||||
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
|
||||
@@ -58,8 +64,49 @@ export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentA
|
||||
|
||||
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
|
||||
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
|
||||
let pushToStartSubscription: { remove: () => void } | null = null;
|
||||
// Activity tokens the relay recently accepted, by acceptance time. The refresh
|
||||
// runs on sign-in, every app foreground, and every environment-connection
|
||||
// update, which arrive in bursts and spammed identical registrations. But the
|
||||
// registration is not a pure no-op: the relay replays the current aggregate to
|
||||
// this device on every accepted registration, and that replay is the
|
||||
// foreground reconciliation that repairs drifted or orphaned activities. So
|
||||
// dedupe only within a short window — bursts collapse to one request, while a
|
||||
// foreground after real time away still triggers a replay. Cleared on
|
||||
// sign-out/identity change alongside the device registration state.
|
||||
const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
|
||||
const registeredActivityPushTokens = new Map<string, number>();
|
||||
let pushTokenSubscription: { remove: () => void } | null = null;
|
||||
let appStateSubscription: { remove: () => void } | null = null;
|
||||
|
||||
// Whether the relay has actually accepted this device's registration. The
|
||||
// notification/Live Activity settings toggles must reflect this rather than
|
||||
// only local iOS permission or saved preferences: if the registration request
|
||||
// never succeeded, the device cannot receive anything, so the switches must
|
||||
// not read as enabled.
|
||||
export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "registered" | "failed";
|
||||
let registrationStatus: AgentAwarenessRegistrationStatus = "unknown";
|
||||
const registrationStatusListeners = new Set<() => void>();
|
||||
|
||||
function setRegistrationStatus(next: AgentAwarenessRegistrationStatus): void {
|
||||
if (registrationStatus === next) {
|
||||
return;
|
||||
}
|
||||
registrationStatus = next;
|
||||
for (const listener of registrationStatusListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus {
|
||||
return registrationStatus;
|
||||
}
|
||||
|
||||
export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {
|
||||
registrationStatusListeners.add(listener);
|
||||
return () => {
|
||||
registrationStatusListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
|
||||
let relayTokenProvider: (() => Promise<string | null>) | null = null;
|
||||
let relayTokenProviderIdentity: string | null = null;
|
||||
@@ -74,7 +121,6 @@ let pendingDeviceRegistration: {
|
||||
} | null = null;
|
||||
|
||||
interface DeviceRegistrationInput {
|
||||
readonly pushToStartToken?: string;
|
||||
readonly observedPushToken?: string;
|
||||
}
|
||||
|
||||
@@ -120,32 +166,66 @@ export function setAgentAwarenessRelayTokenProvider(
|
||||
deviceRegistrationGeneration++;
|
||||
activeDeviceRegistration = null;
|
||||
pendingDeviceRegistration = null;
|
||||
registeredActivityPushTokens.clear();
|
||||
}
|
||||
relayTokenProvider = provider;
|
||||
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
|
||||
if (!provider) {
|
||||
pushToStartSubscription?.remove();
|
||||
pushToStartSubscription = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
}
|
||||
// Without a signed-in user the relay can no longer update or end these
|
||||
// activities, so they would sit orphaned on the lock screen.
|
||||
endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
|
||||
setRegistrationStatus("unknown");
|
||||
// Sign-out is the only thing that invalidates a stored registration, so the
|
||||
// next sign-in re-registers.
|
||||
void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
|
||||
logRegistrationError("clear registration record on sign-out failed", error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
ensurePushToStartListener();
|
||||
ensurePushTokenListener();
|
||||
ensureAppStateListener();
|
||||
runRegistrationInBackground(
|
||||
refreshActiveLiveActivityRemoteRegistration(),
|
||||
"active live activity registration after cloud sign-in failed",
|
||||
);
|
||||
if (isExistingIdentity) {
|
||||
// Same account re-activating (e.g. Clerk token refresh) normally needs no
|
||||
// re-registration — but if the previous attempt never succeeded, this is
|
||||
// the only trigger that will retry it before the next cold start.
|
||||
if (registrationStatus !== "registered") {
|
||||
enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
|
||||
}
|
||||
|
||||
// Detach the provider and native listeners without the destructive sign-out
|
||||
// cleanup. For provider teardown while the user is still signed in (e.g. the
|
||||
// auth bridge unmounting/remounting), ending lock-screen activities and wiping
|
||||
// the persisted registration would be wrong — the relay still holds a valid
|
||||
// registration and the next mount reuses it.
|
||||
export function releaseAgentAwarenessRelayTokenProvider(): void {
|
||||
relayTokenProvider = null;
|
||||
relayTokenProviderIdentity = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
}
|
||||
}
|
||||
|
||||
function iosMajorVersion(): number {
|
||||
const version = Platform.Version;
|
||||
if (typeof version === "number") {
|
||||
@@ -211,6 +291,27 @@ const relayToken = (
|
||||
});
|
||||
});
|
||||
|
||||
// Stable fingerprint of everything the relay stores for this device. When it
|
||||
// matches the last accepted registration for the same account, re-registering
|
||||
// is a no-op, so a launch that changed nothing skips the request entirely.
|
||||
function registrationSignature(body: RelayDeviceRegistrationRequest): string {
|
||||
return [
|
||||
body.deviceId,
|
||||
body.pushToken ?? "",
|
||||
body.bundleId ?? "",
|
||||
body.apsEnvironment ?? "",
|
||||
body.appVersion ?? "",
|
||||
body.label,
|
||||
body.iosMajorVersion,
|
||||
body.preferences.notificationsEnabled,
|
||||
body.preferences.liveActivitiesEnabled,
|
||||
body.preferences.notifyOnApproval,
|
||||
body.preferences.notifyOnInput,
|
||||
body.preferences.notifyOnCompletion,
|
||||
body.preferences.notifyOnFailure,
|
||||
].join("|");
|
||||
}
|
||||
|
||||
function registerDeviceWithRelay(
|
||||
body: RelayDeviceRegistrationRequest,
|
||||
expectedGeneration: number,
|
||||
@@ -223,7 +324,13 @@ function registerDeviceWithRelay(
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!readRelayConfig()) return;
|
||||
const relayConfig = readRelayConfig();
|
||||
if (!relayConfig) {
|
||||
// Nothing is in flight and nothing can succeed until configuration
|
||||
// appears; "pending" would otherwise stick forever.
|
||||
setRegistrationStatus("unknown");
|
||||
return;
|
||||
}
|
||||
const token = yield* relayToken("read-device-registration-relay-token");
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
logRegistrationDebug("device registration cancelled after auth lookup", {
|
||||
@@ -234,6 +341,37 @@ function registerDeviceWithRelay(
|
||||
}
|
||||
if (!token) {
|
||||
logRegistrationDebug("relay device registration skipped; user is not signed in");
|
||||
setRegistrationStatus("unknown");
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip the request when this account already registered an identical
|
||||
// payload; the relay upsert would be a no-op. The record is only cleared on
|
||||
// sign-out, so a device stays registered across launches without re-hitting
|
||||
// the relay every time the app opens.
|
||||
const identity = relayTokenProviderIdentity ?? "";
|
||||
const persisted = yield* Effect.tryPromise({
|
||||
try: () => loadAgentAwarenessRegistrationRecord(),
|
||||
catch: (cause) => cause,
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
// Signed out while the record loaded — do not resurrect the cleared
|
||||
// record or report the previous account's registration as current.
|
||||
logRegistrationDebug("device registration cancelled after record lookup", {
|
||||
expectedGeneration,
|
||||
currentGeneration: deviceRegistrationGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const payload = body;
|
||||
// The relay URL participates so pointing the app at a different relay
|
||||
// invalidates the record and re-registers there.
|
||||
const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
|
||||
if (persisted && persisted.identity === identity && persisted.signature === signature) {
|
||||
setRegistrationStatus("registered");
|
||||
logRegistrationDebug("relay device registration skipped; already registered for account", {
|
||||
expectedGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -243,8 +381,27 @@ function registerDeviceWithRelay(
|
||||
});
|
||||
yield* client.registerDevice({
|
||||
clerkToken: token,
|
||||
payload: body,
|
||||
payload,
|
||||
});
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
// Signed out while the request was in flight: the sign-out path already
|
||||
// reset the status and cleared the record for the next account, so a
|
||||
// stale success must not overwrite either.
|
||||
logRegistrationDebug("device registration completed after sign-out; result discarded", {
|
||||
expectedGeneration,
|
||||
currentGeneration: deviceRegistrationGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setRegistrationStatus("registered");
|
||||
yield* Effect.promise(() =>
|
||||
saveAgentAwarenessRegistrationRecord({
|
||||
identity,
|
||||
signature,
|
||||
}).catch((error: unknown) => {
|
||||
logRegistrationError("persist registration record failed", error);
|
||||
}),
|
||||
);
|
||||
logRegistrationDebug("relay device registration request completed", {
|
||||
expectedGeneration,
|
||||
});
|
||||
@@ -278,6 +435,91 @@ function unregisterDeviceWithRelay(input: {
|
||||
});
|
||||
}
|
||||
|
||||
// Arms the lock-screen card the moment the user starts agent work from this
|
||||
// phone, while the app is still foregrounded and the fresh activity's token
|
||||
// can be registered immediately. The seeded row is a best-effort placeholder;
|
||||
// the relay's registration replay repaints it with the authoritative
|
||||
// aggregate within seconds. No-ops when a card is already armed.
|
||||
export function armAgentAwarenessLiveActivityForLocalWork(input: {
|
||||
readonly threadTitle: string;
|
||||
readonly projectTitle: string;
|
||||
}): void {
|
||||
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
|
||||
return;
|
||||
}
|
||||
void loadPreferences()
|
||||
.catch(() => null)
|
||||
.then((preferences) => {
|
||||
if (preferences?.liveActivitiesEnabled === false) {
|
||||
return;
|
||||
}
|
||||
armAgentAwarenessLiveActivityForLocalWorkNow(input);
|
||||
});
|
||||
}
|
||||
|
||||
function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
|
||||
readonly threadTitle: string;
|
||||
readonly projectTitle: string;
|
||||
}): void {
|
||||
try {
|
||||
if (AgentActivity.getInstances().length > 0) {
|
||||
return;
|
||||
}
|
||||
const nowIso = new Date(Date.now()).toISOString();
|
||||
const activity = AgentActivity.start({
|
||||
title: "T3 Code",
|
||||
subtitle: "Agent work in progress",
|
||||
activeCount: 1,
|
||||
updatedAt: nowIso,
|
||||
activities: [
|
||||
{
|
||||
environmentId: "",
|
||||
threadId: "",
|
||||
projectTitle: input.projectTitle,
|
||||
threadTitle: input.threadTitle,
|
||||
modelTitle: "",
|
||||
phase: "starting",
|
||||
status: "Connecting",
|
||||
updatedAt: nowIso,
|
||||
deepLink: "/",
|
||||
},
|
||||
],
|
||||
});
|
||||
logRegistrationDebug("live activity card armed for local work", {
|
||||
threadTitle: input.threadTitle,
|
||||
});
|
||||
runRegistrationInBackground(
|
||||
registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),
|
||||
"live activity arming after local task start failed",
|
||||
);
|
||||
} catch (error) {
|
||||
logRegistrationError("live activity arming failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
function readAgentActivitySnapshot(): Effect.Effect<
|
||||
RelayAgentActivitySnapshotResponse | null,
|
||||
never,
|
||||
ManagedRelay.ManagedRelayClient
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
if (!readRelayConfig()) return null;
|
||||
const token = yield* relayToken("read-live-activity-registration-relay-token");
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
const client = yield* ManagedRelay.ManagedRelayClient;
|
||||
return yield* client.getAgentActivitySnapshot({ clerkToken: token });
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
logRegistrationError("agent activity snapshot read failed", error);
|
||||
return null;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function registerLiveActivityWithRelay(
|
||||
body: RelayLiveActivityRegistrationRequest,
|
||||
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
@@ -332,14 +574,8 @@ function mergeDeviceRegistrationInput(
|
||||
current: DeviceRegistrationInput,
|
||||
next: DeviceRegistrationInput,
|
||||
): DeviceRegistrationInput {
|
||||
return {
|
||||
...((next.pushToStartToken ?? current.pushToStartToken)
|
||||
? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken }
|
||||
: {}),
|
||||
...((next.observedPushToken ?? current.observedPushToken)
|
||||
? { observedPushToken: next.observedPushToken ?? current.observedPushToken }
|
||||
: {}),
|
||||
};
|
||||
const observedPushToken = next.observedPushToken ?? current.observedPushToken;
|
||||
return observedPushToken ? { observedPushToken } : {};
|
||||
}
|
||||
|
||||
function registrationAddsInformation(
|
||||
@@ -347,8 +583,7 @@ function registrationAddsInformation(
|
||||
next: DeviceRegistrationInput,
|
||||
): boolean {
|
||||
return (
|
||||
(next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) ||
|
||||
(next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken)
|
||||
next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken
|
||||
);
|
||||
}
|
||||
|
||||
@@ -363,8 +598,10 @@ function startPendingDeviceRegistration(): void {
|
||||
logRegistrationDebug("device registration started", {
|
||||
generation,
|
||||
hasObservedPushToken: next.input.observedPushToken !== undefined,
|
||||
hasPushToStartToken: next.input.pushToStartToken !== undefined,
|
||||
});
|
||||
if (registrationStatus !== "registered") {
|
||||
setRegistrationStatus("pending");
|
||||
}
|
||||
const registration = {
|
||||
input: next.input,
|
||||
operation: Promise.resolve(),
|
||||
@@ -375,6 +612,13 @@ function startPendingDeviceRegistration(): void {
|
||||
runtime.runPromiseExit(registerDevice(next.input, generation)),
|
||||
);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
// A transient failure on a later refresh (e.g. token rotation) leaves
|
||||
// the prior accepted registration intact on the relay, so an already
|
||||
// registered device stays "registered" rather than flipping the
|
||||
// settings toggles off.
|
||||
if (registrationStatus !== "registered") {
|
||||
setRegistrationStatus("failed");
|
||||
}
|
||||
logRegistrationError(next.context, squashAtomCommandFailure(result));
|
||||
}
|
||||
logRegistrationDebug("device registration finished", { generation });
|
||||
@@ -444,14 +688,16 @@ function registerDevice(
|
||||
expectedGeneration,
|
||||
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
|
||||
});
|
||||
const bundleId = Constants.expoConfig?.ios?.bundleIdentifier?.trim();
|
||||
yield* registerDeviceWithRelay(
|
||||
makeRelayDeviceRegistrationRequest({
|
||||
deviceId,
|
||||
label: Constants.deviceName?.trim() || "iOS device",
|
||||
iosMajorVersion: iosMajorVersion(),
|
||||
appVersion: Constants.expoConfig?.version,
|
||||
...(bundleId ? { bundleId } : {}),
|
||||
apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant),
|
||||
...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
|
||||
...(input?.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
|
||||
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
|
||||
preferences,
|
||||
}),
|
||||
@@ -460,27 +706,12 @@ function registerDevice(
|
||||
});
|
||||
}
|
||||
|
||||
function registerDeviceForCurrentUser(
|
||||
pushToStartToken?: string,
|
||||
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
return registerDevice(pushToStartToken ? { pushToStartToken } : undefined);
|
||||
}
|
||||
|
||||
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
|
||||
enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed");
|
||||
}
|
||||
|
||||
function ensurePushToStartListener(): void {
|
||||
if (pushToStartSubscription || !canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
|
||||
pushToStartSubscription = addPushToStartTokenListener((event) => {
|
||||
const token = event.activityPushToStartToken;
|
||||
if (token) {
|
||||
registerPushToStartTokenForCurrentUser(token);
|
||||
}
|
||||
});
|
||||
function registerDeviceForCurrentUser(): Effect.Effect<
|
||||
void,
|
||||
unknown,
|
||||
ManagedRelay.ManagedRelayClient
|
||||
> {
|
||||
return registerDevice(undefined);
|
||||
}
|
||||
|
||||
function ensurePushTokenListener(): void {
|
||||
@@ -498,14 +729,51 @@ function ensurePushTokenListener(): void {
|
||||
});
|
||||
}
|
||||
|
||||
// Re-registering activity tokens on foreground makes the relay replay the
|
||||
// current aggregate to this device, which updates content that drifted while
|
||||
// pushes could not be delivered and ends orphaned activities whose end push
|
||||
// never arrived. (Deduped by ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS: rapid
|
||||
// foreground/sign-in bursts collapse to one registration, but returning after
|
||||
// real time away still replays.)
|
||||
function ensureAppStateListener(): void {
|
||||
if (appStateSubscription || !canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
|
||||
appStateSubscription = AppState.addEventListener("change", (state) => {
|
||||
if (state !== "active") {
|
||||
return;
|
||||
}
|
||||
runRegistrationInBackground(
|
||||
refreshActiveLiveActivityRemoteRegistration(),
|
||||
"active live activity reconciliation after app foreground failed",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function endLocalLiveActivities(context: string): void {
|
||||
if (!canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (const activity of AgentActivity.getInstances()) {
|
||||
activity.end("immediate").catch((error: unknown) => {
|
||||
logRegistrationError(context, error);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logRegistrationError(context, error);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {
|
||||
if (!canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
|
||||
environmentConnections.set(connection.environmentId, connection);
|
||||
ensurePushToStartListener();
|
||||
ensurePushTokenListener();
|
||||
ensureAppStateListener();
|
||||
enqueueDeviceRegistration({}, "device registration failed");
|
||||
runRegistrationInBackground(
|
||||
refreshActiveLiveActivityRemoteRegistration(),
|
||||
@@ -523,10 +791,10 @@ export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId)
|
||||
|
||||
export function unregisterAllAgentAwarenessConnections(): void {
|
||||
environmentConnections.clear();
|
||||
pushToStartSubscription?.remove();
|
||||
pushToStartSubscription = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
@@ -541,6 +809,11 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
|
||||
return registerDeviceForCurrentUser().pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
// Same rationale as the queued path: a failed refresh does not undo an
|
||||
// already accepted registration.
|
||||
if (registrationStatus !== "registered") {
|
||||
setRegistrationStatus("failed");
|
||||
}
|
||||
logRegistrationError("device registration refresh failed", error);
|
||||
}),
|
||||
),
|
||||
@@ -549,10 +822,10 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
|
||||
|
||||
export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
|
||||
environmentConnections.clear();
|
||||
pushToStartSubscription?.remove();
|
||||
pushToStartSubscription = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
@@ -562,6 +835,9 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
|
||||
deviceRegistrationGeneration++;
|
||||
activeDeviceRegistration = null;
|
||||
pendingDeviceRegistration = null;
|
||||
registrationStatus = "unknown";
|
||||
registrationStatusListeners.clear();
|
||||
registeredActivityPushTokens.clear();
|
||||
}
|
||||
|
||||
export function unregisterAgentAwarenessDeviceForCurrentUser(
|
||||
@@ -649,6 +925,13 @@ function registerLiveActivityPushTokenValue(input: {
|
||||
readonly activityPushToken: string;
|
||||
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
|
||||
if (
|
||||
acceptedAt !== undefined &&
|
||||
Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
@@ -662,6 +945,7 @@ function registerLiveActivityPushTokenValue(input: {
|
||||
activityPushToken: input.activityPushToken,
|
||||
});
|
||||
if (registered) {
|
||||
registeredActivityPushTokens.set(input.activityPushToken, Date.now());
|
||||
logRegistrationDebug("live activity push token registered", {
|
||||
tokenSuffix: input.activityPushToken.slice(-8),
|
||||
});
|
||||
@@ -694,7 +978,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
|
||||
return;
|
||||
}
|
||||
|
||||
const activities = yield* Effect.try({
|
||||
let activities = yield* Effect.try({
|
||||
try: () => AgentActivity.getInstances(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
@@ -710,6 +994,79 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
|
||||
),
|
||||
);
|
||||
|
||||
// The relay tracks exactly one card per device; if concurrent arming ever
|
||||
// produced extras, end them so only one keeps receiving updates.
|
||||
if (activities.length > 1) {
|
||||
for (const extra of activities.slice(1)) {
|
||||
extra.end("immediate").catch((error: unknown) => {
|
||||
logRegistrationError("duplicate live activity cleanup failed", error);
|
||||
});
|
||||
}
|
||||
activities = activities.slice(0, 1);
|
||||
}
|
||||
|
||||
// Activities are only ever created here, in the foreground, where the
|
||||
// update token can be observed and registered immediately — the relay
|
||||
// never remote-starts one (background push-to-start wakes proved too
|
||||
// unreliable to hand the token over). Arming is conditional: the relay is
|
||||
// asked what the card would show first, so an idle open never creates an
|
||||
// empty lock-screen card, and an armed card is born with the real
|
||||
// aggregate instead of a placeholder.
|
||||
if (activities.length === 0) {
|
||||
const preferences = yield* Effect.tryPromise({
|
||||
try: () => loadPreferences(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-live-activity-prime-preferences",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
// The toggle defaults to on: an unset preference (fresh install) must
|
||||
// prime, so only an explicit false blocks it.
|
||||
if (preferences?.liveActivitiesEnabled !== false) {
|
||||
const snapshot = yield* readAgentActivitySnapshot();
|
||||
// The snapshot request yields; an arm-on-send may have created the
|
||||
// card in the meantime. Re-check so two cards are never started.
|
||||
const armedMeanwhile = yield* Effect.try({
|
||||
try: () => AgentActivity.getInstances(),
|
||||
catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
|
||||
}).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
|
||||
if (armedMeanwhile.length > 0) {
|
||||
activities = [...armedMeanwhile];
|
||||
} else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
|
||||
const aggregate = snapshot.aggregate;
|
||||
const primed = yield* Effect.try({
|
||||
try: () =>
|
||||
AgentActivity.start({
|
||||
title: aggregate.title,
|
||||
subtitle: aggregate.subtitle,
|
||||
activeCount: aggregate.activeCount,
|
||||
updatedAt: aggregate.updatedAt,
|
||||
activities: aggregate.activities,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "prime-live-activity",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
logRegistrationError("live activity priming failed", error);
|
||||
return null;
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (primed) {
|
||||
logRegistrationDebug("live activity card primed", {
|
||||
activeCount: aggregate.activeCount,
|
||||
});
|
||||
activities = [primed];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const registrationResults = yield* Effect.forEach(activities, (activity) =>
|
||||
registerLiveActivityPushToken({ activity }).pipe(
|
||||
Effect.map((registered) => !registered),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useFocusEffect } from "expo-router";
|
||||
import { useFocusEffect } from "@react-navigation/native";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
|
||||
@@ -2,23 +2,22 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Stack } from "expo-router";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { useCallback, useMemo, useRef, type ComponentProps } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Platform,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
ScrollView,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import ReanimatedSwipeable, {
|
||||
type SwipeableMethods,
|
||||
} from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
@@ -26,11 +25,8 @@ import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
THREAD_SWIPE_SPRING,
|
||||
ThreadSwipeActions,
|
||||
} from "../home/thread-swipe-actions";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
|
||||
|
||||
export interface ArchivedThreadsHeaderEnvironment {
|
||||
@@ -52,84 +48,185 @@ const THREAD_ACTIONS: MenuAction[] = [
|
||||
},
|
||||
];
|
||||
|
||||
type ArchivedThreadListItem =
|
||||
| {
|
||||
readonly kind: "project";
|
||||
readonly key: string;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly project: EnvironmentProject;
|
||||
}
|
||||
| {
|
||||
readonly kind: "thread";
|
||||
readonly key: string;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly isFirst: boolean;
|
||||
readonly isLast: boolean;
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
};
|
||||
|
||||
function ArchivedThreadsHeader(props: {
|
||||
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
}) {
|
||||
const { width } = useWindowDimensions();
|
||||
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
|
||||
const usesNativeChrome = Platform.OS === "ios";
|
||||
const usesCompactMailToolbar = Platform.OS === "ios" && width < 700;
|
||||
const archiveFilterMenu = {
|
||||
title: "Archived thread options",
|
||||
items: [
|
||||
{
|
||||
type: "submenu" as const,
|
||||
title: "Environment",
|
||||
items: [
|
||||
{
|
||||
type: "action" as const,
|
||||
title: "All environments",
|
||||
state: props.selectedEnvironmentId === null ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(null),
|
||||
},
|
||||
...props.environments.map((environment) => ({
|
||||
type: "action" as const,
|
||||
title: environment.label,
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(environment.environmentId),
|
||||
})),
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "submenu" as const,
|
||||
title: "Sort by archived date",
|
||||
items: [
|
||||
{
|
||||
type: "action" as const,
|
||||
title: "Newest first",
|
||||
state: props.sortOrder === "newest" ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onSortOrderChange("newest"),
|
||||
},
|
||||
{
|
||||
type: "action" as const,
|
||||
title: "Oldest first",
|
||||
state: props.sortOrder === "oldest" ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onSortOrderChange("oldest"),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
{/* Static header config (glass preset + title) lives in Stack.tsx; only
|
||||
dynamic toolbar/search wiring is set here. */}
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
title: "Archived Threads",
|
||||
headerSearchBarOptions: {
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Search archived threads",
|
||||
placement: "stacked",
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
},
|
||||
unstable_headerToolbarItems: usesCompactMailToolbar
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
composeButtonId: "archived-refresh",
|
||||
composeSystemImageName: "arrow.clockwise",
|
||||
filterMenu: archiveFilterMenu,
|
||||
filterButtonId: "archived-filter",
|
||||
filterSystemImageName: hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease",
|
||||
onComposePress: props.onRefresh,
|
||||
onSearchTextChange: props.onSearchQueryChange,
|
||||
placeholder: "Search",
|
||||
searchTextChangeId: "archived-search-text",
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
headerSearchBarOptions: usesCompactMailToolbar
|
||||
? undefined
|
||||
: {
|
||||
...(usesNativeChrome
|
||||
? {
|
||||
allowToolbarIntegration: true,
|
||||
placement: "integratedButton" as const,
|
||||
}
|
||||
: {
|
||||
placement: "stacked" as const,
|
||||
}),
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Search archived threads",
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
accessibilityLabel="Filter and sort archived threads"
|
||||
icon={
|
||||
hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Archived thread options"
|
||||
>
|
||||
<Stack.Toolbar.Menu title="Environment">
|
||||
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
>
|
||||
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
{usesCompactMailToolbar ? null : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{usesNativeChrome ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Refresh archived threads"
|
||||
icon="arrow.clockwise"
|
||||
onPress={props.onRefresh}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Menu
|
||||
accessibilityLabel="Filter and sort archived threads"
|
||||
icon={
|
||||
hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Archived thread options"
|
||||
>
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort by archived date">
|
||||
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "newest"}
|
||||
onPress={() => props.onSortOrderChange("newest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "oldest"}
|
||||
onPress={() => props.onSortOrderChange("oldest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
<NativeHeaderToolbar.Menu title="Sort by archived date">
|
||||
<NativeHeaderToolbar.Label>Sort by archived date</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.sortOrder === "newest"}
|
||||
onPress={() => props.onSortOrderChange("newest")}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Newest first</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.sortOrder === "oldest"}
|
||||
onPress={() => props.onSortOrderChange("oldest")}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Oldest first</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -164,30 +261,25 @@ function ProjectGroupLabel(props: {
|
||||
|
||||
function ArchivedThreadRow(props: {
|
||||
readonly environmentLabel: string | null;
|
||||
readonly isFirst: boolean;
|
||||
readonly isLast: boolean;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
typeof ThreadSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
readonly onUnarchive: () => void;
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const cardColor = useThemeColor("--color-card");
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
|
||||
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
|
||||
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
|
||||
Boolean(part),
|
||||
);
|
||||
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
|
||||
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
fullSwipeArmedRef.current = armed;
|
||||
}, []);
|
||||
const handleMenuAction = useCallback(
|
||||
(event: { nativeEvent: { event: string } }) => {
|
||||
if (event.nativeEvent.event === "unarchive") {
|
||||
@@ -200,114 +292,84 @@ function ArchivedThreadRow(props: {
|
||||
);
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
ref={swipeableRef}
|
||||
animationOptions={THREAD_SWIPE_SPRING}
|
||||
childrenContainerStyle={{ backgroundColor: cardColor }}
|
||||
containerStyle={{ backgroundColor: cardColor }}
|
||||
dragOffsetFromRightEdge={8}
|
||||
enableTrackpadTwoFingerGesture
|
||||
friction={1}
|
||||
onSwipeableClose={() => {
|
||||
fullSwipeArmedRef.current = false;
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableClose(swipeableRef.current);
|
||||
}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeWidth={windowWidth - 32}
|
||||
onDelete={props.onDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Unarchive ${props.thread.title}`,
|
||||
icon: "arrow.uturn.backward",
|
||||
label: "Unarchive",
|
||||
onPress: props.onUnarchive,
|
||||
}}
|
||||
onSwipeableOpenStartDrag={() => {
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableWillOpen(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableWillOpen={() => {
|
||||
const methods = swipeableRef.current;
|
||||
if (!methods) return;
|
||||
|
||||
props.onSwipeableWillOpen(methods);
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
overshootRight
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Unarchive ${props.thread.title}`,
|
||||
icon: "arrow.uturn.backward",
|
||||
label: "Unarchive",
|
||||
onPress: props.onUnarchive,
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.thread.title}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={props.thread.title}
|
||||
>
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3"
|
||||
style={{
|
||||
borderBottomColor: separatorColor,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
}}
|
||||
>
|
||||
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
|
||||
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
{() => (
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3"
|
||||
style={{
|
||||
borderBottomColor: separatorColor,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
borderTopLeftRadius: props.isFirst ? 20 : 0,
|
||||
borderTopRightRadius: props.isFirst ? 20 : 0,
|
||||
borderBottomLeftRadius: props.isLast ? 20 : 0,
|
||||
borderBottomRightRadius: props.isLast ? 20 : 0,
|
||||
}}
|
||||
>
|
||||
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
|
||||
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
{subtitle.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
|
||||
className="min-w-0 flex-1 text-base font-t3-bold leading-snug text-foreground"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitle.join(" · ")}
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"], minWidth: 30, textAlign: "right" }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{subtitle.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitle.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel={`Actions for ${props.thread.title}`}
|
||||
accessibilityRole="button"
|
||||
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
|
||||
hitSlop={6}
|
||||
>
|
||||
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
</ReanimatedSwipeable>
|
||||
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel={`Actions for ${props.thread.title}`}
|
||||
accessibilityRole="button"
|
||||
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
|
||||
hitSlop={6}
|
||||
>
|
||||
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
)}
|
||||
</ThreadSwipeable>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -317,7 +379,7 @@ function ArchiveError(props: { readonly message: string; readonly onRetry: () =>
|
||||
<Text className="text-base font-t3-bold text-danger-foreground">
|
||||
Could not load every archive
|
||||
</Text>
|
||||
<Text className="mt-1 text-sm leading-[18px] text-foreground-muted">{props.message}</Text>
|
||||
<Text className="mt-1 text-sm text-foreground-muted">{props.message}</Text>
|
||||
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
|
||||
<Text className="text-sm font-t3-bold text-danger-foreground">Try again</Text>
|
||||
</Pressable>
|
||||
@@ -340,8 +402,41 @@ export function ArchivedThreadsScreen(props: {
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
}) {
|
||||
const { onDeleteThread, onUnarchiveThread } = props;
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const refreshTint = useThemeColor("--color-icon");
|
||||
const environmentLabelsById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
props.environments.map((environment) => [environment.environmentId, environment.label]),
|
||||
),
|
||||
[props.environments],
|
||||
);
|
||||
const listItems = useMemo<ReadonlyArray<ArchivedThreadListItem>>(() => {
|
||||
const items: ArchivedThreadListItem[] = [];
|
||||
for (const group of props.groups) {
|
||||
const environmentLabel = environmentLabelsById.get(group.project.environmentId) ?? null;
|
||||
items.push({
|
||||
kind: "project",
|
||||
key: `${group.key}:project`,
|
||||
environmentLabel,
|
||||
project: group.project,
|
||||
});
|
||||
|
||||
group.threads.forEach((thread, index) => {
|
||||
items.push({
|
||||
kind: "thread",
|
||||
key: `${thread.environmentId}:${thread.id}`,
|
||||
environmentLabel,
|
||||
isFirst: index === 0,
|
||||
isLast: index === group.threads.length - 1,
|
||||
thread,
|
||||
});
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}, [environmentLabelsById, props.groups]);
|
||||
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
|
||||
openSwipeableRef.current.close();
|
||||
@@ -355,82 +450,103 @@ export function ArchivedThreadsScreen(props: {
|
||||
}, []);
|
||||
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
|
||||
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
|
||||
const renderListItem = useCallback(
|
||||
({ item }: { item: ArchivedThreadListItem }) => {
|
||||
if (item.kind === "project") {
|
||||
return (
|
||||
<View className="pt-4">
|
||||
<ProjectGroupLabel environmentLabel={item.environmentLabel} project={item.project} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ArchivedThreadRow
|
||||
environmentLabel={item.environmentLabel}
|
||||
isFirst={item.isFirst}
|
||||
isLast={item.isLast}
|
||||
onDelete={() => onDeleteThread(item.thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
onUnarchive={() => onUnarchiveThread(item.thread)}
|
||||
simultaneousSwipeGesture={archiveScrollGesture}
|
||||
thread={item.thread}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
archiveScrollGesture,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
onDeleteThread,
|
||||
onUnarchiveThread,
|
||||
],
|
||||
);
|
||||
const listEmptyComponent = useMemo(() => {
|
||||
if (isInitialLoad) {
|
||||
return (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-sm text-foreground-muted">Loading archive...</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<EmptyState
|
||||
detail={
|
||||
isFiltered
|
||||
? "Try another search or environment."
|
||||
: "Threads you archive will appear here."
|
||||
}
|
||||
title={isFiltered ? "No matching threads" : "No archived threads"}
|
||||
/>
|
||||
);
|
||||
}, [isFiltered, isInitialLoad, refreshTint]);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<ArchivedThreadsHeader
|
||||
environments={props.environments}
|
||||
onEnvironmentChange={props.onEnvironmentChange}
|
||||
onRefresh={props.onRefresh}
|
||||
onSearchQueryChange={props.onSearchQueryChange}
|
||||
onSortOrderChange={props.onSortOrderChange}
|
||||
selectedEnvironmentId={props.selectedEnvironmentId}
|
||||
sortOrder={props.sortOrder}
|
||||
/>
|
||||
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
onRefresh={props.onRefresh}
|
||||
refreshing={props.isLoading && !isInitialLoad}
|
||||
tintColor={String(refreshTint)}
|
||||
/>
|
||||
}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
|
||||
|
||||
{isInitialLoad ? (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
|
||||
</View>
|
||||
) : props.groups.length === 0 ? (
|
||||
<EmptyState
|
||||
detail={
|
||||
isFiltered
|
||||
? "Try another search or environment."
|
||||
: "Threads you archive will appear here."
|
||||
}
|
||||
title={isFiltered ? "No matching threads" : "No archived threads"}
|
||||
/>
|
||||
) : (
|
||||
props.groups.map((group) => {
|
||||
const environmentLabel =
|
||||
props.environments.find(
|
||||
(environment) => environment.environmentId === group.project.environmentId,
|
||||
)?.label ?? null;
|
||||
|
||||
return (
|
||||
<View key={group.key} collapsable={false}>
|
||||
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
|
||||
<View
|
||||
className="overflow-hidden rounded-[20px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{group.threads.map((thread, index) => (
|
||||
<ArchivedThreadRow
|
||||
key={`${thread.environmentId}:${thread.id}`}
|
||||
environmentLabel={environmentLabel}
|
||||
isLast={index === group.threads.length - 1}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
onUnarchive={() => props.onUnarchiveThread(thread)}
|
||||
thread={thread}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ScrollView>
|
||||
<GestureDetector gesture={archiveScrollGesture}>
|
||||
<LegendList
|
||||
className="flex-1"
|
||||
contentContainerStyle={{
|
||||
paddingBottom: 32,
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 4,
|
||||
}}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
data={listItems}
|
||||
estimatedItemSize={62}
|
||||
getItemType={(item) => item.kind}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyExtractor={(item) => item.key}
|
||||
ListEmptyComponent={listEmptyComponent}
|
||||
ListHeaderComponent={
|
||||
props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null
|
||||
}
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
onRefresh={props.onRefresh}
|
||||
refreshing={props.isLoading && !isInitialLoad}
|
||||
tintColor={String(refreshTint)}
|
||||
/>
|
||||
}
|
||||
renderItem={renderListItem}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
</GestureDetector>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
import { makeRawThreadShell } from "../../test-fixtures";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
@@ -22,40 +24,30 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
|
||||
readonly branch?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
|
||||
return makeRawThreadShell({
|
||||
...input,
|
||||
};
|
||||
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
|
||||
});
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,9 +14,11 @@ import { runtime } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import {
|
||||
releaseAgentAwarenessRelayTokenProvider,
|
||||
setAgentAwarenessRelayTokenProvider,
|
||||
unregisterAgentAwarenessDeviceForCurrentUser,
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
|
||||
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
|
||||
|
||||
function resetManagedRelayTokenCache() {
|
||||
@@ -66,6 +68,19 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
const nextAccount = isSignedIn && userId ? userId : null;
|
||||
observedAccountRef.current = nextAccount;
|
||||
|
||||
// Every sign-in or account switch that completes during this session (a
|
||||
// cold start observes undefined → account and must not re-prompt) requests
|
||||
// the T3 Connect onboarding sheet — account transitions clear the
|
||||
// connected environments, so each new session starts with no devices to
|
||||
// reach. The request itself is issued after the cleanup transition inside
|
||||
// activateSession, so the sheet never lists the previous account's
|
||||
// environments; sign-out drops any not-yet-presented request instead.
|
||||
const isAccountTransition =
|
||||
previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;
|
||||
if (isAccountTransition && nextAccount === null) {
|
||||
clearConnectOnboardingRequest();
|
||||
}
|
||||
|
||||
const queueAccountCleanup = (
|
||||
previous: {
|
||||
readonly userId: string;
|
||||
@@ -113,6 +128,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
}
|
||||
previousTokenProviderRef.current = { userId, provider: tokenProvider };
|
||||
activateCloudRelayAccount(userId, tokenProvider);
|
||||
if (isAccountTransition) {
|
||||
requestConnectOnboarding(userId);
|
||||
}
|
||||
};
|
||||
const activateAfterTransition = (transition: Promise<void>) => {
|
||||
void (async () => {
|
||||
@@ -143,7 +161,11 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
useEffect(
|
||||
() => () => {
|
||||
previousTokenProviderRef.current = null;
|
||||
deactivateCloudRelayAccount();
|
||||
// Unmounting is not a sign-out: the user is usually still signed in, so
|
||||
// detach the provider without ending lock-screen activities or wiping the
|
||||
// persisted registration (a remount reuses both).
|
||||
releaseAgentAwarenessRelayTokenProvider();
|
||||
setManagedRelaySession(appAtomRegistry, null);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useWaitlist } from "@clerk/expo";
|
||||
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
||||
import { useState } from "react";
|
||||
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
|
||||
|
||||
@@ -36,9 +35,11 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
if (waitlist.id) {
|
||||
return (
|
||||
<View style={styles.content}>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>You are on the waitlist</Text>
|
||||
<Text style={[styles.body, styles.confirmationBody, { color: colors.secondaryForeground }]}>
|
||||
We will email you when your T3 Cloud access is ready.
|
||||
<Text className="text-center font-t3-bold text-xl text-foreground">
|
||||
You are on the waitlist
|
||||
</Text>
|
||||
<Text className="text-center font-sans text-base text-foreground-secondary">
|
||||
We will email you when your T3 Connect access is ready.
|
||||
</Text>
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
@@ -47,17 +48,18 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
|
||||
return (
|
||||
<View style={styles.content}>
|
||||
<Text style={[styles.body, { color: colors.secondaryForeground }]}>
|
||||
<Text className="font-sans text-base text-foreground-secondary">
|
||||
Enter your email and we will let you know when access is ready.
|
||||
</Text>
|
||||
|
||||
<View style={styles.field}>
|
||||
<Text style={[styles.label, { color: colors.secondaryForeground }]}>Email address</Text>
|
||||
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Email address"
|
||||
autoCapitalize="none"
|
||||
autoComplete="email"
|
||||
autoCorrect={false}
|
||||
className="font-sans text-lg text-foreground"
|
||||
keyboardType="email-address"
|
||||
onChangeText={(value) => {
|
||||
setEmailAddress(value);
|
||||
@@ -73,7 +75,6 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
backgroundColor: colors.input,
|
||||
borderColor:
|
||||
fieldError || requestError ? colors.dangerForeground : colors.inputBorder,
|
||||
color: colors.foreground,
|
||||
},
|
||||
]}
|
||||
textContentType="emailAddress"
|
||||
@@ -82,7 +83,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
{fieldError || requestError ? (
|
||||
<Text
|
||||
accessibilityLiveRegion="polite"
|
||||
style={[styles.error, { color: colors.dangerForeground }]}
|
||||
className="font-sans text-sm text-danger-foreground"
|
||||
selectable
|
||||
>
|
||||
{fieldError ?? requestError}
|
||||
@@ -107,7 +108,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
]}
|
||||
>
|
||||
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
|
||||
<Text style={[styles.buttonText, { color: colors.primaryForeground }]}>
|
||||
<Text className="font-t3-bold text-base text-primary-foreground">
|
||||
{isSubmitting ? "Joining" : "Join the waitlist"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -118,12 +119,11 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
}
|
||||
|
||||
function SignInAction(props: { readonly onPress: () => void }) {
|
||||
const colors = useCloudWaitlistColors();
|
||||
return (
|
||||
<View style={styles.signInRow}>
|
||||
<Text style={[styles.body, { color: colors.secondaryForeground }]}>Already have access?</Text>
|
||||
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
|
||||
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
|
||||
<Text style={[styles.signInText, { color: colors.foreground }]}>Sign in</Text>
|
||||
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
@@ -132,35 +132,18 @@ function SignInAction(props: { readonly onPress: () => void }) {
|
||||
function useCloudWaitlistColors() {
|
||||
return {
|
||||
dangerForeground: String(useThemeColor("--color-danger-foreground")),
|
||||
foreground: String(useThemeColor("--color-foreground")),
|
||||
input: String(useThemeColor("--color-input")),
|
||||
inputBorder: String(useThemeColor("--color-input-border")),
|
||||
placeholder: String(useThemeColor("--color-placeholder")),
|
||||
primary: String(useThemeColor("--color-primary")),
|
||||
primaryForeground: String(useThemeColor("--color-primary-foreground")),
|
||||
secondaryForeground: String(useThemeColor("--color-foreground-secondary")),
|
||||
};
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
body: {
|
||||
fontFamily: "DMSans_400Regular",
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
},
|
||||
buttonText: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.body.fontSize,
|
||||
},
|
||||
content: {
|
||||
gap: 18,
|
||||
},
|
||||
confirmationBody: {
|
||||
textAlign: "center",
|
||||
},
|
||||
error: {
|
||||
fontFamily: "DMSans_400Regular",
|
||||
...MOBILE_TYPOGRAPHY.footnote,
|
||||
},
|
||||
field: {
|
||||
gap: 8,
|
||||
},
|
||||
@@ -168,16 +151,10 @@ const styles = StyleSheet.create({
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 16,
|
||||
borderWidth: 1,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
|
||||
minHeight: 54,
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
label: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
...MOBILE_TYPOGRAPHY.footnote,
|
||||
},
|
||||
primaryButton: {
|
||||
alignItems: "center",
|
||||
borderRadius: 999,
|
||||
@@ -195,13 +172,4 @@ const styles = StyleSheet.create({
|
||||
justifyContent: "center",
|
||||
paddingTop: 4,
|
||||
},
|
||||
signInText: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
},
|
||||
title: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
...MOBILE_TYPOGRAPHY.title,
|
||||
textAlign: "center",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { NativeHeaderToolbar } from "../../native/StackHeader";
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
import { splitEnvironmentSections } from "../connection/environmentSections";
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
|
||||
import { hasCloudPublicConfig } from "./publicConfig";
|
||||
|
||||
/**
|
||||
* Post-sign-in onboarding sheet for T3 Connect. Mobile never publishes
|
||||
* environments itself — it consumes ones published elsewhere — so this simply
|
||||
* surfaces the account's T3 Connect environments right after sign-in so every
|
||||
* device can be connected in one go. It shows on every sign-in: sign-out
|
||||
* clears the connected environments, so each new session starts from zero.
|
||||
*/
|
||||
export function ConnectOnboardingRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
// The route is deep-linkable; without cloud config the sheet would present
|
||||
// empty with no chrome to dismiss it, so bail back out instead.
|
||||
useEffect(() => {
|
||||
if (hasCloudPublicConfig()) {
|
||||
return;
|
||||
}
|
||||
if (navigation.canGoBack()) {
|
||||
navigation.goBack();
|
||||
} else {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
}
|
||||
}, [navigation]);
|
||||
|
||||
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
|
||||
}
|
||||
|
||||
function ConfiguredConnectOnboardingRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();
|
||||
const { refreshRelayEnvironments } = useConnectionController();
|
||||
const { connectedCloudEnvironments } = splitEnvironmentSections({
|
||||
connectedEnvironments,
|
||||
cloudEnvironments: null,
|
||||
});
|
||||
|
||||
// Pull-to-refresh tracks its own spinner instead of discovery's refreshing
|
||||
// flag, so background refreshes (e.g. the sign-in one) don't yank the
|
||||
// content down.
|
||||
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
|
||||
const handlePullRefresh = useCallback(() => {
|
||||
void (async () => {
|
||||
setIsPullRefreshing(true);
|
||||
await refreshRelayEnvironments();
|
||||
setIsPullRefreshing(false);
|
||||
})();
|
||||
}, [refreshRelayEnvironments]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
navigation.goBack();
|
||||
}, [navigation]);
|
||||
|
||||
// Persist before dismissing so a quick sign-out/sign-in cannot race ahead
|
||||
// of the preference write; the write is a local secure-store update.
|
||||
const handleDontShowAgain = useCallback(() => {
|
||||
void (async () => {
|
||||
if (userId) {
|
||||
const result = await settlePromise(() => optOutOfConnectOnboarding(userId));
|
||||
reportAtomCommandResult(result, { label: "connect onboarding opt-out" });
|
||||
}
|
||||
navigation.goBack();
|
||||
})();
|
||||
}, [navigation, userId]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
<ScrollView
|
||||
alwaysBounceVertical
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
gap: 16,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={isPullRefreshing} onRefresh={handlePullRefresh} />
|
||||
}
|
||||
>
|
||||
{isSignedIn ? (
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
showHeader={false}
|
||||
/>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card p-5">
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
Sign in to your T3 account to set up T3 Connect.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{userId ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
hitSlop={8}
|
||||
onPress={handleDontShowAgain}
|
||||
className="items-center py-1 active:opacity-70"
|
||||
>
|
||||
<Text className="text-xs text-foreground-muted">{"Don't show this again"}</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
|
||||
// Signals RootStackLayout (inside the navigation tree) that an in-session
|
||||
// sign-in just completed. Holds the account id so a sign-out between the
|
||||
// request and the navigation cannot present the sheet for the wrong account.
|
||||
export const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:connect-onboarding-request"),
|
||||
);
|
||||
|
||||
/**
|
||||
* Requests the onboarding sheet for the given account. Sign-out clears the
|
||||
* connected environments, so onboarding runs on every in-session sign-in —
|
||||
* each new session starts with no connected devices.
|
||||
*/
|
||||
export function requestConnectOnboarding(accountId: string): void {
|
||||
appAtomRegistry.set(connectOnboardingRequestAtom, accountId);
|
||||
}
|
||||
|
||||
export function clearConnectOnboardingRequest(): void {
|
||||
appAtomRegistry.set(connectOnboardingRequestAtom, null);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
|
||||
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
|
||||
|
||||
// Sign-in happens inside the Settings sheet; give its detent/session-state
|
||||
// transitions a beat to settle before presenting another formSheet on top.
|
||||
const PRESENT_ONBOARDING_DELAY_MS = 600;
|
||||
|
||||
/**
|
||||
* Consumes the onboarding request inside the navigation tree (RootStackLayout)
|
||||
* and presents the onboarding formSheet. Lives apart from connectOnboarding.ts
|
||||
* so non-navigation consumers (CloudAuthProvider) do not pull
|
||||
* @react-navigation into their module graph.
|
||||
*/
|
||||
export function useConnectOnboardingNavigation(): void {
|
||||
const navigation = useNavigation();
|
||||
const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);
|
||||
|
||||
useEffect(() => {
|
||||
if (requestedAccountId === null) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
const timer = setTimeout(() => {
|
||||
void (async () => {
|
||||
// A failed preference read prefers showing the sheet.
|
||||
const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false);
|
||||
// The cancelled flag covers effect re-runs, but a sign-out can clear
|
||||
// the request atom moments before this render commits — re-check the
|
||||
// atom so a stale request never presents the sheet.
|
||||
if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) {
|
||||
return;
|
||||
}
|
||||
clearConnectOnboardingRequest();
|
||||
if (!optedOut) {
|
||||
navigation.navigate("ConnectOnboarding");
|
||||
}
|
||||
})();
|
||||
}, PRESENT_ONBOARDING_DELAY_MS);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [navigation, requestedAccountId]);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { loadPreferences, updatePreferences } from "../../lib/storage";
|
||||
|
||||
// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports
|
||||
// the request signal) never pulls lib/storage — expo-secure-store — into its
|
||||
// module graph; that breaks CloudAuthProvider.test.ts suite loading.
|
||||
|
||||
/** Whether the account chose "Don't show this again". */
|
||||
export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {
|
||||
const preferences = await loadPreferences();
|
||||
return preferences.connectOnboardingOptOutAccounts?.includes(accountId) ?? false;
|
||||
}
|
||||
|
||||
/** Persists "Don't show this again" for the account. */
|
||||
export async function optOutOfConnectOnboarding(accountId: string): Promise<void> {
|
||||
await updatePreferences((current) => {
|
||||
const optedOut = current.connectOnboardingOptOutAccounts ?? [];
|
||||
return optedOut.includes(accountId)
|
||||
? {}
|
||||
: { connectOnboardingOptOutAccounts: [...optedOut, accountId] };
|
||||
});
|
||||
}
|
||||
Loaded 100 of 1009 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user