Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60608dff91 | ||
|
|
85b166df0e | ||
|
|
47b65e7e7b | ||
|
|
8535bb3d67 | ||
|
|
18c8101084 | ||
|
|
d1784e4212 | ||
|
|
0ccd1c0ce8 | ||
|
|
69fb1fc503 | ||
|
|
35ebbc4026 | ||
|
|
30262cdb1c | ||
|
|
7b38fb5c6b | ||
|
|
7537adc30f | ||
|
|
94696b0f54 | ||
|
|
fff6a5b028 | ||
|
|
da6e1a9678 | ||
|
|
8eca20005b | ||
|
|
2fa1fec8d8 | ||
|
|
9bd2a4c688 | ||
|
|
4fb03aff0b | ||
|
|
d7950ac153 | ||
|
|
36caf34c68 | ||
|
|
90e3778660 | ||
|
|
94331c58ec | ||
|
|
c30a6d9b99 | ||
|
|
37ae1abbe9 | ||
|
|
82b76e2138 | ||
|
|
8a16cadbaf | ||
|
|
2b1d4fecb8 | ||
|
|
cec1bb9de3 | ||
|
|
25ec0b9d13 | ||
|
|
966cc05a90 | ||
|
|
1cbd88aba0 | ||
|
|
553867262c | ||
|
|
11639bf439 | ||
|
|
a261a6440a | ||
|
|
6f04a5cffb |
No files matched your search
@@ -0,0 +1,22 @@
|
||||
.git
|
||||
.repos
|
||||
.t3
|
||||
.vite-plus
|
||||
node_modules
|
||||
apps/*/node_modules
|
||||
packages/*/node_modules
|
||||
apps/*/dist
|
||||
packages/*/dist
|
||||
release
|
||||
release-mock
|
||||
artifacts
|
||||
native/**/target
|
||||
*.log
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.key
|
||||
*.pem
|
||||
auth.json
|
||||
.codex
|
||||
.claude
|
||||
@@ -70,16 +70,6 @@ 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:
|
||||
|
||||
@@ -1,246 +0,0 @@
|
||||
# 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,4 +12,3 @@
|
||||
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`
|
||||
@@ -69,6 +69,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
|
||||
- [Permission modes](./docs/user/permission-modes.md)
|
||||
- [Keyboard shortcuts](./docs/user/keybindings.md)
|
||||
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
|
||||
- [Deploy a cloud environment on Render](./docs/user/render.md)
|
||||
- [Keeping app and server in sync](./docs/user/updating.md)
|
||||
- [Source control integrations](./docs/user/source-control.md)
|
||||
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
@@ -19,6 +20,7 @@ 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 DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
@@ -225,17 +227,45 @@ const startup = Effect.gen(function* () {
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
yield* shellEnvironment.installIntoProcess;
|
||||
const hasCommandLinePasswordStore =
|
||||
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
|
||||
const linuxElectronOptions =
|
||||
environment.platform === "linux" && !hasCommandLinePasswordStore
|
||||
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
|
||||
: preReadyElectronOptions.linux;
|
||||
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
|
||||
if (
|
||||
linuxElectronOptions.passwordStore !== null ||
|
||||
preReadyElectronOptions.linux?.passwordStore !== null
|
||||
) {
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
}
|
||||
if (linuxElectronOptions.passwordStore !== null) {
|
||||
yield* electronApp.appendCommandLineSwitch(
|
||||
"password-store",
|
||||
linuxElectronOptions.passwordStore,
|
||||
);
|
||||
}
|
||||
}
|
||||
const userDataPath = yield* appIdentity.resolveUserDataPath;
|
||||
yield* electronApp.setPath("userData", userDataPath);
|
||||
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
|
||||
yield* desktopSettings.load;
|
||||
|
||||
if (environment.platform === "linux") {
|
||||
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
|
||||
if (linuxElectronOptions !== null) {
|
||||
yield* logStartupInfo("linux password store configured", {
|
||||
passwordStore: hasCommandLinePasswordStore
|
||||
? "command-line"
|
||||
: (linuxElectronOptions.passwordStore ?? "electron-default"),
|
||||
xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
|
||||
xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
yield* appIdentity.configure;
|
||||
@@ -247,6 +277,12 @@ const startup = Effect.gen(function* () {
|
||||
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
|
||||
);
|
||||
yield* logStartupInfo("app ready");
|
||||
if (environment.platform === "linux") {
|
||||
const selectedBackend = yield* safeStorage.selectedStorageBackend;
|
||||
yield* logStartupInfo("safe storage ready", {
|
||||
backend: Option.getOrElse(selectedBackend, () => "unknown"),
|
||||
});
|
||||
}
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
|
||||
@@ -64,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
|
||||
import * as NodePath from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
resolveEarlyLinuxElectronOptions,
|
||||
resolveEarlyLinuxPasswordStorePreference,
|
||||
} from "./DesktopEarlyElectronStartup.ts";
|
||||
|
||||
describe("DesktopEarlyElectronStartup", () => {
|
||||
const joinPath = NodePath.posix.join;
|
||||
|
||||
it("reads the persisted linux password-store preference before Electron is ready", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("accepts JSONC in the early desktop settings file", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => `{
|
||||
// manually edited setting
|
||||
"linuxPasswordStore": "gnome-libsecret",
|
||||
}`,
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
|
||||
it("falls back to auto when the early settings document is missing or invalid", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => {
|
||||
throw new Error("missing");
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "auto");
|
||||
});
|
||||
|
||||
it("preserves absolute root paths when resolving early settings", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("resolves the early linux Electron switches", () => {
|
||||
const options = resolveEarlyLinuxElectronOptions({
|
||||
env: {
|
||||
T3CODE_HOME: "/home/user/.t3-test",
|
||||
XDG_CURRENT_DESKTOP: "niri",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "auto" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(options, {
|
||||
linuxWmClass: "t3code-dev",
|
||||
passwordStore: "gnome-libsecret",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet");
|
||||
});
|
||||
|
||||
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
T3CODE_HOME: " ",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import {
|
||||
resolveDesktopBaseDir,
|
||||
resolveDesktopStateDir,
|
||||
type JoinPath,
|
||||
} from "./DesktopStatePaths.ts";
|
||||
|
||||
interface EarlyDesktopSettingsInput {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly readFileString: (path: string) => string;
|
||||
}
|
||||
|
||||
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
|
||||
|
||||
export interface EarlyLinuxElectronOptions {
|
||||
readonly linuxWmClass: string;
|
||||
readonly passwordStore: LinuxPasswordStoreSwitch | null;
|
||||
}
|
||||
|
||||
const trimNonEmpty = (value: string | undefined): string | null => {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
};
|
||||
|
||||
const EarlyDesktopSettingsJson = fromLenientJson(
|
||||
Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
}),
|
||||
);
|
||||
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
|
||||
|
||||
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
|
||||
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
|
||||
|
||||
function resolveEarlyDesktopSettingsPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
}): string {
|
||||
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory: input.homeDirectory,
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment: isDevelopmentEnvironment(input.env),
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
return input.joinPath(stateDir, "desktop-settings.json");
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxPasswordStorePreference(
|
||||
input: EarlyDesktopSettingsInput,
|
||||
): LinuxPasswordStorePreference {
|
||||
const settingsPath = resolveEarlyDesktopSettingsPath(input);
|
||||
try {
|
||||
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
|
||||
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
|
||||
} catch {
|
||||
return DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxElectronOptions(
|
||||
input: EarlyLinuxElectronOptionsInput,
|
||||
): EarlyLinuxElectronOptions {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference(input);
|
||||
return {
|
||||
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
|
||||
passwordStore: resolveLinuxPasswordStoreSwitch({
|
||||
preference,
|
||||
env: input.env,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -95,8 +95,6 @@ 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)");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
|
||||
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
export interface MakeDesktopEnvironmentInput {
|
||||
@@ -149,8 +150,11 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
: input.platform === "darwin"
|
||||
? path.join(homeDirectory, "Library", "Application Support")
|
||||
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
@@ -158,10 +162,12 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
isDevelopment,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const linuxApplicationsDir = path.join(
|
||||
|
||||
@@ -35,6 +35,7 @@ describe("DesktopLifecycle", () => {
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
|
||||
() => ({
|
||||
appendSwitchMock: vi.fn(),
|
||||
getSwitchValueMock: vi.fn(),
|
||||
hasSwitchMock: vi.fn(),
|
||||
registerSchemesMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
getSwitchValue: getSwitchValueMock,
|
||||
hasSwitch: hasSwitchMock,
|
||||
},
|
||||
},
|
||||
protocol: {
|
||||
registerSchemesAsPrivileged: registerSchemesMock,
|
||||
},
|
||||
}));
|
||||
|
||||
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
|
||||
describe("DesktopPreReadyPlatform", () => {
|
||||
beforeEach(() => {
|
||||
appendSwitchMock.mockReset();
|
||||
getSwitchValueMock.mockReset();
|
||||
hasSwitchMock.mockReset();
|
||||
registerSchemesMock.mockReset();
|
||||
});
|
||||
|
||||
it("reads an explicit Electron command-line switch value", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: (switchName) => switchName === "password-store",
|
||||
getSwitchValue: (switchName) => {
|
||||
assert.equal(switchName, "password-store");
|
||||
return "basic";
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.equal(value, "basic");
|
||||
});
|
||||
|
||||
it("treats valueless Electron command-line switches as absent", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => true,
|
||||
getSwitchValue: () => "",
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it("returns null for missing Electron command-line switches", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => false,
|
||||
getSwitchValue: () => {
|
||||
throw new Error("Unexpected switch value read.");
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
|
||||
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
|
||||
) {}
|
||||
|
||||
const events: Array<string> = [];
|
||||
registerSchemesMock.mockImplementation(() => {
|
||||
events.push("pre-ready");
|
||||
});
|
||||
|
||||
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
|
||||
);
|
||||
|
||||
const clerkShapedLayer = Layer.effect(
|
||||
ClerkShaped,
|
||||
Effect.promise(() => Promise.resolve()).pipe(
|
||||
Effect.map(() => {
|
||||
events.push("clerk");
|
||||
return { ready: true as const };
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runtimeLayer = clerkShapedLayer.pipe(
|
||||
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(preReadyLayer),
|
||||
);
|
||||
|
||||
const result = yield* Effect.all({
|
||||
clerk: ClerkShaped,
|
||||
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
|
||||
}).pipe(Effect.provide(runtimeLayer));
|
||||
|
||||
assert.deepEqual(result, {
|
||||
clerk: { ready: true },
|
||||
preReady: {
|
||||
linux: null,
|
||||
linuxPasswordStoreCommandLine: null,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(events, ["pre-ready", "clerk"]);
|
||||
assert.equal(registerSchemesMock.mock.calls.length, 1);
|
||||
assert.equal(appendSwitchMock.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
|
||||
export interface DesktopPreReadyCommandLineReader {
|
||||
readonly hasSwitch: (switchName: string) => boolean;
|
||||
readonly getSwitchValue: (switchName: string) => string;
|
||||
}
|
||||
|
||||
export function readCommandLineSwitchValue(
|
||||
commandLine: DesktopPreReadyCommandLineReader,
|
||||
switchName: string,
|
||||
): string | null {
|
||||
if (!commandLine.hasSwitch(switchName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const value = commandLine.getSwitchValue(switchName).trim();
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
export const resolveEarlyLinuxElectronOptionsFromProcess =
|
||||
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
|
||||
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
|
||||
env: process.env,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
joinPath: NodePath.posix.join,
|
||||
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
|
||||
});
|
||||
|
||||
export class DesktopPreReadyElectronOptions extends Context.Service<
|
||||
DesktopPreReadyElectronOptions,
|
||||
{
|
||||
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
|
||||
readonly linuxPasswordStoreCommandLine: string | null;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
|
||||
const linuxPasswordStoreCommandLine =
|
||||
platform === "linux"
|
||||
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
|
||||
: null;
|
||||
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
|
||||
|
||||
if (linux !== null) {
|
||||
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
|
||||
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
|
||||
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
|
||||
}
|
||||
}
|
||||
|
||||
return { linux, linuxPasswordStoreCommandLine };
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
|
||||
|
||||
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
|
||||
// observe app readiness before scheme privileges and command-line switches exist.
|
||||
export const layer = Layer.mergeAll(
|
||||
ElectronProtocol.layerSchemePrivileges,
|
||||
Layer.effect(DesktopPreReadyElectronOptions, make),
|
||||
);
|
||||
@@ -0,0 +1,32 @@
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
export type JoinPath = (first: string, ...segments: string[]) => string;
|
||||
|
||||
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
|
||||
if (Option.isNone(t3Home)) {
|
||||
return Option.none();
|
||||
}
|
||||
const trimmed = t3Home.value.trim();
|
||||
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
|
||||
}
|
||||
|
||||
export function resolveDesktopBaseDir(input: {
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
|
||||
input.joinPath(input.homeDirectory, ".t3"),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveDesktopStateDir(input: {
|
||||
readonly baseDir: string;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
const useDevSubdir =
|
||||
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
|
||||
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
|
||||
}
|
||||
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed((): string | null => null),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
|
||||
@@ -14,6 +14,7 @@ const {
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
removeSwitchMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
@@ -34,6 +35,7 @@ const {
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
removeSwitchMock: vi.fn(),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
@@ -52,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
removeSwitch: removeSwitchMock,
|
||||
},
|
||||
dock: {
|
||||
setIcon: setDockIconMock,
|
||||
@@ -89,6 +92,7 @@ describe("ElectronApp", () => {
|
||||
quitMock.mockClear();
|
||||
relaunchMock.mockClear();
|
||||
removeListenerMock.mockClear();
|
||||
removeSwitchMock.mockClear();
|
||||
setPathMock.mockClear();
|
||||
});
|
||||
|
||||
@@ -178,4 +182,13 @@ describe("ElectronApp", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("removes command-line switches through the service", () =>
|
||||
Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
|
||||
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
});
|
||||
@@ -69,6 +69,7 @@ export class ElectronApp extends Context.Service<
|
||||
readonly onBeforeQuitForUpdate: (
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
@@ -191,6 +192,10 @@ export const make = ElectronApp.of({
|
||||
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
removeCommandLineSwitch: (switchName) =>
|
||||
Effect.sync(() => {
|
||||
Electron.app.commandLine.removeSwitch(switchName);
|
||||
}),
|
||||
on: addScopedAppListener,
|
||||
});
|
||||
|
||||
|
||||
@@ -105,6 +105,38 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Must run synchronously during process bootstrap, before Electron emits `ready`.
|
||||
*/
|
||||
export function registerDesktopSchemePrivilegesSync(): void {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_PRODUCTION_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
scheme: DESKTOP_DEVELOPMENT_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
|
||||
);
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
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 Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
const electronSafeStorageErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
@@ -60,24 +62,39 @@ export class ElectronSafeStorage extends Context.Service<
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
export const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
|
||||
return ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
}),
|
||||
selectedStorageBackend: Effect.sync(() => {
|
||||
if (platform !== "linux") {
|
||||
return Option.none();
|
||||
}
|
||||
try {
|
||||
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
|
||||
} catch {
|
||||
return Option.none();
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronSafeStorage, make);
|
||||
export const layer = Layer.effect(ElectronSafeStorage, make);
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAnnotationSubmissionResultSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
resolveLinuxSecretStorageUnavailableMessage,
|
||||
} from "./linuxSecretStorage.ts";
|
||||
|
||||
const autoSwitch = (env: NodeJS.ProcessEnv) =>
|
||||
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
|
||||
|
||||
describe("linuxSecretStorage", () => {
|
||||
it("preserves explicit supported password-store preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
|
||||
});
|
||||
|
||||
it("falls back to auto for missing or unsupported preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
|
||||
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
|
||||
});
|
||||
|
||||
it("uses explicit preferences instead of the auto heuristic", () => {
|
||||
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
|
||||
).toBe(preference);
|
||||
// An explicit preference also wins where auto would have stayed out of the way.
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
|
||||
).toBe(preference);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not force a password-store for desktops Electron already recognizes", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
|
||||
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({})).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
|
||||
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
|
||||
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("overrides KDE sessions identified only by legacy variables", () => {
|
||||
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
|
||||
// basic text for the rest. Either way these are the variables a previous session leaves behind,
|
||||
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
|
||||
for (const session of [
|
||||
"kde",
|
||||
"kde-plasma",
|
||||
"kde4",
|
||||
"plasma",
|
||||
"plasmawayland",
|
||||
"plasmawayland-dev",
|
||||
"plasmax11",
|
||||
"plasmax11-dev",
|
||||
]) {
|
||||
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
|
||||
}
|
||||
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
|
||||
expect(
|
||||
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
|
||||
).toBe("gnome-libsecret");
|
||||
// A previous KDE session left these behind; the compositor running now is not KDE.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
|
||||
expect(
|
||||
autoSwitch({
|
||||
XDG_CURRENT_DESKTOP: "Hyprland",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
KDE_SESSION_VERSION: "6",
|
||||
}),
|
||||
).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "gnome-libsecret",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet6",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet",
|
||||
selectedBackend: "gnome-libsecret",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
});
|
||||
|
||||
it("uses KWallet remediation wording for KDE-looking sessions", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "kwallet6",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { DESKTOP_SESSION: "plasmawayland" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
// A desktop name outranks a bare KDE marker when choosing the wording.
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
export type LinuxPasswordStorePreference =
|
||||
| "auto"
|
||||
| "gnome-libsecret"
|
||||
| "kwallet"
|
||||
| "kwallet5"
|
||||
| "kwallet6";
|
||||
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
|
||||
|
||||
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
|
||||
|
||||
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
|
||||
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
|
||||
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
|
||||
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
|
||||
"Deepin",
|
||||
"GNOME",
|
||||
"Pantheon",
|
||||
"UKUI",
|
||||
"Unity",
|
||||
"X-Cinnamon",
|
||||
"XFCE",
|
||||
]);
|
||||
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
|
||||
const ELECTRON_KDE_DESKTOP = "KDE";
|
||||
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
|
||||
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
|
||||
|
||||
const KDE_NAME_PREFIXES = ["kde", "plasma"];
|
||||
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
|
||||
export function normalizeLinuxPasswordStorePreference(
|
||||
value: unknown,
|
||||
): LinuxPasswordStorePreference {
|
||||
return value === "gnome-libsecret" ||
|
||||
value === "kwallet" ||
|
||||
value === "kwallet5" ||
|
||||
value === "kwallet6"
|
||||
? value
|
||||
: DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
|
||||
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
|
||||
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
|
||||
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
|
||||
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
|
||||
// specific one sets linuxPasswordStore explicitly.
|
||||
export function resolveLinuxPasswordStoreSwitch(input: {
|
||||
readonly preference: LinuxPasswordStorePreference;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): LinuxPasswordStoreSwitch | null {
|
||||
if (input.preference !== "auto") {
|
||||
return input.preference;
|
||||
}
|
||||
|
||||
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
|
||||
}
|
||||
|
||||
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
|
||||
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
|
||||
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
|
||||
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
|
||||
// it lands on the same backend.
|
||||
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
|
||||
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveLinuxSecretStorageUnavailableMessage(input: {
|
||||
readonly configuredPreference: LinuxPasswordStorePreference;
|
||||
readonly selectedBackend: string | null;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): string {
|
||||
if (input.configuredPreference === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
input.configuredPreference === "kwallet" ||
|
||||
input.configuredPreference === "kwallet5" ||
|
||||
input.configuredPreference === "kwallet6"
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
|
||||
if (backend === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
backend === "kwallet" ||
|
||||
backend === "kwallet5" ||
|
||||
backend === "kwallet6" ||
|
||||
looksLikeKdeSession(input.env)
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
function getGnomeKeyringRemediationMessage(): string {
|
||||
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
|
||||
}
|
||||
|
||||
function getKWalletRemediationMessage(): string {
|
||||
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
|
||||
}
|
||||
|
||||
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
|
||||
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
|
||||
// rather than an unprotected credential store.
|
||||
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
|
||||
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
|
||||
if (currentDesktopNames.length > 0) {
|
||||
return currentDesktopNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
const legacyNames = legacyDesktopNames(env);
|
||||
if (legacyNames.length > 0) {
|
||||
return legacyNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
|
||||
}
|
||||
|
||||
function isKdeDesktopName(name: string): boolean {
|
||||
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
|
||||
}
|
||||
|
||||
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
|
||||
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonEmptyDesktopNames(value: string | undefined): string[] {
|
||||
return splitDesktopNameList(value).flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function isSet(value: string | undefined): boolean {
|
||||
return Boolean(value?.trim());
|
||||
}
|
||||
|
||||
function isAffirmativeFlag(value: string | undefined): boolean {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
|
||||
}
|
||||
|
||||
function splitDesktopNameList(value: string | undefined): string[] {
|
||||
return value?.split(":") ?? [];
|
||||
}
|
||||
|
||||
function normalizeDesktopName(value: string | undefined): string | null {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedStorageBackend(value: string | null): string | null {
|
||||
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
@@ -50,6 +50,7 @@ import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
|
||||
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
|
||||
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
@@ -197,16 +198,20 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
);
|
||||
|
||||
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
|
||||
// yield and let Electron emit ready.
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
),
|
||||
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
|
||||
),
|
||||
Layer.provideMerge(DesktopPreReadyPlatform.layer),
|
||||
);
|
||||
|
||||
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
|
||||
const keyboardEvent = (
|
||||
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
|
||||
) => ({
|
||||
key: "Enter",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
isComposing: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("resolveAnnotationSubmission", () => {
|
||||
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
|
||||
});
|
||||
|
||||
it("leaves Shift+Enter and composition events available for editing", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
|
||||
|
||||
interface AnnotationKeyboardEvent {
|
||||
readonly key: string;
|
||||
readonly metaKey: boolean;
|
||||
readonly ctrlKey: boolean;
|
||||
readonly shiftKey: boolean;
|
||||
readonly isComposing: boolean;
|
||||
}
|
||||
|
||||
export function resolveAnnotationSubmission(
|
||||
event: AnnotationKeyboardEvent,
|
||||
): PreviewAnnotationSubmission | null {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
|
||||
return event.metaKey || event.ctrlKey ? "send" : "attach";
|
||||
}
|
||||
@@ -23,6 +23,10 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
|
||||
// and silently granting it would hand every page the user's installed-font
|
||||
// fingerprint (and font file bytes via FontData.blob()). The app's own font
|
||||
// picker runs in the main window session, which is unaffected by this list.
|
||||
]);
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
|
||||
@@ -36,6 +36,28 @@ describe("fitPictureInPictureContentSize", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPreviewRefreshShortcut", () => {
|
||||
const input = (overrides: Partial<Electron.Input> = {}) =>
|
||||
({
|
||||
type: "keyDown",
|
||||
key: "r",
|
||||
meta: true,
|
||||
control: false,
|
||||
shift: false,
|
||||
alt: false,
|
||||
...overrides,
|
||||
}) as Electron.Input;
|
||||
|
||||
it("recognizes the platform refresh chord without matching modified variants", () => {
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const {
|
||||
browserWindowConstructor,
|
||||
createFromPath,
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
PreviewAnnotationSubmissionResult,
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewScreenshotArtifact,
|
||||
@@ -109,7 +110,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
|
||||
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
|
||||
const AGENT_CURSOR_MOVE_MS = 160;
|
||||
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
|
||||
colorScheme: "light",
|
||||
radius: "0.625rem",
|
||||
@@ -406,6 +407,13 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
|
||||
{ key: "w", meta: true, shift: false, control: false },
|
||||
]);
|
||||
|
||||
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
|
||||
input.type === "keyDown" &&
|
||||
input.key.toLowerCase() === "r" &&
|
||||
(input.meta || input.control) &&
|
||||
!input.shift &&
|
||||
!input.alt;
|
||||
|
||||
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
|
||||
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
|
||||
if (value.kind === "pointer") {
|
||||
@@ -1365,6 +1373,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
});
|
||||
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
|
||||
if (isPreviewRefreshShortcut(input)) {
|
||||
event.preventDefault();
|
||||
runFork(
|
||||
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
|
||||
wc.reload(),
|
||||
).pipe(Effect.ignore),
|
||||
);
|
||||
return;
|
||||
}
|
||||
runFork(forwardShortcut(event, input));
|
||||
};
|
||||
yield* Scope.addFinalizer(
|
||||
@@ -1792,7 +1809,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* cancelPickElement(tabId);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
|
||||
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
|
||||
(resume) => {
|
||||
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
|
||||
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
|
||||
@@ -1807,14 +1824,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
|
||||
payload: PreviewAnnotationPayload | null,
|
||||
payload: PreviewAnnotationSubmissionResult | null,
|
||||
) {
|
||||
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
|
||||
if (!active || active.cancel !== cancel) return;
|
||||
yield* cleanup();
|
||||
resume(Effect.succeed(payload));
|
||||
});
|
||||
const settle = (payload: PreviewAnnotationPayload | null) => {
|
||||
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
|
||||
runFork(settlePick(payload));
|
||||
};
|
||||
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
|
||||
@@ -1844,11 +1861,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return;
|
||||
}
|
||||
const cropRect = normalizeCaptureRect(args[1]);
|
||||
const submission = args[2] === "send" ? "send" : "attach";
|
||||
runFork(
|
||||
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: () => Effect.sync(() => settle(payload)),
|
||||
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
|
||||
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
|
||||
onSuccess: (screenshot) =>
|
||||
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
|
||||
}),
|
||||
Effect.ensuring(
|
||||
attempt(
|
||||
@@ -3586,7 +3605,7 @@ export class PreviewManager extends Context.Service<
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
|
||||
@@ -11,8 +11,10 @@ import type {
|
||||
PreviewAnnotationRegionTarget,
|
||||
PreviewAnnotationStrokeTarget,
|
||||
PreviewAnnotationStyleChange,
|
||||
PreviewAnnotationSubmission,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
|
||||
import {
|
||||
ANNOTATION_CAPTURED_CHANNEL,
|
||||
@@ -426,7 +428,7 @@ function startAnnotation(): void {
|
||||
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
|
||||
composerRow.appendChild(dragHandle);
|
||||
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot");
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
|
||||
submit.className +=
|
||||
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
|
||||
composerRow.appendChild(submit);
|
||||
@@ -1182,7 +1184,7 @@ function startAnnotation(): void {
|
||||
refreshToolButtons();
|
||||
};
|
||||
|
||||
submit.addEventListener("click", () => {
|
||||
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
|
||||
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
|
||||
return;
|
||||
pendingCapture = true;
|
||||
@@ -1223,13 +1225,18 @@ function startAnnotation(): void {
|
||||
...regions.map((region) => region.rect),
|
||||
...strokes.map((stroke) => stroke.bounds),
|
||||
]);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
|
||||
});
|
||||
});
|
||||
comment.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
|
||||
};
|
||||
submit.addEventListener("click", () => submitAnnotation("attach"));
|
||||
root.addEventListener("keydown", (event) => {
|
||||
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
|
||||
// Keep this in the bubble phase so editor inputs receive the event before
|
||||
// it is isolated from listeners installed by the inspected page.
|
||||
event.stopImmediatePropagation();
|
||||
if (!submission) return;
|
||||
event.preventDefault();
|
||||
submit.click();
|
||||
submitAnnotation(submission);
|
||||
});
|
||||
|
||||
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
|
||||
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
|
||||
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
|
||||
|
||||
@@ -11,6 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(
|
||||
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
|
||||
),
|
||||
mainWindowBounds: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
@@ -102,6 +105,7 @@ describe("DesktopSettings", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -121,6 +125,7 @@ describe("DesktopSettings", () => {
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
@@ -129,6 +134,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -235,6 +241,7 @@ describe("DesktopSettings", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -268,6 +275,44 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"normalizes unsupported linux password-store values without dropping other settings",
|
||||
() =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
environment.desktopSettingsPath,
|
||||
`{
|
||||
"linuxPasswordStore": "unsupported-store",
|
||||
"serverExposureMode": "network-accessible",
|
||||
"tailscaleServeEnabled": true,
|
||||
"tailscaleServePort": 8443,
|
||||
"updateChannel": "nightly",
|
||||
"updateChannelConfiguredByUser": true
|
||||
}\n`,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists sparse desktop settings documents", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -300,6 +345,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -327,6 +373,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -353,6 +400,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
|
||||
@@ -16,10 +16,16 @@ import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly linuxPasswordStore: LinuxPasswordStorePreference;
|
||||
readonly mainWindowBounds: DesktopWindowBounds | null;
|
||||
readonly mainWindowMaximized: boolean;
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
@@ -67,6 +73,7 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -87,6 +94,7 @@ const DesktopWindowBoundsDocument = Schema.Struct({
|
||||
});
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
|
||||
@@ -216,6 +224,7 @@ function normalizeDesktopSettingsDocument(
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
|
||||
mainWindowBounds,
|
||||
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
|
||||
serverExposureMode:
|
||||
@@ -238,6 +247,9 @@ function toDesktopSettingsDocument(
|
||||
): DesktopSettingsDocument {
|
||||
const document: Mutable<DesktopSettingsDocument> = {};
|
||||
|
||||
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
|
||||
document.linuxPasswordStore = settings.linuxPasswordStore;
|
||||
}
|
||||
if (settings.mainWindowBounds !== null) {
|
||||
document.mainWindowBounds = settings.mainWindowBounds;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,15 @@ const clientSettings: ClientSettings = {
|
||||
diffIgnoreWhitespace: true,
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
fontFamilyCode: "",
|
||||
fontFamilyComposer: "",
|
||||
fontFamilySans: "",
|
||||
fontFamilyTerminal: "",
|
||||
fontSizeCode: 13,
|
||||
fontSizeInterface: 16,
|
||||
fontSizePrompt: 14,
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
|
||||
@@ -86,6 +86,7 @@ function makeSafeStorageLayer(input: {
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -90,7 +91,7 @@ function runShellEnvironment(input: {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopShellEnvironment.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -243,6 +244,65 @@ describe("DesktopShellEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "wrong-launcher",
|
||||
XDG_SESSION_DESKTOP: "wrong-launcher",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "KDE",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
XDG_SESSION_TYPE: "wayland",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_TYPE, "wayland");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("overrides stale dbus session addresses from the login shell", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
|
||||
}),
|
||||
);
|
||||
|
||||
it("resolves dbus runtime dir candidates with existence checks", () => {
|
||||
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
|
||||
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
|
||||
uid: 1000,
|
||||
exists: (path) => path === "/run/user/1000/bus",
|
||||
});
|
||||
|
||||
assert.equal(busPath, "unix:path=/run/user/1000/bus");
|
||||
});
|
||||
|
||||
it.effect("logs command failures with safe probe context and the exact cause", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/bash",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
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";
|
||||
@@ -68,12 +69,19 @@ export class DesktopShellEnvironment extends Context.Service<
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"DISPLAY",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const;
|
||||
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
|
||||
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
|
||||
@@ -92,6 +100,47 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
|
||||
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
|
||||
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
|
||||
|
||||
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
|
||||
|
||||
const linuxRuntimeDirCandidates = (
|
||||
env: NodeJS.ProcessEnv,
|
||||
uid: number | undefined,
|
||||
): ReadonlyArray<string> => {
|
||||
const candidates: string[] = [];
|
||||
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
|
||||
if (Option.isSome(fromEnv)) {
|
||||
candidates.push(normalizeRuntimeDir(fromEnv.value));
|
||||
}
|
||||
if (uid !== undefined) {
|
||||
candidates.push(`/run/user/${uid}`);
|
||||
}
|
||||
return candidates.filter((candidate) => candidate.length > 0);
|
||||
};
|
||||
|
||||
function resolveDefaultLinuxDbusSessionBusPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly uid: number | undefined;
|
||||
readonly exists?: (path: string) => boolean;
|
||||
}): string | null {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
|
||||
const busPath = `${runtimeDir}/bus`;
|
||||
if (input.exists === undefined || input.exists(busPath)) {
|
||||
return busPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly exists: (path: string) => boolean;
|
||||
readonly uid: number | undefined;
|
||||
}): string | null {
|
||||
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
|
||||
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
|
||||
}
|
||||
|
||||
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
|
||||
const normalized = entry.trim().replace(/^"+|"+$/g, "");
|
||||
return platform === "win32" ? normalized.toLowerCase() : normalized;
|
||||
@@ -356,7 +405,12 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const shellEnvironment: EnvironmentPatch = {};
|
||||
|
||||
for (const shell of listLoginShellCandidates(config)) {
|
||||
@@ -383,23 +437,54 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
|
||||
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
|
||||
const shellPreferredEnvNames = [
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
] as const;
|
||||
for (const name of shellPreferredEnvNames) {
|
||||
if (shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
for (const name of [
|
||||
"DISPLAY",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const) {
|
||||
if (!config.env[name] && shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
config.platform === "linux" &&
|
||||
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
|
||||
) {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
|
||||
const dbusSessionBusPath = `${runtimeDir}/bus`;
|
||||
const busExists = yield* fileSystem
|
||||
.exists(dbusSessionBusPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (busExists) {
|
||||
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const installShellEnvironment = (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
|
||||
if (config.platform === "win32") {
|
||||
return installWindowsEnvironment(config);
|
||||
}
|
||||
@@ -411,6 +496,7 @@ const installShellEnvironment = (
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
|
||||
installShellEnvironment({
|
||||
@@ -418,6 +504,7 @@ export const make = Effect.gen(function* () {
|
||||
platform: environment.platform,
|
||||
userShell: Option.none(),
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
|
||||
);
|
||||
|
||||
@@ -43,6 +43,7 @@ function makeElectronAppLayer(
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
@@ -46,6 +46,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
|
||||
if (!beforeInput) {
|
||||
return yield* Effect.die("before-input-event listener was not registered");
|
||||
}
|
||||
|
||||
let prevented = false;
|
||||
const event = { preventDefault: () => (prevented = true) };
|
||||
const input = {
|
||||
type: "keyDown",
|
||||
isAutoRepeat: true,
|
||||
key: "W",
|
||||
meta: true,
|
||||
control: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
};
|
||||
beforeInput(event, input);
|
||||
assert.isTrue(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, isAutoRepeat: false });
|
||||
assert.isFalse(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, meta: false });
|
||||
assert.isFalse(prevented);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the persisted main window bounds when opening the window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -25,6 +26,12 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
|
||||
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
|
||||
// that dies on boot cannot reload-loop forever.
|
||||
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
|
||||
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
|
||||
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
@@ -514,6 +521,18 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
|
||||
// close-terminal shortcut can outlive the terminal that handled its first
|
||||
// press, so reject repeats before they reach the native window accelerator.
|
||||
// Deliberate presses still flow through the renderer or native menu.
|
||||
window.webContents.on("before-input-event", (event, input) => {
|
||||
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
|
||||
const modifier = environment.platform === "darwin" ? input.meta : input.control;
|
||||
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
@@ -537,6 +556,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
let rendererRecoveryTimestamps: number[] = [];
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
@@ -618,10 +638,39 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
window.webContents.on("render-process-gone", (_event, details) => {
|
||||
void runPromise(
|
||||
logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
const recoverable =
|
||||
details.reason === "crashed" ||
|
||||
details.reason === "oom" ||
|
||||
details.reason === "abnormal-exit";
|
||||
// Long sessions can OOM the renderer (V8 heap exhaustion from
|
||||
// accumulated thread state). Without a reload the user is left staring
|
||||
// at a dead white window while agents keep running invisibly, so
|
||||
// recover by reloading — the renderer rehydrates from the backend,
|
||||
// which is unaffected. Recovery attempts are bounded so a renderer
|
||||
// that dies immediately on boot cannot reload-loop forever.
|
||||
runFork(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
|
||||
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
|
||||
);
|
||||
const shouldRecover =
|
||||
recoverable &&
|
||||
!window.isDestroyed() &&
|
||||
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
|
||||
yield* logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
recovering: shouldRecover,
|
||||
});
|
||||
if (!shouldRecover) {
|
||||
return;
|
||||
}
|
||||
rendererRecoveryTimestamps.push(now);
|
||||
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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/sdk</div>
|
||||
<div class="harness-tag">cursor-agent</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="harness">
|
||||
|
||||
@@ -50,6 +50,8 @@ import {
|
||||
IconMinus,
|
||||
IconNetwork,
|
||||
IconPalette,
|
||||
IconPin,
|
||||
IconPinnedOff,
|
||||
IconPlayerPlay,
|
||||
IconPlayerStopFilled,
|
||||
IconPlus,
|
||||
@@ -121,6 +123,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
magnifyingglass: IconSearch,
|
||||
paintbrush: IconPalette,
|
||||
"person.crop.circle": IconUserCircle,
|
||||
pin: IconPin,
|
||||
"pin.slash": IconPinnedOff,
|
||||
play: IconPlayerPlay,
|
||||
plus: IconPlus,
|
||||
"qrcode.viewfinder": IconQrcode,
|
||||
|
||||
@@ -3,9 +3,14 @@ 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";
|
||||
|
||||
@@ -17,7 +22,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
return (
|
||||
<View className="flex-row items-center gap-3">
|
||||
<Image
|
||||
source={T3_CODE_BRAND_MARK_SOURCE}
|
||||
source={BRAND_MARK_SOURCE}
|
||||
accessibilityIgnoresInvertColors
|
||||
style={{
|
||||
width: iconSize,
|
||||
|
||||
@@ -9,6 +9,7 @@ type ProviderIconProps = {
|
||||
export function ProviderIcon(props: ProviderIconProps) {
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const size = props.size ?? 16;
|
||||
const mono = isDarkMode ? "#e5e5e5" : "#171717";
|
||||
|
||||
if (props.provider === "claudeAgent") {
|
||||
return (
|
||||
@@ -21,10 +22,47 @@ export function ProviderIcon(props: ProviderIconProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "grok") {
|
||||
const fill = isDarkMode ? "#F5F5F5" : "#0F0F0F";
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861"
|
||||
/>
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "cursor") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#EDECEC" : "#26251E"}
|
||||
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "opencode") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
|
||||
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
|
||||
<Path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill={isDarkMode ? "#F1ECEC" : "#211E1E"} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
// codex (and unknown drivers)
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#e5e5e5" : "#171717"}
|
||||
fill={mono}
|
||||
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
|
||||
/>
|
||||
</Svg>
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
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,15 +1,5 @@
|
||||
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 { EnvironmentId, 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";
|
||||
|
||||
@@ -17,121 +7,6 @@ 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: [
|
||||
{
|
||||
@@ -153,16 +28,13 @@ 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(() => {
|
||||
const id = cacheId(environmentId, kind, cacheKey);
|
||||
values.set(id, payload);
|
||||
schemaVersions.set(id, schemaVersion);
|
||||
values.set(cacheId(environmentId, kind, cacheKey), payload);
|
||||
}),
|
||||
removeCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.sync(() => {
|
||||
@@ -187,37 +59,10 @@ function makeDatabase() {
|
||||
loadPreferencesJson: Effect.succeed(Option.none()),
|
||||
savePreferencesJson: () => Effect.void,
|
||||
});
|
||||
return { database, removed, schemaVersions, values };
|
||||
return { database, removed, 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,11 +1,14 @@
|
||||
import {
|
||||
ConnectionPersistenceError,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ServerConfig,
|
||||
VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -13,9 +16,22 @@ 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,
|
||||
@@ -29,17 +45,13 @@ const StoredVcsRefs = Schema.Struct({
|
||||
});
|
||||
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
Schema.fromJsonString(StoredShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
Schema.fromJsonString(StoredThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
|
||||
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredServerConfig),
|
||||
);
|
||||
@@ -115,12 +127,12 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
),
|
||||
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
|
||||
const payload = yield* encodeStoredShellSnapshot({
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "shell", "snapshot", ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
|
||||
}),
|
||||
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
|
||||
@@ -138,15 +150,15 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
}),
|
||||
),
|
||||
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
|
||||
const threadId = snapshot.projection.thread.id;
|
||||
const threadId = snapshot.thread.id;
|
||||
const payload = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "thread", threadId, ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
|
||||
}),
|
||||
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
|
||||
|
||||
@@ -17,7 +17,6 @@ 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,11 +1,9 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, 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");
|
||||
|
||||
@@ -24,30 +22,42 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
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: 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,
|
||||
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
|
||||
});
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -42,6 +42,8 @@ export function HomeRouteScreen() {
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -155,6 +157,8 @@ export function HomeRouteScreen() {
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
|
||||
@@ -111,6 +111,8 @@ interface HomeScreenProps {
|
||||
) => Promise<boolean>;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -185,7 +187,7 @@ function deriveEmptyState(props: {
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding runtime in one of your connected projects.",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
@@ -516,6 +518,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onUnsnoozeThread],
|
||||
);
|
||||
const handlePinThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onPinThread(thread);
|
||||
},
|
||||
[props.onPinThread],
|
||||
);
|
||||
const handleUnpinThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onUnpinThread(thread);
|
||||
},
|
||||
[props.onUnpinThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -575,6 +589,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinningEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinning === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -718,6 +741,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
snoozed={item.item.snoozed}
|
||||
pinned={item.item.pinned}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={
|
||||
@@ -732,7 +756,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
@@ -753,9 +777,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={handleSnoozeThread}
|
||||
onUnsnoozeThread={handleUnsnoozeThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onPinThread={handlePinThread}
|
||||
onUnpinThread={handleUnpinThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
@@ -768,12 +795,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handlePinThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
handleUnsnoozeThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
@@ -1025,7 +1055,7 @@ 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 runtime." />
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
)
|
||||
) : null;
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import {
|
||||
presentThreadShell,
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
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 {
|
||||
@@ -34,41 +32,29 @@ function makeProject(id: string, title: string): EnvironmentProject {
|
||||
};
|
||||
}
|
||||
|
||||
const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z");
|
||||
|
||||
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
const threadId = ThreadId.make(id);
|
||||
return presentThreadShell(environmentId, {
|
||||
id: threadId,
|
||||
return {
|
||||
environmentId,
|
||||
id: ThreadId.make(id),
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: threadTimestamp,
|
||||
updatedAt: threadTimestamp,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -31,21 +30,25 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return makeThreadShellFixture({
|
||||
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: 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,40 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
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"
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,6 @@ 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). */
|
||||
@@ -30,6 +29,13 @@ function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["enviro
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsPinning(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadPinning === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -101,9 +107,13 @@ function useThreadActionExecutor(
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// 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)) {
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (
|
||||
action === "archive" &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
@@ -199,10 +209,14 @@ export function useThreadListActions(): {
|
||||
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
|
||||
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
|
||||
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
@@ -307,6 +321,62 @@ export function useThreadListActions(): {
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const pinThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
if (!environmentSupportsPinning(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not pin thread",
|
||||
"This environment's server does not support pinning yet. Update the server to use Pin.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
selectionHaptic();
|
||||
const result = await pinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not pin thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be pinned.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[pinMutation],
|
||||
);
|
||||
const unpinThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
if (!environmentSupportsPinning(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not unpin thread",
|
||||
"This environment's server does not support pinning yet. Update the server to use Pin.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
selectionHaptic();
|
||||
const result = await unpinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not unpin thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be unpinned.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[unpinMutation],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
@@ -317,6 +387,8 @@ export function useThreadListActions(): {
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -55,10 +55,7 @@ export function subscribeToHardwareKeyboardCommandRegistrations(listener: () =>
|
||||
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
|
||||
const commandHandlers = handlers.get(command);
|
||||
if (!commandHandlers) return false;
|
||||
const handlersInRegistrationOrder = Array.from(commandHandlers);
|
||||
for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) {
|
||||
const handler = handlersInRegistrationOrder[index];
|
||||
if (!handler) continue;
|
||||
for (const handler of [...commandHandlers].toReversed()) {
|
||||
if (handler() !== false) return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -561,6 +561,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
projectId,
|
||||
workspaceRoot,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
const result = await createProject({
|
||||
environmentId: environment.environmentId,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import {
|
||||
MessageId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type ReviewDiffPreviewSource,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildReviewListItems,
|
||||
@@ -14,9 +18,9 @@ import {
|
||||
} from "./reviewModel";
|
||||
|
||||
function makeCheckpoint(
|
||||
input: Partial<ThreadCheckpointSummary> &
|
||||
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
|
||||
): ThreadCheckpointSummary {
|
||||
input: Partial<OrchestrationCheckpointSummary> &
|
||||
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
|
||||
): OrchestrationCheckpointSummary {
|
||||
return {
|
||||
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
|
||||
status: "ready",
|
||||
@@ -48,12 +52,12 @@ describe("buildReviewSectionItems", () => {
|
||||
it("keeps one chip per checkpoint and appends git sources", () => {
|
||||
const checkpoints = [
|
||||
makeCheckpoint({
|
||||
runId: RunId.make("run-1"),
|
||||
turnId: TurnId.make("turn-1"),
|
||||
checkpointTurnCount: 1,
|
||||
completedAt: "2026-04-01T00:00:00.000Z",
|
||||
}),
|
||||
makeCheckpoint({
|
||||
runId: RunId.make("run-2"),
|
||||
turnId: TurnId.make("turn-2"),
|
||||
checkpointTurnCount: 2,
|
||||
completedAt: "2026-04-02T00:00:00.000Z",
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
|
||||
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Order from "effect/Order";
|
||||
@@ -129,11 +128,11 @@ export type ReviewParsedDiff =
|
||||
readonly notice: string | null;
|
||||
};
|
||||
|
||||
function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
return `Turn ${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
const fileCount = checkpoint.files.length;
|
||||
if (checkpoint.status !== "ready") {
|
||||
return `Diff ${checkpoint.status}`;
|
||||
@@ -142,8 +141,8 @@ function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
}
|
||||
|
||||
function compareCheckpointTurnCountDescending(
|
||||
left: ThreadCheckpointSummary,
|
||||
right: ThreadCheckpointSummary,
|
||||
left: OrchestrationCheckpointSummary,
|
||||
right: OrchestrationCheckpointSummary,
|
||||
): -1 | 0 | 1 {
|
||||
if (left.checkpointTurnCount === right.checkpointTurnCount) {
|
||||
return 0;
|
||||
@@ -152,7 +151,7 @@ function compareCheckpointTurnCountDescending(
|
||||
return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
|
||||
}
|
||||
|
||||
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
|
||||
const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
|
||||
compareCheckpointTurnCountDescending,
|
||||
);
|
||||
|
||||
@@ -511,14 +510,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
|
||||
}
|
||||
|
||||
export function getReviewSectionIdForCheckpoint(
|
||||
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
|
||||
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
|
||||
): string {
|
||||
return `turn:${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
export function getReadyReviewCheckpoints(
|
||||
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): ReadonlyArray<OrchestrationCheckpointSummary> {
|
||||
return pipe(
|
||||
checkpoints,
|
||||
Arr.filter((checkpoint) => checkpoint.status === "ready"),
|
||||
@@ -527,7 +526,7 @@ export function getReadyReviewCheckpoints(
|
||||
}
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
deriveThreadCheckpointSummaries,
|
||||
type ThreadCheckpointSummary,
|
||||
} from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { useCheckpointDiff } from "../../state/queries";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { reviewEnvironment } from "../../state/review";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import {
|
||||
buildReviewSectionItems,
|
||||
@@ -34,7 +30,7 @@ export function useReviewSections(input: {
|
||||
}) {
|
||||
const { environmentId, reviewCache, threadId } = input;
|
||||
const enabled = input.enabled ?? true;
|
||||
const selectedThread = useSelectedThreadProjection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const diffPreview = useEnvironmentQuery(
|
||||
enabled && environmentId !== undefined && selectedThreadCwd !== null
|
||||
@@ -53,11 +49,8 @@ export function useReviewSections(input: {
|
||||
}, [diffPreview.data, reviewCache.threadKey]);
|
||||
|
||||
const readyCheckpoints = useMemo(
|
||||
() =>
|
||||
getReadyReviewCheckpoints(
|
||||
selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
|
||||
),
|
||||
[selectedThread],
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
);
|
||||
const checkpointBySectionId = useMemo(
|
||||
() =>
|
||||
@@ -66,7 +59,7 @@ export function useReviewSections(input: {
|
||||
getReviewSectionIdForCheckpoint(checkpoint),
|
||||
checkpoint,
|
||||
]),
|
||||
) as Record<string, ThreadCheckpointSummary>,
|
||||
) as Record<string, OrchestrationCheckpointSummary>,
|
||||
[readyCheckpoints],
|
||||
);
|
||||
const reviewSections = useMemo(
|
||||
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
useKnownTerminalSessions,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
@@ -172,9 +172,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
const params = props.route.params;
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadProjection();
|
||||
const selectedThreadDetailWorktreePath =
|
||||
selectedThreadDetail?.projection.thread.worktreePath ?? null;
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const routeThreadIdRaw = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentId = routeEnvironmentIdRaw
|
||||
@@ -285,13 +283,13 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
activeSessionLocation: activeKnownSession?.state.summary ?? null,
|
||||
workspaceRoot: selectedThreadProject.workspaceRoot,
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetailWorktreePath,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
});
|
||||
}, [
|
||||
activeKnownSession?.state.summary,
|
||||
pendingLaunch,
|
||||
selectedThread,
|
||||
selectedThreadDetailWorktreePath,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
]);
|
||||
const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -6,16 +6,14 @@ import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: RuntimeRequestId,
|
||||
requestId: ApprovalRequestId,
|
||||
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">
|
||||
@@ -29,23 +27,17 @@ 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={disabled}
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
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={disabled}
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
|
||||
@@ -54,7 +46,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={disabled}
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
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 { RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
@@ -9,10 +9,14 @@ export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
requestId: RuntimeRequestId,
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -20,7 +24,6 @@ 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">
|
||||
@@ -29,12 +32,6 @@ 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 (
|
||||
@@ -52,7 +49,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
disabled={!canRespond}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
@@ -82,7 +78,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
editable={canRespond}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
@@ -99,9 +94,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
|
||||
)}
|
||||
disabled={
|
||||
!canRespond ||
|
||||
props.answers === null ||
|
||||
props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
}
|
||||
onPress={() => void props.onSubmit()}
|
||||
>
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
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,
|
||||
@@ -97,11 +97,10 @@ export interface ThreadComposerProps {
|
||||
* are on screen while they reconcile with the server.
|
||||
*/
|
||||
readonly threadSyncPhase?: "loading" | "syncing" | null;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
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>;
|
||||
@@ -306,7 +305,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
setIsFocused(false);
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
const showStopAction = props.canStopThread;
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
|
||||
|
||||
@@ -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,14 +26,11 @@ 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";
|
||||
@@ -43,32 +40,28 @@ 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: EnvironmentThreadShell;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
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: RuntimeRequestId | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | 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;
|
||||
@@ -89,16 +82,16 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onRespondToApproval: (
|
||||
requestId: RuntimeRequestId,
|
||||
requestId: ApprovalRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: RuntimeRequestId,
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
requestId: RuntimeRequestId,
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -243,39 +236,6 @@ 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;
|
||||
@@ -398,8 +358,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
threadTitle={props.selectedThread.title}
|
||||
latestRun={props.activityRun}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
@@ -408,12 +367,6 @@ 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}
|
||||
@@ -435,11 +388,6 @@ 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"
|
||||
@@ -482,7 +430,6 @@ 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,15 +1,7 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
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 type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -35,7 +27,6 @@ import {
|
||||
} from "react-native-nitro-markdown";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Image,
|
||||
Linking,
|
||||
Platform,
|
||||
@@ -88,7 +79,6 @@ 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,
|
||||
@@ -101,9 +91,8 @@ import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons
|
||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestRun,
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
@@ -114,13 +103,7 @@ 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",
|
||||
@@ -164,12 +147,11 @@ 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 latestRun: ThreadFeedLatestRun | null;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
@@ -177,7 +159,6 @@ 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;
|
||||
@@ -185,90 +166,6 @@ 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;
|
||||
@@ -922,16 +819,15 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
|
||||
function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: RunId | null;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleWorkGroup: (groupId: string) => void;
|
||||
readonly onToggleWorkRow: (rowId: string, anchorKey?: string) => void;
|
||||
readonly onToggleTurnFold: (runId: RunId) => void;
|
||||
readonly onToggleWorkRow: (rowId: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||
readonly onMarkdownLinkPress: (href: string) => void;
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
@@ -940,7 +836,6 @@ function renderFeedEntry(
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly reviewCommentBubbleWidth: number;
|
||||
readonly userBubbleMaxWidth: number;
|
||||
readonly threadTitle: string;
|
||||
},
|
||||
) {
|
||||
const entry = info.item;
|
||||
@@ -950,12 +845,12 @@ function renderFeedEntry(
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "run-fold") {
|
||||
if (entry.type === "turn-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: entry.expanded }}
|
||||
onPress={() => props.onToggleTurnFold(entry.runId)}
|
||||
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
||||
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]"
|
||||
>
|
||||
@@ -994,7 +889,7 @@ function renderFeedEntry(
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
message.runId === props.unsettledTurnId;
|
||||
message.turnId === props.unsettledTurnId;
|
||||
const showAssistantMeta =
|
||||
message.role === "assistant" &&
|
||||
props.terminalAssistantMessageIds.has(message.id) &&
|
||||
@@ -1003,17 +898,11 @@ 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={{
|
||||
@@ -1044,30 +933,6 @@ 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>
|
||||
@@ -1129,12 +994,6 @@ 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}
|
||||
@@ -1155,15 +1014,10 @@ 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}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={(rowId) => props.onToggleWorkRow(rowId, entry.id)}
|
||||
workspaceRoot={props.workspaceRoot}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1466,9 +1320,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(() =>
|
||||
@@ -1480,7 +1334,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<RunId>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
@@ -1553,7 +1407,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1563,7 +1416,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1639,20 +1491,31 @@ 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.latestRun,
|
||||
props.latestTurn,
|
||||
expandedTurnIds,
|
||||
new Set(
|
||||
Object.entries(expandedWorkGroups)
|
||||
.filter(([, expanded]) => expanded)
|
||||
.map(([groupId]) => groupId),
|
||||
),
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
),
|
||||
[expandedTurnIds, expandedWorkGroups, props.activeWorkStartedAt, props.feed, props.latestRun],
|
||||
[
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
@@ -1681,25 +1544,29 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[presentedFeed, props.anchorMessageId, anchorTopInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<RunId, string>();
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
for (const entry of props.feed) {
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
|
||||
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
|
||||
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
|
||||
}
|
||||
}
|
||||
return new Set(terminalIdsByTurn.values());
|
||||
}, [props.feed]);
|
||||
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
|
||||
const unsettledTurnId =
|
||||
props.latestTurn &&
|
||||
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestRun;
|
||||
if (!props.latestRun || !previous) {
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
if (!props.latestTurn || !previous) {
|
||||
return;
|
||||
}
|
||||
if (props.latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && props.latestRun.status === "interrupted") {
|
||||
const interruptedTurnId = props.latestRun.runId;
|
||||
if (props.latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
|
||||
const interruptedTurnId = props.latestTurn.turnId;
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
|
||||
@@ -1708,14 +1575,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return;
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
if (!current.expandedTurnIds.has(previous.runId)) {
|
||||
if (!current.expandedTurnIds.has(previous.turnId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
next.delete(previous.runId);
|
||||
next.delete(previous.turnId);
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
}, [props.latestRun]);
|
||||
}, [props.latestTurn]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1796,8 +1663,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleWorkRow = useCallback(
|
||||
(rowId: string, anchorKey?: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
|
||||
(rowId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
@@ -1810,14 +1677,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(runId: RunId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(runId);
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
@@ -1842,7 +1709,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const getFixedItemSize = useCallback(
|
||||
(entry: ThreadFeedEntry) => {
|
||||
switch (entry.type) {
|
||||
case "run-fold":
|
||||
case "turn-fold":
|
||||
return TURN_FOLD_HEIGHT;
|
||||
case "work-toggle":
|
||||
return WORK_GROUP_TOGGLE_HEIGHT;
|
||||
@@ -1865,9 +1732,7 @@ 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,
|
||||
@@ -1883,13 +1748,10 @@ 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,
|
||||
@@ -1906,10 +1768,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onToggleWorkGroup,
|
||||
onToggleWorkRow,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.threadTitle,
|
||||
props.skills,
|
||||
props.workspaceRoot,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2034,10 +1893,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
<>
|
||||
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
|
||||
{props.topAccessory}
|
||||
</>
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
|
||||
@@ -205,6 +205,8 @@ function ThreadNavigationSidebarPane(
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -481,6 +483,15 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinningEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinning === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -792,6 +803,7 @@ function ThreadNavigationSidebarPane(
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.snoozed === item.item.snoozed &&
|
||||
previous.item.pinned === item.item.pinned &&
|
||||
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
|
||||
);
|
||||
}
|
||||
@@ -879,6 +891,7 @@ function ThreadNavigationSidebarPane(
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
snoozed={item.item.snoozed}
|
||||
pinned={item.item.pinned}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
@@ -889,7 +902,7 @@ function ThreadNavigationSidebarPane(
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
@@ -915,9 +928,12 @@ function ThreadNavigationSidebarPane(
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
@@ -1045,6 +1061,8 @@ function ThreadNavigationSidebarPane(
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
openPendingTask,
|
||||
pinThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
@@ -1064,6 +1082,7 @@ function ThreadNavigationSidebarPane(
|
||||
nowMinute,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
unpinThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateGroupDisplay,
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
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?.thread.worktreePath ?? null;
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
|
||||
const handleReconnectEnvironment = useCallback(() => {
|
||||
if (!environmentId) {
|
||||
return;
|
||||
@@ -461,17 +461,23 @@ function ThreadRouteContent(
|
||||
void navigation.navigate("Connections");
|
||||
}, [navigation]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (!selectedThread || composer.interruptibleRunId === null) {
|
||||
if (
|
||||
!selectedThread ||
|
||||
(selectedThread.session?.status !== "running" &&
|
||||
selectedThread.session?.status !== "starting")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
runId: composer.interruptibleRunId,
|
||||
...(selectedThread.session.activeTurnId
|
||||
? { turnId: selectedThread.session.activeTurnId }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
|
||||
const handleOpenTerminal = useCallback(
|
||||
(nextTerminalId?: string | null) => {
|
||||
@@ -749,7 +755,6 @@ function ThreadRouteContent(
|
||||
connectionError={routeConnectionError}
|
||||
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
activityRun={composer.selectedThreadActivityRun}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
@@ -762,7 +767,6 @@ function ThreadRouteContent(
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
canStopThread={composer.interruptibleRunId !== null}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
|
||||
@@ -28,11 +28,10 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import {
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
threadHasUnseenCompletion,
|
||||
type ThreadListV2Status,
|
||||
} from "./threadListV2";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
@@ -306,6 +305,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly variant: "card" | "slim";
|
||||
/** Snoozed-shelf row: shows its wake time and offers Wake. */
|
||||
readonly snoozed?: boolean;
|
||||
/** Pinned-block row: shows the pin glyph and offers Unpin. */
|
||||
readonly pinned?: boolean;
|
||||
/** Preformatted against the parent minute tick so this memoized row's
|
||||
countdown keeps moving. */
|
||||
readonly snoozeWakeLabelText?: string;
|
||||
@@ -338,11 +339,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnpinThread: (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;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: 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
|
||||
@@ -369,9 +374,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onUnsnoozeThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onPinThread,
|
||||
onUnpinThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
const pinnedRow = props.pinned === true;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
@@ -384,17 +392,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
const pinTintColor = useThemeColor("--color-foreground-muted");
|
||||
const sidebarPane = props.pane === "sidebar";
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
// "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 statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
@@ -405,6 +408,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
);
|
||||
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
|
||||
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
@@ -441,6 +446,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
})),
|
||||
[snoozePresets],
|
||||
);
|
||||
// Pinned cards keep the full lifecycle menu; only the pin item flips to
|
||||
// Unpin. (Settling a pinned thread clears the pin server-side; snoozing
|
||||
// hides the card until wake with the pin intact.)
|
||||
const pinMenuItem = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
props.pinningSupported
|
||||
? [
|
||||
pinnedRow
|
||||
? { id: "unpin", title: "Unpin", image: "pin.slash" }
|
||||
: { id: "pin", title: "Pin", image: "pin" },
|
||||
]
|
||||
: [],
|
||||
[pinnedRow, props.pinningSupported],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
@@ -450,15 +469,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
image: "clock",
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[snoozePresetActions],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
);
|
||||
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 === "pin") handlePin();
|
||||
if (nativeEvent.event === "unpin") handleUnpin();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
@@ -475,8 +501,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handlePin,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
handleUnpin,
|
||||
handleUnsettle,
|
||||
handleUnsnooze,
|
||||
snoozePresets,
|
||||
@@ -567,6 +595,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
>
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
</Text>
|
||||
{pinnedRow ? (
|
||||
<SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
@@ -595,7 +626,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</View>
|
||||
) : null}
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.runtime?.lastError ? (
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
@@ -605,7 +636,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.runtime.lastError}
|
||||
{thread.session.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
/* "branch · machine" share one truncating line. The machine sits
|
||||
@@ -812,7 +843,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: CARD_MENU_ACTIONS
|
||||
: cardMenuActions
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
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,22 +1,14 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Image } from "expo-image";
|
||||
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
|
||||
import { LayoutAnimation, Pressable, ScrollView, 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: {
|
||||
@@ -79,87 +71,6 @@ 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;
|
||||
@@ -211,15 +122,10 @@ 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)";
|
||||
@@ -232,15 +138,10 @@ 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-3 px-1 py-0.5">
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
work log
|
||||
@@ -248,21 +149,17 @@ export function ThreadWorkLog(props: {
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{visibleRows.map((row) => {
|
||||
{rows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.canExpand;
|
||||
const detail = compactActivityDetail(row.detail);
|
||||
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
|
||||
const textIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
const fullDetail = expanded ? row.getFullDetail() : null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
const iconIsDestructive = 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}
|
||||
@@ -284,24 +181,30 @@ export function ThreadWorkLog(props: {
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
className="rounded-md px-0.5 py-0"
|
||||
>
|
||||
<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 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>
|
||||
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-foreground",
|
||||
textIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
iconIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
)}
|
||||
>
|
||||
{row.summary}
|
||||
</Text>
|
||||
{detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {detail}</Text>
|
||||
{row.detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
|
||||
@@ -345,63 +248,28 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
{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}
|
||||
/>
|
||||
{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>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -415,36 +283,48 @@ 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 = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
|
||||
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";
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1">
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded ? `Show fewer ${noun}` : `Show ${props.hiddenCount} previous ${noun}`
|
||||
}
|
||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
void Haptics.selectionAsync();
|
||||
props.onToggle();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5"
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
|
||||
>
|
||||
<View className="h-[18px] w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
name={
|
||||
props.expanded
|
||||
? { ios: "chevron.up", android: "keyboard_arrow_up" }
|
||||
: { ios: "chevron.down", android: "keyboard_arrow_down" }
|
||||
}
|
||||
size={12}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded ? `Show fewer ${noun}` : `+${props.hiddenCount} previous ${noun}`}
|
||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
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))) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -7,13 +7,12 @@ import {
|
||||
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,
|
||||
@@ -30,10 +29,27 @@ const environmentId = EnvironmentId.make("environment-1");
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return makeThreadShellFixture({
|
||||
return {
|
||||
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";
|
||||
@@ -106,16 +122,18 @@ describe("resolveThreadListV2Enabled", () => {
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running runtime", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
runtime: {
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
status: "running",
|
||||
activeRunId: RunId.make("run-t"),
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
@@ -241,68 +259,6 @@ 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: [
|
||||
@@ -332,6 +288,57 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("pinned-settled"),
|
||||
title: "Pinned while settled",
|
||||
pinnedAt: "2026-06-01T12:00:00.000Z",
|
||||
// Stale settled state (the decider clears it on pin): the pin wins.
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]);
|
||||
expect(layout.items.map((item) => item.pinned)).toEqual([true, false]);
|
||||
expect(layout.settledCount).toBe(0);
|
||||
});
|
||||
|
||||
it("snooze hides a pinned thread and wake restores it to the pinned block", () => {
|
||||
const snoozedInput = {
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("pinned-snoozed"),
|
||||
title: "Pinned and snoozed",
|
||||
pinnedAt: "2026-06-01T12:00:00.000Z",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T11:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
};
|
||||
|
||||
// Before the wake time: the snooze wins; the pin holds underneath.
|
||||
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });
|
||||
expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
|
||||
expect(whileSnoozed.snoozedCount).toBe(1);
|
||||
|
||||
// After the wake time: the thread returns pinned, back on top.
|
||||
const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" });
|
||||
expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);
|
||||
expect(afterWake.items[0]?.pinned).toBe(true);
|
||||
expect(afterWake.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("classifies snooze with the second-precise clock and reports the next wake", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
@@ -619,11 +626,10 @@ 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"), projectId, title: "Included" }),
|
||||
makeThread({ id: ThreadId.make("included"), title: "Included" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("excluded"),
|
||||
projectId: otherProjectId,
|
||||
@@ -631,7 +637,7 @@ describe("buildThreadListV2Items", () => {
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [{ environmentId, projectId }],
|
||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
@@ -641,21 +647,19 @@ 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"), projectId, title: "Local" }),
|
||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("remote"),
|
||||
projectId,
|
||||
title: "Remote",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [
|
||||
{ environmentId, projectId },
|
||||
{ environmentId: remoteEnvironmentId, projectId },
|
||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
||||
],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
@@ -678,9 +682,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.
|
||||
latestRun: {
|
||||
runId: RunId.make(`run-${index}`),
|
||||
status: "completed",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${index}`),
|
||||
state: "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`,
|
||||
|
||||
@@ -84,7 +84,7 @@ export function resolveThreadListV2SwipeActions(input: {
|
||||
export function resolveThreadListV2SnoozeGateExpiryMs(
|
||||
thread: Pick<
|
||||
EnvironmentThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestRun" | "latestUserMessageAt" | "runtime"
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): number | null {
|
||||
@@ -121,29 +121,8 @@ 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" | "runtime">,
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
): ThreadListV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
@@ -151,13 +130,10 @@ export function resolveThreadListV2Status(
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "input";
|
||||
}
|
||||
if (
|
||||
thread.runtime !== null &&
|
||||
["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
|
||||
) {
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
return "working";
|
||||
}
|
||||
if (thread.runtime?.status === "failed") {
|
||||
if (thread.session?.status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
return "ready";
|
||||
@@ -204,6 +180,8 @@ export interface ThreadListV2Item {
|
||||
readonly variant: "card" | "slim";
|
||||
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
|
||||
readonly snoozed: boolean;
|
||||
/** Pinned-block row: renders the pin glyph and offers Unpin. */
|
||||
readonly pinned: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
@@ -375,12 +353,12 @@ export function buildThreadListV2Items(input: {
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
: null;
|
||||
|
||||
const pinned: EnvironmentThreadShell[] = [];
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
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;
|
||||
@@ -403,9 +381,10 @@ export function buildThreadListV2Items(input: {
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: a snoozed thread leaves the list until it
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
// Visibility parity with web: snooze outranks everything, including a
|
||||
// pin — a snoozed thread leaves the list until it wakes (or raises its
|
||||
// hand). The pin survives underneath, so a woken thread reappears at
|
||||
// its original spot in the creation-ordered pinned block.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozed.push(thread);
|
||||
if (
|
||||
@@ -417,6 +396,12 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A pin otherwise overrides the lifecycle: pinned threads render above
|
||||
// the inbox and never auto-settle out of sight.
|
||||
if (thread.pinnedAt != null) {
|
||||
pinned.push(thread);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
@@ -459,11 +444,21 @@ export function buildThreadListV2Items(input: {
|
||||
);
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of sortThreadsForListV2(pinned)) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
snoozed: false,
|
||||
pinned: true,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
for (const thread of orderedActive) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
snoozed: false,
|
||||
pinned: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
@@ -473,6 +468,7 @@ export function buildThreadListV2Items(input: {
|
||||
thread,
|
||||
variant: "slim",
|
||||
snoozed: true,
|
||||
pinned: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
@@ -482,6 +478,7 @@ export function buildThreadListV2Items(input: {
|
||||
thread,
|
||||
variant: "slim",
|
||||
snoozed: false,
|
||||
pinned: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts";
|
||||
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
export function threadSortValue(thread: EnvironmentThreadShell): number {
|
||||
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
|
||||
@@ -33,10 +31,14 @@ export const THREAD_STATUS_NEUTRAL_ICON = {
|
||||
iconBackground: "rgba(142,142,147,0.22)",
|
||||
} as const;
|
||||
|
||||
function isLatestRunSettled(thread: EnvironmentThreadShell): boolean {
|
||||
if (!thread.latestRun?.startedAt) return false;
|
||||
if (!thread.latestRun.completedAt) return false;
|
||||
return !threadRuntimeIsActive(thread.runtime);
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,9 +73,7 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
const runtimeStatus = thread.runtime?.status;
|
||||
|
||||
if (runtimeStatus === "running" || runtimeStatus === "waiting") {
|
||||
if (thread.session?.status === "running") {
|
||||
return {
|
||||
kind: "working",
|
||||
label: "Working",
|
||||
@@ -85,7 +85,7 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (runtimeStatus === "preparing" || runtimeStatus === "queued" || runtimeStatus === "starting") {
|
||||
if (thread.session?.status === "starting") {
|
||||
return {
|
||||
kind: "connecting",
|
||||
label: "Connecting",
|
||||
@@ -97,7 +97,7 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (runtimeStatus === "failed" || thread.latestRun?.status === "failed") {
|
||||
if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
|
||||
return {
|
||||
kind: "error",
|
||||
label: "Error",
|
||||
@@ -111,7 +111,7 @@ export function resolveThreadStatus(
|
||||
|
||||
const hasPlanReadyPrompt =
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestRunSettled(thread) &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
thread.hasActionableProposedPlan;
|
||||
if (hasPlanReadyPrompt) {
|
||||
return {
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,6 @@ 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,7 +4,6 @@ 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">,
|
||||
@@ -24,20 +23,24 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
|
||||
): EnvironmentThreadShell {
|
||||
return makeThreadShellFixture({
|
||||
return {
|
||||
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", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentId, ProjectId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
|
||||
import { ApprovalRequestId, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
|
||||
return `${environmentId}:${projectId}`;
|
||||
@@ -10,7 +10,7 @@ export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId
|
||||
|
||||
export function scopedRequestKey(
|
||||
environmentId: EnvironmentId,
|
||||
requestId: RuntimeRequestId,
|
||||
requestId: ApprovalRequestId,
|
||||
): string {
|
||||
return `${environmentId}:${requestId}`;
|
||||
}
|
||||
@@ -1,282 +1,466 @@
|
||||
import {
|
||||
MessageId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type OrchestrationV2TurnItem,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const sourceThreadId = ThreadId.make("thread-source");
|
||||
const runId = RunId.make("run-1");
|
||||
|
||||
function base(id: string, updatedAt: string, ordinal: number) {
|
||||
const timestamp = DateTime.makeUnsafe(updatedAt);
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: TurnItemId.make(id),
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt: timestamp,
|
||||
completedAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
tone: "info",
|
||||
payload: {},
|
||||
turnId: null,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function projected(
|
||||
item: OrchestrationV2TurnItem,
|
||||
position: number,
|
||||
visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
|
||||
): OrchestrationV2ProjectedTurnItem {
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,
|
||||
): OrchestrationThread {
|
||||
return {
|
||||
position,
|
||||
visibility,
|
||||
sourceThreadId: visibility === "local" ? threadId : sourceThreadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
};
|
||||
}
|
||||
|
||||
function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") {
|
||||
return {
|
||||
...base("item-user", updatedAt, 0),
|
||||
type: "user_message" as const,
|
||||
messageId: MessageId.make("message-user"),
|
||||
createdBy: "user" as const,
|
||||
creationSource: "mobile" as const,
|
||||
inputIntent: "turn_start" as const,
|
||||
text: "Run checks",
|
||||
attachments: [],
|
||||
};
|
||||
}
|
||||
|
||||
function command(updatedAt = "2026-06-20T00:00:02.000Z") {
|
||||
return {
|
||||
...base("item-command", updatedAt, 1),
|
||||
type: "command_execution" as const,
|
||||
input: "vp check",
|
||||
output: "ok",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
|
||||
return {
|
||||
...base("item-assistant", updatedAt, 2),
|
||||
type: "assistant_message" as const,
|
||||
messageId: MessageId.make("message-assistant"),
|
||||
text: "Done",
|
||||
streaming: false,
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
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,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("does not treat a queued-only run as live feed activity", () => {
|
||||
expect(
|
||||
threadFeedRunIsUnsettled({
|
||||
runId,
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
it("keeps historic work entries attributed to their turns", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Runtime warning thread",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
threadFeedRunIsUnsettled({
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("activity-old"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-old"),
|
||||
payload: {
|
||||
message: "Old warning",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("activity-latest"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
payload: {
|
||||
message: "Latest warning",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-old",
|
||||
activities: [{ id: "activity-old", turnId: "turn-old" }],
|
||||
},
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-latest",
|
||||
activities: [{ id: "activity-latest", turnId: "turn-latest" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("adds queued input only after dispatch creates its turn item", () => {
|
||||
const dispatchedRunId = RunId.make("run-dispatched-queued");
|
||||
const dispatchedMessageId = MessageId.make("message-dispatched-queued");
|
||||
expect(buildThreadFeed([])).toEqual([]);
|
||||
it("collapses matching tool lifecycle rows like desktop", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Collapsed tools",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-updated"),
|
||||
kind: "tool.updated",
|
||||
tone: "tool",
|
||||
summary: "Run tests",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run tests completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const promotedEntries = buildThreadFeed([
|
||||
projected(
|
||||
{
|
||||
...userMessage(),
|
||||
id: TurnItemId.make("item-dispatched-queued"),
|
||||
runId: dispatchedRunId,
|
||||
messageId: dispatchedMessageId,
|
||||
inputIntent: "turn_start",
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
type: "activity-group",
|
||||
});
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(1);
|
||||
expect(group.activities[0]).toMatchObject({
|
||||
id: "tool-completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: "turn-1",
|
||||
summary: "Run tests",
|
||||
detail: "bun run test",
|
||||
canExpand: true,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status: "success",
|
||||
});
|
||||
expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'");
|
||||
expect(group.activities[0]?.getCopyText()).toBe(
|
||||
"Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps MCP inputs available to expanded mobile work rows", () => {
|
||||
const turnId = TurnId.make("turn-mcp");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-mcp"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Expandable MCP call",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("mcp-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Call repository tool",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Call repository tool",
|
||||
itemType: "mcp_tool_call",
|
||||
detail: "repository.search",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
server: "repository",
|
||||
tool: "search",
|
||||
arguments: { query: "work log" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
|
||||
});
|
||||
|
||||
it("defers large tool output expansion until a work row is opened or copied", () => {
|
||||
let serializedToolOutputs = 0;
|
||||
const activities = Array.from({ length: 5_000 }, (_, index) =>
|
||||
makeActivity({
|
||||
id: EventId.make(`large-tool-${index}`),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: `Tool ${index}`,
|
||||
createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(),
|
||||
payload: {
|
||||
title: `Tool ${index}`,
|
||||
itemType: "mcp_tool_call",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
toJSON: () => {
|
||||
serializedToolOutputs += 1;
|
||||
return { output: "x".repeat(32_768) };
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
0,
|
||||
),
|
||||
]);
|
||||
expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]);
|
||||
expect(
|
||||
promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined,
|
||||
).toBe("turn_start");
|
||||
});
|
||||
|
||||
it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
|
||||
const rows = [
|
||||
projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
|
||||
projected(command("2026-06-20T00:00:01.000Z"), 1),
|
||||
projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2),
|
||||
];
|
||||
|
||||
const feed = buildThreadFeed(rows);
|
||||
expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
|
||||
expect(feed.map((entry) => entry.id)).toEqual([
|
||||
"message-user",
|
||||
"local:thread-1:item-command",
|
||||
"message-assistant",
|
||||
]);
|
||||
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
|
||||
expect(activity?.projectedItem).toBe(rows[1]);
|
||||
expect(activity?.getFullDetail()).toContain('"input": "vp check"');
|
||||
});
|
||||
|
||||
it("retains inherited and synthetic rows with their original projected identity", () => {
|
||||
const inherited = projected(command(), 0, "inherited");
|
||||
const { providerThreadId: _providerThreadId, ...forkBase } = base(
|
||||
"item-fork",
|
||||
"2026-06-20T00:00:03.000Z",
|
||||
2,
|
||||
}),
|
||||
);
|
||||
const synthetic = projected(
|
||||
{
|
||||
...forkBase,
|
||||
type: "fork",
|
||||
source: { type: "run", threadId: sourceThreadId, runId },
|
||||
targetThreadId: threadId,
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-large-tools"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Large tools",
|
||||
activities,
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(serializedToolOutputs).toBe(0);
|
||||
|
||||
const group = feed[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(5_000);
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
expect(group.activities[0]?.getCopyText()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
});
|
||||
|
||||
it("folds settled turn work while leaving the terminal answer visible", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-3"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Folded work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:18.000Z",
|
||||
assistantMessageId: MessageId.make("assistant-final"),
|
||||
},
|
||||
1,
|
||||
"synthetic",
|
||||
);
|
||||
|
||||
const feed = buildThreadFeed([inherited, synthetic]);
|
||||
const activities = feed.flatMap((entry) =>
|
||||
entry.type === "activity-group" ? entry.activities : [],
|
||||
);
|
||||
expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]);
|
||||
expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([
|
||||
"inherited",
|
||||
"synthetic",
|
||||
]);
|
||||
expect(activities.at(-1)?.prominent).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps orchestration relationship cards visible when a completed run is folded", () => {
|
||||
const { providerThreadId: _providerThreadId, ...forkBase } = base(
|
||||
"item-fork",
|
||||
"2026-06-20T00:00:02.500Z",
|
||||
2,
|
||||
);
|
||||
const feed = buildThreadFeed([
|
||||
projected(userMessage(), 0),
|
||||
projected(command(), 1),
|
||||
projected(
|
||||
messages: [
|
||||
{
|
||||
...forkBase,
|
||||
type: "fork",
|
||||
source: { type: "run", threadId, runId },
|
||||
targetThreadId: sourceThreadId,
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "I am checking.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
},
|
||||
2,
|
||||
),
|
||||
projected(assistantMessage(), 3),
|
||||
]);
|
||||
{
|
||||
id: MessageId.make("assistant-final"),
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:18.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Read files",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Read files",
|
||||
itemType: "file_read",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(
|
||||
feed,
|
||||
{
|
||||
runId,
|
||||
status: "completed",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: "2026-06-20T00:00:03.000Z",
|
||||
},
|
||||
new Set(),
|
||||
);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
type: "turn-fold",
|
||||
label: "Worked for 17s",
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
collapsed.some(
|
||||
(entry) =>
|
||||
entry.type === "activity-group" &&
|
||||
entry.activities.some((activity) => activity.projectedItem.item.type === "fork"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
collapsed.some(
|
||||
(entry) =>
|
||||
entry.type === "activity-group" &&
|
||||
entry.activities.some(
|
||||
(activity) => activity.projectedItem.item.type === "command_execution",
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
|
||||
const feed = buildThreadFeed([
|
||||
projected(userMessage(), 0),
|
||||
projected(command(), 1),
|
||||
projected(assistantMessage(), 2),
|
||||
]);
|
||||
const latestRun = {
|
||||
runId,
|
||||
status: "completed" as const,
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: "2026-06-20T00:00:03.000Z",
|
||||
};
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
|
||||
expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
|
||||
expect(expanded.map((entry) => entry.type)).toEqual([
|
||||
"message",
|
||||
"run-fold",
|
||||
"activity-group",
|
||||
"message",
|
||||
const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"turn-fold:turn-1",
|
||||
"assistant-commentary",
|
||||
"tool-completed",
|
||||
"assistant-final",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an active run expanded and marks failed tools as failures", () => {
|
||||
const failedCommand: OrchestrationV2TurnItem = {
|
||||
...command(),
|
||||
status: "failed",
|
||||
completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
|
||||
};
|
||||
const feed = buildThreadFeed([projected(userMessage(), 0), projected(failedCommand, 1)]);
|
||||
const presented = deriveThreadFeedPresentation(
|
||||
feed,
|
||||
{
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
it("measures a steer-superseded turn from its user boundary through trailing work", () => {
|
||||
const firstTurnId = TurnId.make("turn-1");
|
||||
const secondTurnId = TurnId.make("turn-2");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-steered"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Steered work",
|
||||
latestTurn: {
|
||||
turnId: secondTurnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:14.000Z",
|
||||
startedAt: "2026-04-01T00:00:14.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: MessageId.make("assistant-next"),
|
||||
},
|
||||
new Set(),
|
||||
);
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("user-1"),
|
||||
role: "user",
|
||||
text: "Do it once more.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "Kicking off call 1.",
|
||||
turnId: firstTurnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:09.000Z",
|
||||
updatedAt: "2026-04-01T00:00:09.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("user-2"),
|
||||
role: "user",
|
||||
text: "Actually do 15.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:14.000Z",
|
||||
updatedAt: "2026-04-01T00:00:14.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-next"),
|
||||
role: "assistant",
|
||||
text: "One down - adjusting.",
|
||||
turnId: secondTurnId,
|
||||
streaming: true,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:17.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("work-1"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Ran command",
|
||||
createdAt: "2026-04-01T00:00:12.000Z",
|
||||
turnId: firstTurnId,
|
||||
payload: {
|
||||
title: "Ran command",
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
|
||||
expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe(
|
||||
"failure",
|
||||
);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
label: "Worked for 12s",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an active turn expanded and classifies error-shaped tool output", () => {
|
||||
const turnId = TurnId.make("turn-running");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-4"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Running work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-failed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run command",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Run command",
|
||||
itemType: "command_execution",
|
||||
detail: "zsh: command not found: nope",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
@@ -301,25 +485,22 @@ describe("buildThreadFeed", () => {
|
||||
): ThreadFeedActivity => ({
|
||||
id,
|
||||
createdAt,
|
||||
runId: null,
|
||||
turnId: null,
|
||||
summary: `Tool ${id}`,
|
||||
detail: null,
|
||||
canExpand: false,
|
||||
getFullDetail: () => null,
|
||||
getCopyText: () => id,
|
||||
icon: "command",
|
||||
logo: null,
|
||||
toolLike: true,
|
||||
prominent: false,
|
||||
status,
|
||||
projectedItem: projected(command(createdAt), 0),
|
||||
});
|
||||
const feed: ThreadFeedEntry[] = [
|
||||
{
|
||||
type: "activity-group",
|
||||
id: "work-group-1",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
runId: null,
|
||||
turnId: null,
|
||||
activities: [
|
||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
||||
@@ -350,21 +531,4 @@ describe("buildThreadFeed", () => {
|
||||
expanded: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("pretty prints T3 MCP dynamic tool activities and attaches the product logo", () => {
|
||||
const toolItem: OrchestrationV2TurnItem = {
|
||||
...base("item-t3-tool", "2026-06-20T00:00:04.000Z", 3),
|
||||
type: "dynamic_tool",
|
||||
toolName: "mcp__t3-code__t3_thread_read",
|
||||
input: { threadId: "thread-child" },
|
||||
output: { messages: [] },
|
||||
};
|
||||
|
||||
const feed = buildThreadFeed([projected(toolItem, 0)]);
|
||||
const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null;
|
||||
|
||||
expect(activity?.summary).toBe("Read a T3 thread");
|
||||
expect(activity?.logo).toBe("t3-code");
|
||||
expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread");
|
||||
});
|
||||
});
|
||||
+1104
-404
File diff suppressed because it is too large.
Load diff
@@ -1,257 +0,0 @@
|
||||
import { EMPTY_V2_ITEM_SUPPORT } from "@t3tools/client-runtime/state/item-support";
|
||||
import {
|
||||
CheckpointId,
|
||||
CheckpointScopeId,
|
||||
NodeId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type OrchestrationV2TurnItem,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadFeed, type ThreadFeedActivity } from "./threadActivity";
|
||||
import { buildThreadActivityInspector } from "./threadActivityInspector";
|
||||
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const sourceThreadId = ThreadId.make("thread-source");
|
||||
const runId = RunId.make("run-1");
|
||||
const nodeId = NodeId.make("node-1");
|
||||
const startedAt = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
|
||||
const completedAt = DateTime.makeUnsafe("2026-06-20T00:00:02.000Z");
|
||||
|
||||
function itemBase(id: string) {
|
||||
return {
|
||||
id: TurnItemId.make(id),
|
||||
threadId,
|
||||
runId,
|
||||
nodeId,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt,
|
||||
completedAt,
|
||||
updatedAt: completedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function activityFor(item: OrchestrationV2TurnItem): ThreadFeedActivity {
|
||||
const row: OrchestrationV2ProjectedTurnItem = {
|
||||
position: 0,
|
||||
visibility: "inherited",
|
||||
sourceThreadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
};
|
||||
const group = buildThreadFeed([row])[0];
|
||||
if (group?.type !== "activity-group" || !group.activities[0]) {
|
||||
throw new Error("Expected an activity group");
|
||||
}
|
||||
return group.activities[0];
|
||||
}
|
||||
|
||||
describe("buildThreadActivityInspector", () => {
|
||||
it("presents command lifecycle, execution support, output, and exit state", () => {
|
||||
const item: OrchestrationV2TurnItem = {
|
||||
...itemBase("command"),
|
||||
type: "command_execution",
|
||||
input: "vp check",
|
||||
output: "all checks passed",
|
||||
exitCode: 0,
|
||||
};
|
||||
const support = {
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
run: { status: "completed" } as never,
|
||||
attempts: [
|
||||
{
|
||||
id: "attempt-1",
|
||||
attemptOrdinal: 1,
|
||||
status: "superseded",
|
||||
reason: "initial",
|
||||
},
|
||||
{
|
||||
id: "attempt-2",
|
||||
attemptOrdinal: 2,
|
||||
status: "completed",
|
||||
reason: "steering_restart",
|
||||
},
|
||||
] as never,
|
||||
node: { kind: "tool_call", status: "completed" } as never,
|
||||
providerSession: {
|
||||
status: "ready",
|
||||
model: "gpt-5.4",
|
||||
cwd: "/workspace/project",
|
||||
} as never,
|
||||
};
|
||||
|
||||
const model = buildThreadActivityInspector(activityFor(item), support, sourceThreadId);
|
||||
expect(model.fields).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ label: "Duration", value: "2.0s" },
|
||||
{ label: "Run", value: "completed" },
|
||||
{ label: "Working directory", value: "/workspace/project" },
|
||||
{ label: "Visibility", value: "inherited" },
|
||||
]),
|
||||
);
|
||||
expect(model.blocks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ label: "Command", value: "vp check" }),
|
||||
expect.objectContaining({ label: "Output", value: "all checks passed" }),
|
||||
expect.objectContaining({ label: "Exit", value: "Process exited with code 0" }),
|
||||
expect.objectContaining({ label: "Attempt history" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes file and web result provenance plus dynamic structured data", () => {
|
||||
const fileSearch: OrchestrationV2TurnItem = {
|
||||
...itemBase("file-search"),
|
||||
type: "file_search",
|
||||
pattern: "resolveSession",
|
||||
results: [{ fileName: "src/session.ts", line: 42, preview: "function resolveSession()" }],
|
||||
};
|
||||
const fileModel = buildThreadActivityInspector(
|
||||
activityFor(fileSearch),
|
||||
EMPTY_V2_ITEM_SUPPORT,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(fileModel.fileLinks).toEqual([
|
||||
{
|
||||
label: "src/session.ts — function resolveSession()",
|
||||
path: "src/session.ts",
|
||||
line: 42,
|
||||
},
|
||||
]);
|
||||
|
||||
const webSearch: OrchestrationV2TurnItem = {
|
||||
...itemBase("web-search"),
|
||||
type: "web_search",
|
||||
patterns: ["Effect Schema docs"],
|
||||
results: [
|
||||
{ title: "Schema", url: "https://effect.website/docs/schema", snippet: "Typed schemas" },
|
||||
],
|
||||
};
|
||||
const webModel = buildThreadActivityInspector(
|
||||
activityFor(webSearch),
|
||||
EMPTY_V2_ITEM_SUPPORT,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(webModel.webLinks).toEqual([
|
||||
{ label: "Schema", url: "https://effect.website/docs/schema" },
|
||||
]);
|
||||
expect(webModel.blocks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ label: "Schema", value: "Typed schemas" }),
|
||||
]),
|
||||
);
|
||||
|
||||
const dynamicTool: OrchestrationV2TurnItem = {
|
||||
...itemBase("dynamic"),
|
||||
type: "dynamic_tool",
|
||||
toolName: "custom",
|
||||
input: { nested: { value: 1 } },
|
||||
output: { ok: true },
|
||||
};
|
||||
const dynamicModel = buildThreadActivityInspector(
|
||||
activityFor(dynamicTool),
|
||||
EMPTY_V2_ITEM_SUPPORT,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(dynamicModel.blocks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ label: "Input", value: expect.stringContaining('"nested"') }),
|
||||
expect.objectContaining({ label: "Output", value: expect.stringContaining('"ok"') }),
|
||||
]),
|
||||
);
|
||||
expect(dynamicModel.structuredDetails).toContain('"type": "dynamic_tool"');
|
||||
});
|
||||
|
||||
it("enables rollback only for the matching ready checkpoint", () => {
|
||||
const checkpointId = CheckpointId.make("checkpoint-1");
|
||||
const scopeId = CheckpointScopeId.make("scope-1");
|
||||
const item: OrchestrationV2TurnItem = {
|
||||
...itemBase("checkpoint"),
|
||||
type: "checkpoint",
|
||||
checkpointId,
|
||||
scopeId,
|
||||
files: [{ path: "src/main.ts", kind: "modified", additions: 2, deletions: 1 }],
|
||||
};
|
||||
const checkpoint = { id: checkpointId, scopeId, status: "ready" } as never;
|
||||
const model = buildThreadActivityInspector(
|
||||
activityFor(item),
|
||||
{
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
checkpoint,
|
||||
},
|
||||
sourceThreadId,
|
||||
);
|
||||
|
||||
expect(model.canRollback).toBe(true);
|
||||
expect(model.rollbackTarget).toEqual({
|
||||
threadId: sourceThreadId,
|
||||
checkpointId,
|
||||
scopeId,
|
||||
});
|
||||
|
||||
const inheritedModel = buildThreadActivityInspector(
|
||||
activityFor(item),
|
||||
{
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
checkpoint,
|
||||
},
|
||||
ThreadId.make("child-thread"),
|
||||
);
|
||||
expect(inheritedModel.canRollback).toBe(false);
|
||||
expect(inheritedModel.rollbackTarget).toBeNull();
|
||||
});
|
||||
|
||||
it("prefers live subagent progress from supporting state", () => {
|
||||
const item: OrchestrationV2TurnItem = {
|
||||
...itemBase("subagent"),
|
||||
type: "subagent",
|
||||
subagentId: nodeId,
|
||||
origin: "provider_native",
|
||||
driver: ProviderDriverKind.make("claude"),
|
||||
providerInstanceId: ProviderInstanceId.make("claude"),
|
||||
childThreadId: null,
|
||||
prompt: "Audit the reducer",
|
||||
progress: "Starting",
|
||||
result: null,
|
||||
};
|
||||
const model = buildThreadActivityInspector(
|
||||
activityFor(item),
|
||||
{
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
subagent: {
|
||||
origin: "provider_native",
|
||||
status: "running",
|
||||
progress: "Reading projection tests",
|
||||
result: null,
|
||||
} as never,
|
||||
},
|
||||
sourceThreadId,
|
||||
);
|
||||
|
||||
expect(model.fields).toContainEqual({
|
||||
label: "Delegated task",
|
||||
value: "provider native · running",
|
||||
});
|
||||
expect(model.blocks).toContainEqual({
|
||||
label: "Progress",
|
||||
value: "Reading projection tests",
|
||||
monospaced: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,308 +0,0 @@
|
||||
import type { V2ItemSupport } from "@t3tools/client-runtime/state/item-support";
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { ThreadFeedActivity } from "./threadActivity";
|
||||
|
||||
export interface ThreadActivityInspectorField {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
export interface ThreadActivityInspectorBlock {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly monospaced: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadActivityFileLink {
|
||||
readonly label: string;
|
||||
readonly path: string;
|
||||
readonly line?: number;
|
||||
}
|
||||
|
||||
export interface ThreadActivityWebLink {
|
||||
readonly label: string;
|
||||
readonly url: string;
|
||||
}
|
||||
|
||||
export interface ThreadActivityInspectorModel {
|
||||
readonly fields: ReadonlyArray<ThreadActivityInspectorField>;
|
||||
readonly blocks: ReadonlyArray<ThreadActivityInspectorBlock>;
|
||||
readonly fileLinks: ReadonlyArray<ThreadActivityFileLink>;
|
||||
readonly webLinks: ReadonlyArray<ThreadActivityWebLink>;
|
||||
readonly canRollback: boolean;
|
||||
readonly rollbackTarget: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly checkpointId: string;
|
||||
readonly scopeId: string;
|
||||
} | null;
|
||||
readonly structuredDetails: string;
|
||||
}
|
||||
|
||||
function formatStructured(value: unknown): string {
|
||||
if (typeof value === "string") return value;
|
||||
try {
|
||||
return JSON.stringify(value, null, 2) ?? String(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function durationLabel(
|
||||
startedAt: DateTime.Utc | null,
|
||||
completedAt: DateTime.Utc | null,
|
||||
): string | null {
|
||||
if (startedAt === null) return null;
|
||||
const start = DateTime.toEpochMillis(startedAt);
|
||||
const end = completedAt === null ? Date.now() : DateTime.toEpochMillis(completedAt);
|
||||
return formatDuration(Math.max(0, end - start));
|
||||
}
|
||||
|
||||
function addBlock(
|
||||
blocks: ThreadActivityInspectorBlock[],
|
||||
label: string,
|
||||
value: unknown,
|
||||
monospaced = true,
|
||||
): void {
|
||||
if (value === undefined || value === null || value === "") return;
|
||||
blocks.push({ label, value: formatStructured(value), monospaced });
|
||||
}
|
||||
|
||||
export function buildThreadActivityInspector(
|
||||
activity: ThreadFeedActivity,
|
||||
support: V2ItemSupport,
|
||||
currentThreadId: ThreadId,
|
||||
): ThreadActivityInspectorModel {
|
||||
const row = activity.projectedItem;
|
||||
const item = row.item;
|
||||
const fields: ThreadActivityInspectorField[] = [
|
||||
{ label: "Item", value: item.type.replaceAll("_", " ") },
|
||||
{ label: "Status", value: item.status.replaceAll("_", " ") },
|
||||
];
|
||||
const duration = durationLabel(item.startedAt, item.completedAt);
|
||||
if (duration) fields.push({ label: "Duration", value: duration });
|
||||
if (row.visibility !== "local") fields.push({ label: "Visibility", value: row.visibility });
|
||||
if (support.run) fields.push({ label: "Run", value: support.run.status });
|
||||
|
||||
const latestAttempt = support.attempts.at(-1);
|
||||
if (latestAttempt) {
|
||||
fields.push({
|
||||
label: "Attempt",
|
||||
value: `${latestAttempt.attemptOrdinal} · ${latestAttempt.status} · ${latestAttempt.reason.replaceAll("_", " ")}`,
|
||||
});
|
||||
}
|
||||
if (support.node) {
|
||||
fields.push({
|
||||
label: "Node",
|
||||
value: `${support.node.kind.replaceAll("_", " ")} · ${support.node.status}`,
|
||||
});
|
||||
}
|
||||
if (support.providerThread) {
|
||||
fields.push({
|
||||
label: "Provider thread",
|
||||
value: `${support.providerThread.providerInstanceId} · ${support.providerThread.status}`,
|
||||
});
|
||||
}
|
||||
if (support.providerTurn) {
|
||||
fields.push({ label: "Provider turn", value: support.providerTurn.status });
|
||||
}
|
||||
if (support.providerSession) {
|
||||
fields.push({
|
||||
label: "Session",
|
||||
value: `${support.providerSession.status} · ${support.providerSession.model ?? "default model"}`,
|
||||
});
|
||||
fields.push({ label: "Working directory", value: support.providerSession.cwd });
|
||||
}
|
||||
if (support.runtimeRequest) {
|
||||
fields.push({
|
||||
label: "Request",
|
||||
value: `${support.runtimeRequest.status} · ${support.runtimeRequest.responseCapability.type.replaceAll("_", " ")}`,
|
||||
});
|
||||
}
|
||||
|
||||
const blocks: ThreadActivityInspectorBlock[] = [];
|
||||
const fileLinks: ThreadActivityFileLink[] = [];
|
||||
const webLinks: ThreadActivityWebLink[] = [];
|
||||
|
||||
if (support.attempts.length > 1) {
|
||||
addBlock(
|
||||
blocks,
|
||||
"Attempt history",
|
||||
support.attempts
|
||||
.map(
|
||||
(attempt) =>
|
||||
`Attempt ${attempt.attemptOrdinal} · ${attempt.status} · ${attempt.reason.replaceAll("_", " ")}`,
|
||||
)
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
switch (item.type) {
|
||||
case "reasoning":
|
||||
addBlock(blocks, "Reasoning", item.text, false);
|
||||
break;
|
||||
case "command_execution":
|
||||
addBlock(blocks, "Command", item.input);
|
||||
addBlock(blocks, "Output", item.output);
|
||||
if (item.exitCode !== undefined) {
|
||||
addBlock(blocks, "Exit", `Process exited with code ${item.exitCode}`);
|
||||
}
|
||||
break;
|
||||
case "file_change":
|
||||
fileLinks.push({ label: item.fileName, path: item.fileName });
|
||||
if (item.additions !== undefined || item.deletions !== undefined) {
|
||||
fields.push({
|
||||
label: "Changes",
|
||||
value: `+${item.additions ?? 0} −${item.deletions ?? 0}`,
|
||||
});
|
||||
}
|
||||
addBlock(blocks, "Patch", item.diffStr);
|
||||
addBlock(blocks, "Before", item.oldStr);
|
||||
addBlock(blocks, "After", item.newStr);
|
||||
break;
|
||||
case "file_search":
|
||||
addBlock(blocks, "Query", item.pattern);
|
||||
for (const result of item.results ?? []) {
|
||||
fileLinks.push({
|
||||
label: result.preview ? `${result.fileName} — ${result.preview}` : result.fileName,
|
||||
path: result.fileName,
|
||||
...(result.line === undefined ? {} : { line: result.line }),
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "web_search":
|
||||
addBlock(blocks, "Queries", item.patterns?.join("\n"));
|
||||
for (const result of item.results ?? []) {
|
||||
if (result.url) {
|
||||
webLinks.push({
|
||||
label: result.title ?? result.url,
|
||||
url: result.url,
|
||||
});
|
||||
}
|
||||
if (result.snippet)
|
||||
addBlock(blocks, result.title ?? "Search result", result.snippet, false);
|
||||
}
|
||||
break;
|
||||
case "dynamic_tool":
|
||||
addBlock(blocks, "Input", item.input);
|
||||
addBlock(blocks, "Output", item.output);
|
||||
break;
|
||||
case "approval_request":
|
||||
addBlock(blocks, "Prompt", item.prompt, false);
|
||||
break;
|
||||
case "user_input_request":
|
||||
addBlock(
|
||||
blocks,
|
||||
"Questions",
|
||||
item.questions.map((question) => question.question).join("\n"),
|
||||
false,
|
||||
);
|
||||
break;
|
||||
case "checkpoint":
|
||||
addBlock(
|
||||
blocks,
|
||||
"Files",
|
||||
item.files
|
||||
.map((file) => `${file.path} +${file.additions} −${file.deletions} ${file.kind}`)
|
||||
.join("\n"),
|
||||
);
|
||||
break;
|
||||
case "subagent":
|
||||
addBlock(blocks, "Prompt", item.prompt, false);
|
||||
addBlock(blocks, "Progress", support.subagent?.progress ?? item.progress, false);
|
||||
addBlock(blocks, "Result", support.subagent?.result ?? item.result, false);
|
||||
if (support.subagent) {
|
||||
fields.push({
|
||||
label: "Delegated task",
|
||||
value: `${support.subagent.origin.replaceAll("_", " ")} · ${support.subagent.status}`,
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "handoff":
|
||||
addBlock(blocks, "Summary", item.summary, false);
|
||||
fields.push({
|
||||
label: "Handoff",
|
||||
value: `${item.strategy.replaceAll("_", " ")} · ${support.contextHandoff?.status ?? item.status}`,
|
||||
});
|
||||
if (support.contextTransfer) {
|
||||
fields.push({
|
||||
label: "Transfer",
|
||||
value: `${support.contextTransfer.type.replaceAll("_", " ")} · ${support.contextTransfer.status}`,
|
||||
});
|
||||
if (support.contextTransfer.resolution) {
|
||||
fields.push({
|
||||
label: "Context",
|
||||
value: support.contextTransfer.resolution.strategy.replaceAll("_", " "),
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "error":
|
||||
addBlock(blocks, "Error", item.failure.message, false);
|
||||
if (item.failure.code) fields.push({ label: "Code", value: item.failure.code });
|
||||
if (item.failure.retryable !== null) {
|
||||
fields.push({ label: "Retryable", value: item.failure.retryable ? "yes" : "no" });
|
||||
}
|
||||
break;
|
||||
case "proposed_plan":
|
||||
addBlock(blocks, "Plan", item.markdown, false);
|
||||
break;
|
||||
case "todo_list":
|
||||
addBlock(
|
||||
blocks,
|
||||
"Tasks",
|
||||
item.steps
|
||||
.map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`)
|
||||
.join("\n"),
|
||||
false,
|
||||
);
|
||||
addBlock(blocks, "Explanation", item.explanation, false);
|
||||
break;
|
||||
case "compaction":
|
||||
addBlock(blocks, "Summary", item.summary, false);
|
||||
if (item.beforeTokenCount !== undefined || item.afterTokenCount !== undefined) {
|
||||
fields.push({
|
||||
label: "Context tokens",
|
||||
value: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"}`,
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "run_interrupt_request":
|
||||
case "run_interrupt_result":
|
||||
addBlock(blocks, "Message", item.message, false);
|
||||
break;
|
||||
case "fork":
|
||||
case "thread_created":
|
||||
case "user_message":
|
||||
case "assistant_message":
|
||||
break;
|
||||
}
|
||||
|
||||
const checkpoint =
|
||||
item.type === "checkpoint" && row.sourceThreadId === currentThreadId
|
||||
? support.checkpoint
|
||||
: null;
|
||||
return {
|
||||
fields,
|
||||
blocks,
|
||||
fileLinks,
|
||||
webLinks,
|
||||
canRollback: checkpoint?.status === "ready",
|
||||
rollbackTarget:
|
||||
checkpoint?.status === "ready"
|
||||
? {
|
||||
threadId: row.sourceThreadId,
|
||||
checkpointId: checkpoint.id,
|
||||
scopeId: checkpoint.scopeId,
|
||||
}
|
||||
: null,
|
||||
structuredDetails: formatStructured({
|
||||
visibility: row.visibility,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
item,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { useEffect, useMemo, useState } from "react";
|
||||
import { orchestrationEnvironment } from "./orchestration";
|
||||
import { projectEnvironment } from "./projects";
|
||||
import { useEnvironmentQuery } from "./query";
|
||||
import { useEnvironmentThread } from "./threads";
|
||||
import { vcsEnvironment } from "./vcs";
|
||||
import {
|
||||
buildCheckpointDiffTargets,
|
||||
@@ -38,6 +39,13 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
labelPrefix: "mobile:thread-search",
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
}
|
||||
|
||||
export interface ComposerPathSearchTarget {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
@@ -84,6 +92,19 @@ export function useThreadSearch(
|
||||
};
|
||||
}
|
||||
|
||||
export function useThreadDetail(
|
||||
environmentId: EnvironmentId | null,
|
||||
threadId: ThreadId | null,
|
||||
): ThreadDetailView {
|
||||
const state = useEnvironmentThread(environmentId, threadId);
|
||||
return {
|
||||
data: Option.getOrNull(state.data),
|
||||
error: Option.getOrNull(state.error),
|
||||
isPending: state.status === "synchronizing",
|
||||
isDeleted: state.status === "deleted",
|
||||
};
|
||||
}
|
||||
|
||||
export function useBranches(input: {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
|
||||
@@ -38,9 +38,8 @@ export function useEnvironmentThread(
|
||||
? environmentThreads.stateAtom(environmentId, threadId)
|
||||
: EMPTY_THREAD_STATE_ATOM,
|
||||
);
|
||||
const state = Option.getOrElse(
|
||||
return Option.getOrElse(
|
||||
AsyncResult.value(result),
|
||||
() => EMPTY_ENVIRONMENT_THREAD_STATE,
|
||||
) as EnvironmentThreadState;
|
||||
return state;
|
||||
}
|
||||
@@ -1,19 +1,21 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
|
||||
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { scopedRequestKey } from "../lib/scopedEntities";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useSelectedThreadProjection } from "./use-thread-detail";
|
||||
import { useSelectedThreadDetail } from "./use-thread-detail";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
|
||||
@@ -62,21 +64,27 @@ export function useSelectedThreadRequests() {
|
||||
"thread user input response",
|
||||
);
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThread = useSelectedThreadProjection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const pendingRequests = useMemo(
|
||||
() =>
|
||||
selectedThread === null
|
||||
? { approvals: [], userInputs: [] }
|
||||
: derivePendingThreadRequests(selectedThread.projection),
|
||||
// Sort once; both derivations expect the same lifecycle ordering.
|
||||
const sortedActivities = useMemo(
|
||||
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApprovals = pendingRequests.approvals;
|
||||
const activePendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = pendingRequests.userInputs;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => derivePendingUserInputs(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
activePendingUserInput && selectedThreadShell
|
||||
@@ -89,7 +97,7 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: RuntimeRequestId, questionId: string, label: string) => {
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -101,7 +109,7 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onChangeUserInputCustomAnswer = useCallback(
|
||||
(requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
|
||||
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -113,16 +121,10 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
activePendingApprovals.find((approval) => approval.requestId === requestId)
|
||||
?.responseCapability !== "live"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingApprovalId(requestId);
|
||||
const result = await respondToApproval({
|
||||
@@ -136,16 +138,11 @@ export function useSelectedThreadRequests() {
|
||||
setRespondingApprovalId((current) => (current === requestId ? null : current));
|
||||
return result;
|
||||
},
|
||||
[activePendingApprovals, respondToApproval, selectedThreadShell],
|
||||
[respondToApproval, selectedThreadShell],
|
||||
);
|
||||
|
||||
const onSubmitUserInput = useCallback(async () => {
|
||||
if (
|
||||
!selectedThreadShell ||
|
||||
!activePendingUserInput ||
|
||||
activePendingUserInput.responseCapability !== "live" ||
|
||||
!activePendingUserInputAnswers
|
||||
) {
|
||||
if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useSelectedThreadProjection } from "./use-thread-detail";
|
||||
import { useSelectedThreadDetail } from "./use-thread-detail";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
import { resolvePreferredThreadWorktreePath } from "../features/terminal/terminalLaunchContext";
|
||||
|
||||
export function useSelectedThreadWorktree() {
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadProjection();
|
||||
const detailWorktreePath = selectedThreadDetail?.projection.thread.worktreePath ?? null;
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
|
||||
const selectedThreadWorktreePath = useMemo(
|
||||
() =>
|
||||
resolvePreferredThreadWorktreePath({
|
||||
threadShellWorktreePath: selectedThread?.worktreePath ?? null,
|
||||
threadDetailWorktreePath: detailWorktreePath,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
}),
|
||||
[detailWorktreePath, selectedThread?.worktreePath],
|
||||
[selectedThread?.worktreePath, selectedThreadDetail?.worktreePath],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
deriveThreadActivityRun,
|
||||
deriveThreadRuntime,
|
||||
} from "@t3tools/client-runtime/state/thread-execution";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -42,10 +37,7 @@ import {
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
import {
|
||||
useSelectedThreadProjection,
|
||||
useSelectedThreadVisibleTurnItems,
|
||||
} from "../state/use-thread-detail";
|
||||
import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
@@ -83,8 +75,7 @@ export function useThreadDraftForThread(input: {
|
||||
|
||||
export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadProjection = useSelectedThreadProjection();
|
||||
const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
@@ -100,57 +91,47 @@ export function useThreadComposerState() {
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
const selectedThreadFeed = useMemo(
|
||||
() => buildThreadFeed(selectedThreadVisibleTurnItems),
|
||||
[selectedThreadVisibleTurnItems],
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
const draftAttachments = selectedDraft?.attachments ?? [];
|
||||
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
|
||||
const selectedThread = selectedThreadShell;
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
|
||||
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
|
||||
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
|
||||
const selectedThreadRuntime = useMemo(
|
||||
() =>
|
||||
selectedThreadProjection
|
||||
? deriveThreadRuntime(selectedThreadProjection.projection)
|
||||
: (selectedThreadShell?.runtime ?? null),
|
||||
[selectedThreadProjection, selectedThreadShell?.runtime],
|
||||
);
|
||||
const selectedThreadActivityRun = useMemo(
|
||||
() =>
|
||||
selectedThreadProjection
|
||||
? deriveThreadActivityRun(selectedThreadProjection.projection)
|
||||
: (selectedThreadShell?.latestRun ?? null),
|
||||
[selectedThreadProjection, selectedThreadShell?.latestRun],
|
||||
);
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
if (!selectedThreadRuntime) {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread?.session) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
orchestrationStatus: selectedThreadRuntime.status,
|
||||
activeRunId: selectedThreadRuntime.activeRunId ?? undefined,
|
||||
orchestrationStatus: selectedThread.session.status,
|
||||
activeTurnId: selectedThread.session.activeTurnId ?? undefined,
|
||||
};
|
||||
}, [selectedThreadRuntime]);
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
if (!selectedThreadShell) {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThreadActivityRun,
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
);
|
||||
}, [selectedThreadActivityRun, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
|
||||
const interruptibleRunId = selectedThreadRuntime?.activeRunId ?? null;
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
@@ -159,7 +140,7 @@ export function useThreadComposerState() {
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
const draft = getComposerDraftSnapshot(threadKey);
|
||||
const thread = selectedThreadShell;
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
@@ -198,7 +179,7 @@ export function useThreadComposerState() {
|
||||
);
|
||||
});
|
||||
return messageId;
|
||||
}, [selectedThreadShell]);
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
@@ -320,7 +301,6 @@ export function useThreadComposerState() {
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadActivityRun,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
@@ -329,7 +309,6 @@ export function useThreadComposerState() {
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
interruptibleRunId,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
onPasteIntoDraft,
|
||||
|
||||
Loaded 100 of 987 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user