Compare commits
254
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27ecbe1ab7 | ||
|
|
d935c9cc62 | ||
|
|
c2c79b769a | ||
|
|
ba24598606 | ||
|
|
2ac7918f5a | ||
|
|
04a12b8f1f | ||
|
|
ac0664048f | ||
|
|
e5cbabf0b1 | ||
|
|
e151f62c2a | ||
|
|
e51a097fd5 | ||
|
|
bb73e6306f | ||
|
|
81adc111a7 | ||
|
|
0a1e41e29c | ||
|
|
61857dbb77 | ||
|
|
26dafdc72c | ||
|
|
bdf082072d | ||
|
|
c0a38525ea | ||
|
|
3f82967507 | ||
|
|
bcbab62dc1 | ||
|
|
9c888b6b18 | ||
|
|
3d4bf8d828 | ||
|
|
bbbeafa853 | ||
|
|
06829caa73 | ||
|
|
074c0c183f | ||
|
|
c1929c2b5b | ||
|
|
378615bb51 | ||
|
|
8a3d81d52c | ||
|
|
87ff166fa0 | ||
|
|
252ce04576 | ||
|
|
f22182942c | ||
|
|
7a5cc479f5 | ||
|
|
353f352c1e | ||
|
|
607ddc3618 | ||
|
|
bb12ad5e99 | ||
|
|
f29edafe04 | ||
|
|
b76a0919dc | ||
|
|
413089399d | ||
|
|
8b88bc70bf | ||
|
|
64d8fcd8b6 | ||
|
|
099c78a119 | ||
|
|
9d5e81ba49 | ||
|
|
3ba2d0278b | ||
|
|
b4bc329f73 | ||
|
|
b65e09cdd8 | ||
|
|
b6577a862a | ||
|
|
d1fbf7d250 | ||
|
|
dcfd6c9848 | ||
|
|
e9e68f8a6c | ||
|
|
faa853a149 | ||
|
|
96ae1a48f4 | ||
|
|
3cd87892c0 | ||
|
|
08be31c2e9 | ||
|
|
cfc63a2022 | ||
|
|
2a408a8ced | ||
|
|
4f6fed549d | ||
|
|
2d309f1468 | ||
|
|
03dde37679 | ||
|
|
7c9e146f4f | ||
|
|
9de147e306 | ||
|
|
bb2bdc93ab | ||
|
|
f1a331d7be | ||
|
|
5ded72aba2 | ||
|
|
e29797b966 | ||
|
|
6a803d092d | ||
|
|
45b8157e53 | ||
|
|
192b160428 | ||
|
|
7aecec1ab1 | ||
|
|
c5aa1a244b | ||
|
|
563f03ef58 | ||
|
|
eca5fd07e9 | ||
|
|
b6d7072140 | ||
|
|
70f452ba3a | ||
|
|
0620dae3a4 | ||
|
|
9ce464b3d0 | ||
|
|
8f3bafe2f9 | ||
|
|
396eb47419 | ||
|
|
6ab4ce9fe3 | ||
|
|
091a76003e | ||
|
|
d93083fe50 | ||
|
|
3d1db82e1c | ||
|
|
a70b7acd83 | ||
|
|
74f8c7ceed | ||
|
|
25463fe2b1 | ||
|
|
fe5df2b650 | ||
|
|
61b181443c | ||
|
|
e647f444d2 | ||
|
|
f96a785978 | ||
|
|
263ad34710 | ||
|
|
b244cc81ce | ||
|
|
5ee040a06e | ||
|
|
f691c18da4 | ||
|
|
ead7f56c6d | ||
|
|
55be8808d4 | ||
|
|
134d0b62ba | ||
|
|
f52e8be137 | ||
|
|
c592c62104 | ||
|
|
b4137f061d | ||
|
|
1aad8b5450 | ||
|
|
6ae33d8b0c | ||
|
|
660f947a19 | ||
|
|
30617478c9 | ||
|
|
523d078020 | ||
|
|
350b0ef151 | ||
|
|
2d8f6c3b96 | ||
|
|
267c0b22b2 | ||
|
|
701ccd2213 | ||
|
|
e703b2a03d | ||
|
|
b201a7c28f | ||
|
|
77870e9ff7 | ||
|
|
d956fccbac | ||
|
|
dac4ad26b0 | ||
|
|
eda0ca15b7 | ||
|
|
f14c150cf3 | ||
|
|
664d82753f | ||
|
|
389879cd81 | ||
|
|
f609654f11 | ||
|
|
590622b97b | ||
|
|
9b91d3b8ca | ||
|
|
e63d49f66b | ||
|
|
cc8cc854f7 | ||
|
|
ff3aca1dd4 | ||
|
|
6a1ba3ca2b | ||
|
|
e754e8027e | ||
|
|
4b41243e6d | ||
|
|
751da6d2c4 | ||
|
|
597b02dc53 | ||
|
|
f2e1dd1e27 | ||
|
|
85b6490c33 | ||
|
|
87497f2ed7 | ||
|
|
9923f6a2ef | ||
|
|
5867968b3a | ||
|
|
5d92ac8b35 | ||
|
|
81a82d88e7 | ||
|
|
bb5e91260a | ||
|
|
335708df8b | ||
|
|
7791d6b2bf | ||
|
|
638b9fc854 | ||
|
|
14d20c8665 | ||
|
|
bc40ae8d28 | ||
|
|
0ccf9c60bd | ||
|
|
60dc48a413 | ||
|
|
022452d02e | ||
|
|
e2f21f8be6 | ||
|
|
ff09cda0f8 | ||
|
|
9479d6f7cc | ||
|
|
5b41d69b3a | ||
|
|
9b8b3f8f67 | ||
|
|
3c680b50c8 | ||
|
|
beab58b45b | ||
|
|
2fde64e80f | ||
|
|
391c46f9d9 | ||
|
|
0ee3425c03 | ||
|
|
e0f509e5c0 | ||
|
|
64c3fccf36 | ||
|
|
00b7fd1245 | ||
|
|
efdf72ec8c | ||
|
|
82ffe9862c | ||
|
|
cb6012aeb8 | ||
|
|
3991a00629 | ||
|
|
75e126993b | ||
|
|
b77ac60a0e | ||
|
|
4009dfbc1b | ||
|
|
27a003d555 | ||
|
|
edf5d6f2db | ||
|
|
2fd952bd3d | ||
|
|
28ea5e1104 | ||
|
|
f2481dfbfd | ||
|
|
6b64376033 | ||
|
|
27897acd26 | ||
|
|
ddb255a7db | ||
|
|
96b3a4e578 | ||
|
|
bd23813e34 | ||
|
|
d699990254 | ||
|
|
5705dde188 | ||
|
|
da9a6788ee | ||
|
|
020d32190d | ||
|
|
14539c234a | ||
|
|
471005ff2f | ||
|
|
556b9464f8 | ||
|
|
2e1166b21f | ||
|
|
3c58565361 | ||
|
|
09aadd6f34 | ||
|
|
50b57e11a1 | ||
|
|
fd06b57382 | ||
|
|
40747fff7b | ||
|
|
13ed2dbdca | ||
|
|
adcc3165ec | ||
|
|
2ad2fd9c86 | ||
|
|
1e421221d4 | ||
|
|
1f5579b072 | ||
|
|
bf5ebea4c8 | ||
|
|
a88130487b | ||
|
|
232e12c720 | ||
|
|
ab534f465d | ||
|
|
7cfdb4e79e | ||
|
|
74f73e39ea | ||
|
|
510e49e2cc | ||
|
|
1671e1f046 | ||
|
|
8a6d895830 | ||
|
|
e124f3b462 | ||
|
|
9602252189 | ||
|
|
72649cde7c | ||
|
|
aaae99ec50 | ||
|
|
4953425822 | ||
|
|
540407ce07 | ||
|
|
7949333a18 | ||
|
|
51e5d3f6b7 | ||
|
|
7813c01e9e | ||
|
|
d1bd26e788 | ||
|
|
fdca6bc683 | ||
|
|
243a78e3aa | ||
|
|
9dd9a45568 | ||
|
|
a38b30441f | ||
|
|
21622d5bb7 | ||
|
|
30c9622806 | ||
|
|
69dfb7f09a | ||
|
|
e60821f0e0 | ||
|
|
64bf016191 | ||
|
|
5192f777fe | ||
|
|
283c7ac4ba | ||
|
|
78eb3ecae9 | ||
|
|
d3037064e6 | ||
|
|
0ad91b6e7f | ||
|
|
ca72e381c6 | ||
|
|
491219bf1f | ||
|
|
e5c7547067 | ||
|
|
bfc31507f8 | ||
|
|
03adf215ce | ||
|
|
916cff733c | ||
|
|
a041981276 | ||
|
|
964cc27901 | ||
|
|
acf761b2f5 | ||
|
|
ab8182cb4e | ||
|
|
ef4ec2ad4b | ||
|
|
61514c1294 | ||
|
|
894d6d68f5 | ||
|
|
fccec9f097 | ||
|
|
50a3d6b872 | ||
|
|
e259dd23c7 | ||
|
|
df78cda8bf | ||
|
|
605c2bb734 | ||
|
|
cb11a71d63 | ||
|
|
41124c7260 | ||
|
|
b0b275227b | ||
|
|
cb293fe790 | ||
|
|
1d694dcbd8 | ||
|
|
32407df9c5 | ||
|
|
162e774294 | ||
|
|
063ed7120a | ||
|
|
34b15a9ace | ||
|
|
fbecb7365e | ||
|
|
4029b858ea | ||
|
|
5b2577f6a9 | ||
|
|
bc142f84a2 |
No files matched your search
@@ -66,7 +66,7 @@ Use these client origins:
|
||||
- Android Emulator: `http://10.0.2.2:<server-port>`
|
||||
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
|
||||
|
||||
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
|
||||
Enter the complete `http://` origin to make the test transport explicit. Bare IP addresses default to HTTP, while bare hostnames default to HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
|
||||
|
||||
## Start or reuse Metro safely
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ body:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- apps/mobile
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
|
||||
@@ -30,6 +30,7 @@ body:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- apps/mobile
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
|
||||
@@ -70,6 +70,16 @@ jobs:
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
# Blacksmith boots GitHub's Ubuntu runner image (gcc is usually present),
|
||||
# but ACP process-tree live tests compile a small pthread fixture with `cc`
|
||||
# and soft-skip when it is missing. Install build-essential so that path
|
||||
# always runs in CI instead of silently no-oping.
|
||||
- name: Install C toolchain for process-tree fixtures
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends build-essential
|
||||
command -v cc
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
|
||||
@@ -39,10 +39,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
# when the partial clone can't serve the unfetched blobs.
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -57,10 +57,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
# when the partial clone can't serve the unfetched blobs.
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -52,6 +52,7 @@ jobs:
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
@@ -100,6 +101,7 @@ jobs:
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
|
||||
@@ -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
@@ -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`
|
||||
@@ -17,6 +17,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
@@ -220,6 +221,7 @@ const startup = Effect.gen(function* () {
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
@@ -248,6 +250,7 @@ const startup = Effect.gen(function* () {
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
|
||||
@@ -54,7 +54,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
calls.setAboutPanelOptions.push(options);
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
|
||||
@@ -45,6 +45,27 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
: Option.none();
|
||||
};
|
||||
|
||||
export const resolveUserDataPath = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const legacyPath = environment.path.join(
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
@@ -90,24 +111,11 @@ export const make = Effect.gen(function* () {
|
||||
return commitHash;
|
||||
});
|
||||
|
||||
const resolveUserDataPath = Effect.gen(function* () {
|
||||
const legacyPath = environment.path.join(
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
|
||||
const userDataPath = resolveUserDataPath.pipe(
|
||||
Effect.provide(
|
||||
yield* Effect.context<DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem>(),
|
||||
),
|
||||
);
|
||||
|
||||
const configure = Effect.gen(function* () {
|
||||
const commitHash = yield* resolveAboutCommitHash;
|
||||
@@ -136,7 +144,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
|
||||
|
||||
return DesktopAppIdentity.of({
|
||||
resolveUserDataPath,
|
||||
resolveUserDataPath: userDataPath,
|
||||
configure,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,17 +22,38 @@ vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const makeDesktopClerkLayer = (isDevelopment = true) => {
|
||||
const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment,
|
||||
appDataDirectory: "/tmp/app-data",
|
||||
userDataDirName: isDevelopment ? "t3code-dev" : "t3code",
|
||||
legacyUserDataDirName: isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)",
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const electronApp = {
|
||||
setPath: (name: string, value: string) =>
|
||||
Effect.sync(() => {
|
||||
events.push(`setPath:${name}:${value}`);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
|
||||
return DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Layer.succeed(ElectronApp.ElectronApp, electronApp),
|
||||
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -55,11 +76,15 @@ describe("DesktopClerk", () => {
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
const events: string[] = [];
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
createClerkBridgeMock.mockImplementation(() => {
|
||||
events.push("createClerkBridge");
|
||||
return { cleanup, isPrimaryInstance: true };
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
@@ -71,6 +96,10 @@ describe("DesktopClerk", () => {
|
||||
],
|
||||
]);
|
||||
assert.equal(cleanup.mock.calls.length, 1);
|
||||
// The bridge acquires Electron's single-instance lock at creation, and
|
||||
// the lock both lives in and creates the userData directory — so the
|
||||
// real path must be set before the bridge exists.
|
||||
assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
@@ -124,11 +153,67 @@ describe("DesktopClerk", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("registers the second-instance handler in the primary instance", () => {
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
|
||||
const quit = vi.fn();
|
||||
const registeredEvents: string[] = [];
|
||||
const electronApp = {
|
||||
quit: Effect.sync(quit),
|
||||
on: (eventName: string) =>
|
||||
Effect.sync(() => {
|
||||
registeredEvents.push(eventName);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
|
||||
|
||||
assert.isTrue(Exit.isSuccess(exit));
|
||||
assert.equal(quit.mock.calls.length, 0);
|
||||
assert.deepEqual(registeredEvents, ["second-instance"]);
|
||||
}).pipe(
|
||||
Effect.provide(makeDesktopClerkLayer()),
|
||||
Effect.provideService(ElectronApp.ElectronApp, electronApp),
|
||||
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("quits and interrupts startup in a secondary instance", () => {
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
|
||||
const quit = vi.fn();
|
||||
const registeredEvents: string[] = [];
|
||||
const electronApp = {
|
||||
quit: Effect.sync(quit),
|
||||
on: (eventName: string) =>
|
||||
Effect.sync(() => {
|
||||
registeredEvents.push(eventName);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
|
||||
|
||||
assert.isTrue(Exit.hasInterrupts(exit));
|
||||
assert.equal(quit.mock.calls.length, 1);
|
||||
assert.deepEqual(registeredEvents, []);
|
||||
}).pipe(
|
||||
Effect.provide(makeDesktopClerkLayer()),
|
||||
Effect.provideService(ElectronApp.ElectronApp, electronApp),
|
||||
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isDevelopment: true, scheme: "t3code-dev" },
|
||||
{ isDevelopment: false, scheme: "t3code" },
|
||||
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
|
||||
const bridge = { cleanup: vi.fn() };
|
||||
const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
@@ -84,7 +85,18 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
|
||||
// Electron scopes the single-instance lock to the userData directory and
|
||||
// creates that directory when the lock is acquired. The SDK bridge takes
|
||||
// the lock at creation, so userData must already point at the real
|
||||
// directory here — under the default productName-derived path, acquiring
|
||||
// the lock would create "T3 Code (Alpha)" and make the legacy-install
|
||||
// detection in resolveUserDataPath match on fresh installs.
|
||||
const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
|
||||
yield* electronApp.setPath("userData", userDataPath);
|
||||
|
||||
const bridge = yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
|
||||
catch: (cause) =>
|
||||
@@ -113,7 +125,12 @@ export const make = Effect.gen(function* () {
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
// The SDK bridge holds Electron's single-instance lock (acquired at
|
||||
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
|
||||
// forwarded to the running app. In a secondary instance the bridge has
|
||||
// already begun quitting the app; app.quit() is asynchronous, so stop
|
||||
// bootstrap here before whenReady can fire.
|
||||
if (!bridge.isPrimaryInstance) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
|
||||
export const DesktopConfig = Config.all({
|
||||
appDataDirectory: trimmedString("APPDATA"),
|
||||
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
|
||||
xdgDataHome: trimmedString("XDG_DATA_HOME"),
|
||||
t3Home: trimmedString("T3CODE_HOME"),
|
||||
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
|
||||
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
|
||||
|
||||
@@ -95,6 +95,8 @@ describe("DesktopEnvironment", () => {
|
||||
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.userDataDirName, "t3code");
|
||||
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha)");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -66,6 +66,8 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly linuxApplicationsDir: string;
|
||||
readonly appImagePath: Option.Option<string>;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
@@ -162,6 +164,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
);
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const linuxApplicationsDir = path.join(
|
||||
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
|
||||
"applications",
|
||||
);
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
@@ -205,6 +211,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
),
|
||||
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
linuxApplicationsDir,
|
||||
appImagePath: config.appImagePath,
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
|
||||
@@ -29,7 +29,6 @@ describe("DesktopLifecycle", () => {
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
|
||||
interface RecordedRegistration {
|
||||
readonly directories: string[];
|
||||
readonly files: Array<{ readonly path: string; readonly content: string }>;
|
||||
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
|
||||
}
|
||||
|
||||
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: "linux",
|
||||
isPackaged: true,
|
||||
isDevelopment: false,
|
||||
displayName: "T3 Code (Alpha)",
|
||||
linuxWmClass: "t3code",
|
||||
linuxApplicationsDir: "/home/alice/.local/share/applications",
|
||||
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
...overrides,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const mockProcess = (exitCode: number) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const makeHandlerLayer = (
|
||||
recorded: RecordedRegistration,
|
||||
input: {
|
||||
readonly environment?: Record<string, unknown>;
|
||||
readonly xdgMimeExitCode?: number;
|
||||
readonly writeError?: PlatformError.PlatformError;
|
||||
} = {},
|
||||
) =>
|
||||
DesktopLinuxUrlHandler.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
|
||||
FileSystem.layerNoop({
|
||||
makeDirectory: (path) =>
|
||||
Effect.sync(() => {
|
||||
recorded.directories.push(path);
|
||||
}),
|
||||
writeFileString: (path, content) =>
|
||||
input.writeError
|
||||
? Effect.fail(input.writeError)
|
||||
: Effect.sync(() => {
|
||||
recorded.files.push({ path, content });
|
||||
}),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
recorded.commands.push({
|
||||
command: childProcess.command,
|
||||
args: childProcess.args,
|
||||
});
|
||||
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runRegister = (
|
||||
recorded: RecordedRegistration,
|
||||
input: Parameters<typeof makeHandlerLayer>[1] = {},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
yield* handler.register;
|
||||
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
|
||||
|
||||
const emptyRecording = (): RecordedRegistration => ({
|
||||
directories: [],
|
||||
files: [],
|
||||
commands: [],
|
||||
});
|
||||
|
||||
describe("DesktopLinuxUrlHandler", () => {
|
||||
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
|
||||
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
|
||||
displayName: "T3 Code (Nightly)",
|
||||
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
|
||||
scheme: "t3code",
|
||||
});
|
||||
|
||||
assert.include(entry, "[Desktop Entry]");
|
||||
assert.include(entry, "Name=T3 Code (Nightly)");
|
||||
// Exec composes both escaping layers: a literal backslash becomes four
|
||||
// backslashes in the file, a quote three characters, a dollar sign two
|
||||
// backslashes plus the sign.
|
||||
assert.include(
|
||||
entry,
|
||||
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
|
||||
);
|
||||
assert.include(entry, "NoDisplay=true");
|
||||
assert.notInclude(entry, "StartupWMClass=");
|
||||
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
|
||||
});
|
||||
|
||||
it("carries structured context on registration errors", () => {
|
||||
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme: "t3code",
|
||||
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
cause: new Error("boom"),
|
||||
});
|
||||
assert.equal(
|
||||
writeError.message,
|
||||
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
|
||||
);
|
||||
assert.equal(
|
||||
writeError.desktopEntryPath,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
|
||||
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme: "t3code",
|
||||
exitCode: 4,
|
||||
});
|
||||
assert.equal(
|
||||
exitError.message,
|
||||
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded);
|
||||
|
||||
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
|
||||
assert.equal(recorded.files.length, 1);
|
||||
assert.equal(
|
||||
recorded.files[0]?.path,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
|
||||
);
|
||||
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
|
||||
assert.deepEqual(recorded.commands, [
|
||||
{
|
||||
command: "xdg-mime",
|
||||
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("falls back to the process executable outside an AppImage", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
|
||||
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does nothing on other platforms or unpackaged builds", () => {
|
||||
const nonLinux = emptyRecording();
|
||||
const unpackaged = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
|
||||
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
|
||||
|
||||
for (const recorded of [nonLinux, unpackaged]) {
|
||||
assert.deepEqual(recorded.directories, []);
|
||||
assert.deepEqual(recorded.files, []);
|
||||
assert.deepEqual(recorded.commands, []);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("never fails startup when registration cannot complete", () => {
|
||||
const xdgMimeFailed = emptyRecording();
|
||||
const writeFailed = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
|
||||
yield* runRegister(writeFailed, {
|
||||
writeError: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFileString",
|
||||
description: "read-only filesystem",
|
||||
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(xdgMimeFailed.files.length, 1);
|
||||
assert.deepEqual(writeFailed.commands, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
|
||||
// Linux ships as an AppImage, so the .desktop entry users end up with is
|
||||
// created by whatever integration tool they use (AppImageLauncher names it
|
||||
// appimagekit_<hash>-….desktop) and its filename is not under our control.
|
||||
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
|
||||
// setDesktopName, which cannot match those files — so the browser keeps
|
||||
// prompting "Choose an application" for every OAuth callback. Instead, write
|
||||
// our own handler entry pointing at the current AppImage and claim the
|
||||
// scheme default via xdg-mime, exactly what the file manager's "set as
|
||||
// default" checkbox would record in mimeapps.list.
|
||||
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
|
||||
|
||||
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
|
||||
|
||||
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
|
||||
"DesktopLinuxUrlHandlerRegistrationError",
|
||||
{
|
||||
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
|
||||
scheme: Schema.String,
|
||||
desktopEntryPath: Schema.optionalKey(Schema.String),
|
||||
exitCode: Schema.optionalKey(Schema.Number),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
|
||||
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
|
||||
|
||||
const escapeDesktopEntryString = (value: string): string =>
|
||||
value
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("\n", "\\n")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\t", "\\t");
|
||||
|
||||
// Exec values are unescaped twice by implementations: first the general
|
||||
// string-value rules, then the Exec quoting rules — so writing composes the
|
||||
// layers in reverse. The argument is double-quoted with reserved characters
|
||||
// backslash-escaped and literal percent signs doubled (field codes), and the
|
||||
// general string escaping is applied on top: a literal backslash ends up as
|
||||
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
|
||||
export function escapeDesktopEntryExecArgument(value: string): string {
|
||||
const quoted = value
|
||||
.replaceAll("\\", () => "\\\\")
|
||||
.replaceAll("`", () => "\\`")
|
||||
.replaceAll("$", () => "\\$")
|
||||
.replaceAll('"', () => '\\"')
|
||||
.replaceAll("%", () => "%%");
|
||||
return escapeDesktopEntryString(`"${quoted}"`);
|
||||
}
|
||||
|
||||
// The AppImage integration entry owns the window identity and icon. This
|
||||
// hidden URL-only entry must not compete with it for StartupWMClass matching.
|
||||
export function renderUrlHandlerDesktopEntry(input: {
|
||||
readonly displayName: string;
|
||||
readonly execTarget: string;
|
||||
readonly scheme: string;
|
||||
}): string {
|
||||
return [
|
||||
"[Desktop Entry]",
|
||||
"Type=Application",
|
||||
`Name=${escapeDesktopEntryString(input.displayName)}`,
|
||||
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
|
||||
"Terminal=false",
|
||||
"NoDisplay=true",
|
||||
"StartupNotify=false",
|
||||
`MimeType=x-scheme-handler/${input.scheme};`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export class DesktopLinuxUrlHandler extends Context.Service<
|
||||
DesktopLinuxUrlHandler,
|
||||
{
|
||||
readonly register: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
|
||||
const desktopEntryPath = environment.path.join(
|
||||
environment.linuxApplicationsDir,
|
||||
URL_HANDLER_DESKTOP_ENTRY_NAME,
|
||||
);
|
||||
|
||||
const writeDesktopEntry = Effect.gen(function* () {
|
||||
// Inside the mounted AppImage, process.execPath points at a transient
|
||||
// /tmp/.mount_* path — the handler must launch the AppImage itself.
|
||||
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
|
||||
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
desktopEntryPath,
|
||||
renderUrlHandlerDesktopEntry({
|
||||
displayName: environment.displayName,
|
||||
execTarget,
|
||||
scheme,
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme,
|
||||
desktopEntryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const setDefaultHandler = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"xdg-mime",
|
||||
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return yield* new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
exitCode: Number(exitCode),
|
||||
});
|
||||
}
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isRegistrationError(error)
|
||||
? error
|
||||
: new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const register = Effect.gen(function* () {
|
||||
if (environment.platform !== "linux" || !environment.isPackaged) {
|
||||
return;
|
||||
}
|
||||
yield* writeDesktopEntry;
|
||||
yield* setDefaultHandler;
|
||||
yield* logInfo("registered URL scheme handler", { scheme });
|
||||
}).pipe(
|
||||
// Registration is best-effort: a missing xdg-mime or read-only home must
|
||||
// never block startup — the OS chooser remains as fallback.
|
||||
Effect.catch((error) =>
|
||||
logWarning("URL scheme handler registration failed", {
|
||||
scheme,
|
||||
step: error.step,
|
||||
message: error.message,
|
||||
...(error.desktopEntryPath === undefined
|
||||
? {}
|
||||
: { desktopEntryPath: error.desktopEntryPath }),
|
||||
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.linuxUrlHandler.register"),
|
||||
);
|
||||
|
||||
return DesktopLinuxUrlHandler.of({ register });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
|
||||
@@ -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
|
||||
|
||||
@@ -14,7 +14,6 @@ const {
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
requestSingleInstanceLockMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
@@ -35,7 +34,6 @@ const {
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
requestSingleInstanceLockMock: vi.fn(() => true),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
@@ -67,7 +65,6 @@ vi.mock("electron", () => ({
|
||||
quit: quitMock,
|
||||
relaunch: relaunchMock,
|
||||
removeListener: removeListenerMock,
|
||||
requestSingleInstanceLock: requestSingleInstanceLockMock,
|
||||
runningUnderARM64Translation: false,
|
||||
setAboutPanelOptions: setAboutPanelOptionsMock,
|
||||
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
|
||||
|
||||
@@ -56,7 +56,6 @@ export class ElectronApp extends Context.Service<
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
@@ -153,7 +152,6 @@ export const make = ElectronApp.of({
|
||||
Effect.sync(() => {
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
@@ -212,6 +212,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
|
||||
@@ -71,6 +71,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
|
||||
@@ -43,6 +43,7 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
@@ -181,6 +182,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopLinuxUrlHandler.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
|
||||
@@ -34,7 +34,6 @@ function makeElectronAppLayer(
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
|
||||
@@ -39,7 +39,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
|
||||
@@ -218,7 +218,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 class="harness">
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "0.1.0",
|
||||
version: "1.0.1",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
@@ -181,6 +181,9 @@ const config: ExpoConfig = {
|
||||
ios: {
|
||||
icon: variant.assets.iosIcon,
|
||||
supportsTablet: true,
|
||||
// Multitasking-capable iPad apps cannot rotate programmatically, so the
|
||||
// showcase capture build requires full screen (see infoPlist below).
|
||||
requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1",
|
||||
bundleIdentifier: 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,
|
||||
@@ -197,6 +200,21 @@ const config: ExpoConfig = {
|
||||
NSLocalNetworkUsageDescription:
|
||||
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
|
||||
ITSAppUsesNonExemptEncryption: false,
|
||||
// The App Store screenshot harness rotates the iPad interface from
|
||||
// inside the app (CI denies osascript the Accessibility access that
|
||||
// Simulator menu scripting needs), and iPadOS ignores programmatic
|
||||
// orientation requests for multitasking-capable apps — so the capture
|
||||
// build opts out of multitasking and declares landscape support.
|
||||
...(process.env.T3_SHOWCASE_CAPTURE_BUILD === "1"
|
||||
? {
|
||||
"UISupportedInterfaceOrientations~ipad": [
|
||||
"UIInterfaceOrientationPortrait",
|
||||
"UIInterfaceOrientationPortraitUpsideDown",
|
||||
"UIInterfaceOrientationLandscapeLeft",
|
||||
"UIInterfaceOrientationLandscapeRight",
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
android: {
|
||||
@@ -275,10 +293,12 @@ const config: ExpoConfig = {
|
||||
"expo-camera",
|
||||
{
|
||||
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
|
||||
microphonePermission: false,
|
||||
barcodeScannerEnabled: true,
|
||||
recordAudioAndroid: false,
|
||||
},
|
||||
],
|
||||
["expo-image-picker", { photosPermission: false, microphonePermission: false }],
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import ExpoModulesCore
|
||||
import Security
|
||||
import UIKit
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
@@ -32,6 +33,50 @@ public final class T3NativeControlsModule: Module {
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("getShowcaseOrientation") { () -> String? in
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcaseOrientation"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
// Rotates the interface without Simulator menu UI scripting, which CI
|
||||
// runners cannot perform (osascript is denied Accessibility access there).
|
||||
AsyncFunction("applyShowcaseOrientation") { (orientation: String) in
|
||||
guard #available(iOS 16.0, *) else { return }
|
||||
let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
|
||||
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
|
||||
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
|
||||
NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
|
||||
}
|
||||
for window in windowScene.windows {
|
||||
window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
|
||||
}
|
||||
}
|
||||
}.runOnQueue(.main)
|
||||
|
||||
// The geometry request above can fail transiently (for example before the
|
||||
// scene is foreground-active), so callers poll this until it settles.
|
||||
// Screen bounds — not the scene's interface orientation — decide the
|
||||
// answer because they match the captured framebuffer: with iPadOS
|
||||
// windowing active, a floating landscape window still reports a portrait
|
||||
// screen, and screenshots would come out portrait.
|
||||
AsyncFunction("getInterfaceOrientation") { () -> String in
|
||||
guard
|
||||
let windowScene = UIApplication.shared.connectedScenes
|
||||
.compactMap({ $0 as? UIWindowScene })
|
||||
.first
|
||||
else {
|
||||
return "unknown"
|
||||
}
|
||||
let bounds = windowScene.screen.coordinateSpace.bounds
|
||||
return bounds.width > bounds.height ? "landscape" : "portrait"
|
||||
}.runOnQueue(.main)
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
|
||||
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
|
||||
|
||||
@@ -40,7 +40,7 @@ fails, run `xcodebuild -downloadComponent MetalToolchain`.
|
||||
## Rebuilding libghostty-vt for Android
|
||||
|
||||
The checked-in Android shared libraries and headers are pinned to the revision recorded in
|
||||
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
|
||||
`native/libghostty-vt/VERSION` at the repository root. Set `ANDROID_NDK_HOME` and run:
|
||||
|
||||
```bash
|
||||
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
|
||||
|
||||
@@ -18,13 +18,14 @@ Ghostty's MIT license applies to the vendored framework. Keep this notice in syn
|
||||
## Ghostty / libghostty-vt
|
||||
|
||||
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
|
||||
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
|
||||
|
||||
- Upstream project: https://github.com/ghostty-org/ghostty
|
||||
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
|
||||
- License: MIT
|
||||
|
||||
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
|
||||
updating `Vendor/libghostty-vt`.
|
||||
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
|
||||
artifacts in sync when updating the repository-root `native/libghostty-vt`.
|
||||
|
||||
## MesloLGS NF (Android terminal font)
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ add_library(t3terminal SHARED t3_terminal_jni.cpp)
|
||||
|
||||
target_include_directories(
|
||||
t3terminal
|
||||
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include"
|
||||
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../../../native/libghostty-vt/include"
|
||||
)
|
||||
|
||||
target_link_options(
|
||||
|
||||
@@ -4,7 +4,7 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
VENDOR_DIR="${MODULE_DIR}/Vendor/libghostty-vt"
|
||||
VENDOR_DIR="${MODULE_DIR}/../../../../native/libghostty-vt"
|
||||
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
|
||||
|
||||
GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
"start:preview": "APP_VARIANT=preview expo start",
|
||||
"start:prod": "APP_VARIANT=production expo start",
|
||||
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
|
||||
"showcase": "APP_VARIANT=production EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code --clear",
|
||||
"screenshots": "node ../../scripts/mobile-showcase.ts",
|
||||
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
|
||||
|
||||
@@ -15,6 +15,7 @@ import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "re
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
@@ -392,7 +393,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerBackVisible: false,
|
||||
title: "Threads",
|
||||
...getCompactBrandHeaderOptions(),
|
||||
},
|
||||
}),
|
||||
Thread: createNativeStackScreen({
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IconChevronUp,
|
||||
IconCircleCheck,
|
||||
IconCircleXFilled,
|
||||
IconClock,
|
||||
IconCopy,
|
||||
IconDeviceDesktop,
|
||||
IconDots,
|
||||
@@ -96,6 +97,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
camera: IconCamera,
|
||||
checkmark: IconCheck,
|
||||
"checkmark.circle": IconCircleCheck,
|
||||
clock: IconClock,
|
||||
"chevron.down": IconChevronDown,
|
||||
"chevron.left": IconChevronLeft,
|
||||
"chevron.left.forwardslash.chevron.right": IconCode,
|
||||
|
||||
@@ -3,14 +3,9 @@ import { Image } from "expo-image";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3_CODE_BRAND_MARK_SOURCE } from "./brandAssets";
|
||||
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
const BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
const DEFAULT_STAGE_LABEL =
|
||||
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
|
||||
|
||||
@@ -22,7 +17,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
return (
|
||||
<View className="flex-row items-center gap-3">
|
||||
<Image
|
||||
source={BRAND_MARK_SOURCE}
|
||||
source={T3_CODE_BRAND_MARK_SOURCE}
|
||||
accessibilityIgnoresInvertColors
|
||||
style={{
|
||||
width: iconSize,
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import Constants from "expo-constants";
|
||||
import type {
|
||||
NativeStackHeaderItem,
|
||||
NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { Platform, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3Wordmark } from "./T3Wordmark";
|
||||
import { IPAD_HOME_TITLE_OFFSET } from "../lib/layoutMetrics";
|
||||
import { resolveMobileStageLabel } from "../lib/mobileBranding";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
|
||||
|
||||
// Native leading items inherit different UIKit margins than title views.
|
||||
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
|
||||
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
export function CompactBrandTitle(
|
||||
props: {
|
||||
readonly nativeLeadingItem?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
const titleOffset =
|
||||
Platform.OS !== "ios"
|
||||
? 0
|
||||
: props.nativeLeadingItem
|
||||
? Platform.isPad
|
||||
? IPAD_NATIVE_LEADING_TITLE_OFFSET
|
||||
: IOS_NATIVE_LEADING_TITLE_OFFSET
|
||||
: Platform.isPad
|
||||
? IPAD_HOME_TITLE_OFFSET
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<View
|
||||
aria-level={1}
|
||||
accessibilityLabel="T3 Code, Threads"
|
||||
accessible
|
||||
role="heading"
|
||||
style={{
|
||||
alignItems: "center",
|
||||
flexDirection: "row",
|
||||
gap: 6,
|
||||
marginLeft: titleOffset,
|
||||
}}
|
||||
>
|
||||
<T3Wordmark color={iconColor} height={15} />
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Medium",
|
||||
fontSize: 21,
|
||||
letterSpacing: -0.5,
|
||||
}}
|
||||
>
|
||||
Code
|
||||
</Text>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Bold",
|
||||
fontSize: 9,
|
||||
letterSpacing: 0.9,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
{stageLabel}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function renderCompactBrandTitle() {
|
||||
return <CompactBrandTitle />;
|
||||
}
|
||||
|
||||
export function renderCompactBrandHeaderItems(): NativeStackHeaderItem[] {
|
||||
return [
|
||||
{
|
||||
element: <CompactBrandTitle nativeLeadingItem />,
|
||||
hidesSharedBackground: true,
|
||||
type: "custom",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function getCompactBrandHeaderOptions(
|
||||
fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"],
|
||||
): NativeStackNavigationOptions {
|
||||
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
|
||||
return {
|
||||
headerTitle: "Threads",
|
||||
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
|
||||
title: "Threads",
|
||||
unstable_headerLeftItems: renderCompactBrandHeaderItems,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
headerTitleStyle: fallbackTitleStyle,
|
||||
title: "Threads",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import Constants from "expo-constants";
|
||||
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
|
||||
export const T3_CODE_BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
@@ -1,5 +1,15 @@
|
||||
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
|
||||
import { ORCHESTRATION_CACHE_SCHEMA_VERSION } from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadDetailSnapshot,
|
||||
type VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
@@ -7,6 +17,121 @@ import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-data
|
||||
import { make } from "./environment-cache-store";
|
||||
|
||||
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
|
||||
const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
|
||||
const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 3,
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-07-29T12:00:00.000Z",
|
||||
updatedAt: "2026-07-29T12:00:00.000Z",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
providerInstanceId: PROVIDER_INSTANCE_ID,
|
||||
modelSelection: {
|
||||
instanceId: PROVIDER_INSTANCE_ID,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
rootThreadId: THREAD_ID,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
latestUserMessageAt: NOW,
|
||||
hasActionableProposedPlan: false,
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: NOW,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
archivedThreads: [],
|
||||
};
|
||||
const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
|
||||
snapshotSequence: 4,
|
||||
projection: {
|
||||
thread: {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
providerInstanceId: PROVIDER_INSTANCE_ID,
|
||||
modelSelection: {
|
||||
instanceId: PROVIDER_INSTANCE_ID,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
rootThreadId: THREAD_ID,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: NOW,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
subagentActivations: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: NOW,
|
||||
},
|
||||
};
|
||||
const REFS: VcsListRefsResult = {
|
||||
refs: [
|
||||
{
|
||||
@@ -28,13 +153,16 @@ function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey:
|
||||
|
||||
function makeDatabase() {
|
||||
const values = new Map<string, string>();
|
||||
const schemaVersions = new Map<string, number>();
|
||||
const removed: Array<string> = [];
|
||||
const database = MobileDatabase.of({
|
||||
loadCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
|
||||
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
|
||||
saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
|
||||
Effect.sync(() => {
|
||||
values.set(cacheId(environmentId, kind, cacheKey), payload);
|
||||
const id = cacheId(environmentId, kind, cacheKey);
|
||||
values.set(id, payload);
|
||||
schemaVersions.set(id, schemaVersion);
|
||||
}),
|
||||
removeCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.sync(() => {
|
||||
@@ -59,10 +187,37 @@ function makeDatabase() {
|
||||
loadPreferencesJson: Effect.succeed(Option.none()),
|
||||
savePreferencesJson: () => Effect.void,
|
||||
});
|
||||
return { database, removed, values };
|
||||
return { database, removed, schemaVersions, values };
|
||||
}
|
||||
|
||||
describe("mobile SQLite environment cache store", () => {
|
||||
it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
|
||||
|
||||
yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
|
||||
yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
|
||||
|
||||
const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
|
||||
const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
|
||||
|
||||
expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
|
||||
expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
);
|
||||
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("round-trips schema-validated VCS refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import {
|
||||
ConnectionPersistenceError,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ServerConfig,
|
||||
VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -16,22 +13,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: Schema.String,
|
||||
threadId: Schema.String,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
});
|
||||
const StoredServerConfig = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
|
||||
environmentId: Schema.String,
|
||||
@@ -45,13 +29,17 @@ const StoredVcsRefs = Schema.Struct({
|
||||
});
|
||||
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredShellSnapshot),
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredThreadSnapshot),
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
|
||||
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredServerConfig),
|
||||
);
|
||||
@@ -127,12 +115,12 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
),
|
||||
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
|
||||
const payload = yield* encodeStoredShellSnapshot({
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "shell", "snapshot", ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
|
||||
}),
|
||||
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
|
||||
@@ -150,15 +138,15 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
}),
|
||||
),
|
||||
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
|
||||
const threadId = snapshot.thread.id;
|
||||
const threadId = snapshot.projection.thread.id;
|
||||
const payload = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "thread", threadId, ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
|
||||
}),
|
||||
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
|
||||
|
||||
@@ -17,6 +17,7 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as CatalogStore from "./catalog-store";
|
||||
|
||||
function targetPersistenceError(
|
||||
|
||||
@@ -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,42 +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,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
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",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,11 +1,32 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildPairingUrl,
|
||||
extractPairingUrlFromQrPayload,
|
||||
PairingQrPayloadEmptyError,
|
||||
parsePairingUrl,
|
||||
} from "./pairing";
|
||||
|
||||
describe("buildPairingUrl", () => {
|
||||
it("uses HTTP for a schemeless IP address", () => {
|
||||
expect(buildPairingUrl("192.168.1.100:3773", "pairing-token")).toBe(
|
||||
"http://192.168.1.100:3773/#token=pairing-token",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps HTTPS as the default for a schemeless hostname", () => {
|
||||
expect(buildPairingUrl("remote.example.com", "pairing-token")).toBe(
|
||||
"https://remote.example.com/#token=pairing-token",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves an explicit scheme for an IP address", () => {
|
||||
expect(buildPairingUrl("https://192.168.1.100:3773", "pairing-token")).toBe(
|
||||
"https://192.168.1.100:3773/#token=pairing-token",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractPairingUrlFromQrPayload", () => {
|
||||
it("trims raw pairing urls from qr payloads", () => {
|
||||
expect(
|
||||
|
||||
@@ -3,6 +3,21 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
|
||||
|
||||
function isIpLiteral(host: string): boolean {
|
||||
try {
|
||||
const hostname = new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, "");
|
||||
if (hostname.includes(":")) return true;
|
||||
|
||||
const octets = hostname.split(".");
|
||||
return (
|
||||
octets.length === 4 &&
|
||||
octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export class PairingQrPayloadEmptyError extends Schema.TaggedErrorClass<PairingQrPayloadEmptyError>()(
|
||||
"PairingQrPayloadEmptyError",
|
||||
{},
|
||||
@@ -19,7 +34,7 @@ export function buildPairingUrl(host: string, code: string): string {
|
||||
if (!c) return h;
|
||||
|
||||
try {
|
||||
const url = new URL(h.includes("://") ? h : `https://${h}`);
|
||||
const url = new URL(h.includes("://") ? h : `${isIpLiteral(h) ? "http" : "https"}://${h}`);
|
||||
url.hash = new URLSearchParams([["token", c]]).toString();
|
||||
return url.toString();
|
||||
} catch {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import Constants from "expo-constants";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
@@ -9,6 +10,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
|
||||
import { resolveMobileStageLabel } from "../../lib/mobileBranding";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
@@ -64,6 +67,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
@@ -195,8 +199,9 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View
|
||||
className="border-b border-header-border bg-header px-4 pb-3"
|
||||
className="border-b border-header-border bg-header pb-3"
|
||||
style={{
|
||||
paddingHorizontal: HOME_HORIZONTAL_INSET,
|
||||
paddingTop: Math.max(insets.top, 12),
|
||||
}}
|
||||
>
|
||||
@@ -210,7 +215,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
</RNText>
|
||||
<View className="rounded-full bg-subtle px-2 py-0.75">
|
||||
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
|
||||
Alpha
|
||||
{stageLabel}
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
@@ -35,8 +36,14 @@ export function HomeRouteScreen() {
|
||||
void checkForAppUpdateOnLaunch();
|
||||
}, []);
|
||||
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(() => {
|
||||
@@ -93,7 +100,9 @@ export function HomeRouteScreen() {
|
||||
if (layout.usesSplitView) {
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ title: "", headerTitle: "" }} />
|
||||
<NativeStackScreenOptions
|
||||
options={{ title: "", headerTitle: "", unstable_headerLeftItems: () => [] }}
|
||||
/>
|
||||
<WorkspaceSidebarToolbar
|
||||
afterSidebarButton={
|
||||
<NativeHeaderToolbar.Button
|
||||
@@ -115,8 +124,8 @@ export function HomeRouteScreen() {
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title in case the split branch blanked it. */}
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
{/* Restore the compact title after the split branch blanks the detail header. */}
|
||||
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
@@ -143,6 +152,8 @@ export function HomeRouteScreen() {
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
|
||||
@@ -41,7 +41,12 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
ThreadListV2PendingRow,
|
||||
ThreadListV2Row,
|
||||
ThreadListV2SettledShelfHeader,
|
||||
ThreadListV2SnoozedShelfHeader,
|
||||
} from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
@@ -100,6 +105,11 @@ interface HomeScreenProps {
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** Resolves true iff the settle was dispatched and succeeded. */
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSnoozeThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
snoozedUntil: string,
|
||||
) => Promise<boolean>;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
@@ -175,7 +185,7 @@ function deriveEmptyState(props: {
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
detail: "Create a task to start a new coding runtime in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
@@ -494,6 +504,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
const handleSnoozeThread = useCallback(
|
||||
(thread: EnvironmentThreadShell, snoozedUntil: string) => {
|
||||
void props.onSnoozeThread(thread, snoozedUntil);
|
||||
},
|
||||
[props.onSnoozeThread],
|
||||
);
|
||||
const handleUnsnoozeThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onUnsnoozeThread(thread);
|
||||
},
|
||||
[props.onUnsnoozeThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -511,6 +533,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
// now is quantized to the minute and ticks so the inactivity auto-settle
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
@@ -551,7 +577,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return {
|
||||
items: [],
|
||||
hiddenSettledCount: 0,
|
||||
snoozedCount: 0,
|
||||
snoozedShelfHeaderIndex: null,
|
||||
settledCount: 0,
|
||||
settledShelfHeaderIndex: null,
|
||||
nextSnoozeWakeAt: null,
|
||||
};
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -566,11 +600,16 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
selectedThreadKey: null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
@@ -620,8 +659,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
buildThreadListV2ListItems({
|
||||
items: threadListV2Layout.items,
|
||||
pendingTasks: v2PendingTasks,
|
||||
snoozedCount: threadListV2Layout.snoozedCount,
|
||||
snoozedShelfExpanded,
|
||||
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
|
||||
settledCount: threadListV2Layout.settledCount,
|
||||
settledShelfExpanded,
|
||||
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
|
||||
snoozeLabelNow: `${nowMinute}:00.000Z`,
|
||||
}),
|
||||
[threadListV2Layout.items, v2PendingTasks],
|
||||
[settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks],
|
||||
);
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
@@ -648,12 +694,32 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.type === "v2-snoozed-shelf") {
|
||||
return (
|
||||
<ThreadListV2SnoozedShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSnoozedShelf}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.type === "v2-settled-shelf") {
|
||||
return (
|
||||
<ThreadListV2SettledShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSettledShelf}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const thread = item.item.thread;
|
||||
return (
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
snoozed={item.item.snoozed}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
}
|
||||
@@ -666,7 +732,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
@@ -686,6 +752,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={handleSnoozeThread}
|
||||
onUnsnoozeThread={handleUnsnoozeThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
@@ -700,6 +769,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnsnoozeThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
@@ -712,9 +783,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadSearchMatchByKey,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
props.searchQuery,
|
||||
nowMinute,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
|
||||
@@ -730,6 +805,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
searchQuery: props.searchQuery,
|
||||
snoozePresetMinute: nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
}),
|
||||
[
|
||||
@@ -738,6 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
@@ -948,36 +1025,16 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
detail="Choose another environment or create a new task."
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding runtime." />
|
||||
)
|
||||
) : null;
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
// is empty. Snoozed threads need no special empty state: their shelf header
|
||||
// is a list row even while collapsed.
|
||||
const v2ListEmpty =
|
||||
hasSearchQuery && threadSearch.isPending && v2SnoozedCount === 0 ? null : hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
@@ -998,7 +1055,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
extraData={v2ExtraData}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
import {
|
||||
presentThreadShell,
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
@@ -32,29 +34,41 @@ function makeProject(id: string, title: string): EnvironmentProject {
|
||||
};
|
||||
}
|
||||
|
||||
const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z");
|
||||
|
||||
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
id: ThreadId.make(id),
|
||||
const threadId = ThreadId.make(id);
|
||||
return presentThreadShell(environmentId, {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: `Thread ${id}`,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
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: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: threadTimestamp,
|
||||
updatedAt: threadTimestamp,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
}
|
||||
|
||||
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -30,25 +31,21 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
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: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import {
|
||||
createContext,
|
||||
@@ -47,13 +49,67 @@ export const THREAD_SWIPE_SPRING = {
|
||||
stiffness: 330,
|
||||
};
|
||||
|
||||
interface ThreadSwipePrimaryAction {
|
||||
interface ThreadSwipeAction {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly menu?: {
|
||||
readonly actions: MenuAction[];
|
||||
readonly onPressAction: NonNullable<ComponentProps<typeof ControlPillMenu>["onPressAction"]>;
|
||||
readonly title?: string;
|
||||
};
|
||||
readonly onPress: () => void;
|
||||
}
|
||||
|
||||
interface ThreadSwipeSecondaryAction extends ThreadSwipeAction {
|
||||
readonly backgroundColor: string;
|
||||
}
|
||||
|
||||
function swipeActionsWidth(hasSecondaryAction: boolean) {
|
||||
return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH;
|
||||
}
|
||||
|
||||
/** `undefined` keeps the v1 Delete default; `null` means one action only. */
|
||||
function resolveSecondaryAction(input: {
|
||||
readonly close: () => void;
|
||||
readonly onDelete: () => void;
|
||||
readonly secondaryAction: ThreadSwipeAction | null | undefined;
|
||||
readonly threadTitle: string;
|
||||
}): ThreadSwipeSecondaryAction | null {
|
||||
if (input.secondaryAction === null) return null;
|
||||
if (input.secondaryAction === undefined) {
|
||||
return {
|
||||
accessibilityLabel: `Delete ${input.threadTitle}`,
|
||||
backgroundColor: "#ff2d55",
|
||||
icon: "trash",
|
||||
label: "Delete",
|
||||
onPress: () => {
|
||||
input.close();
|
||||
input.onDelete();
|
||||
},
|
||||
};
|
||||
}
|
||||
const action = input.secondaryAction;
|
||||
return {
|
||||
...action,
|
||||
backgroundColor: "#5856d6",
|
||||
menu:
|
||||
action.menu === undefined
|
||||
? undefined
|
||||
: {
|
||||
...action.menu,
|
||||
onPressAction: (event) => {
|
||||
input.close();
|
||||
action.menu?.onPressAction(event);
|
||||
},
|
||||
},
|
||||
onPress: () => {
|
||||
input.close();
|
||||
action.onPress();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers the scroll gate to swipeables via context so that flipping it does
|
||||
* NOT re-render whole rows: putting the flag in list extraData/renderItem deps
|
||||
@@ -173,17 +229,22 @@ export function ThreadSwipeable(props: {
|
||||
readonly enabled?: boolean;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
/**
|
||||
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
|
||||
* button stretches) or "primary" — the advertised primary action fires and
|
||||
* its button stretches instead. A full swipe must always match the action
|
||||
* the stretching button advertises.
|
||||
* What a full swipe commits. Omitted keeps the v1 Delete behavior only when
|
||||
* the built-in Delete secondary action is in use; custom or absent
|
||||
* secondary actions default to the advertised primary action.
|
||||
*/
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly primaryAction: ThreadSwipeAction;
|
||||
/**
|
||||
* Omitted keeps the v1 destructive Delete action. Explicit null opts out of
|
||||
* a secondary action entirely so a gated Snooze can never fall back to an
|
||||
* unadvertised Delete.
|
||||
*/
|
||||
readonly secondaryAction?: ThreadSwipeAction | null;
|
||||
/**
|
||||
* Identity of the content being wrapped. When a recycled list reuses this
|
||||
* component for a different item, the swipeable snaps back to closed so an
|
||||
@@ -197,7 +258,11 @@ export function ThreadSwipeable(props: {
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
|
||||
const hasSecondaryAction = props.secondaryAction !== null;
|
||||
const actionsWidth = swipeActionsWidth(hasSecondaryAction);
|
||||
const fullSwipeThreshold = Math.max(actionsWidth + 44, props.fullSwipeWidth * 0.58);
|
||||
const fullSwipeAction =
|
||||
props.fullSwipeAction ?? (props.secondaryAction === undefined ? "delete" : "primary");
|
||||
const close = useCallback(() => swipeableRef.current?.close(), []);
|
||||
const gateEnabled = use(SwipeableScrollGateContext);
|
||||
const resetKey = props.resetKey;
|
||||
@@ -251,7 +316,7 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
if (fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
@@ -264,9 +329,8 @@ export function ThreadSwipeable(props: {
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
compact={props.compactActions === true}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeAction={fullSwipeAction}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
...props.primaryAction,
|
||||
@@ -275,12 +339,16 @@ export function ThreadSwipeable(props: {
|
||||
props.primaryAction.onPress();
|
||||
},
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.threadTitle}
|
||||
secondaryAction={resolveSecondaryAction({
|
||||
close: () => methods.close(),
|
||||
onDelete: props.onDelete,
|
||||
secondaryAction: props.secondaryAction,
|
||||
threadTitle: props.threadTitle,
|
||||
})}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
rightThreshold={actionsWidth * 0.42}
|
||||
simultaneousWithExternalGesture={props.simultaneousWithExternalGesture}
|
||||
>
|
||||
{props.children(close)}
|
||||
@@ -290,12 +358,14 @@ export function ThreadSwipeable(props: {
|
||||
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly actionsWidth: number;
|
||||
readonly backgroundColor: string;
|
||||
readonly compact: boolean;
|
||||
readonly entryRange: readonly [number, number];
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly menu?: ThreadSwipeAction["menu"];
|
||||
readonly onPress: () => void;
|
||||
readonly stretchesOnFullSwipe: boolean;
|
||||
readonly translation: SharedValue<number>;
|
||||
@@ -305,10 +375,10 @@ function SwipeActionButton(props: {
|
||||
const actionStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
const stretch = Math.max(reveal - props.actionsWidth, 0);
|
||||
const fullSwipeProgress = interpolate(
|
||||
reveal,
|
||||
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
|
||||
[props.actionsWidth, props.fullSwipeThreshold + 20],
|
||||
[0, 1],
|
||||
Extrapolation.CLAMP,
|
||||
);
|
||||
@@ -327,9 +397,7 @@ function SwipeActionButton(props: {
|
||||
});
|
||||
const circleStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch }],
|
||||
@@ -338,9 +406,7 @@ function SwipeActionButton(props: {
|
||||
});
|
||||
const iconStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
|
||||
const armedProgress = interpolate(
|
||||
reveal,
|
||||
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
|
||||
@@ -358,7 +424,7 @@ function SwipeActionButton(props: {
|
||||
}
|
||||
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
const stretch = Math.max(reveal - props.actionsWidth, 0);
|
||||
return {
|
||||
opacity: interpolate(
|
||||
reveal,
|
||||
@@ -370,6 +436,63 @@ function SwipeActionButton(props: {
|
||||
};
|
||||
});
|
||||
|
||||
const button = (
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
accessibilityRole="button"
|
||||
onPress={props.menu === undefined ? props.onPress : undefined}
|
||||
style={({ pressed }) => ({
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
justifyContent: "center",
|
||||
opacity: pressed ? 0.72 : 1,
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: circleSize, width: circleSize }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: circleSize,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
},
|
||||
circleStyle,
|
||||
]}
|
||||
/>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: circleSize,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: circleSize,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View
|
||||
style={[
|
||||
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
|
||||
labelStyle,
|
||||
]}
|
||||
>
|
||||
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
style={[
|
||||
@@ -383,60 +506,18 @@ function SwipeActionButton(props: {
|
||||
actionStyle,
|
||||
]}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
style={({ pressed }) => ({
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
justifyContent: "center",
|
||||
opacity: pressed ? 0.72 : 1,
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: circleSize, width: circleSize }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: circleSize,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
},
|
||||
circleStyle,
|
||||
]}
|
||||
/>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: circleSize,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: circleSize,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View
|
||||
style={[
|
||||
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
|
||||
labelStyle,
|
||||
]}
|
||||
{props.menu === undefined ? (
|
||||
button
|
||||
) : (
|
||||
<ControlPillMenu
|
||||
actions={props.menu.actions}
|
||||
onPressAction={props.menu.onPressAction}
|
||||
title={props.menu.title}
|
||||
style={{ height: "100%", width: "100%" }}
|
||||
>
|
||||
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
{button}
|
||||
</ControlPillMenu>
|
||||
)}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@@ -446,14 +527,14 @@ export function ThreadSwipeActions(props: {
|
||||
readonly compact: boolean;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly swipeableMethods: SwipeableMethods;
|
||||
readonly threadTitle: string;
|
||||
readonly primaryAction: ThreadSwipeAction;
|
||||
readonly secondaryAction: ThreadSwipeSecondaryAction | null;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
const secondaryAction = props.secondaryAction;
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary" || secondaryAction === null;
|
||||
const actionsWidth = swipeActionsWidth(secondaryAction !== null);
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -470,14 +551,19 @@ export function ThreadSwipeActions(props: {
|
||||
backgroundColor: props.backgroundColor,
|
||||
flexDirection: "row",
|
||||
height: "100%",
|
||||
width: THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
width: actionsWidth,
|
||||
}}
|
||||
>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={props.primaryAction.accessibilityLabel}
|
||||
actionsWidth={actionsWidth}
|
||||
backgroundColor="#007aff"
|
||||
compact={props.compact}
|
||||
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
|
||||
entryRange={
|
||||
secondaryAction === null
|
||||
? [8, ACTION_ITEM_WIDTH * 0.72]
|
||||
: [ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]
|
||||
}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
@@ -485,21 +571,22 @@ export function ThreadSwipeActions(props: {
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={`Delete ${props.threadTitle}`}
|
||||
backgroundColor="#ff2d55"
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon="trash"
|
||||
label="Delete"
|
||||
onPress={() => {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
{secondaryAction === null ? null : (
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={secondaryAction.accessibilityLabel}
|
||||
actionsWidth={actionsWidth}
|
||||
backgroundColor={secondaryAction.backgroundColor}
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={secondaryAction.icon}
|
||||
label={secondaryAction.label}
|
||||
menu={secondaryAction.menu}
|
||||
onPress={secondaryAction.onPress}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { ProviderInstanceId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
|
||||
import { threadCanArchive } from "./threadArchive";
|
||||
|
||||
function runtime(
|
||||
status: ThreadRuntimeSummary["status"],
|
||||
activeRunId: ThreadRuntimeSummary["activeRunId"],
|
||||
): ThreadRuntimeSummary {
|
||||
return {
|
||||
status,
|
||||
activeRunId,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
providerName: "codex",
|
||||
lastError: null,
|
||||
updatedAt: "2026-07-28T10:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("threadCanArchive", () => {
|
||||
it("blocks provider-active work", () => {
|
||||
const activeRunId = RunId.make("run-live");
|
||||
expect(threadCanArchive(runtime("preparing", activeRunId))).toBe(false);
|
||||
expect(threadCanArchive(runtime("starting", activeRunId))).toBe(false);
|
||||
expect(threadCanArchive(runtime("running", activeRunId))).toBe(false);
|
||||
});
|
||||
|
||||
it("only allows queued work when no provider run remains active", () => {
|
||||
const activeRunId = RunId.make("run-live");
|
||||
expect(threadCanArchive(runtime("queued", null))).toBe(true);
|
||||
expect(threadCanArchive(runtime("queued", activeRunId))).toBe(false);
|
||||
});
|
||||
|
||||
it("allows post-provider waiting work despite a retained active run id", () => {
|
||||
const staleActiveRunId = RunId.make("run-finished");
|
||||
expect(threadCanArchive(runtime("waiting", null))).toBe(true);
|
||||
expect(threadCanArchive(runtime("waiting", staleActiveRunId))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
|
||||
|
||||
/**
|
||||
* Archiving may discard queued work, but it must not detach a provider while
|
||||
* that provider is still executing a turn.
|
||||
*/
|
||||
export function threadCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
|
||||
if (runtime?.status === "queued") {
|
||||
return runtime.activeRunId === null;
|
||||
}
|
||||
return (
|
||||
runtime?.status !== "preparing" &&
|
||||
runtime?.status !== "starting" &&
|
||||
runtime?.status !== "running"
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
@@ -12,6 +12,7 @@ import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { threadCanArchive } from "./threadArchive";
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
(capability defaults false on decode for older servers). */
|
||||
@@ -22,6 +23,13 @@ function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["en
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -93,13 +101,9 @@ function useThreadActionExecutor(
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (
|
||||
action === "archive" &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
// The server cancels queued runs on archive. Only an actual provider
|
||||
// turn still needs the user to interrupt it first.
|
||||
if (action === "archive" && !threadCanArchive(thread.runtime)) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
@@ -192,9 +196,14 @@ export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
|
||||
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -206,6 +215,94 @@ export function useThreadListActions(): {
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const snoozeThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (snoozeInFlightThreadKeys.current.has(key)) {
|
||||
return false;
|
||||
}
|
||||
snoozeInFlightThreadKeys.current.add(key);
|
||||
try {
|
||||
if (!environmentSupportsSnooze(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
"This environment's server does not support snoozing yet. Update the server to use Snooze.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (!canSnooze(thread, { now: new Date().toISOString() })) {
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
thread.hasPendingApprovals || thread.hasPendingUserInput
|
||||
? "This thread is waiting on you. Respond to the pending request before snoozing it."
|
||||
: "This thread is still starting a turn. Try again once it's running.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
selectionHaptic();
|
||||
const result = await snoozeMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: {
|
||||
threadId: thread.id,
|
||||
snoozedUntil,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be snoozed.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
snoozeInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[snoozeMutation],
|
||||
);
|
||||
const unsnoozeThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (snoozeInFlightThreadKeys.current.has(key)) {
|
||||
return false;
|
||||
}
|
||||
snoozeInFlightThreadKeys.current.add(key);
|
||||
try {
|
||||
if (!environmentSupportsSnooze(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not wake thread",
|
||||
"This environment's server does not support snoozing yet. Update the server to wake this thread.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
selectionHaptic();
|
||||
const result = await unsnoozeMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not wake thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be woken.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
snoozeInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[unsnoozeMutation],
|
||||
);
|
||||
const unsettleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
@@ -213,7 +310,14 @@ export function useThreadListActions(): {
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
|
||||
return {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
};
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -55,7 +55,10 @@ export function subscribeToHardwareKeyboardCommandRegistrations(listener: () =>
|
||||
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
|
||||
const commandHandlers = handlers.get(command);
|
||||
if (!commandHandlers) return false;
|
||||
for (const handler of [...commandHandlers].toReversed()) {
|
||||
const handlersInRegistrationOrder = Array.from(commandHandlers);
|
||||
for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) {
|
||||
const handler = handlersInRegistrationOrder[index];
|
||||
if (!handler) continue;
|
||||
if (handler() !== false) return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -561,7 +561,6 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
projectId,
|
||||
workspaceRoot,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
const result = await createProject({
|
||||
environmentId: environment.environmentId,
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MessageId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type ReviewDiffPreviewSource,
|
||||
} from "@t3tools/contracts";
|
||||
import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
|
||||
import {
|
||||
buildReviewListItems,
|
||||
@@ -18,9 +14,9 @@ import {
|
||||
} from "./reviewModel";
|
||||
|
||||
function makeCheckpoint(
|
||||
input: Partial<OrchestrationCheckpointSummary> &
|
||||
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
|
||||
): OrchestrationCheckpointSummary {
|
||||
input: Partial<ThreadCheckpointSummary> &
|
||||
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
|
||||
): ThreadCheckpointSummary {
|
||||
return {
|
||||
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
|
||||
status: "ready",
|
||||
@@ -52,12 +48,12 @@ describe("buildReviewSectionItems", () => {
|
||||
it("keeps one chip per checkpoint and appends git sources", () => {
|
||||
const checkpoints = [
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-1"),
|
||||
runId: RunId.make("run-1"),
|
||||
checkpointTurnCount: 1,
|
||||
completedAt: "2026-04-01T00:00:00.000Z",
|
||||
}),
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("run-2"),
|
||||
checkpointTurnCount: 2,
|
||||
completedAt: "2026-04-02T00:00:00.000Z",
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
|
||||
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
|
||||
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Order from "effect/Order";
|
||||
@@ -128,11 +129,11 @@ export type ReviewParsedDiff =
|
||||
readonly notice: string | null;
|
||||
};
|
||||
|
||||
function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
return `Turn ${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
const fileCount = checkpoint.files.length;
|
||||
if (checkpoint.status !== "ready") {
|
||||
return `Diff ${checkpoint.status}`;
|
||||
@@ -141,8 +142,8 @@ function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string
|
||||
}
|
||||
|
||||
function compareCheckpointTurnCountDescending(
|
||||
left: OrchestrationCheckpointSummary,
|
||||
right: OrchestrationCheckpointSummary,
|
||||
left: ThreadCheckpointSummary,
|
||||
right: ThreadCheckpointSummary,
|
||||
): -1 | 0 | 1 {
|
||||
if (left.checkpointTurnCount === right.checkpointTurnCount) {
|
||||
return 0;
|
||||
@@ -151,7 +152,7 @@ function compareCheckpointTurnCountDescending(
|
||||
return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
|
||||
}
|
||||
|
||||
const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
|
||||
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
|
||||
compareCheckpointTurnCountDescending,
|
||||
);
|
||||
|
||||
@@ -510,14 +511,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
|
||||
}
|
||||
|
||||
export function getReviewSectionIdForCheckpoint(
|
||||
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
|
||||
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
|
||||
): string {
|
||||
return `turn:${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
export function getReadyReviewCheckpoints(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): ReadonlyArray<OrchestrationCheckpointSummary> {
|
||||
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
return pipe(
|
||||
checkpoints,
|
||||
Arr.filter((checkpoint) => checkpoint.status === "ready"),
|
||||
@@ -526,7 +527,7 @@ export function getReadyReviewCheckpoints(
|
||||
}
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
deriveThreadCheckpointSummaries,
|
||||
type ThreadCheckpointSummary,
|
||||
} from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { useCheckpointDiff } from "../../state/queries";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { reviewEnvironment } from "../../state/review";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import {
|
||||
buildReviewSectionItems,
|
||||
@@ -30,7 +34,7 @@ export function useReviewSections(input: {
|
||||
}) {
|
||||
const { environmentId, reviewCache, threadId } = input;
|
||||
const enabled = input.enabled ?? true;
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const selectedThread = useSelectedThreadProjection();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const diffPreview = useEnvironmentQuery(
|
||||
enabled && environmentId !== undefined && selectedThreadCwd !== null
|
||||
@@ -49,8 +53,11 @@ export function useReviewSections(input: {
|
||||
}, [diffPreview.data, reviewCache.threadKey]);
|
||||
|
||||
const readyCheckpoints = useMemo(
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
() =>
|
||||
getReadyReviewCheckpoints(
|
||||
selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
|
||||
),
|
||||
[selectedThread],
|
||||
);
|
||||
const checkpointBySectionId = useMemo(
|
||||
() =>
|
||||
@@ -59,7 +66,7 @@ export function useReviewSections(input: {
|
||||
getReviewSectionIdForCheckpoint(checkpoint),
|
||||
checkpoint,
|
||||
]),
|
||||
) as Record<string, OrchestrationCheckpointSummary>,
|
||||
) as Record<string, ThreadCheckpointSummary>,
|
||||
[readyCheckpoints],
|
||||
);
|
||||
const reviewSections = useMemo(
|
||||
|
||||
@@ -9,6 +9,8 @@ import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import {
|
||||
applyNativeShowcaseOrientation,
|
||||
getNativeShowcaseOrientation,
|
||||
getNativeShowcasePairingUrls,
|
||||
getNativeShowcaseScene,
|
||||
markNativeShowcaseReady,
|
||||
@@ -47,6 +49,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
const [pendingTasksReady, setPendingTasksReady] = useState(false);
|
||||
const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
|
||||
const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
|
||||
const [orientationSettled, setOrientationSettled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return;
|
||||
@@ -60,6 +63,25 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
return () => clearInterval(interval);
|
||||
}, [pairingUrls.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || orientationSettled) return;
|
||||
const orientation = getNativeShowcaseOrientation();
|
||||
if (orientation === null) {
|
||||
setOrientationSettled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
void retryShowcaseOperation(async () => applyNativeShowcaseOrientation(orientation), {
|
||||
isCancelled: () => cancelled,
|
||||
}).then((applied) => {
|
||||
if (!cancelled && applied) setOrientationSettled(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [orientationSettled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED) return;
|
||||
|
||||
@@ -182,7 +204,10 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
scene === null ||
|
||||
requestedScene === null ||
|
||||
scene !== requestedScene ||
|
||||
!hasFixture
|
||||
!hasFixture ||
|
||||
// Never report a scene ready while the capture orientation is still
|
||||
// being applied — a screenshot taken early has the wrong dimensions.
|
||||
!orientationSettled
|
||||
) {
|
||||
setReadyScene(null);
|
||||
return;
|
||||
@@ -210,7 +235,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
if (renderFrame !== null) cancelAnimationFrame(renderFrame);
|
||||
if (readyFrame !== null) cancelAnimationFrame(readyFrame);
|
||||
};
|
||||
}, [hasFixture, requestedScene, scene]);
|
||||
}, [hasFixture, orientationSettled, requestedScene, scene]);
|
||||
|
||||
if (!SHOWCASE_ENABLED || readyScene === null) return null;
|
||||
|
||||
|
||||
@@ -3,9 +3,14 @@ import { requireOptionalNativeModule } from "expo";
|
||||
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
|
||||
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
|
||||
|
||||
export type ShowcaseOrientation = "portrait" | "landscape";
|
||||
|
||||
interface NativeShowcaseControls {
|
||||
readonly getShowcasePairingUrl?: () => string | null;
|
||||
readonly getShowcaseScene?: () => string | null;
|
||||
readonly getShowcaseOrientation?: () => string | null;
|
||||
readonly applyShowcaseOrientation?: (orientation: ShowcaseOrientation) => Promise<void>;
|
||||
readonly getInterfaceOrientation?: () => Promise<string>;
|
||||
readonly prepareShowcaseCapture?: () => void;
|
||||
readonly markShowcaseReady?: (scene: ShowcaseScene) => void;
|
||||
}
|
||||
@@ -59,6 +64,35 @@ export function prepareNativeShowcaseCapture(): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function getNativeShowcaseOrientation(): ShowcaseOrientation | null {
|
||||
try {
|
||||
const orientation = nativeShowcaseControls()?.getShowcaseOrientation?.()?.trim();
|
||||
return orientation === "portrait" || orientation === "landscape" ? orientation : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyNativeShowcaseOrientation(
|
||||
orientation: ShowcaseOrientation,
|
||||
): Promise<boolean> {
|
||||
const controls = nativeShowcaseControls();
|
||||
if (!controls?.applyShowcaseOrientation || !controls.getInterfaceOrientation) {
|
||||
// A development build that predates this helper keeps its default
|
||||
// orientation; report success so callers do not retry forever.
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
await controls.applyShowcaseOrientation(orientation);
|
||||
// The geometry request settles asynchronously; confirm it took effect so
|
||||
// callers can retry attempts made before the scene was foreground-active.
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
return (await controls.getInterfaceOrientation()) === orientation;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function markNativeShowcaseReady(scene: ShowcaseScene): void {
|
||||
try {
|
||||
nativeShowcaseControls()?.markShowcaseReady?.(scene);
|
||||
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
useKnownTerminalSessions,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
@@ -172,7 +172,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
const params = props.route.params;
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const selectedThreadDetail = useSelectedThreadProjection();
|
||||
const selectedThreadDetailWorktreePath =
|
||||
selectedThreadDetail?.projection.thread.worktreePath ?? null;
|
||||
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const routeThreadIdRaw = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentId = routeEnvironmentIdRaw
|
||||
@@ -283,13 +285,13 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
activeSessionLocation: activeKnownSession?.state.summary ?? null,
|
||||
workspaceRoot: selectedThreadProject.workspaceRoot,
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetailWorktreePath,
|
||||
});
|
||||
}, [
|
||||
activeKnownSession?.state.summary,
|
||||
pendingLaunch,
|
||||
selectedThread,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThreadDetailWorktreePath,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
]);
|
||||
const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
|
||||
|
||||
@@ -42,7 +42,8 @@ import {
|
||||
restoreComposerDraftSnapshot,
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
|
||||
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
@@ -90,6 +91,9 @@ export function NewTaskDraftScreen(props: {
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
selectedProject?.environmentId ?? null,
|
||||
);
|
||||
const environmentConnected =
|
||||
selectedProject !== null &&
|
||||
connectedEnvironments.find(
|
||||
@@ -539,27 +543,7 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
const modelMenuActions = useMemo(
|
||||
() =>
|
||||
flow.providerGroups.map((group) => ({
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: group.models.find(
|
||||
(model) =>
|
||||
flow.selectedModel &&
|
||||
model.selection.instanceId === flow.selectedModel.instanceId &&
|
||||
model.selection.model === flow.selectedModel.model,
|
||||
)?.label,
|
||||
subactions: group.models.map((option) => ({
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
flow.selectedModel &&
|
||||
option.selection.instanceId === flow.selectedModel.instanceId &&
|
||||
option.selection.model === flow.selectedModel.model
|
||||
? ("on" as const)
|
||||
: undefined,
|
||||
})),
|
||||
})),
|
||||
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
|
||||
[flow.providerGroups, flow.selectedModel],
|
||||
);
|
||||
const providerOptionDescriptors = useMemo(
|
||||
@@ -795,7 +779,14 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(draftKey);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
// Snapshot read keeps just-typed selector state; the availability gate
|
||||
// still applies so a stored selection on a disabled provider falls back
|
||||
// to the flow's resolved model.
|
||||
const modelSelection =
|
||||
resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
draft.modelSelection ?? null,
|
||||
) ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
@@ -847,7 +838,10 @@ export function NewTaskDraftScreen(props: {
|
||||
if (editingPendingTask) {
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
clearComposerDraftContent(draftKey);
|
||||
// Drop the workspace selection with the content: the next task should
|
||||
// re-resolve mode/branch/origin from the server's configured defaults
|
||||
// instead of resurrecting this task's picks.
|
||||
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
|
||||
}
|
||||
navigation.getParent()?.goBack();
|
||||
return;
|
||||
@@ -905,7 +899,7 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
clearComposerDraftContent(draftKey);
|
||||
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -6,14 +6,16 @@ import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
const canRespond = props.approval.responseCapability === "live";
|
||||
const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId;
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -27,17 +29,23 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
{props.approval.detail}
|
||||
</Text>
|
||||
) : null}
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
|
||||
@@ -46,7 +54,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import type { RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
@@ -9,14 +9,10 @@ export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -24,6 +20,7 @@ export interface PendingUserInputCardProps {
|
||||
}
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
const canRespond = props.pendingUserInput.responseCapability === "live";
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -32,6 +29,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
@@ -49,6 +52,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
disabled={!canRespond}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
@@ -78,6 +82,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
editable={canRespond}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
@@ -94,7 +99,9 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
|
||||
)}
|
||||
disabled={
|
||||
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
!canRespond ||
|
||||
props.answers === null ||
|
||||
props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
}
|
||||
onPress={() => void props.onSubmit()}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import { buildThreadActivityInspector } from "../../lib/threadActivityInspector";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useV2ItemSupport } from "../../state/v2-item-support";
|
||||
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
|
||||
|
||||
export function ThreadActivityInspector(props: {
|
||||
readonly activity: ThreadFeedActivity;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly iconColor: ColorValue;
|
||||
readonly workspaceRoot?: string | null;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
const row = props.activity.projectedItem;
|
||||
const support = useV2ItemSupport({
|
||||
environmentId: props.environmentId,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
});
|
||||
const model = useMemo(
|
||||
() => buildThreadActivityInspector(props.activity, support, props.currentThreadId),
|
||||
[props.activity, props.currentThreadId, support],
|
||||
);
|
||||
const revertCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, {
|
||||
label: "checkpoint rollback",
|
||||
reportFailure: true,
|
||||
});
|
||||
const [rollingBack, setRollingBack] = useState(false);
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<View className="flex-row flex-wrap gap-x-4 gap-y-2 rounded-lg border border-neutral-300/50 bg-black/[0.025] p-2.5 dark:border-white/[0.1] dark:bg-white/[0.025]">
|
||||
{model.fields.map((field) => (
|
||||
<View key={`${field.label}:${field.value}`} className="min-w-[42%] flex-1 gap-0.5">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
{field.label}
|
||||
</Text>
|
||||
<Text selectable className="text-2xs leading-4 text-foreground">
|
||||
{field.value}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
|
||||
{model.blocks.map((block) => (
|
||||
<View key={`${block.label}:${block.value}`} className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
{block.label}
|
||||
</Text>
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ maxHeight: 240 }}
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-2xs leading-[17px] text-foreground-muted"
|
||||
style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}
|
||||
>
|
||||
{block.value}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
))}
|
||||
|
||||
{model.fileLinks.length > 0 ? (
|
||||
<View className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Files
|
||||
</Text>
|
||||
{model.fileLinks.map((link) => {
|
||||
const relativePath =
|
||||
resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
|
||||
(link.path.startsWith("/") ? null : link.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={`${link.path}:${link.line ?? 0}:${link.label}`}
|
||||
accessibilityRole={relativePath ? "link" : undefined}
|
||||
disabled={relativePath === null}
|
||||
onPress={() => {
|
||||
if (!relativePath) return;
|
||||
void Haptics.selectionAsync();
|
||||
navigation.navigate(
|
||||
"ThreadFile",
|
||||
buildThreadActivityFileParams({
|
||||
environmentId: props.environmentId,
|
||||
currentThreadId: props.currentThreadId,
|
||||
activitySourceThreadId: row.sourceThreadId,
|
||||
relativePath,
|
||||
line: link.line,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="doc.text"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
|
||||
{link.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{model.webLinks.length > 0 ? (
|
||||
<View className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Sources
|
||||
</Text>
|
||||
{model.webLinks.map((link) => (
|
||||
<Pressable
|
||||
key={link.url}
|
||||
accessibilityRole="link"
|
||||
onPress={() => void Linking.openURL(link.url)}
|
||||
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="arrow.up.right.square"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
|
||||
{link.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{model.rollbackTarget ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Roll back to this checkpoint"
|
||||
disabled={rollingBack}
|
||||
onPress={() => {
|
||||
setRollingBack(true);
|
||||
void Haptics.selectionAsync();
|
||||
void revertCheckpoint({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
threadId: model.rollbackTarget!.threadId,
|
||||
checkpointId: model.rollbackTarget!.checkpointId,
|
||||
scopeId: model.rollbackTarget!.scopeId,
|
||||
},
|
||||
}).finally(() => setRollingBack(false));
|
||||
}}
|
||||
className="min-h-10 flex-row items-center justify-center gap-2 rounded-lg border border-neutral-300/60 px-3 py-2 dark:border-white/[0.12]"
|
||||
>
|
||||
<SymbolView
|
||||
name={rollingBack ? "hourglass" : "arrow.counterclockwise"}
|
||||
size={14}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="font-t3-medium text-xs text-foreground">
|
||||
{rollingBack ? "Rolling back…" : "Roll back to checkpoint"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
|
||||
<View className="gap-1 border-t border-neutral-300/50 pt-2 dark:border-white/[0.1]">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Structured details
|
||||
</Text>
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ maxHeight: 280 }}
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-2xs leading-[17px] text-foreground-muted"
|
||||
style={{ fontFamily: "ui-monospace" }}
|
||||
>
|
||||
{model.structuredDetails}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
@@ -53,7 +53,7 @@ import {
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import type { RemoteClientConnectionState } from "../../lib/connection";
|
||||
import {
|
||||
@@ -97,10 +97,11 @@ export interface ThreadComposerProps {
|
||||
* are on screen while they reconcile with the server.
|
||||
*/
|
||||
readonly threadSyncPhase?: "loading" | "syncing" | null;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectCwd: string | null;
|
||||
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
|
||||
@@ -305,9 +306,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
setIsFocused(false);
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
const showStopAction = props.canStopThread;
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
|
||||
@@ -606,25 +605,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
[providerOptionDescriptors],
|
||||
);
|
||||
const modelMenuActions = useMemo(
|
||||
() =>
|
||||
providerGroups.map((group) => ({
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: group.models.find(
|
||||
(model) =>
|
||||
model.selection.instanceId === currentModelSelection.instanceId &&
|
||||
model.selection.model === currentModelSelection.model,
|
||||
)?.label,
|
||||
subactions: group.models.map((option) => ({
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
option.selection.instanceId === currentModelSelection.instanceId &&
|
||||
option.selection.model === currentModelSelection.model
|
||||
? ("on" as const)
|
||||
: undefined,
|
||||
})),
|
||||
})),
|
||||
() => buildModelMenuActions(providerGroups, currentModelSelection),
|
||||
[providerGroups, currentModelSelection],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
RuntimeRequestId,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -26,11 +26,14 @@ import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
PendingUserInputDraftAnswer,
|
||||
ThreadFeedEntry,
|
||||
ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
@@ -40,28 +43,32 @@ import {
|
||||
ThreadComposer,
|
||||
} from "./ThreadComposer";
|
||||
import { ThreadFeed } from "./ThreadFeed";
|
||||
import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
|
||||
import { ThreadQueueControl } from "./ThreadQueueControl";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
|
||||
export interface ThreadDetailScreenProps {
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly screenTone: StatusTone;
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly activityRun: ThreadFeedLatestRun | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
@@ -82,16 +89,16 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -236,6 +243,39 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
|
||||
const lastDispatchedVisitRef = useRef<string | null>(null);
|
||||
const selectedThreadId = props.selectedThread.id;
|
||||
const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
|
||||
const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
|
||||
useEffect(() => {
|
||||
// Records the server-side visited watermark while the thread is on
|
||||
// screen (mirror of web ChatView), so the "Done" marker clears on every
|
||||
// device. Field absent → the server predates visited tracking.
|
||||
if (selectedThreadLastVisitedAt === undefined) return;
|
||||
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
|
||||
if (Number.isNaN(threadUpdatedAtMs)) return;
|
||||
const lastVisitedAtMs = selectedThreadLastVisitedAt
|
||||
? Date.parse(selectedThreadLastVisitedAt)
|
||||
: NaN;
|
||||
if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
|
||||
// Dedupe per watermark — the effect re-runs before the command echo lands.
|
||||
const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
|
||||
if (lastDispatchedVisitRef.current === dispatchKey) return;
|
||||
lastDispatchedVisitRef.current = dispatchKey;
|
||||
void visitThread({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
|
||||
});
|
||||
}, [
|
||||
props.environmentId,
|
||||
selectedThreadId,
|
||||
selectedThreadKey,
|
||||
selectedThreadLastVisitedAt,
|
||||
selectedThreadUpdatedAt,
|
||||
visitThread,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
@@ -358,7 +398,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
threadTitle={props.selectedThread.title}
|
||||
latestRun={props.activityRun}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
@@ -367,6 +408,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
topAccessory={
|
||||
<ThreadRelationshipsBanner
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
/>
|
||||
}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
@@ -388,6 +435,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
<ThreadQueueControl
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
/>
|
||||
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
@@ -430,6 +482,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
canStopThread={props.canStopThread}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import {
|
||||
ThreadId,
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -27,6 +35,7 @@ import {
|
||||
} from "react-native-nitro-markdown";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Image,
|
||||
Linking,
|
||||
Platform,
|
||||
@@ -79,6 +88,7 @@ import {
|
||||
import { buildReviewParsedDiff } from "../review/reviewModel";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import {
|
||||
resolveMarkdownFontSizes,
|
||||
resolveNativeMarkdownTypography,
|
||||
@@ -91,8 +101,9 @@ import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons
|
||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
type ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
@@ -103,7 +114,13 @@ import {
|
||||
} from "./thread-work-log";
|
||||
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useV2ItemSupport } from "../../state/v2-item-support";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
import { waitForThreadShellReady } from "./threadForkNavigation";
|
||||
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
|
||||
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
@@ -147,11 +164,12 @@ function isFreshTimestamp(input: string): boolean {
|
||||
export interface ThreadFeedProps {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly threadTitle: string;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly latestRun: ThreadFeedLatestRun | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
@@ -159,6 +177,7 @@ export interface ThreadFeedProps {
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly topAccessory?: ReactNode;
|
||||
readonly contentMaxWidth?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
@@ -166,6 +185,90 @@ export interface ThreadFeedProps {
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
}
|
||||
|
||||
async function waitForThreadShell(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
): Promise<boolean> {
|
||||
const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId));
|
||||
return waitForThreadShellReady({
|
||||
read: () => appAtomRegistry.get(atom) !== null,
|
||||
});
|
||||
}
|
||||
|
||||
function AssistantForkButton(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly iconColor: ColorValue;
|
||||
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
|
||||
readonly sourceTitle: string;
|
||||
}) {
|
||||
const support = useV2ItemSupport({
|
||||
environmentId: props.environmentId,
|
||||
sourceThreadId: props.projectedItem.sourceThreadId,
|
||||
sourceItemId: props.projectedItem.sourceItemId,
|
||||
});
|
||||
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
|
||||
const navigation = useNavigation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const canFork = canForkProjectedAssistantItem({
|
||||
projectedItem: props.projectedItem,
|
||||
capabilities: support.providerSession?.capabilities,
|
||||
});
|
||||
const runId = props.projectedItem.item.runId;
|
||||
|
||||
if (!canFork || runId === null) return null;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Fork from this response"
|
||||
disabled={busy}
|
||||
onPress={() => {
|
||||
const targetThreadId = ThreadId.make(uuidv4());
|
||||
setBusy(true);
|
||||
void Haptics.selectionAsync();
|
||||
void forkFromRun({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
sourceThreadId: props.projectedItem.sourceThreadId,
|
||||
targetThreadId,
|
||||
runId,
|
||||
title: `${props.sourceTitle} fork`,
|
||||
creationSource: "mobile",
|
||||
},
|
||||
})
|
||||
.then(async (result) => {
|
||||
if (result._tag !== "Success") return;
|
||||
const targetThreadReady = await waitForThreadShell(props.environmentId, targetThreadId);
|
||||
if (!targetThreadReady) {
|
||||
Alert.alert(
|
||||
"Fork created",
|
||||
"Its thread data did not reach this client. Reconnect and try opening it from the thread list.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: props.environmentId,
|
||||
threadId: targetThreadId,
|
||||
});
|
||||
})
|
||||
.finally(() => setBusy(false));
|
||||
}}
|
||||
className="h-7 w-7 items-center justify-center disabled:opacity-40"
|
||||
>
|
||||
{busy ? (
|
||||
<ActivityIndicator size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageAttachmentImage(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachmentId: string;
|
||||
@@ -819,15 +922,16 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
|
||||
function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
readonly unsettledTurnId: RunId | null;
|
||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleWorkGroup: (groupId: string) => void;
|
||||
readonly onToggleWorkRow: (rowId: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onToggleWorkRow: (rowId: string, anchorKey?: string) => void;
|
||||
readonly onToggleTurnFold: (runId: RunId) => void;
|
||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||
readonly onMarkdownLinkPress: (href: string) => void;
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
@@ -836,6 +940,7 @@ function renderFeedEntry(
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly reviewCommentBubbleWidth: number;
|
||||
readonly userBubbleMaxWidth: number;
|
||||
readonly threadTitle: string;
|
||||
},
|
||||
) {
|
||||
const entry = info.item;
|
||||
@@ -845,12 +950,12 @@ function renderFeedEntry(
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
if (entry.type === "run-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: entry.expanded }}
|
||||
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
||||
onPress={() => props.onToggleTurnFold(entry.runId)}
|
||||
hitSlop={4}
|
||||
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
@@ -889,7 +994,7 @@ function renderFeedEntry(
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
message.turnId === props.unsettledTurnId;
|
||||
message.runId === props.unsettledTurnId;
|
||||
const showAssistantMeta =
|
||||
message.role === "assistant" &&
|
||||
props.terminalAssistantMessageIds.has(message.id) &&
|
||||
@@ -898,11 +1003,17 @@ function renderFeedEntry(
|
||||
|
||||
if (isUser) {
|
||||
const enterAnimated = isFreshTimestamp(message.createdAt);
|
||||
const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
|
||||
return (
|
||||
<Animated.View
|
||||
className="mb-5 items-end"
|
||||
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
|
||||
>
|
||||
{message.createdBy === "agent" ? (
|
||||
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
Sent by another agent
|
||||
</Text>
|
||||
) : null}
|
||||
<View
|
||||
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
|
||||
style={{
|
||||
@@ -933,6 +1044,30 @@ function renderFeedEntry(
|
||||
})}
|
||||
</View>
|
||||
<View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
|
||||
{intentBadge ? (
|
||||
<View
|
||||
accessible
|
||||
accessibilityRole="text"
|
||||
accessibilityLabel={intentBadge.accessibilityLabel}
|
||||
className={cn(
|
||||
"rounded-full border px-1.5 py-0.5",
|
||||
intentBadge.tone === "queued"
|
||||
? "border-amber-500/25 bg-amber-500/10 dark:border-amber-400/25 dark:bg-amber-400/10"
|
||||
: "border-sky-500/25 bg-sky-500/10 dark:border-sky-400/25 dark:bg-sky-400/10",
|
||||
)}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-2xs tracking-wide",
|
||||
intentBadge.tone === "queued"
|
||||
? "text-amber-700 dark:text-amber-300"
|
||||
: "text-sky-700 dark:text-sky-300",
|
||||
)}
|
||||
>
|
||||
{intentBadge.label}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
||||
{timestampLabel}
|
||||
</Text>
|
||||
@@ -994,6 +1129,12 @@ function renderFeedEntry(
|
||||
})}
|
||||
{showAssistantMeta ? (
|
||||
<View className="mt-1 flex-row items-center gap-1">
|
||||
<AssistantForkButton
|
||||
environmentId={props.environmentId}
|
||||
iconColor={iconSubtleColor}
|
||||
projectedItem={message.projectedItem}
|
||||
sourceTitle={props.threadTitle}
|
||||
/>
|
||||
<CopyTextButton
|
||||
accessibilityLabel="Copy message"
|
||||
text={message.text}
|
||||
@@ -1014,10 +1155,15 @@ function renderFeedEntry(
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
copiedRowId={props.copiedRowId}
|
||||
currentThreadId={props.threadId}
|
||||
environmentId={props.environmentId}
|
||||
expanded={props.expandedWorkGroups[entry.id] ?? false}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={(rowId) => props.onToggleWorkRow(rowId, entry.id)}
|
||||
workspaceRoot={props.workspaceRoot}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1320,9 +1466,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const previousLatestTurnRef = useRef(props.latestRun);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
@@ -1334,7 +1480,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
readonly expandedTurnIds: ReadonlySet<RunId>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
@@ -1407,6 +1553,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1416,6 +1563,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1491,31 +1639,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
if (expanded) {
|
||||
ids.add(groupId);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}, [expandedWorkGroups]);
|
||||
const presentedFeed = useMemo(
|
||||
() =>
|
||||
deriveThreadFeedPresentation(
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
props.latestRun,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
new Set(
|
||||
Object.entries(expandedWorkGroups)
|
||||
.filter(([, expanded]) => expanded)
|
||||
.map(([groupId]) => groupId),
|
||||
),
|
||||
props.activeWorkStartedAt,
|
||||
),
|
||||
[
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
],
|
||||
[expandedTurnIds, expandedWorkGroups, props.activeWorkStartedAt, props.feed, props.latestRun],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
@@ -1544,29 +1681,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[presentedFeed, props.anchorMessageId, anchorTopInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
const terminalIdsByTurn = new Map<RunId, string>();
|
||||
for (const entry of props.feed) {
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
|
||||
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
|
||||
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
|
||||
}
|
||||
}
|
||||
return new Set(terminalIdsByTurn.values());
|
||||
}, [props.feed]);
|
||||
const unsettledTurnId =
|
||||
props.latestTurn &&
|
||||
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
if (!props.latestTurn || !previous) {
|
||||
previousLatestTurnRef.current = props.latestRun;
|
||||
if (!props.latestRun || !previous) {
|
||||
return;
|
||||
}
|
||||
if (props.latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
|
||||
const interruptedTurnId = props.latestTurn.turnId;
|
||||
if (props.latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && props.latestRun.status === "interrupted") {
|
||||
const interruptedTurnId = props.latestRun.runId;
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
|
||||
@@ -1575,14 +1708,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return;
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
if (!current.expandedTurnIds.has(previous.turnId)) {
|
||||
if (!current.expandedTurnIds.has(previous.runId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
}, [props.latestTurn]);
|
||||
}, [props.latestRun]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1663,8 +1796,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleWorkRow = useCallback(
|
||||
(rowId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
||||
(rowId: string, anchorKey?: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
@@ -1677,14 +1810,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
(runId: RunId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
next.add(runId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
@@ -1709,7 +1842,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const getFixedItemSize = useCallback(
|
||||
(entry: ThreadFeedEntry) => {
|
||||
switch (entry.type) {
|
||||
case "turn-fold":
|
||||
case "run-fold":
|
||||
return TURN_FOLD_HEIGHT;
|
||||
case "work-toggle":
|
||||
return WORK_GROUP_TOGGLE_HEIGHT;
|
||||
@@ -1732,7 +1865,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
(info: { item: ThreadFeedEntry; index: number }) =>
|
||||
renderFeedEntry(info, {
|
||||
environmentId: props.environmentId,
|
||||
threadId: props.threadId,
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1748,10 +1883,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
userBubbleMaxWidth,
|
||||
threadTitle: props.threadTitle,
|
||||
skills: props.skills,
|
||||
workspaceRoot: props.workspaceRoot,
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1768,7 +1906,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onToggleWorkGroup,
|
||||
onToggleWorkRow,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.threadTitle,
|
||||
props.skills,
|
||||
props.workspaceRoot,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1893,7 +2034,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
<>
|
||||
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
|
||||
{props.topAccessory}
|
||||
</>
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
|
||||
@@ -67,7 +67,12 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "./thread-list-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
|
||||
import {
|
||||
ThreadListV2PendingRow,
|
||||
ThreadListV2Row,
|
||||
ThreadListV2SettledShelfHeader,
|
||||
ThreadListV2SnoozedShelfHeader,
|
||||
} from "./thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
@@ -193,8 +198,14 @@ function ThreadNavigationSidebarPane(
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const headerIsOverContentRef = useRef(false);
|
||||
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
@@ -428,6 +439,10 @@ function ThreadNavigationSidebarPane(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
// now ticks per minute so the inactivity auto-settle boundary is actually
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
@@ -468,7 +483,15 @@ function ThreadNavigationSidebarPane(
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return {
|
||||
items: [],
|
||||
hiddenSettledCount: 0,
|
||||
snoozedCount: 0,
|
||||
snoozedShelfHeaderIndex: null,
|
||||
settledCount: 0,
|
||||
settledShelfHeaderIndex: null,
|
||||
nextSnoozeWakeAt: null,
|
||||
};
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -481,11 +504,17 @@ function ThreadNavigationSidebarPane(
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
selectedThreadKey: props.selectedThreadKey ?? null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
props.selectedThreadKey,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
@@ -532,8 +561,15 @@ function ThreadNavigationSidebarPane(
|
||||
const items: SidebarListItem[] = buildThreadListV2ListItems({
|
||||
items: threadListV2Layout.items,
|
||||
pendingTasks: v2PendingTasks,
|
||||
snoozedCount: threadListV2Layout.snoozedCount,
|
||||
snoozedShelfExpanded,
|
||||
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
|
||||
settledCount: threadListV2Layout.settledCount,
|
||||
settledShelfExpanded,
|
||||
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
|
||||
snoozeLabelNow: `${nowMinute}:00.000Z`,
|
||||
});
|
||||
if (threadListV2Layout.hiddenSettledCount > 0) {
|
||||
if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
|
||||
items.push({
|
||||
type: "v2-show-more",
|
||||
key: "v2-show-more",
|
||||
@@ -543,10 +579,13 @@ function ThreadNavigationSidebarPane(
|
||||
return items;
|
||||
}, [
|
||||
listLayout.items,
|
||||
nowMinute,
|
||||
options.selectedEnvironmentId,
|
||||
pendingTasks,
|
||||
props.searchQuery,
|
||||
selectedProjectRefs,
|
||||
settledShelfExpanded,
|
||||
snoozedShelfExpanded,
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
@@ -731,6 +770,7 @@ function ThreadNavigationSidebarPane(
|
||||
projectTitleByProjectKey,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
snoozePresetMinute: nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
}),
|
||||
[
|
||||
@@ -740,6 +780,7 @@ function ThreadNavigationSidebarPane(
|
||||
projectTitleByProjectKey,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
],
|
||||
);
|
||||
@@ -750,7 +791,8 @@ function ThreadNavigationSidebarPane(
|
||||
previous.key === item.key &&
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.showSettledDivider === item.item.showSettledDivider
|
||||
previous.item.snoozed === item.item.snoozed &&
|
||||
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
|
||||
);
|
||||
}
|
||||
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
|
||||
@@ -762,13 +804,23 @@ function ThreadNavigationSidebarPane(
|
||||
previous.showPendingDivider === item.showPendingDivider
|
||||
);
|
||||
}
|
||||
if (previous.type === "v2-snoozed-shelf" && item.type === "v2-snoozed-shelf") {
|
||||
return previous.count === item.count && previous.expanded === item.expanded;
|
||||
}
|
||||
if (previous.type === "v2-settled-shelf" && item.type === "v2-settled-shelf") {
|
||||
return previous.count === item.count && previous.expanded === item.expanded;
|
||||
}
|
||||
if (
|
||||
previous.type === "v2-thread" ||
|
||||
previous.type === "v2-show-more" ||
|
||||
previous.type === "v2-pending" ||
|
||||
previous.type === "v2-snoozed-shelf" ||
|
||||
previous.type === "v2-settled-shelf" ||
|
||||
item.type === "v2-thread" ||
|
||||
item.type === "v2-show-more" ||
|
||||
item.type === "v2-pending"
|
||||
item.type === "v2-pending" ||
|
||||
item.type === "v2-snoozed-shelf" ||
|
||||
item.type === "v2-settled-shelf"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -826,7 +878,9 @@ function ThreadNavigationSidebarPane(
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
snoozed={item.item.snoozed}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
@@ -835,7 +889,7 @@ function ThreadNavigationSidebarPane(
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
@@ -860,6 +914,9 @@ function ThreadNavigationSidebarPane(
|
||||
onArchiveThread={archiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
@@ -869,6 +926,24 @@ function ThreadNavigationSidebarPane(
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "v2-snoozed-shelf":
|
||||
return (
|
||||
<ThreadListV2SnoozedShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSnoozedShelf}
|
||||
pane="sidebar"
|
||||
/>
|
||||
);
|
||||
case "v2-settled-shelf":
|
||||
return (
|
||||
<ThreadListV2SettledShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSettledShelf}
|
||||
pane="sidebar"
|
||||
/>
|
||||
);
|
||||
case "v2-show-more":
|
||||
return (
|
||||
<Pressable
|
||||
@@ -984,7 +1059,13 @@ function ThreadNavigationSidebarPane(
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
sidebarScrollGesture,
|
||||
snoozeEnvironmentIds,
|
||||
snoozeThread,
|
||||
nowMinute,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
@@ -1031,30 +1112,19 @@ function ThreadNavigationSidebarPane(
|
||||
}),
|
||||
[filterIcon, filterMenu, props.onOpenSettings],
|
||||
);
|
||||
// "No threads yet" over an inbox that is merely all-snoozed reads as
|
||||
// data loss; name the snoozed threads instead.
|
||||
const snoozedCount = threadListV2Layout.snoozedCount;
|
||||
// Snoozed threads need no special case: the shelf header is a list row
|
||||
// even while collapsed.
|
||||
const listEmpty = (
|
||||
<Text className="px-2 py-4 text-sm text-foreground-muted">
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? threadSearch.isPending && snoozedCount === 0
|
||||
? threadSearch.isPending
|
||||
? "Searching thread messages…"
|
||||
: snoozedCount > 0
|
||||
? // Snoozed matches passed this same search filter — "No
|
||||
// matching threads" would misreport them as nonexistent.
|
||||
snoozedCount === 1
|
||||
? "1 matching thread snoozed"
|
||||
: "All matching threads snoozed"
|
||||
: "No matching threads"
|
||||
: snoozedCount > 0
|
||||
? snoozedCount === 1
|
||||
? "1 thread snoozed"
|
||||
: `${snoozedCount} threads snoozed`
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
: "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThreadProjection } from "../../state/use-thread-detail";
|
||||
|
||||
export function ThreadQueueControl(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
}) {
|
||||
const scoped = useThreadProjection(props);
|
||||
const workflow = useMemo(
|
||||
() => (scoped ? deriveThreadQueueWorkflowState(scoped.projection) : null),
|
||||
[scoped],
|
||||
);
|
||||
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
|
||||
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
|
||||
const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
|
||||
if (!workflow || workflow.queuedRuns.length === 0) return null;
|
||||
|
||||
const move = async (runId: RunId, beforeRunId: RunId | null) => {
|
||||
setBusyRunId(runId);
|
||||
void Haptics.selectionAsync();
|
||||
await reorder({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: props.threadId, runId, beforeRunId },
|
||||
});
|
||||
setBusyRunId(null);
|
||||
};
|
||||
|
||||
const steer = async (queuedRunId: RunId) => {
|
||||
if (!workflow.activeRun || !workflow.canPromoteToSteer) return;
|
||||
setBusyRunId(queuedRunId);
|
||||
void Haptics.selectionAsync();
|
||||
await promote({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
threadId: props.threadId,
|
||||
queuedRunId,
|
||||
targetRunId: workflow.activeRun.id,
|
||||
},
|
||||
});
|
||||
setBusyRunId(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<View className="mx-4 mb-3 overflow-hidden rounded-2xl border border-neutral-300/60 bg-card dark:border-white/[0.1]">
|
||||
<View className="flex-row items-center gap-2 border-b border-neutral-300/50 px-3 py-2 dark:border-white/[0.08]">
|
||||
<SymbolView name="list.number" size={13} tintColor={iconColor} type="monochrome" />
|
||||
<Text className="font-t3-medium text-xs text-foreground">Queue</Text>
|
||||
<Text className="ml-auto text-2xs tabular-nums text-foreground-muted">
|
||||
{workflow.queuedRuns.length}
|
||||
</Text>
|
||||
</View>
|
||||
<ScrollView style={{ maxHeight: 156 }} contentContainerStyle={{ paddingVertical: 4 }}>
|
||||
{workflow.queuedRuns.map(({ run, text }, index) => (
|
||||
<View key={run.id} className="min-h-11 flex-row items-center gap-1.5 px-2">
|
||||
<Text className="w-5 text-right text-3xs tabular-nums text-foreground-muted">
|
||||
{index + 1}
|
||||
</Text>
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
{text}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message up"
|
||||
disabled={busyRunId !== null || !workflow.canReorder || index === 0}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index - 1]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.up" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message down"
|
||||
disabled={
|
||||
busyRunId !== null ||
|
||||
!workflow.canReorder ||
|
||||
index === workflow.queuedRuns.length - 1
|
||||
}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.down" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Promote queued message to steer"
|
||||
disabled={busyRunId !== null || !workflow.canPromoteToSteer}
|
||||
onPress={() => void steer(run.id)}
|
||||
className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="arrow.turn.left.up"
|
||||
size={12}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="font-t3-medium text-2xs text-foreground">Steer</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView, type SFSymbol } from "expo-symbols";
|
||||
import {
|
||||
deriveThreadRelationshipGraph,
|
||||
immediateThreadRelationships,
|
||||
resolveMergeBackTargetThreadId,
|
||||
type ThreadRelationshipEdge,
|
||||
} from "@t3tools/client-runtime/state/thread-relationships";
|
||||
import {
|
||||
canDetachThreadProviderSession,
|
||||
resolveLatestMergeBackRun,
|
||||
} from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
|
||||
import { copySorted } from "@t3tools/shared/Array";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadShells } from "../../state/entities";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThreadProjection } from "../../state/use-thread-detail";
|
||||
import { useArchivedThreadSnapshots } from "../archive/useArchivedThreadSnapshots";
|
||||
|
||||
function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId): string {
|
||||
if (edge.kind === "transfer") {
|
||||
return edge.sourceThreadId === currentThreadId ? "Context sent to" : "Context received from";
|
||||
}
|
||||
if (edge.kind === "subagent") {
|
||||
return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
|
||||
}
|
||||
return edge.sourceThreadId === currentThreadId ? "Fork" : "Forked from";
|
||||
}
|
||||
|
||||
function relationshipSymbol(edge: ThreadRelationshipEdge): SFSymbol {
|
||||
if (edge.kind === "subagent") return "person.2";
|
||||
if (edge.kind === "transfer") return "arrow.left.arrow.right";
|
||||
return "arrow.triangle.branch";
|
||||
}
|
||||
|
||||
function threadAvailability(
|
||||
thread: OrchestrationV2ThreadShell | null,
|
||||
missing: boolean,
|
||||
): string | null {
|
||||
if (missing) return "Unavailable";
|
||||
if (thread?.deletedAt !== null && thread?.deletedAt !== undefined) return "Deleted";
|
||||
if (thread?.archivedAt !== null && thread?.archivedAt !== undefined) return "Archived";
|
||||
return null;
|
||||
}
|
||||
|
||||
const EMPTY_THREAD_SHELLS: ReadonlyArray<OrchestrationV2ThreadShell> = [];
|
||||
|
||||
export function ThreadRelationshipsBanner(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
}) {
|
||||
const scopedProjection = useThreadProjection(props);
|
||||
const projection = scopedProjection?.projection ?? null;
|
||||
const threadShells = useThreadShells();
|
||||
const environmentIds = useMemo(() => [props.environmentId], [props.environmentId]);
|
||||
const archived = useArchivedThreadSnapshots(environmentIds);
|
||||
const archivedShells =
|
||||
archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot
|
||||
.threads ?? EMPTY_THREAD_SHELLS;
|
||||
const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(() => {
|
||||
const environmentShells: OrchestrationV2ThreadShell[] = [];
|
||||
for (const thread of threadShells) {
|
||||
if (thread.environmentId === props.environmentId) {
|
||||
environmentShells.push(thread.source);
|
||||
}
|
||||
}
|
||||
environmentShells.push(...archivedShells);
|
||||
return environmentShells;
|
||||
}, [archivedShells, props.environmentId, threadShells]);
|
||||
const graph = useMemo(
|
||||
() => deriveThreadRelationshipGraph({ threads: shells, projection }),
|
||||
[projection, shells],
|
||||
);
|
||||
const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
copySorted(
|
||||
immediateThreadRelationships(graph, props.threadId),
|
||||
(left, right) =>
|
||||
Number(right.threadId === mergeTargetThreadId) -
|
||||
Number(left.threadId === mergeTargetThreadId),
|
||||
),
|
||||
[graph, mergeTargetThreadId, props.threadId],
|
||||
);
|
||||
const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
|
||||
const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
|
||||
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
|
||||
const navigation = useNavigation();
|
||||
const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
|
||||
const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
|
||||
const insets = useSafeAreaInsets();
|
||||
const backdropColor = useThemeColor("--color-backdrop");
|
||||
const sheetColor = useThemeColor("--color-sheet");
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
|
||||
if (rows.length === 0 && !canDetach) return null;
|
||||
|
||||
const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];
|
||||
const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;
|
||||
const summary = primaryParent
|
||||
? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`
|
||||
: "Agent session connected";
|
||||
|
||||
const openThread = (threadId: ThreadId, archivedThread: boolean) => {
|
||||
setVisible(false);
|
||||
void Haptics.selectionAsync();
|
||||
if (archivedThread) {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsArchive" });
|
||||
return;
|
||||
}
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: props.environmentId,
|
||||
threadId,
|
||||
});
|
||||
};
|
||||
|
||||
const merge = async () => {
|
||||
if (!canMerge || mergeTargetThreadId === null || latestMergeBackRun === null) return;
|
||||
setBusyAction("merge");
|
||||
const result = await mergeBack({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
sourceThreadId: props.threadId,
|
||||
targetThreadId: mergeTargetThreadId,
|
||||
runId: latestMergeBackRun.id,
|
||||
creationSource: "mobile",
|
||||
},
|
||||
});
|
||||
setBusyAction(null);
|
||||
if (result._tag === "Success") openThread(mergeTargetThreadId, false);
|
||||
};
|
||||
|
||||
const detach = async () => {
|
||||
if (!canDetach) return;
|
||||
setBusyAction("detach");
|
||||
await stopSession({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: props.threadId },
|
||||
});
|
||||
setBusyAction(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`${summary}. Show thread relationships`}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
setVisible(true);
|
||||
}}
|
||||
className="mb-4 min-h-11 flex-row items-center gap-2 rounded-xl border border-neutral-300/60 bg-card px-3 py-2.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name={primaryParent ? relationshipSymbol(primaryParent.edge) : "link"}
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 font-t3-medium text-xs text-foreground" numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
{rows.length > 1 ? (
|
||||
<Text className="text-2xs tabular-nums text-foreground-muted">+{rows.length - 1}</Text>
|
||||
) : null}
|
||||
<SymbolView name="chevron.right" size={12} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
|
||||
<Modal
|
||||
transparent
|
||||
animationType="fade"
|
||||
visible={visible}
|
||||
statusBarTranslucent
|
||||
onRequestClose={() => setVisible(false)}
|
||||
>
|
||||
<View className="flex-1 justify-end">
|
||||
<View
|
||||
pointerEvents="none"
|
||||
className="absolute inset-0"
|
||||
style={{ backgroundColor: backdropColor }}
|
||||
/>
|
||||
<Pressable className="absolute inset-0" onPress={() => setVisible(false)} />
|
||||
<View
|
||||
className="max-h-[78%] rounded-t-[28px] px-4 pt-3"
|
||||
style={{ backgroundColor: sheetColor, paddingBottom: Math.max(insets.bottom, 16) }}
|
||||
>
|
||||
<View className="mb-4 h-1 w-10 self-center rounded-full bg-neutral-400/40" />
|
||||
<View className="mb-3 flex-row items-center justify-between px-1">
|
||||
<View>
|
||||
<Text className="font-t3-bold text-lg text-foreground">Thread lineage</Text>
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{rows.length} related {rows.length === 1 ? "thread" : "threads"}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close thread lineage"
|
||||
onPress={() => setVisible(false)}
|
||||
className="h-10 w-10 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/[0.07]"
|
||||
>
|
||||
<SymbolView name="xmark" size={14} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<ScrollView contentContainerStyle={{ gap: 8 }} showsVerticalScrollIndicator={false}>
|
||||
{rows.map(({ threadId, edge }) => {
|
||||
const node = graph.nodes.get(threadId);
|
||||
const availability = threadAvailability(
|
||||
node?.thread ?? null,
|
||||
node?.missing ?? true,
|
||||
);
|
||||
const archivedThread = availability === "Archived";
|
||||
const disabled = availability === "Unavailable" || availability === "Deleted";
|
||||
return (
|
||||
<Pressable
|
||||
key={`${edge.kind}:${threadId}`}
|
||||
accessibilityRole={disabled ? undefined : "link"}
|
||||
accessibilityState={{ disabled }}
|
||||
disabled={disabled}
|
||||
onPress={() => openThread(threadId, archivedThread)}
|
||||
className="min-h-14 flex-row items-center gap-3 rounded-2xl border border-neutral-300/50 bg-card px-3 py-2.5 dark:border-white/[0.08]"
|
||||
>
|
||||
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/60 dark:bg-white/[0.06]">
|
||||
<SymbolView
|
||||
name={relationshipSymbol(edge)}
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-3xs uppercase tracking-wide text-foreground-muted">
|
||||
{relationshipLabel(edge, props.threadId)}
|
||||
</Text>
|
||||
<Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
|
||||
{node?.thread?.title ?? threadId}
|
||||
</Text>
|
||||
</View>
|
||||
{availability ? (
|
||||
<Text className="text-2xs text-foreground-muted">{availability}</Text>
|
||||
) : (
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={12}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
|
||||
{canMerge || canDetach ? (
|
||||
<View className="mt-4 gap-2 border-t border-neutral-300/50 pt-4 dark:border-white/[0.08]">
|
||||
{canMerge ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={busyAction !== null}
|
||||
onPress={() => void merge()}
|
||||
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl bg-primary px-3"
|
||||
>
|
||||
{busyAction === "merge" ? (
|
||||
<ActivityIndicator color="white" />
|
||||
) : (
|
||||
<SymbolView name="arrow.triangle.merge" size={14} tintColor="white" />
|
||||
)}
|
||||
<Text className="font-t3-medium text-sm text-primary-foreground">
|
||||
Merge back to source
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{canDetach ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={busyAction !== null}
|
||||
onPress={() => void detach()}
|
||||
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl border border-neutral-300/60 px-3 dark:border-white/[0.1]"
|
||||
>
|
||||
{busyAction === "detach" ? <ActivityIndicator /> : null}
|
||||
<Text className="font-t3-medium text-sm text-foreground">
|
||||
Disconnect agent session
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -307,7 +307,7 @@ function ThreadRouteContent(
|
||||
}),
|
||||
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
|
||||
);
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
|
||||
const handleReconnectEnvironment = useCallback(() => {
|
||||
if (!environmentId) {
|
||||
return;
|
||||
@@ -461,23 +461,17 @@ function ThreadRouteContent(
|
||||
void navigation.navigate("Connections");
|
||||
}, [navigation]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
(selectedThread.session?.status !== "running" &&
|
||||
selectedThread.session?.status !== "starting")
|
||||
) {
|
||||
if (!selectedThread || composer.interruptibleRunId === null) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
...(selectedThread.session.activeTurnId
|
||||
? { turnId: selectedThread.session.activeTurnId }
|
||||
: {}),
|
||||
runId: composer.interruptibleRunId,
|
||||
},
|
||||
});
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
}, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
|
||||
|
||||
const handleOpenTerminal = useCallback(
|
||||
(nextTerminalId?: string | null) => {
|
||||
@@ -755,6 +749,7 @@ function ThreadRouteContent(
|
||||
connectionError={routeConnectionError}
|
||||
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
activityRun={composer.selectedThreadActivityRun}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
@@ -767,6 +762,7 @@ function ThreadRouteContent(
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
canStopThread={composer.interruptibleRunId !== null}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
|
||||
@@ -22,7 +22,11 @@ import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../
|
||||
import type { TurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import {
|
||||
buildModelOptions,
|
||||
groupByProvider,
|
||||
resolveSelectableModelSelection,
|
||||
} from "../../lib/modelOptions";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
@@ -347,7 +351,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
// The server's configured default decides the mode until the user picks one
|
||||
// explicitly — same resolution web uses for new draft threads.
|
||||
const defaultWorkspaceMode: WorkspaceMode =
|
||||
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
// Keep the user's explicit choice separate from the resolved display value:
|
||||
@@ -361,22 +369,29 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
// Stored selections (draft and project default) only count while their
|
||||
// provider is usable on the server; otherwise the server's default model
|
||||
// wins instead of silently targeting a disabled provider.
|
||||
const draftModelSelection = resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? null,
|
||||
);
|
||||
const projectDefaultModelSelection = resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
);
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
draftModelSelection ?? projectDefaultModelSelection,
|
||||
),
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
[selectedEnvironmentServerConfig, draftModelSelection, projectDefaultModelSelection],
|
||||
);
|
||||
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
draftModelSelection ??
|
||||
projectDefaultModelSelection ??
|
||||
modelOptions.find((option) => option.isDefault)?.selection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
@@ -675,12 +690,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
|
||||
const text = draft.text.trim();
|
||||
const draftModelSelection = draft.modelSelection ?? selectedModel;
|
||||
// Same availability gate the composer display applies: a stored
|
||||
// selection targeting a disabled provider must not ride into the queue.
|
||||
const draftModelSelection =
|
||||
resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
draft.modelSelection ?? null,
|
||||
) ?? selectedModel;
|
||||
if (text.length === 0 || !draftModelSelection) {
|
||||
return null;
|
||||
}
|
||||
const workspaceSelection = draft.workspaceSelection;
|
||||
const mode = workspaceSelection?.mode ?? "local";
|
||||
// Fall back to the resolved mode (server default) so queued tasks drain
|
||||
// with the same mode the composer displayed.
|
||||
const mode = workspaceSelection?.mode ?? workspaceMode;
|
||||
// When the selection is the stand-in built from the queued snapshot,
|
||||
// persist the original (possibly absent) snapshot values — the
|
||||
// stand-in's placeholder title/workspaceRoot must never be written back
|
||||
@@ -722,10 +745,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
[
|
||||
editingPendingProject,
|
||||
editingPendingTask,
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
startFromOrigin,
|
||||
workspaceMode,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { ReactNode } from "react";
|
||||
import { Platform, useColorScheme } from "react-native";
|
||||
|
||||
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
|
||||
|
||||
@@ -35,10 +36,9 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? { backgroundColor: "transparent" } : undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
...getCompactBrandHeaderOptions({ fontSize: 18, fontWeight: "800" }),
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? SCROLL_EDGE_EFFECTS : undefined,
|
||||
title: "Threads",
|
||||
unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined,
|
||||
};
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
@@ -33,7 +34,7 @@ import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
export type ThreadListVariant = "compact" | "sidebar";
|
||||
|
||||
/** Left inset that aligns compact secondary rows with the title column. */
|
||||
export const THREAD_LIST_COMPACT_INSET = 20;
|
||||
export const THREAD_LIST_COMPACT_INSET = HOME_HORIZONTAL_INSET;
|
||||
const SIDEBAR_ROW_RADIUS = 12;
|
||||
|
||||
function pullRequestTintColor(
|
||||
|
||||
@@ -3,11 +3,20 @@ import type {
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
|
||||
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Platform,
|
||||
Pressable,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
@@ -18,7 +27,14 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
|
||||
import {
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
threadHasUnseenCompletion,
|
||||
type ThreadListV2Status,
|
||||
} from "./threadListV2";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
|
||||
/**
|
||||
@@ -62,6 +78,11 @@ const SLIM_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
const SNOOZED_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "unsnooze", title: "Wake thread", image: "clock" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
// Pre-settlement servers: no lifecycle items, archive fills the gap.
|
||||
const LEGACY_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
@@ -90,6 +111,81 @@ export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivid
|
||||
);
|
||||
});
|
||||
|
||||
const SNOOZE_ACCENT_LIGHT = "#2563eb";
|
||||
const SNOOZE_ACCENT_DARK = "#60a5fa";
|
||||
|
||||
export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader(props: {
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint={
|
||||
props.expanded ? "Collapses the snoozed threads." : "Expands the snoozed threads."
|
||||
}
|
||||
accessibilityLabel={props.count === 1 ? "1 snoozed thread" : `${props.count} snoozed threads`}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
onPress={props.onToggle}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-blue-600 dark:text-blue-400">
|
||||
{props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
|
||||
</Text>
|
||||
<View className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={colorScheme === "dark" ? SNOOZE_ACCENT_DARK : SNOOZE_ACCENT_LIGHT}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadListV2SettledShelfHeader = memo(function ThreadListV2SettledShelfHeader(props: {
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
}) {
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint={
|
||||
props.expanded ? "Collapses the settled threads." : "Expands the settled threads."
|
||||
}
|
||||
accessibilityLabel={props.count === 1 ? "1 settled thread" : `${props.count} settled threads`}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
onPress={props.onToggle}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">
|
||||
{props.expanded ? "Settled" : `Settled (${props.count})`}
|
||||
</Text>
|
||||
<View className="h-px flex-1 bg-border" />
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={mutedColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
@@ -208,7 +304,14 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
/** Snoozed-shelf row: shows its wake time and offers Wake. */
|
||||
readonly snoozed?: boolean;
|
||||
/** Preformatted against the parent minute tick so this memoized row's
|
||||
countdown keeps moving. */
|
||||
readonly snoozeWakeLabelText?: string;
|
||||
/** Parent minute tick passed as a prop so this memoized row refreshes its
|
||||
native snooze menu while mounted. */
|
||||
readonly snoozePresetMinute: string;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly providerDriver: string | null;
|
||||
@@ -231,11 +334,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** False on environments whose server predates thread.settle/unsettle:
|
||||
swipe + menu fall back to Archive instead of failing on use. */
|
||||
readonly settlementSupported: boolean;
|
||||
/** False on servers that predate thread.snooze/unsnooze. */
|
||||
readonly snoozeSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
@@ -258,10 +365,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
@@ -278,32 +388,105 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
// "Done" marks a completion the user has not opened yet — same emerald
|
||||
// label as the web sidebar, sourced from the server-side visited watermark
|
||||
// so checking a thread on any device clears it everywhere.
|
||||
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
|
||||
const statusLabel =
|
||||
STATUS_LABEL_BY_STATUS[status] ??
|
||||
(isUnread ? { label: "Done", className: "text-emerald-700 dark:text-emerald-300" } : undefined);
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleSnooze = useCallback(
|
||||
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
|
||||
[onSnoozeThread, thread],
|
||||
);
|
||||
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle],
|
||||
);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
// row can un-settle — explicit settles clear the override, auto-settled
|
||||
// rows get pinned active until real activity clears the pin.
|
||||
const canUnsettle = variant === "slim";
|
||||
const [snoozeGateTick, bumpSnoozeGateTick] = useState(0);
|
||||
const snoozeGateExpiryMs = props.snoozeSupported
|
||||
? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: new Date().toISOString() })
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (snoozeGateExpiryMs === null) return;
|
||||
const delayMs = Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeGateTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
}, [snoozeGateExpiryMs, snoozeGateTick]);
|
||||
const swipeActions = resolveThreadListV2SwipeActions({
|
||||
variant,
|
||||
settlementSupported: props.settlementSupported,
|
||||
snoozeSupported: props.snoozeSupported,
|
||||
snoozable: canSnooze(thread, { now: new Date().toISOString() }),
|
||||
snoozed: snoozedRow,
|
||||
});
|
||||
const snoozePresets = useMemo(
|
||||
() => (swipeActions.secondary === "snooze" ? resolveSnoozePresets(new Date()) : ([] as const)),
|
||||
[props.snoozePresetMinute, swipeActions.secondary],
|
||||
);
|
||||
const snoozePresetActions = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
snoozePresets.map((preset) => ({
|
||||
id: `snooze:${preset.id}`,
|
||||
title: preset.label,
|
||||
subtitle: preset.whenLabel,
|
||||
})),
|
||||
[snoozePresets],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{
|
||||
id: "snooze",
|
||||
title: "Snooze",
|
||||
image: "clock",
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[snoozePresetActions],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "unsnooze") handleUnsnooze();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: nativeEvent.event,
|
||||
displayedPresets: snoozePresets,
|
||||
now: new Date(),
|
||||
});
|
||||
if (snoozeSelection._tag === "selected") {
|
||||
handleSnooze(snoozeSelection.preset.snoozedUntil);
|
||||
} else if (snoozeSelection._tag === "expired") {
|
||||
Alert.alert("Could not snooze thread", "That snooze time has passed. Choose another time.");
|
||||
}
|
||||
},
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
handleUnsettle,
|
||||
handleUnsnooze,
|
||||
snoozePresets,
|
||||
],
|
||||
);
|
||||
const primaryAction = useMemo(() => {
|
||||
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
|
||||
// rows cannot occur here — unsupported environments never classify as
|
||||
// settled.)
|
||||
if (!props.settlementSupported) {
|
||||
if (swipeActions.primary === "archive") {
|
||||
return {
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
icon: "archivebox" as const,
|
||||
@@ -311,7 +494,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onPress: handleArchive,
|
||||
};
|
||||
}
|
||||
return canUnsettle
|
||||
if (swipeActions.primary === "unsnooze") {
|
||||
return {
|
||||
accessibilityLabel: `Wake ${thread.title} now`,
|
||||
icon: "clock" as const,
|
||||
label: "Wake",
|
||||
onPress: handleUnsnooze,
|
||||
};
|
||||
}
|
||||
return swipeActions.primary === "unsettle"
|
||||
? {
|
||||
accessibilityLabel: `Un-settle ${thread.title}`,
|
||||
icon: "arrow.uturn.backward" as const,
|
||||
@@ -325,13 +516,34 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onPress: handleSettle,
|
||||
};
|
||||
}, [
|
||||
canUnsettle,
|
||||
handleArchive,
|
||||
handleSettle,
|
||||
handleUnsettle,
|
||||
props.settlementSupported,
|
||||
handleUnsnooze,
|
||||
swipeActions.primary,
|
||||
thread.title,
|
||||
]);
|
||||
const secondaryAction = useMemo(
|
||||
() =>
|
||||
swipeActions.secondary === "snooze"
|
||||
? {
|
||||
accessibilityLabel: `Choose when to snooze ${thread.title}`,
|
||||
icon: "clock" as const,
|
||||
label: "Snooze",
|
||||
menu: {
|
||||
actions: snoozePresetActions,
|
||||
onPressAction: handleMenuAction,
|
||||
title: "Snooze until",
|
||||
},
|
||||
onPress: () => undefined,
|
||||
}
|
||||
: null,
|
||||
[handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title],
|
||||
);
|
||||
const swipeAccessibilityHint =
|
||||
secondaryAction === null
|
||||
? `Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`
|
||||
: `Opens the thread. Swipe left for ${primaryAction.label.toLowerCase()} and snooze actions.`;
|
||||
|
||||
// The sidebar pane fills selected rows with the accent color (matching the
|
||||
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
|
||||
@@ -383,7 +595,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</View>
|
||||
) : null}
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
{status === "failed" && thread.runtime?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
@@ -393,7 +605,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
{thread.runtime.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
/* "branch · machine" share one truncating line. The machine sits
|
||||
@@ -453,7 +665,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const rowContent = (close: () => void) =>
|
||||
variant === "card" ? (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityHint={swipeAccessibilityHint}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
@@ -491,7 +703,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</Pressable>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityHint={swipeAccessibilityHint}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
@@ -551,11 +763,17 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<Text
|
||||
className={cn(
|
||||
"text-sm tabular-nums",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: snoozedRow
|
||||
? "text-blue-600 dark:text-blue-400"
|
||||
: "text-foreground-tertiary",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
{snoozedRow && props.snoozeWakeLabelText !== undefined
|
||||
? props.snoozeWakeLabelText
|
||||
: relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
@@ -563,9 +781,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showSettledDivider ? (
|
||||
<ThreadListV2SectionDivider label="Settled" pane={props.pane} />
|
||||
) : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={sidebarPane ? drawerColor : screenColor}
|
||||
compactActions={variant === "slim"}
|
||||
@@ -574,13 +789,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
}
|
||||
enableTrackpadSwipe
|
||||
// Full swipe commits the advertised lifecycle action (Settle /
|
||||
// Un-settle), never the destructive delete.
|
||||
// Un-settle), never the secondary snooze action.
|
||||
fullSwipeAction="primary"
|
||||
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
|
||||
onDelete={handleDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={primaryAction}
|
||||
secondaryAction={secondaryAction}
|
||||
resetKey={`${thread.environmentId}:${thread.id}`}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={thread.title}
|
||||
@@ -588,11 +804,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{(close) => (
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
!props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: CARD_MENU_ACTIONS
|
||||
snoozedRow
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
: !props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: CARD_MENU_ACTIONS
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
||||
|
||||
describe("thread work log overflow labels", () => {
|
||||
it("describes tool-only groups as tool calls", () => {
|
||||
expect(threadWorkLogOverflowNoun(true, 1)).toBe("tool call");
|
||||
expect(threadWorkLogOverflowNoun(true, 2)).toBe("tool calls");
|
||||
});
|
||||
|
||||
it("describes mixed groups as log entries", () => {
|
||||
expect(threadWorkLogOverflowNoun(false, 1)).toBe("log entry");
|
||||
expect(threadWorkLogOverflowNoun(false, 2)).toBe("log entries");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
export function threadWorkLogOverflowNoun(
|
||||
onlyToolRows: boolean,
|
||||
count: number,
|
||||
): "tool call" | "tool calls" | "log entry" | "log entries" {
|
||||
if (onlyToolRows) {
|
||||
return count === 1 ? "tool call" : "tool calls";
|
||||
}
|
||||
return count === 1 ? "log entry" : "log entries";
|
||||
}
|
||||
@@ -1,14 +1,22 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Image } from "expo-image";
|
||||
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
|
||||
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import Animated, { FadeIn } from "react-native-reanimated";
|
||||
import { useV2ItemSupport } from "../../state/v2-item-support";
|
||||
import { ThreadActivityInspector } from "./ThreadActivityInspector";
|
||||
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
create: {
|
||||
@@ -71,6 +79,87 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
|
||||
}
|
||||
}
|
||||
|
||||
function WorkRowIcon(props: {
|
||||
readonly row: ThreadFeedActivity;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
}) {
|
||||
const iconIsDestructive = props.row.icon === "alert" || props.row.icon === "warning";
|
||||
if (props.row.logo === "t3-code") {
|
||||
return (
|
||||
<Image
|
||||
source={T3_CODE_BRAND_MARK_SOURCE}
|
||||
accessibilityIgnoresInvertColors
|
||||
style={{
|
||||
width: 16,
|
||||
height: 16,
|
||||
borderRadius: 4,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SymbolView
|
||||
name={workRowSymbolName(props.row.icon)}
|
||||
size={14}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadActivityThreadLink(props: {
|
||||
readonly activity: ThreadFeedActivity;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly iconColor: import("react-native").ColorValue;
|
||||
}) {
|
||||
const row = props.activity.projectedItem;
|
||||
const support = useV2ItemSupport({
|
||||
environmentId: props.environmentId,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
});
|
||||
const navigation = useNavigation();
|
||||
const item = row.item;
|
||||
let targetThreadId: ThreadId | null = null;
|
||||
let label = "Open related thread";
|
||||
|
||||
if (item.type === "thread_created") {
|
||||
targetThreadId = item.targetThreadId;
|
||||
label = "Open created thread";
|
||||
} else if (item.type === "subagent") {
|
||||
targetThreadId = support.subagent?.childThreadId ?? item.childThreadId;
|
||||
label = "Open subagent thread";
|
||||
} else if (item.type === "fork") {
|
||||
targetThreadId =
|
||||
item.targetThreadId === row.sourceThreadId && item.source.type === "run"
|
||||
? item.source.threadId
|
||||
: item.targetThreadId;
|
||||
label = targetThreadId === item.targetThreadId ? "Open forked thread" : "Open parent thread";
|
||||
}
|
||||
|
||||
if (targetThreadId === null) return null;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
accessibilityLabel={label}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: props.environmentId,
|
||||
threadId: targetThreadId,
|
||||
});
|
||||
}}
|
||||
className="mx-2 mb-2 min-h-9 flex-row items-center justify-center gap-1.5 rounded-lg border border-neutral-300/50 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
<Text className="font-t3-medium text-2xs text-foreground">{label}</Text>
|
||||
<SymbolView name="arrow.right" size={11} tintColor={props.iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
// Entering fades only for rows created moments ago: rows remount whenever the
|
||||
// list scrolls them back into view, and old rows must not replay an entrance.
|
||||
const FRESH_ROW_WINDOW_MS = 3_000;
|
||||
@@ -122,10 +211,15 @@ export function collapsedWorkLogHeight(
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly expanded: boolean;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleGroup: () => void;
|
||||
readonly onToggleRow: (rowId: string) => void;
|
||||
readonly workspaceRoot?: string | null;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
@@ -138,10 +232,15 @@ export function ThreadWorkLog(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows =
|
||||
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
work log
|
||||
@@ -149,17 +248,21 @@ export function ThreadWorkLog(props: {
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{rows.map((row) => {
|
||||
{visibleRows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.canExpand;
|
||||
const fullDetail = expanded ? row.getFullDetail() : null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
const detail = compactActivityDetail(row.detail);
|
||||
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
|
||||
const textIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
key={row.id}
|
||||
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
|
||||
className={cn(
|
||||
row.prominent &&
|
||||
"mb-2 overflow-hidden rounded-xl border border-neutral-300/60 bg-card dark:border-white/[0.1]",
|
||||
)}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole={canExpand ? "button" : undefined}
|
||||
@@ -181,30 +284,24 @@ export function ThreadWorkLog(props: {
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0"
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="min-h-8 flex-row items-center gap-1.5">
|
||||
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
|
||||
<SymbolView
|
||||
name={workRowSymbolName(row.icon)}
|
||||
size={13}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||
<WorkRowIcon row={row} iconSubtleColor={props.iconSubtleColor} />
|
||||
</View>
|
||||
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-foreground",
|
||||
iconIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
textIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
)}
|
||||
>
|
||||
{row.summary}
|
||||
</Text>
|
||||
{row.detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
|
||||
{detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {detail}</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
|
||||
@@ -248,28 +345,63 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
{fullDetail ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
className="max-h-60"
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="font-mono text-2xs leading-normal text-foreground-muted"
|
||||
>
|
||||
{fullDetail}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
{expanded && canExpand ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ThreadActivityInspector
|
||||
activity={row}
|
||||
currentThreadId={props.currentThreadId}
|
||||
environmentId={props.environmentId}
|
||||
iconColor={props.iconSubtleColor}
|
||||
workspaceRoot={props.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
{row.prominent ? (
|
||||
<ThreadActivityThreadLink
|
||||
activity={row}
|
||||
environmentId={props.environmentId}
|
||||
iconColor={props.iconSubtleColor}
|
||||
/>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded
|
||||
? `Show fewer ${overflowNoun}`
|
||||
: `Show ${hiddenCount} previous ${overflowNoun}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleGroup();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="h-5 w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={13}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded
|
||||
? `Show fewer ${overflowNoun}`
|
||||
: `+${hiddenCount} previous ${overflowNoun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -283,48 +415,36 @@ export function ThreadWorkGroupToggle(props: {
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const noun = props.onlyToolActivities
|
||||
? props.hiddenCount === 1
|
||||
? "tool call"
|
||||
: "tool calls"
|
||||
: props.hiddenCount === 1
|
||||
? "log entry"
|
||||
: "log entries";
|
||||
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
|
||||
const expandedLabel = props.onlyToolActivities
|
||||
? "Show fewer tool calls"
|
||||
: "Show fewer log entries";
|
||||
const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-1 px-1">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
||||
accessibilityLabel={
|
||||
props.expanded ? `Show fewer ${noun}` : `Show ${props.hiddenCount} previous ${noun}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggle();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5"
|
||||
>
|
||||
<View className="h-[18px] w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={
|
||||
props.expanded
|
||||
? { ios: "chevron.up", android: "keyboard_arrow_up" }
|
||||
: { ios: "chevron.down", android: "keyboard_arrow_down" }
|
||||
}
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={12}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
||||
{props.expanded ? `Show fewer ${noun}` : `+${props.hiddenCount} previous ${noun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
|
||||
|
||||
describe("thread activity file navigation", () => {
|
||||
it("keeps inherited activity file links on the currently selected thread", () => {
|
||||
const sourceThreadId = ThreadId.make("source-thread");
|
||||
const currentThreadId = ThreadId.make("current-thread");
|
||||
|
||||
const params = buildThreadActivityFileParams({
|
||||
environmentId: EnvironmentId.make("environment"),
|
||||
currentThreadId,
|
||||
activitySourceThreadId: sourceThreadId,
|
||||
relativePath: "apps/mobile/src/index.ts",
|
||||
line: 12,
|
||||
});
|
||||
|
||||
expect(params).toEqual({
|
||||
environmentId: "environment",
|
||||
threadId: "current-thread",
|
||||
path: ["apps", "mobile", "src", "index.ts"],
|
||||
line: "12",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
interface ThreadActivityFileContext {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly activitySourceThreadId: ThreadId;
|
||||
readonly relativePath: string;
|
||||
readonly line?: number | null;
|
||||
}
|
||||
|
||||
export function buildThreadActivityFileParams(input: ThreadActivityFileContext) {
|
||||
// Activity provenance may come from a parent thread, but file routes stay scoped
|
||||
// to the thread whose workspace is currently selected.
|
||||
return {
|
||||
environmentId: String(input.environmentId),
|
||||
threadId: String(input.currentThreadId),
|
||||
path: input.relativePath.split("/").filter((segment) => segment.length > 0),
|
||||
...(Number.isFinite(input.line) && Number(input.line) > 0
|
||||
? { line: String(Math.floor(Number(input.line))) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { waitForThreadShellReady } from "./threadForkNavigation";
|
||||
|
||||
describe("waitForThreadShellReady", () => {
|
||||
it("returns true when the forked thread shell arrives before the deadline", async () => {
|
||||
let elapsedMs = 0;
|
||||
|
||||
const ready = await waitForThreadShellReady({
|
||||
read: () => elapsedMs >= 80,
|
||||
timeoutMs: 120,
|
||||
pollIntervalMs: 40,
|
||||
now: () => elapsedMs,
|
||||
delay: async (durationMs) => {
|
||||
elapsedMs += durationMs;
|
||||
},
|
||||
});
|
||||
|
||||
expect(ready).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false instead of navigating when the shell never arrives", async () => {
|
||||
let elapsedMs = 0;
|
||||
|
||||
const ready = await waitForThreadShellReady({
|
||||
read: () => false,
|
||||
timeoutMs: 80,
|
||||
pollIntervalMs: 40,
|
||||
now: () => elapsedMs,
|
||||
delay: async (durationMs) => {
|
||||
elapsedMs += durationMs;
|
||||
},
|
||||
});
|
||||
|
||||
expect(ready).toBe(false);
|
||||
expect(elapsedMs).toBe(80);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
const DEFAULT_TIMEOUT_MS = 2_000;
|
||||
const DEFAULT_POLL_INTERVAL_MS = 40;
|
||||
|
||||
export async function waitForThreadShellReady(input: {
|
||||
readonly read: () => boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly pollIntervalMs?: number;
|
||||
readonly now?: () => number;
|
||||
readonly delay?: (durationMs: number) => Promise<void>;
|
||||
}): Promise<boolean> {
|
||||
const now = input.now ?? Date.now;
|
||||
const delay =
|
||||
input.delay ??
|
||||
((durationMs: number) =>
|
||||
new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, durationMs);
|
||||
}));
|
||||
const deadline = now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
||||
const pollIntervalMs = input.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
||||
|
||||
while (!input.read() && now() < deadline) {
|
||||
await delay(Math.min(pollIntervalMs, deadline - now()));
|
||||
}
|
||||
|
||||
return input.read();
|
||||
}
|
||||
@@ -1,22 +1,27 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import { resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
resolveThreadListV2Enabled,
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
|
||||
@@ -25,31 +30,62 @@ const environmentId = EnvironmentId.make("environment-1");
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
environmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
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: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2SnoozeMenuSelection", () => {
|
||||
it("accepts a displayed evening preset while its wake time is still future", () => {
|
||||
const menuOpenedAt = new Date(2026, 4, 8, 16, 59, 30);
|
||||
const selectedAt = new Date(2026, 4, 8, 17, 0, 30);
|
||||
const displayedPresets = resolveSnoozePresets(menuOpenedAt);
|
||||
|
||||
const selection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: "snooze:evening",
|
||||
displayedPresets,
|
||||
now: selectedAt,
|
||||
});
|
||||
|
||||
expect(selection).toEqual({
|
||||
_tag: "selected",
|
||||
preset: displayedPresets.find((preset) => preset.id === "evening"),
|
||||
});
|
||||
});
|
||||
|
||||
it("expires a displayed preset once its wake time has passed", () => {
|
||||
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 16, 59, 30));
|
||||
|
||||
expect(
|
||||
resolveThreadListV2SnoozeMenuSelection({
|
||||
event: "snooze:evening",
|
||||
displayedPresets,
|
||||
now: new Date(2026, 4, 8, 18, 0, 1),
|
||||
}),
|
||||
).toEqual({ _tag: "expired" });
|
||||
});
|
||||
|
||||
it("recomputes presets that remain available instead of using old timestamps", () => {
|
||||
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 10));
|
||||
const selectedAt = new Date(2026, 4, 8, 10, 30);
|
||||
const selection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: "snooze:hour",
|
||||
displayedPresets,
|
||||
now: selectedAt,
|
||||
});
|
||||
|
||||
expect(selection._tag).toBe("selected");
|
||||
if (selection._tag === "selected") {
|
||||
expect(selection.preset.snoozedUntil).toBe(
|
||||
new Date(selectedAt.getTime() + 60 * 60 * 1_000).toISOString(),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2Enabled", () => {
|
||||
it("defaults on when the device has never chosen", () => {
|
||||
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
|
||||
@@ -70,18 +106,16 @@ describe("resolveThreadListV2Enabled", () => {
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
it("prioritizes approval over a running runtime", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
runtime: {
|
||||
status: "running",
|
||||
activeRunId: RunId.make("run-t"),
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
@@ -96,6 +130,105 @@ describe("resolveThreadListV2Status", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2SwipeActions", () => {
|
||||
it("offers settle and snooze for an active snoozable thread", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: "snooze" });
|
||||
});
|
||||
|
||||
it("offers un-settle and snooze for settled history", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "slim",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "unsettle", secondary: "snooze" });
|
||||
});
|
||||
|
||||
it("omits snooze when the server or thread does not allow it", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: false,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: null });
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: false,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: null });
|
||||
});
|
||||
|
||||
it("falls back to archive only for a pre-lifecycle server", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: false,
|
||||
snoozeSupported: false,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "archive", secondary: null });
|
||||
});
|
||||
|
||||
it("offers wake and no snooze on a snoozed row", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "slim",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
snoozed: true,
|
||||
}),
|
||||
).toEqual({ primary: "unsnooze", secondary: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2SnoozeGateExpiryMs", () => {
|
||||
it("reports when an unadopted turn's grace window lapses", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
latestUserMessageAt: "2026-06-02T00:00:30.000Z",
|
||||
});
|
||||
expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: "2026-06-02T00:01:00.000Z" })).toBe(
|
||||
Date.parse("2026-06-02T00:02:30.000Z"),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null once the thread is snoozable or when only data can unblock it", () => {
|
||||
expect(
|
||||
resolveThreadListV2SnoozeGateExpiryMs(
|
||||
makeThread({ id: ThreadId.make("ready"), title: "Ready" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(null);
|
||||
expect(
|
||||
resolveThreadListV2SnoozeGateExpiryMs(
|
||||
makeThread({
|
||||
id: ThreadId.make("blocked"),
|
||||
title: "Blocked",
|
||||
hasPendingApprovals: true,
|
||||
latestUserMessageAt: NOW,
|
||||
}),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForListV2([
|
||||
@@ -108,6 +241,68 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("excludes subagent child threads from top-level rows and counts", () => {
|
||||
const rootThreadId = ThreadId.make("root");
|
||||
const activeChildId = ThreadId.make("active-child");
|
||||
const forkId = ThreadId.make("fork");
|
||||
const settledChildId = ThreadId.make("settled-child");
|
||||
const snoozedChildId = ThreadId.make("snoozed-child");
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: rootThreadId, title: "Root" }),
|
||||
makeThread({
|
||||
id: forkId,
|
||||
title: "Fork",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "fork",
|
||||
},
|
||||
}),
|
||||
makeThread({
|
||||
id: activeChildId,
|
||||
title: "Active child",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "subagent",
|
||||
},
|
||||
}),
|
||||
makeThread({
|
||||
id: settledChildId,
|
||||
title: "Settled child",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "subagent",
|
||||
},
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: snoozedChildId,
|
||||
title: "Snoozed child",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "subagent",
|
||||
},
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
settledLimit: 0,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([forkId, rootThreadId]);
|
||||
expect(layout.hiddenSettledCount).toBe(0);
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
expect(layout.nextSnoozeWakeAt).toBeNull();
|
||||
});
|
||||
|
||||
it("hides snoozed threads and counts them — visibility parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
@@ -167,6 +362,93 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("builds snoozed rows between active and settled when the shelf is expanded", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("later"),
|
||||
title: "Wakes later",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("sooner"),
|
||||
title: "Wakes sooner",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
snoozedShelfExpanded: true,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([
|
||||
"active",
|
||||
"sooner",
|
||||
"later",
|
||||
"settled",
|
||||
]);
|
||||
expect(layout.items.map((item) => item.snoozed)).toEqual([false, true, true, false]);
|
||||
expect(layout.snoozedShelfHeaderIndex).toBe(1);
|
||||
expect(layout.snoozedCount).toBe(2);
|
||||
});
|
||||
|
||||
it("collapses to a header-only shelf", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items).toEqual([]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
expect(layout.snoozedShelfHeaderIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps the selected thread on a collapsed shelf", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("open"),
|
||||
title: "Open",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("other"),
|
||||
title: "Other",
|
||||
snoozedUntil: "2026-06-03T10:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
selectedThreadKey: `${environmentId}:open`,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["open"]);
|
||||
expect(layout.items[0]?.snoozed).toBe(true);
|
||||
expect(layout.snoozedCount).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
@@ -187,8 +469,8 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
it("partitions settled threads into a slim shelf", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
@@ -209,13 +491,64 @@ describe("buildThreadListV2Items", () => {
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["active", "card"],
|
||||
["settled", "slim"],
|
||||
["settled-2", "slim"],
|
||||
]);
|
||||
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
|
||||
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
expect(layout.items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
expect(layout.settledCount).toBe(2);
|
||||
expect(layout.settledShelfHeaderIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("collapses settled threads to a counted shelf header", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
settledShelfExpanded: false,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["active"]);
|
||||
expect(layout.settledCount).toBe(1);
|
||||
expect(layout.settledShelfHeaderIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps the selected settled thread visible when its shelf is collapsed", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("selected"),
|
||||
title: "Selected",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("other"),
|
||||
title: "Other",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
settledShelfExpanded: false,
|
||||
selectedThreadKey: `${environmentId}:selected`,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["selected"]);
|
||||
expect(layout.settledCount).toBe(2);
|
||||
expect(layout.settledShelfHeaderIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps cards in creation order while settled sorts by recency", () => {
|
||||
@@ -286,10 +619,11 @@ describe("buildThreadListV2Items", () => {
|
||||
});
|
||||
|
||||
it("scopes the flat list to one project", () => {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const otherProjectId = ProjectId.make("project-2");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("included"), title: "Included" }),
|
||||
makeThread({ id: ThreadId.make("included"), projectId, title: "Included" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("excluded"),
|
||||
projectId: otherProjectId,
|
||||
@@ -297,7 +631,7 @@ describe("buildThreadListV2Items", () => {
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
||||
projectRefs: [{ environmentId, projectId }],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
@@ -307,19 +641,21 @@ describe("buildThreadListV2Items", () => {
|
||||
|
||||
it("scopes the flat list to every environment member of a logical project", () => {
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
||||
makeThread({ id: ThreadId.make("local"), projectId, title: "Local" }),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("remote"),
|
||||
projectId,
|
||||
title: "Remote",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [
|
||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId, projectId },
|
||||
{ environmentId: remoteEnvironmentId, projectId },
|
||||
],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
@@ -342,9 +678,9 @@ describe("buildThreadListV2Items settled paging", () => {
|
||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
// A turn adopted the message (same requestedAt): without it the
|
||||
// thread reads as a queued turn start, which never settles.
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${index}`),
|
||||
state: "completed",
|
||||
latestRun: {
|
||||
runId: RunId.make(`run-${index}`),
|
||||
status: "completed",
|
||||
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||
@@ -420,13 +756,21 @@ describe("buildThreadListV2ListItems", () => {
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: layout.items,
|
||||
pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
|
||||
settledCount: layout.settledCount,
|
||||
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
|
||||
});
|
||||
|
||||
expect(
|
||||
items.map((item) =>
|
||||
item.type === "v2-pending" ? item.pendingTask.title : item.item.thread.id,
|
||||
item.type === "v2-pending"
|
||||
? item.pendingTask.title
|
||||
: item.type === "v2-thread"
|
||||
? item.item.thread.id
|
||||
: item.type === "v2-snoozed-shelf"
|
||||
? "snoozed-shelf"
|
||||
: "settled-shelf",
|
||||
),
|
||||
).toEqual(["active", "queued-1", "queued-2", "settled"]);
|
||||
).toEqual(["active", "queued-1", "queued-2", "settled-shelf", "settled"]);
|
||||
// Only the leading queued row labels the section, exactly like Settled.
|
||||
expect(
|
||||
items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
|
||||
@@ -448,12 +792,58 @@ describe("buildThreadListV2ListItems", () => {
|
||||
expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
|
||||
});
|
||||
|
||||
it("leaves the thread order untouched when nothing is queued", () => {
|
||||
const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks: [] });
|
||||
it("keeps the settled shelf between active and settled rows when nothing is queued", () => {
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: layout.items,
|
||||
pendingTasks: [],
|
||||
settledCount: layout.settledCount,
|
||||
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual([
|
||||
`v2-thread:${environmentId}:active`,
|
||||
"v2-settled-shelf",
|
||||
`v2-thread:${environmentId}:settled`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("places queued tasks before a collapsed snoozed shelf", () => {
|
||||
const snoozedLayout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: snoozedLayout.items,
|
||||
pendingTasks: [makePendingTask("queued")],
|
||||
snoozedCount: snoozedLayout.snoozedCount,
|
||||
snoozedShelfExpanded: false,
|
||||
snoozedShelfHeaderIndex: snoozedLayout.snoozedShelfHeaderIndex,
|
||||
settledCount: snoozedLayout.settledCount,
|
||||
settledShelfHeaderIndex: snoozedLayout.settledShelfHeaderIndex,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.type)).toEqual([
|
||||
"v2-thread",
|
||||
"v2-pending",
|
||||
"v2-snoozed-shelf",
|
||||
"v2-settled-shelf",
|
||||
"v2-thread",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,20 @@
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
effectiveSettled,
|
||||
effectiveSnoozed,
|
||||
hasQueuedTurnStart,
|
||||
QUEUED_TURN_START_GRACE_MS,
|
||||
resolveSnoozePresets,
|
||||
snoozeWakeLabel,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export { snoozeWakeLabel };
|
||||
|
||||
/**
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
@@ -14,6 +24,76 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
* unlabeled resting state.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
|
||||
|
||||
export function resolveThreadListV2SnoozeMenuSelection(input: {
|
||||
readonly event: string;
|
||||
readonly displayedPresets: ReadonlyArray<SnoozePreset>;
|
||||
readonly now: Date;
|
||||
}):
|
||||
| { readonly _tag: "selected"; readonly preset: SnoozePreset }
|
||||
| { readonly _tag: "expired" }
|
||||
| { readonly _tag: "not-snooze" } {
|
||||
if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
|
||||
|
||||
const currentPreset = resolveSnoozePresets(input.now).find(
|
||||
(candidate) => input.event === `snooze:${candidate.id}`,
|
||||
);
|
||||
if (currentPreset) return { _tag: "selected", preset: currentPreset };
|
||||
|
||||
const displayedPreset = input.displayedPresets.find(
|
||||
(candidate) => input.event === `snooze:${candidate.id}`,
|
||||
);
|
||||
if (displayedPreset && Date.parse(displayedPreset.snoozedUntil) > input.now.getTime()) {
|
||||
return { _tag: "selected", preset: displayedPreset };
|
||||
}
|
||||
return { _tag: "expired" };
|
||||
}
|
||||
|
||||
export function resolveThreadListV2SwipeActions(input: {
|
||||
readonly variant: "card" | "slim";
|
||||
readonly settlementSupported: boolean;
|
||||
readonly snoozeSupported: boolean;
|
||||
readonly snoozable: boolean;
|
||||
/** Row is on the snoozed shelf. */
|
||||
readonly snoozed?: boolean;
|
||||
}): {
|
||||
readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
|
||||
readonly secondary: "snooze" | null;
|
||||
} {
|
||||
if (input.snoozed === true) {
|
||||
return { primary: "unsnooze", secondary: null };
|
||||
}
|
||||
const primary = input.settlementSupported
|
||||
? input.variant === "slim"
|
||||
? "unsettle"
|
||||
: "settle"
|
||||
: "archive";
|
||||
return {
|
||||
primary,
|
||||
secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The point at which a queued-turn snooze guard expires on its own. Rows arm
|
||||
* a one-shot timer for this boundary so Snooze appears without waiting for an
|
||||
* unrelated render. User-blocked threads return null because only fresh
|
||||
* server data can make them snoozable.
|
||||
*/
|
||||
export function resolveThreadListV2SnoozeGateExpiryMs(
|
||||
thread: Pick<
|
||||
EnvironmentThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestRun" | "latestUserMessageAt" | "runtime"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): number | null {
|
||||
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
|
||||
if (!hasQueuedTurnStart(thread, options)) return null;
|
||||
const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
|
||||
if (Number.isNaN(messageAtMs)) return null;
|
||||
return messageAtMs + QUEUED_TURN_START_GRACE_MS;
|
||||
}
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more. Shared by the compact Home list and
|
||||
@@ -41,8 +121,29 @@ export function resolveThreadListV2Enabled(input: {
|
||||
return input.preference ?? true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completed-but-not-yet-seen, mirroring the web sidebar's
|
||||
* hasUnseenCompletion. The visited watermark is server state
|
||||
* (thread.lastVisitedAt), so the marker agrees across web and mobile.
|
||||
* Never-visited threads count as read — a fresh environment must not light
|
||||
* up its whole history — and pre-tracking servers (field absent) never
|
||||
* report unread.
|
||||
*/
|
||||
export function threadHasUnseenCompletion(
|
||||
thread: Pick<EnvironmentThreadShell, "latestRun" | "lastVisitedAt">,
|
||||
): boolean {
|
||||
const completedAt = thread.latestRun?.completedAt;
|
||||
if (!completedAt) return false;
|
||||
const completedAtMs = Date.parse(completedAt);
|
||||
if (Number.isNaN(completedAtMs)) return false;
|
||||
if (!thread.lastVisitedAt) return false;
|
||||
const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
|
||||
if (Number.isNaN(lastVisitedAtMs)) return true;
|
||||
return completedAtMs > lastVisitedAtMs;
|
||||
}
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "runtime">,
|
||||
): ThreadListV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
@@ -50,10 +151,13 @@ export function resolveThreadListV2Status(
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "input";
|
||||
}
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
if (
|
||||
thread.runtime !== null &&
|
||||
["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
|
||||
) {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
if (thread.runtime?.status === "failed") {
|
||||
return "failed";
|
||||
}
|
||||
return "ready";
|
||||
@@ -98,8 +202,8 @@ export function sortThreadsForListV2<T extends { readonly id: string; readonly c
|
||||
export interface ThreadListV2Item {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
/** First settled row after the card block draws the SETTLED divider. */
|
||||
readonly showSettledDivider: boolean;
|
||||
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
|
||||
readonly snoozed: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
@@ -107,10 +211,16 @@ export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
/** Snoozed threads hidden from the list (visibility parity with web's
|
||||
collapsed Snoozed shelf; mobile has no shelf UI yet). */
|
||||
/** Snoozed threads matching the current filters. */
|
||||
readonly snoozedCount: number;
|
||||
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
|
||||
/** Index in `items` where the Snoozed shelf header belongs. The header is
|
||||
still rendered when the shelf is collapsed and no snoozed rows exist. */
|
||||
readonly snoozedShelfHeaderIndex: number | null;
|
||||
/** Total settled threads in scope, including rows hidden by collapse/paging. */
|
||||
readonly settledCount: number;
|
||||
/** Index in `items` where the Settled shelf header belongs. */
|
||||
readonly settledShelfHeaderIndex: number | null;
|
||||
/** Soonest wake time among snoozed threads, or null. Callers arm
|
||||
a timeout at this boundary so the list re-partitions the moment a
|
||||
snooze expires instead of on the next minute tick. */
|
||||
readonly nextSnoozeWakeAt: string | null;
|
||||
@@ -120,6 +230,8 @@ export interface ThreadListV2ThreadListItem {
|
||||
readonly type: "v2-thread";
|
||||
readonly key: string;
|
||||
readonly item: ThreadListV2Item;
|
||||
/** Precomputed so recycled-list equality can see a minute-tick change. */
|
||||
readonly snoozeWakeLabelText: string | undefined;
|
||||
}
|
||||
|
||||
export interface ThreadListV2PendingListItem {
|
||||
@@ -130,28 +242,53 @@ export interface ThreadListV2PendingListItem {
|
||||
readonly showPendingDivider: boolean;
|
||||
}
|
||||
|
||||
export type ThreadListV2ListItem = ThreadListV2ThreadListItem | ThreadListV2PendingListItem;
|
||||
export interface ThreadListV2SnoozedShelfListItem {
|
||||
readonly type: "v2-snoozed-shelf";
|
||||
readonly key: "v2-snoozed-shelf";
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadListV2SettledShelfListItem {
|
||||
readonly type: "v2-settled-shelf";
|
||||
readonly key: "v2-settled-shelf";
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
}
|
||||
|
||||
export type ThreadListV2ListItem =
|
||||
| ThreadListV2ThreadListItem
|
||||
| ThreadListV2PendingListItem
|
||||
| ThreadListV2SnoozedShelfListItem
|
||||
| ThreadListV2SettledShelfListItem;
|
||||
|
||||
/**
|
||||
* Splices queued tasks between the active block and the settled tail, so the
|
||||
* list reads active → pending → settled. Queued work sits below the live
|
||||
* threads because nothing can happen to it until its environment returns:
|
||||
* it is waiting, not asking. Shared by the compact Home list and the iPad
|
||||
* sidebar so both order and label the sections identically.
|
||||
* Builds the shared mobile order: active → pending → snoozed shelf → settled.
|
||||
* Pending tasks are waiting rather than asking, and parked work remains
|
||||
* reachable without competing with either the inbox or settled history.
|
||||
*/
|
||||
export function buildThreadListV2ListItems(input: {
|
||||
readonly items: ReadonlyArray<ThreadListV2Item>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly snoozedCount?: number;
|
||||
readonly snoozedShelfExpanded?: boolean;
|
||||
readonly snoozedShelfHeaderIndex?: number | null;
|
||||
readonly settledCount?: number;
|
||||
readonly settledShelfExpanded?: boolean;
|
||||
readonly settledShelfHeaderIndex?: number | null;
|
||||
readonly snoozeLabelNow?: string;
|
||||
}): ThreadListV2ListItem[] {
|
||||
const threadItems = input.items.map(
|
||||
(item): ThreadListV2ListItem => ({
|
||||
type: "v2-thread",
|
||||
key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
|
||||
item,
|
||||
snoozeWakeLabelText:
|
||||
item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
|
||||
? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
if (input.pendingTasks.length === 0) return threadItems;
|
||||
|
||||
const pendingItems = input.pendingTasks.map(
|
||||
(pendingTask, index): ThreadListV2ListItem => ({
|
||||
type: "v2-pending",
|
||||
@@ -160,14 +297,32 @@ export function buildThreadListV2ListItems(input: {
|
||||
showPendingDivider: index === 0,
|
||||
}),
|
||||
);
|
||||
// The settled tail begins at the row that draws the SETTLED divider; with
|
||||
// no settled rows the queued block simply ends the list.
|
||||
const settledStart = threadItems.findIndex(
|
||||
(entry) => entry.type === "v2-thread" && entry.item.showSettledDivider,
|
||||
);
|
||||
return settledStart === -1
|
||||
? [...threadItems, ...pendingItems]
|
||||
: [...threadItems.slice(0, settledStart), ...pendingItems, ...threadItems.slice(settledStart)];
|
||||
const snoozedCount = input.snoozedCount ?? 0;
|
||||
const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
|
||||
const settledCount = input.settledCount ?? 0;
|
||||
const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
|
||||
const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length;
|
||||
const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
|
||||
const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems];
|
||||
if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
|
||||
result.push({
|
||||
type: "v2-snoozed-shelf",
|
||||
key: "v2-snoozed-shelf",
|
||||
count: snoozedCount,
|
||||
expanded: input.snoozedShelfExpanded === true,
|
||||
});
|
||||
result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
|
||||
}
|
||||
if (settledShelfHeaderIndex !== null && settledCount > 0) {
|
||||
result.push({
|
||||
type: "v2-settled-shelf",
|
||||
key: "v2-settled-shelf",
|
||||
count: settledCount,
|
||||
expanded: input.settledShelfExpanded !== false,
|
||||
});
|
||||
result.push(...threadItems.slice(settledShelfHeaderIndex));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -204,6 +359,13 @@ export function buildThreadListV2Items(input: {
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
/** Expands the snoozed shelf into rows. Collapsed is the default. */
|
||||
readonly snoozedShelfExpanded?: boolean;
|
||||
/** Expands the settled shelf into rows. Expanded is the default. */
|
||||
readonly settledShelfExpanded?: boolean;
|
||||
/** The selected thread remains visible on an otherwise collapsed shelf so
|
||||
a split-view detail can never lose its navigation row. */
|
||||
readonly selectedThreadKey?: string | null;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
@@ -215,9 +377,10 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
if (thread.lineage.relationshipToParent === "subagent") continue;
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
@@ -244,7 +407,7 @@ export function buildThreadListV2Items(input: {
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
snoozed.push(thread);
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
@@ -265,24 +428,60 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
|
||||
const orderedActive = sortThreadsForListV2(active);
|
||||
const orderedSnoozed = [...snoozed].sort(
|
||||
(left, right) =>
|
||||
parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
|
||||
);
|
||||
const selectedThreadKey = input.selectedThreadKey ?? null;
|
||||
const visibleSnoozed =
|
||||
input.snoozedShelfExpanded === true
|
||||
? orderedSnoozed
|
||||
: orderedSnoozed.filter(
|
||||
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
|
||||
);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
|
||||
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
|
||||
);
|
||||
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
|
||||
const visibleSettled =
|
||||
const pagedSettled =
|
||||
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
|
||||
const selectedSettled = orderedSettled
|
||||
.slice(pagedSettled.length)
|
||||
.find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
|
||||
if (selectedSettled !== undefined) pagedSettled.push(selectedSettled);
|
||||
const visibleSettled =
|
||||
input.settledShelfExpanded !== false
|
||||
? pagedSettled
|
||||
: pagedSettled.filter(
|
||||
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
|
||||
);
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of orderedActive) {
|
||||
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
snoozed: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
for (const [index, thread] of visibleSettled.entries()) {
|
||||
const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
|
||||
for (const thread of visibleSnoozed) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: index === 0,
|
||||
snoozed: true,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
|
||||
for (const thread of visibleSettled) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
snoozed: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
@@ -292,8 +491,11 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
hiddenSettledCount: orderedSettled.length - pagedSettled.length,
|
||||
snoozedCount: orderedSnoozed.length,
|
||||
snoozedShelfHeaderIndex,
|
||||
settledCount: orderedSettled.length,
|
||||
settledShelfHeaderIndex,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts";
|
||||
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
export function threadSortValue(thread: EnvironmentThreadShell): number {
|
||||
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
|
||||
@@ -31,14 +33,10 @@ export const THREAD_STATUS_NEUTRAL_ICON = {
|
||||
iconBackground: "rgba(142,142,147,0.22)",
|
||||
} as const;
|
||||
|
||||
function isLatestTurnSettled(
|
||||
latestTurn: OrchestrationLatestTurn | null,
|
||||
session: OrchestrationSession | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
if (!session) return true;
|
||||
return session.status !== "running";
|
||||
function isLatestRunSettled(thread: EnvironmentThreadShell): boolean {
|
||||
if (!thread.latestRun?.startedAt) return false;
|
||||
if (!thread.latestRun.completedAt) return false;
|
||||
return !threadRuntimeIsActive(thread.runtime);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,7 +71,9 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
const runtimeStatus = thread.runtime?.status;
|
||||
|
||||
if (runtimeStatus === "running" || runtimeStatus === "waiting") {
|
||||
return {
|
||||
kind: "working",
|
||||
label: "Working",
|
||||
@@ -85,7 +85,7 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "starting") {
|
||||
if (runtimeStatus === "preparing" || runtimeStatus === "queued" || runtimeStatus === "starting") {
|
||||
return {
|
||||
kind: "connecting",
|
||||
label: "Connecting",
|
||||
@@ -97,7 +97,7 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
|
||||
if (runtimeStatus === "failed" || thread.latestRun?.status === "failed") {
|
||||
return {
|
||||
kind: "error",
|
||||
label: "Error",
|
||||
@@ -111,7 +111,7 @@ export function resolveThreadStatus(
|
||||
|
||||
const hasPlanReadyPrompt =
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
isLatestRunSettled(thread) &&
|
||||
thread.hasActionableProposedPlan;
|
||||
if (hasPlanReadyPrompt) {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
|
||||
|
||||
describe("user message intent badge", () => {
|
||||
it("does not label ordinary turn-start messages", () => {
|
||||
expect(resolveUserMessageIntentBadge(undefined)).toBeNull();
|
||||
expect(resolveUserMessageIntentBadge("turn_start")).toBeNull();
|
||||
});
|
||||
|
||||
it("labels messages waiting behind the active turn", () => {
|
||||
expect(resolveUserMessageIntentBadge("queued_turn")).toEqual({
|
||||
label: "queued",
|
||||
accessibilityLabel: "Queued behind the active turn",
|
||||
tone: "queued",
|
||||
});
|
||||
});
|
||||
|
||||
it("labels messages that steer the active turn", () => {
|
||||
expect(resolveUserMessageIntentBadge("steer")).toEqual({
|
||||
label: "steer",
|
||||
accessibilityLabel: "Steered the active turn",
|
||||
tone: "steer",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the queued origin after promotion to steer", () => {
|
||||
expect(resolveUserMessageIntentBadge("promoted_queued_to_steer")).toEqual({
|
||||
label: "queued → steer",
|
||||
accessibilityLabel: "Originally queued, then promoted to steer the active turn",
|
||||
tone: "steer",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { OrchestrationV2UserMessageInputIntent } from "@t3tools/contracts";
|
||||
|
||||
export interface UserMessageIntentBadgePresentation {
|
||||
readonly label: string;
|
||||
readonly accessibilityLabel: string;
|
||||
readonly tone: "queued" | "steer";
|
||||
}
|
||||
|
||||
export function resolveUserMessageIntentBadge(
|
||||
intent: OrchestrationV2UserMessageInputIntent | undefined,
|
||||
): UserMessageIntentBadgePresentation | null {
|
||||
switch (intent) {
|
||||
case "queued_turn":
|
||||
return {
|
||||
label: "queued",
|
||||
accessibilityLabel: "Queued behind the active turn",
|
||||
tone: "queued",
|
||||
};
|
||||
case "steer":
|
||||
return {
|
||||
label: "steer",
|
||||
accessibilityLabel: "Steered the active turn",
|
||||
tone: "steer",
|
||||
};
|
||||
case "promoted_queued_to_steer":
|
||||
return {
|
||||
label: "queued → steer",
|
||||
accessibilityLabel: "Originally queued, then promoted to steer the active turn",
|
||||
tone: "steer",
|
||||
};
|
||||
case "turn_start":
|
||||
case undefined:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -65,14 +65,6 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
};
|
||||
}
|
||||
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
|
||||
if (!permission.granted) {
|
||||
return {
|
||||
images: [],
|
||||
error: "Allow photo library access to attach images.",
|
||||
};
|
||||
}
|
||||
|
||||
const result = await imagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Horizontal inset shared by the home header and compact thread list. */
|
||||
export const HOME_HORIZONTAL_INSET = 20;
|
||||
|
||||
/** Compensates for the tighter native sidebar title margin on iPad. */
|
||||
export const IPAD_HOME_TITLE_OFFSET = 10;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveMobileStageLabel } from "./mobileBranding";
|
||||
|
||||
describe("resolveMobileStageLabel", () => {
|
||||
it.each([
|
||||
["development", "Dev"],
|
||||
["preview", "Nightly"],
|
||||
["production", "Alpha"],
|
||||
[undefined, "Alpha"],
|
||||
])("maps %s builds to %s", (appVariant, expected) => {
|
||||
expect(resolveMobileStageLabel(appVariant)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export type MobileStageLabel = "Alpha" | "Dev" | "Nightly";
|
||||
|
||||
export function resolveMobileStageLabel(appVariant: unknown): MobileStageLabel {
|
||||
if (appVariant === "development") return "Dev";
|
||||
if (appVariant === "preview") return "Nightly";
|
||||
return "Alpha";
|
||||
}
|
||||
@@ -2,9 +2,92 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
|
||||
|
||||
import { buildModelOptions } from "./modelOptions";
|
||||
import {
|
||||
buildModelMenuActions,
|
||||
buildModelOptions,
|
||||
groupByProvider,
|
||||
resolveSelectableModelSelection,
|
||||
} from "./modelOptions";
|
||||
|
||||
describe("mobile model options", () => {
|
||||
it("folds legacy models into a provider-scoped menu", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
{
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
displayName: "Codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.6-sol",
|
||||
name: "GPT-5.6 Sol",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
isLegacy: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as ServerConfig;
|
||||
|
||||
const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);
|
||||
|
||||
expect(actions).toMatchObject([
|
||||
{
|
||||
title: "Codex",
|
||||
subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],
|
||||
},
|
||||
{
|
||||
id: "legacy-models:codex",
|
||||
title: "Codex legacy models",
|
||||
subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("omits an empty provider menu when every model is legacy", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
{
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
displayName: "Codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
isLegacy: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as ServerConfig;
|
||||
|
||||
expect(
|
||||
buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),
|
||||
).toMatchObject([
|
||||
{
|
||||
id: "legacy-models:codex",
|
||||
title: "Codex legacy models",
|
||||
subactions: [{ id: "model:codex:gpt-5.4" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes a legacy fallback selection against current capabilities", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
@@ -49,4 +132,46 @@ describe("mobile model options", () => {
|
||||
expect(option?.capabilities?.optionDescriptors?.[0]?.id).toBe("serviceTier");
|
||||
expect(option?.selection.options).toEqual([{ id: "serviceTier", value: "default" }]);
|
||||
});
|
||||
|
||||
it("rejects stored selections whose provider is not usable", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
{
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [],
|
||||
},
|
||||
{
|
||||
instanceId: "claudeAgent",
|
||||
driver: "claudeAgent",
|
||||
enabled: false,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [],
|
||||
},
|
||||
],
|
||||
} as unknown as ServerConfig;
|
||||
|
||||
const usable = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.6-sol",
|
||||
};
|
||||
const disabled = {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-5",
|
||||
};
|
||||
const removed = {
|
||||
instanceId: ProviderInstanceId.make("codex_personal"),
|
||||
model: "gpt-5.6-sol",
|
||||
};
|
||||
|
||||
expect(resolveSelectableModelSelection(config, usable)).toBe(usable);
|
||||
expect(resolveSelectableModelSelection(config, disabled)).toBeNull();
|
||||
expect(resolveSelectableModelSelection(config, removed)).toBeNull();
|
||||
// No config (environment offline) — nothing to validate against.
|
||||
expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
ModelSelection,
|
||||
ServerConfig as T3ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import {
|
||||
buildProviderOptionSelectionsFromDescriptors,
|
||||
getProviderOptionDescriptors,
|
||||
@@ -16,6 +17,7 @@ export type ModelOption = {
|
||||
readonly providerLabel: string;
|
||||
readonly providerDriver: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly isLegacy: boolean;
|
||||
readonly capabilities: ModelCapabilities | null;
|
||||
readonly selection: ModelSelection;
|
||||
};
|
||||
@@ -58,6 +60,31 @@ function normalizeSelectionOptions(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A stored model selection is only usable when its provider instance is
|
||||
* currently enabled, installed, and authenticated on the server. Returns the
|
||||
* selection unchanged when usable, otherwise `null` so callers fall through to
|
||||
* the server's default model. A missing config (environment offline) cannot be
|
||||
* validated, so stored selections pass through untouched.
|
||||
*/
|
||||
export function resolveSelectableModelSelection(
|
||||
config: T3ServerConfig | null | undefined,
|
||||
selection: ModelSelection | null,
|
||||
): ModelSelection | null {
|
||||
if (!selection || !config) {
|
||||
return selection;
|
||||
}
|
||||
const provider = config.providers.find(
|
||||
(candidate) => candidate.instanceId === selection.instanceId,
|
||||
);
|
||||
return provider &&
|
||||
provider.enabled &&
|
||||
provider.installed &&
|
||||
provider.auth.status !== "unauthenticated"
|
||||
? selection
|
||||
: null;
|
||||
}
|
||||
|
||||
export function buildModelOptions(
|
||||
config: T3ServerConfig | null | undefined,
|
||||
fallbackModelSelection: ModelSelection | null,
|
||||
@@ -80,6 +107,7 @@ export function buildModelOptions(
|
||||
providerLabel,
|
||||
providerDriver: provider.driver,
|
||||
isDefault: model.isDefault === true,
|
||||
isLegacy: model.isLegacy === true,
|
||||
capabilities: model.capabilities,
|
||||
selection: normalizeSelectionOptions(
|
||||
{
|
||||
@@ -110,6 +138,7 @@ export function buildModelOptions(
|
||||
providerLabel,
|
||||
providerDriver: fallbackModelSelection.instanceId,
|
||||
isDefault: false,
|
||||
isLegacy: false,
|
||||
capabilities: null,
|
||||
selection: fallbackModelSelection,
|
||||
});
|
||||
@@ -139,3 +168,53 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
|
||||
models: group.models,
|
||||
}));
|
||||
}
|
||||
|
||||
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
|
||||
return {
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
option.selection.instanceId === selectedModel?.instanceId &&
|
||||
option.selection.model === selectedModel.model
|
||||
? "on"
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildModelMenuActions(
|
||||
groups: ReadonlyArray<ProviderGroup>,
|
||||
selectedModel: ModelSelection | null,
|
||||
): MenuAction[] {
|
||||
return groups.flatMap((group) => {
|
||||
const currentModels = group.models.filter((model) => !model.isLegacy);
|
||||
const legacyModels = group.models.filter((model) => model.isLegacy);
|
||||
const selected = group.models.find(
|
||||
(model) =>
|
||||
model.selection.instanceId === selectedModel?.instanceId &&
|
||||
model.selection.model === selectedModel.model,
|
||||
);
|
||||
|
||||
return [
|
||||
...(currentModels.length > 0
|
||||
? [
|
||||
{
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
|
||||
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(legacyModels.length > 0
|
||||
? [
|
||||
{
|
||||
id: `legacy-models:${group.providerKey}`,
|
||||
title: `${group.providerLabel} legacy models`,
|
||||
subtitle: selected?.isLegacy ? selected.label : undefined,
|
||||
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -50,6 +50,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
|
||||
const isWorktree = spec.workspaceMode === "worktree";
|
||||
return {
|
||||
commandId: CommandId.make(spec.commandId),
|
||||
creationSource: "mobile" as const,
|
||||
threadId: ThreadId.make(spec.threadId),
|
||||
message: {
|
||||
messageId: MessageId.make(spec.messageId),
|
||||
|
||||
@@ -4,6 +4,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
|
||||
|
||||
import { groupProjectsByRepository } from "./repositoryGroups";
|
||||
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { makeThreadShellFixture } from "../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -23,24 +24,20 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("groupProjectsByRepository", () => {
|
||||
|
||||
Loaded 100 of 1030 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user