Compare commits
339
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c99767e518 | ||
|
|
d45c3e7f9a | ||
|
|
e4a4c60121 | ||
|
|
a1e1ab5f04 | ||
|
|
29ebc7c37e | ||
|
|
200bcc9d8c | ||
|
|
da996a85f9 | ||
|
|
ee333b1929 | ||
|
|
b0839e45b9 | ||
|
|
fc171656c7 | ||
|
|
1aea7ba0d3 | ||
|
|
1391f94470 | ||
|
|
4b3f8be173 | ||
|
|
b95171112d | ||
|
|
ba5b043d1f | ||
|
|
aeecfd01a9 | ||
|
|
4dc6d32100 | ||
|
|
f6e005ba0f | ||
|
|
3a74176b65 | ||
|
|
b8c54e76a3 | ||
|
|
36609fd932 | ||
|
|
0e22482251 | ||
|
|
67022de4a2 | ||
|
|
7ac23a7523 | ||
|
|
87cb5bc0ad | ||
|
|
6894fe9f6f | ||
|
|
9099ca6007 | ||
|
|
c62f0ccded | ||
|
|
75a41ed26e | ||
|
|
3a2622f7ff | ||
|
|
fbb573b62e | ||
|
|
289c000a57 | ||
|
|
53d5009440 | ||
|
|
22e15a8423 | ||
|
|
dedb92f627 | ||
|
|
6ece559186 | ||
|
|
61c76c41ba | ||
|
|
b819de73af | ||
|
|
cdfbb9ac64 | ||
|
|
39bc22bb2e | ||
|
|
ae3a724dc9 | ||
|
|
2feacbf1fc | ||
|
|
5d008944dd | ||
|
|
cb09929e16 | ||
|
|
77168d081a | ||
|
|
f6601420ad | ||
|
|
a29fd51629 | ||
|
|
d6e8dd8161 | ||
|
|
8dcbdcac52 | ||
|
|
402fde73dd | ||
|
|
c03c9926ad | ||
|
|
97c97cec2b | ||
|
|
1a1bb645bb | ||
|
|
d0b6cbdec8 | ||
|
|
5f3ccad35c | ||
|
|
c4b043dc86 | ||
|
|
c6e3aeb591 | ||
|
|
8b747dd4f9 | ||
|
|
2ce54b3885 | ||
|
|
434673d803 | ||
|
|
d256570669 | ||
|
|
931cc7c440 | ||
|
|
c178154106 | ||
|
|
66d820ed32 | ||
|
|
0074bf0ad7 | ||
|
|
afdde33c68 | ||
|
|
f917cddd58 | ||
|
|
c8916f3189 | ||
|
|
a394fe4f0b | ||
|
|
4f633dacec | ||
|
|
35e4a7f429 | ||
|
|
01a1dec618 | ||
|
|
d7e5a004f5 | ||
|
|
a8e09e493e | ||
|
|
8efd4d2253 | ||
|
|
1c31861521 | ||
|
|
14a0d9a84c | ||
|
|
bb23ddfa90 | ||
|
|
94b7d5f7e1 | ||
|
|
4ff868a3bb | ||
|
|
467ff768d2 | ||
|
|
f4e9b3d5e4 | ||
|
|
4171e77b74 | ||
|
|
429a22ac6e | ||
|
|
d8257507a8 | ||
|
|
f682f0a6e6 | ||
|
|
1ad2d3b2a4 | ||
|
|
1e3732d1c6 | ||
|
|
9f23e4888c | ||
|
|
39929faaee | ||
|
|
e6b3d3d3ed | ||
|
|
82616a1b7a | ||
|
|
096bbcfc22 | ||
|
|
d68948d67c | ||
|
|
54ceb2a111 | ||
|
|
86e57c3a7c | ||
|
|
38f272829c | ||
|
|
ec4c3f0171 | ||
|
|
4124948442 | ||
|
|
918e4155dd | ||
|
|
b63287a18b | ||
|
|
a7db564861 | ||
|
|
28142a7862 | ||
|
|
761042383f | ||
|
|
0bba720192 | ||
|
|
b1ce962b44 | ||
|
|
c25c1be21f | ||
|
|
4414baf371 | ||
|
|
48346a72ab | ||
|
|
477d4c46f0 | ||
|
|
371b40e014 | ||
|
|
5ad2e8af28 | ||
|
|
c6079f6b5d | ||
|
|
b2d23ccabb | ||
|
|
8db6d9d7b3 | ||
|
|
ccb3e269ec | ||
|
|
5e711d3b10 | ||
|
|
4c999d746c | ||
|
|
bbfed6c19e | ||
|
|
ee6ff5574d | ||
|
|
2cd862d392 | ||
|
|
ba8b661995 | ||
|
|
0027aa1081 | ||
|
|
4626a059d9 | ||
|
|
c4f3a78407 | ||
|
|
c90070acc9 | ||
|
|
5134929999 | ||
|
|
5552ab5fc4 | ||
|
|
b5a13f386a | ||
|
|
ea9d12b5d8 | ||
|
|
799146af31 | ||
|
|
3752cb5f4b | ||
|
|
8d7afca437 | ||
|
|
5f7840b92f | ||
|
|
29f716986b | ||
|
|
1d3d6f4635 | ||
|
|
91c833c548 | ||
|
|
29075a81c0 | ||
|
|
ff31b55cc9 | ||
|
|
7219dbfea7 | ||
|
|
c30c681c1f | ||
|
|
ffe2daac90 | ||
|
|
4b5e817866 | ||
|
|
955fe1c630 | ||
|
|
685fe6c6de | ||
|
|
377b8f2287 | ||
|
|
3218e5f30b | ||
|
|
a722960f8f | ||
|
|
94eb4ce02f | ||
|
|
03366d5830 | ||
|
|
686806f72a | ||
|
|
a4d4a2d7c0 | ||
|
|
ceaa4ede4f | ||
|
|
111029e383 | ||
|
|
53e89fb4c6 | ||
|
|
1d7aed4354 | ||
|
|
64d2faccc7 | ||
|
|
0830883749 | ||
|
|
4f26e751c7 | ||
|
|
f59a5a4416 | ||
|
|
c567b83aa9 | ||
|
|
24ddaf5694 | ||
|
|
7a26bfc75e | ||
|
|
0ab943a5fb | ||
|
|
f789188c7b | ||
|
|
d90cba6656 | ||
|
|
0bec96fce7 | ||
|
|
165ce66c97 | ||
|
|
b75aa98050 | ||
|
|
daddf826fd | ||
|
|
c8a8c421b2 | ||
|
|
606b9086a7 | ||
|
|
41a16d958a | ||
|
|
32b749d07e | ||
|
|
9c65560b35 | ||
|
|
97474423c7 | ||
|
|
d584feccda | ||
|
|
8ccb33f755 | ||
|
|
1519070601 | ||
|
|
b13febf528 | ||
|
|
4d7d87c3d9 | ||
|
|
d1118b6183 | ||
|
|
6e491d199d | ||
|
|
7fa6cdcbd1 | ||
|
|
4c8471a271 | ||
|
|
f5e797c70e | ||
|
|
c0017bf640 | ||
|
|
728d184c8e | ||
|
|
bd76cc06c0 | ||
|
|
bc76ab4db3 | ||
|
|
e62b8710aa | ||
|
|
b6d302cd82 | ||
|
|
b883940c9a | ||
|
|
fc72144f40 | ||
|
|
8d7bfec473 | ||
|
|
4e28472e91 | ||
|
|
6a0fe7c0f6 | ||
|
|
74217a71af | ||
|
|
6f35159fbe | ||
|
|
89ec767058 | ||
|
|
29cd06590a | ||
|
|
626a879b78 | ||
|
|
bfcf0445d9 | ||
|
|
5e28e470b8 | ||
|
|
3f50a50f8d | ||
|
|
76785f31f7 | ||
|
|
a78e69b1cc | ||
|
|
6b04c941d5 | ||
|
|
96ecd33a39 | ||
|
|
0e80e11955 | ||
|
|
9b3a9fdf5e | ||
|
|
d11747b27c | ||
|
|
5e9bd12edd | ||
|
|
1a03d3232e | ||
|
|
4be1e0fe13 | ||
|
|
6ff48331b7 | ||
|
|
0d295cf098 | ||
|
|
5e1536e260 | ||
|
|
b7f71acd29 | ||
|
|
c996dc479e | ||
|
|
9bf8cea6af | ||
|
|
3aa295a9f6 | ||
|
|
be243ae91a | ||
|
|
559e41a91f | ||
|
|
6d64cac00b | ||
|
|
d358d16a39 | ||
|
|
63f2e161e7 | ||
|
|
27da49519f | ||
|
|
12173fe8e9 | ||
|
|
4aad08e645 | ||
|
|
c8b20831e2 | ||
|
|
34c6d5ea18 | ||
|
|
0e1cf4e0ed | ||
|
|
d7abcb569f | ||
|
|
b38863bbd2 | ||
|
|
3596d26659 | ||
|
|
3211e667fd | ||
|
|
c4fbe434b6 | ||
|
|
df9d6ec566 | ||
|
|
259018c744 | ||
|
|
50106cc8da | ||
|
|
8923fbd180 | ||
|
|
caf564ad94 | ||
|
|
404393a840 | ||
|
|
f929f667f8 | ||
|
|
e852d5ccda | ||
|
|
333cec5023 | ||
|
|
4adae8e308 | ||
|
|
92468574f9 | ||
|
|
adb97a1036 | ||
|
|
2fd7bb706b | ||
|
|
4170d9f395 | ||
|
|
b589aa2976 | ||
|
|
885bde7c3d | ||
|
|
81a47cfe19 | ||
|
|
6fa7bdb177 | ||
|
|
ba559425c7 | ||
|
|
b1c0b267fb | ||
|
|
69676c50bc | ||
|
|
ed09178238 | ||
|
|
f12635c520 | ||
|
|
8c678b9005 | ||
|
|
266b32318c | ||
|
|
4405cb98d3 | ||
|
|
9fe1122f7d | ||
|
|
91e92fb128 | ||
|
|
68b703643d | ||
|
|
ffbe9de9b8 | ||
|
|
8c853d981c | ||
|
|
9ba4535e5e | ||
|
|
70778705f4 | ||
|
|
11b4f021db | ||
|
|
7c0d40fefe | ||
|
|
90d0f40790 | ||
|
|
038560e580 | ||
|
|
21a3669cee | ||
|
|
b3b4b57794 | ||
|
|
6ae44b418a | ||
|
|
4a2f8b04bb | ||
|
|
8f9ab0845d | ||
|
|
baaeda305c | ||
|
|
7e01d33f0e | ||
|
|
9fd788b5a9 | ||
|
|
710fd0eeb3 | ||
|
|
e15f655ba4 | ||
|
|
59be6f7846 | ||
|
|
5304f3e9d4 | ||
|
|
85389b9883 | ||
|
|
db1507e986 | ||
|
|
96bfa67b3d | ||
|
|
5ff3a03ada | ||
|
|
23d45d914e | ||
|
|
bad1143b02 | ||
|
|
92d4a2e996 | ||
|
|
2fab18e289 | ||
|
|
1b16ed663f | ||
|
|
83ad26c3a3 | ||
|
|
fd51561b4e | ||
|
|
9e201941aa | ||
|
|
2ab188f1c0 | ||
|
|
9513e62e24 | ||
|
|
97db94c9bf | ||
|
|
5015d7cf9f | ||
|
|
df19f6cfe3 | ||
|
|
6bc6cb6be4 | ||
|
|
1e59b4c400 | ||
|
|
33f9705926 | ||
|
|
da6253b3dd | ||
|
|
ac1264e2ca | ||
|
|
2eb099fdc8 | ||
|
|
b28f9bf0a1 | ||
|
|
d0b8d6306b | ||
|
|
9666b87516 | ||
|
|
e3a9c2518d | ||
|
|
18918d1c4d | ||
|
|
8d24b5131f | ||
|
|
770946d026 | ||
|
|
8601797233 | ||
|
|
b73232bdd3 | ||
|
|
f131228a59 | ||
|
|
e321667b10 | ||
|
|
849bac8946 | ||
|
|
6fd088af9f | ||
|
|
b54bfc9312 | ||
|
|
e1378a1f4d | ||
|
|
5a84614809 | ||
|
|
63e6faef62 | ||
|
|
d37a9b09b8 | ||
|
|
560d4a4560 | ||
|
|
52e5a75a87 | ||
|
|
c196f422ed | ||
|
|
f0b57ca231 | ||
|
|
2db08457f2 | ||
|
|
083fa4ab24 | ||
|
|
35172010b1 | ||
|
|
57b1052679 | ||
|
|
1e355a2a34 | ||
|
|
44621c345f | ||
|
|
220e573b14 |
No files matched your search
@@ -125,31 +125,29 @@ Do not start, stop, erase, or reconfigure an emulator owned by another task. Tra
|
||||
|
||||
## Pair each client once
|
||||
|
||||
Issue a fresh credential against the running backend's exact base directory:
|
||||
Use the bundled helper from the repository root. It issues a fresh credential against the running backend's exact base directory, opens the existing Add Environment route with the credential in an encoded query parameter, and asks that route to connect once:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--base-url <mobile-origin> \
|
||||
--ttl 15m \
|
||||
--label agent-mobile-<short-device-id>
|
||||
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
|
||||
ios <simulator-udid> <server-port> <base-dir>
|
||||
|
||||
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
|
||||
android <emulator-serial> <server-port> <base-dir>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
|
||||
Run only the command for the selected platform. The helper uses `http://127.0.0.1:<server-port>` for iOS and `http://10.0.2.2:<server-port>` for Android. Pass a fifth argument only when testing a non-development URL scheme.
|
||||
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
|
||||
The helper opens this registered route:
|
||||
|
||||
```bash
|
||||
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d 't3code-dev://connections/new' \
|
||||
com.t3tools.t3code.dev
|
||||
```text
|
||||
t3code-dev://connections/new?pairingUrl=<encoded-pairing-url>&autoConnect=1
|
||||
```
|
||||
|
||||
Run only the command for the selected platform.
|
||||
The Add Environment route owns the behavior: `pairingUrl` prefills its normal host and token inputs, while `autoConnect=1` submits once in development builds and returns to Home after success. Without `autoConnect`, the same route only prefills the form for manual inspection.
|
||||
|
||||
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
|
||||
Do not enter pairing hosts or tokens through simulator keyboard automation. Xcode's semantic typer sends HID-style key events through the simulator's active keyboard state, which can corrupt uppercase tokens and punctuation even when the host Mac uses a U.S. input source. The one-shot route is the deterministic pairing path. Use the visible form only as a fallback, and paste credentials rather than typing them character by character.
|
||||
|
||||
Verify the expected seeded projects appear before exercising the affected flow.
|
||||
|
||||
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
|
||||
|
||||
@@ -183,6 +181,8 @@ Keep local verification focused. Do not turn this workflow into a full repositor
|
||||
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
|
||||
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
|
||||
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
|
||||
- **The pairing form opens but does not connect:** confirm the deep link uses the existing `connections/new` route, includes `autoConnect=1`, and carries a freshly minted encoded `pairingUrl`.
|
||||
- **Pairing text changes case or punctuation:** do not retry semantic typing. Use `scripts/pair-client.sh`; the simulator keyboard layout and HID input path are not reliable for credentials.
|
||||
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
|
||||
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
|
||||
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 <ios|android> <device-id> <server-port> <base-dir> [url-scheme]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
[[ $# -ge 4 && $# -le 5 ]] || usage
|
||||
|
||||
platform="$1"
|
||||
device_id="$2"
|
||||
server_port="$3"
|
||||
base_dir="$4"
|
||||
url_scheme="${5:-t3code-dev}"
|
||||
|
||||
case "$platform" in
|
||||
ios)
|
||||
mobile_origin="http://127.0.0.1:${server_port}"
|
||||
;;
|
||||
android)
|
||||
mobile_origin="http://10.0.2.2:${server_port}"
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
|
||||
repo_root="$(git rev-parse --show-toplevel)"
|
||||
cd "$repo_root"
|
||||
|
||||
if ! pairing_output="$({
|
||||
T3CODE_PORT="$server_port" node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir "$base_dir" \
|
||||
--base-url "$mobile_origin" \
|
||||
--ttl 15m \
|
||||
--label "agent-mobile-${device_id:0:8}"
|
||||
} 2>&1)"; then
|
||||
echo "Could not mint a mobile pairing credential." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
pairing_url="$(printf '%s\n' "$pairing_output" | sed -n 's/^Pair URL: //p' | tail -n 1)"
|
||||
if [[ -z "$pairing_url" ]]; then
|
||||
echo "Could not parse the mobile pairing URL." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
deep_link="$(PAIRING_URL="$pairing_url" URL_SCHEME="$url_scheme" node - <<'NODE'
|
||||
const query = new URLSearchParams({
|
||||
pairingUrl: process.env.PAIRING_URL,
|
||||
autoConnect: "1",
|
||||
});
|
||||
process.stdout.write(`${process.env.URL_SCHEME}://connections/new?${query}`);
|
||||
NODE
|
||||
)"
|
||||
|
||||
case "$platform" in
|
||||
ios)
|
||||
xcrun simctl openurl "$device_id" "$deep_link"
|
||||
;;
|
||||
android)
|
||||
# adb shell re-joins its arguments and evaluates them through the device
|
||||
# shell, so the deep link's `?`/`&` must be quoted once more for that shell.
|
||||
adb -s "$device_id" shell \
|
||||
"am start -W -a android.intent.action.VIEW -d '$deep_link' com.t3tools.t3code.dev" \
|
||||
>/dev/null
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "Opened the existing Add Environment route with a fresh pairing credential."
|
||||
@@ -37,3 +37,5 @@ github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
github:SunkenInTime
|
||||
github:bil0000
|
||||
@@ -1,429 +0,0 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const ARTIFACT_NAME = "thread-transfer-results";
|
||||
const RESULT_FILE = "thread-transfer-result.json";
|
||||
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
|
||||
const PROVIDERS = ["codex", "claudeAgent"];
|
||||
const OBSERVED_KEYS = [
|
||||
"totalWireBytes",
|
||||
"threadSnapshotWireBytes",
|
||||
"threadSnapshotDecodedBytes",
|
||||
"measuredTurnWebSocketWireBytes",
|
||||
"measuredTurnWebSocketDecodedBytes",
|
||||
"measuredTurnWebSocketMessages",
|
||||
];
|
||||
const CEILING_KEYS = [
|
||||
"totalWireBytes",
|
||||
"threadSnapshotWireBytes",
|
||||
"measuredTurnWebSocketWireBytes",
|
||||
"measuredTurnWebSocketDecodedBytes",
|
||||
"measuredTurnWebSocketMessages",
|
||||
];
|
||||
const SCENARIO_KEYS = [
|
||||
"id",
|
||||
"historyTurns",
|
||||
"historyCommandToolsPerTurn",
|
||||
"historyMcpResultBytes",
|
||||
"measuredCommandTools",
|
||||
"measuredMcpResultBytes",
|
||||
];
|
||||
|
||||
function resultShaMarker(sha) {
|
||||
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
|
||||
}
|
||||
|
||||
function assertObject(value, label) {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error(`${label} must be an object`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertExactKeys(value, expected, label) {
|
||||
assertObject(value, label);
|
||||
const actual = Object.keys(value).sort();
|
||||
const wanted = [...expected].sort();
|
||||
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
|
||||
throw new Error(`${label} has unexpected fields`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertMetric(value, label) {
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
|
||||
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateResult(value) {
|
||||
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
|
||||
if (value.schemaVersion !== 1) {
|
||||
throw new Error("result.schemaVersion must be 1");
|
||||
}
|
||||
|
||||
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
|
||||
if (value.scenario.id !== "thread-transfer-v1") {
|
||||
throw new Error("result.scenario.id is not supported");
|
||||
}
|
||||
for (const key of SCENARIO_KEYS.slice(1)) {
|
||||
assertMetric(value.scenario[key], `result.scenario.${key}`);
|
||||
}
|
||||
|
||||
assertExactKeys(value.providers, PROVIDERS, "result.providers");
|
||||
for (const provider of PROVIDERS) {
|
||||
const entry = value.providers[provider];
|
||||
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
|
||||
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
|
||||
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
|
||||
for (const key of OBSERVED_KEYS) {
|
||||
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
|
||||
}
|
||||
for (const key of CEILING_KEYS) {
|
||||
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function readResult(directory) {
|
||||
if (!directory) return undefined;
|
||||
const file = path.join(directory, RESULT_FILE);
|
||||
if (!fs.existsSync(file)) return undefined;
|
||||
const stat = fs.lstatSync(file);
|
||||
if (!stat.isFile() || stat.size > 64 * 1_024) {
|
||||
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
|
||||
}
|
||||
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
if (bytes < 1_024) return `${bytes} B`;
|
||||
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
|
||||
return `${(bytes / 1_024).toFixed(1)} KiB`;
|
||||
}
|
||||
|
||||
function formatValue(value, kind) {
|
||||
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
|
||||
}
|
||||
|
||||
function formatImpact(current, baseline, kind) {
|
||||
if (baseline === undefined) return "—";
|
||||
const delta = current - baseline;
|
||||
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
|
||||
const magnitude = formatValue(Math.abs(delta), kind);
|
||||
const percent =
|
||||
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
|
||||
return `${prefix}${magnitude}${percent}`;
|
||||
}
|
||||
|
||||
function sameScenario(left, right) {
|
||||
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
|
||||
}
|
||||
|
||||
const METRICS = [
|
||||
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
|
||||
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
|
||||
{
|
||||
key: "measuredTurnWebSocketWireBytes",
|
||||
label: "Live turn WebSocket wire",
|
||||
kind: "bytes",
|
||||
},
|
||||
{
|
||||
key: "measuredTurnWebSocketDecodedBytes",
|
||||
label: "Live turn WebSocket decoded",
|
||||
kind: "bytes",
|
||||
},
|
||||
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
|
||||
];
|
||||
|
||||
function renderComment(input) {
|
||||
const current = input.current;
|
||||
const baseline = input.baseline;
|
||||
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
|
||||
const rows = [];
|
||||
const ceilingChanges = [];
|
||||
let failed = false;
|
||||
|
||||
for (const provider of PROVIDERS) {
|
||||
for (const metric of METRICS) {
|
||||
const observed = current.providers[provider].observed[metric.key];
|
||||
const ceiling = current.providers[provider].ceiling[metric.key];
|
||||
const baselineObserved = comparable
|
||||
? baseline.providers[provider].observed[metric.key]
|
||||
: undefined;
|
||||
const pass = observed <= ceiling;
|
||||
failed ||= !pass;
|
||||
rows.push(
|
||||
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
|
||||
);
|
||||
|
||||
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
|
||||
ceilingChanges.push(
|
||||
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const baselineLink = input.baselineRun
|
||||
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
|
||||
: "unavailable";
|
||||
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
|
||||
const notices = [];
|
||||
if (!baseline) {
|
||||
notices.push(
|
||||
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
|
||||
);
|
||||
} else if (!comparable) {
|
||||
notices.push(
|
||||
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
|
||||
);
|
||||
} else if (!input.baselineRun.matchesBase) {
|
||||
notices.push(
|
||||
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
|
||||
);
|
||||
}
|
||||
if (ceilingChanges.length > 0) {
|
||||
notices.push(
|
||||
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
COMMENT_MARKER,
|
||||
resultShaMarker(input.currentRun.sha),
|
||||
"## Thread transfer impact",
|
||||
"",
|
||||
failed
|
||||
? "❌ One or more thread transfer ceilings were exceeded."
|
||||
: "✅ Thread transfer remains within every enforced ceiling.",
|
||||
...(notices.length > 0 ? ["", ...notices] : []),
|
||||
"",
|
||||
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
|
||||
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
|
||||
...rows,
|
||||
"",
|
||||
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
|
||||
"",
|
||||
"<details>",
|
||||
"<summary>Scenario and decoded snapshot size</summary>",
|
||||
"",
|
||||
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
|
||||
"",
|
||||
...PROVIDERS.map(
|
||||
(provider) =>
|
||||
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
|
||||
),
|
||||
"",
|
||||
"</details>",
|
||||
"",
|
||||
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function artifactsForRun(github, owner, repo, runId) {
|
||||
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
|
||||
owner,
|
||||
repo,
|
||||
run_id: runId,
|
||||
per_page: 100,
|
||||
});
|
||||
}
|
||||
|
||||
function findResultArtifact(artifacts) {
|
||||
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
|
||||
}
|
||||
|
||||
async function resolve({ github, context, core }) {
|
||||
const source = context.payload.workflow_run;
|
||||
const { owner, repo } = context.repo;
|
||||
if (source.event !== "pull_request") {
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
let pullNumber = source.pull_requests?.[0]?.number;
|
||||
if (!pullNumber) {
|
||||
const associated = await github.paginate(
|
||||
github.rest.repos.listPullRequestsAssociatedWithCommit,
|
||||
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
|
||||
);
|
||||
const matchingPulls = associated.filter(
|
||||
(pull) =>
|
||||
pull.state === "open" &&
|
||||
pull.head.sha === source.head_sha &&
|
||||
pull.head.ref === source.head_branch,
|
||||
);
|
||||
if (matchingPulls.length !== 1) {
|
||||
core.info(
|
||||
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
|
||||
);
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
pullNumber = matchingPulls[0].number;
|
||||
}
|
||||
if (!pullNumber) {
|
||||
core.info("No open pull request is associated with the completed CI run.");
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
|
||||
if (pull.head.sha !== source.head_sha) {
|
||||
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
|
||||
const sourceArtifact = findResultArtifact(sourceArtifacts);
|
||||
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: source.workflow_id,
|
||||
branch: pull.base.ref,
|
||||
event: "push",
|
||||
status: "success",
|
||||
per_page: 100,
|
||||
});
|
||||
const orderedRuns = [
|
||||
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
|
||||
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
|
||||
].slice(0, 20);
|
||||
|
||||
let baselineRun;
|
||||
for (const run of orderedRuns) {
|
||||
const artifacts = await artifactsForRun(github, owner, repo, run.id);
|
||||
if (findResultArtifact(artifacts)) {
|
||||
baselineRun = run;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
core.setOutput("publish", "true");
|
||||
core.setOutput("pull_number", String(pullNumber));
|
||||
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
|
||||
core.setOutput("pr_run_id", String(source.id));
|
||||
core.setOutput("pr_sha", source.head_sha);
|
||||
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
|
||||
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
|
||||
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
|
||||
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
|
||||
core.setOutput(
|
||||
"baseline_matches_base",
|
||||
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
|
||||
);
|
||||
}
|
||||
|
||||
async function upsertComment(github, context, pullNumber, body, options = {}) {
|
||||
const { owner, repo } = context.repo;
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner,
|
||||
repo,
|
||||
issue_number: pullNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const existing = comments.find(
|
||||
(comment) =>
|
||||
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
|
||||
);
|
||||
if (
|
||||
options.preserveResultSha &&
|
||||
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
|
||||
} else {
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
|
||||
}
|
||||
}
|
||||
|
||||
async function upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
expectedSha,
|
||||
body,
|
||||
options,
|
||||
) {
|
||||
const { owner, repo } = context.repo;
|
||||
const { data: pull } = await github.rest.pulls.get({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: pullNumber,
|
||||
});
|
||||
if (pull.head.sha !== expectedSha) {
|
||||
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
|
||||
return false;
|
||||
}
|
||||
|
||||
await upsertComment(github, context, pullNumber, body, options);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function publish({ github, context, core }) {
|
||||
const pullNumber = Number(process.env.PR_NUMBER);
|
||||
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
|
||||
throw new Error("PR_NUMBER is invalid");
|
||||
}
|
||||
|
||||
const current = readResult(process.env.PR_RESULT_DIR);
|
||||
const currentRun = {
|
||||
sha: process.env.PR_SHA,
|
||||
conclusion: process.env.PR_CONCLUSION,
|
||||
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
|
||||
};
|
||||
if (!current) {
|
||||
await upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
currentRun.sha,
|
||||
[
|
||||
COMMENT_MARKER,
|
||||
"## Thread transfer impact",
|
||||
"",
|
||||
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
|
||||
"",
|
||||
"_This comment will update automatically after the next completed run._",
|
||||
].join("\n"),
|
||||
{ preserveResultSha: currentRun.sha },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
|
||||
const baselineRun = baseline
|
||||
? {
|
||||
sha: process.env.BASELINE_SHA,
|
||||
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
|
||||
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
|
||||
}
|
||||
: undefined;
|
||||
const body = renderComment({ current, baseline, currentRun, baselineRun });
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
currentRun.sha,
|
||||
body,
|
||||
);
|
||||
if (published) {
|
||||
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
publish,
|
||||
readResult,
|
||||
renderComment,
|
||||
resolve,
|
||||
upsertCommentForCurrentHead,
|
||||
validateResult,
|
||||
};
|
||||
@@ -1,292 +0,0 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
|
||||
const {
|
||||
renderComment,
|
||||
resolve,
|
||||
upsertCommentForCurrentHead,
|
||||
validateResult,
|
||||
} = require("./thread-transfer-report.cjs");
|
||||
|
||||
function result(overrides = {}) {
|
||||
const observed = {
|
||||
totalWireBytes: 2_200_000,
|
||||
threadSnapshotWireBytes: 1_950_000,
|
||||
threadSnapshotDecodedBytes: 9_100_000,
|
||||
measuredTurnWebSocketWireBytes: 250_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_150_000,
|
||||
measuredTurnWebSocketMessages: 15,
|
||||
};
|
||||
const ceiling = {
|
||||
totalWireBytes: 2_900_000,
|
||||
threadSnapshotWireBytes: 2_600_000,
|
||||
measuredTurnWebSocketWireBytes: 320_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_550_000,
|
||||
measuredTurnWebSocketMessages: 20,
|
||||
};
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
scenario: {
|
||||
id: "thread-transfer-v1",
|
||||
historyTurns: 10,
|
||||
historyCommandToolsPerTurn: 5,
|
||||
historyMcpResultBytes: 900_000,
|
||||
measuredCommandTools: 20,
|
||||
measuredMcpResultBytes: 1_100_000,
|
||||
},
|
||||
providers: {
|
||||
codex: { observed: { ...observed, ...overrides }, ceiling },
|
||||
claudeAgent: { observed, ceiling },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("validates the fixed artifact schema", () => {
|
||||
assert.equal(validateResult(result()).schemaVersion, 1);
|
||||
assert.throws(
|
||||
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
|
||||
/unexpected fields/,
|
||||
);
|
||||
assert.throws(
|
||||
() => validateResult(result({ totalWireBytes: "lots" })),
|
||||
/non-negative safe integer/,
|
||||
);
|
||||
});
|
||||
|
||||
test("renders baseline, impact, ceiling, and ceiling changes", () => {
|
||||
const baseline = result();
|
||||
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
|
||||
current.providers.codex.ceiling = {
|
||||
...current.providers.codex.ceiling,
|
||||
measuredTurnWebSocketWireBytes: 330_000,
|
||||
};
|
||||
const comment = renderComment({
|
||||
current,
|
||||
baseline,
|
||||
currentRun: {
|
||||
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
conclusion: "success",
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
|
||||
},
|
||||
baselineRun: {
|
||||
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
matchesBase: true,
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
|
||||
},
|
||||
});
|
||||
|
||||
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
|
||||
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
|
||||
assert.match(comment, /This PR changes transfer ceilings/);
|
||||
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
|
||||
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
|
||||
assert.match(
|
||||
comment,
|
||||
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
|
||||
const outputs = {};
|
||||
const listWorkflowRunArtifacts = () => {};
|
||||
const listWorkflowRuns = () => {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
const github = {
|
||||
paginate: async (method, input) => {
|
||||
if (method === listPullRequestsAssociatedWithCommit) {
|
||||
return [
|
||||
{
|
||||
number: 5350,
|
||||
state: "open",
|
||||
head: { sha: "head-sha", ref: "feature-branch", repo: null },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRunArtifacts) {
|
||||
return [
|
||||
{
|
||||
name: "thread-transfer-results",
|
||||
expired: false,
|
||||
runId: input.run_id,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRuns) {
|
||||
return [{ id: 1, head_sha: "base-sha" }];
|
||||
}
|
||||
throw new Error("unexpected pagination call");
|
||||
},
|
||||
rest: {
|
||||
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
|
||||
pulls: {
|
||||
get: async () => ({
|
||||
data: {
|
||||
head: { sha: "head-sha" },
|
||||
base: { sha: "base-sha", ref: "main" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
};
|
||||
await resolve({
|
||||
github,
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "true");
|
||||
assert.equal(outputs.pull_number, "5350");
|
||||
assert.equal(outputs.pr_artifact, "true");
|
||||
assert.equal(outputs.baseline_run_id, "1");
|
||||
assert.equal(outputs.baseline_matches_base, "true");
|
||||
});
|
||||
|
||||
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
|
||||
const outputs = {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
let fetchedPull = false;
|
||||
await resolve({
|
||||
github: {
|
||||
paginate: async (method) => {
|
||||
assert.equal(method, listPullRequestsAssociatedWithCommit);
|
||||
return [5350, 5351].map((number) => ({
|
||||
number,
|
||||
state: "open",
|
||||
head: {
|
||||
sha: "head-sha",
|
||||
ref: "feature-branch",
|
||||
repo: { full_name: "pingdotgg/t3code" },
|
||||
},
|
||||
}));
|
||||
},
|
||||
rest: {
|
||||
actions: {},
|
||||
pulls: {
|
||||
get: async () => {
|
||||
fetchedPull = true;
|
||||
},
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
},
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "false");
|
||||
assert.equal(fetchedPull, false);
|
||||
});
|
||||
|
||||
test("does not publish a stale result after the PR head advances", async () => {
|
||||
let listedComments = false;
|
||||
const info = [];
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => {
|
||||
listedComments = true;
|
||||
return [];
|
||||
},
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
throw new Error("must not create a stale comment");
|
||||
},
|
||||
updateComment: () => {
|
||||
throw new Error("must not update a stale comment");
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: (message) => info.push(message) },
|
||||
5350,
|
||||
"old-head-sha",
|
||||
"stale body",
|
||||
);
|
||||
|
||||
assert.equal(published, false);
|
||||
assert.equal(listedComments, false);
|
||||
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
|
||||
});
|
||||
|
||||
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
|
||||
let updatedComment = false;
|
||||
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => [
|
||||
{
|
||||
id: 1,
|
||||
user: { login: "github-actions[bot]" },
|
||||
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
|
||||
},
|
||||
],
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
updateComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: () => {} },
|
||||
5350,
|
||||
sha,
|
||||
"missing artifact warning",
|
||||
{ preserveResultSha: sha },
|
||||
);
|
||||
|
||||
assert.equal(published, true);
|
||||
assert.equal(updatedComment, false);
|
||||
});
|
||||
@@ -70,6 +70,16 @@ jobs:
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
# Blacksmith boots GitHub's Ubuntu runner image (gcc is usually present),
|
||||
# but ACP process-tree live tests compile a small pthread fixture with `cc`
|
||||
# and soft-skip when it is missing. Install build-essential so that path
|
||||
# always runs in CI instead of silently no-oping.
|
||||
- name: Install C toolchain for process-tree fixtures
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends build-essential
|
||||
command -v cc
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
name: Thread Transfer Report
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish PR comment
|
||||
if: github.event.workflow_run.event == 'pull_request'
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
# workflow_run has a write-capable token even for fork PRs. Only load the
|
||||
# publisher from the trusted default branch and never execute PR code.
|
||||
- name: Checkout trusted publisher
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
sparse-checkout: .github/scripts
|
||||
|
||||
- name: Test trusted publisher
|
||||
run: node --test .github/scripts/thread-transfer-report.test.cjs
|
||||
|
||||
- id: resolve
|
||||
name: Resolve PR and baseline artifacts
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.resolve({ github, context, core });
|
||||
|
||||
- name: Download PR result
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/pr
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
|
||||
- name: Download main baseline
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/main
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
|
||||
- name: Update thread transfer comment
|
||||
if: steps.resolve.outputs.publish == 'true'
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_NUMBER: ${{ steps.resolve.outputs.pull_number }}
|
||||
PR_SHA: ${{ steps.resolve.outputs.pr_sha }}
|
||||
PR_CONCLUSION: ${{ steps.resolve.outputs.pr_conclusion }}
|
||||
PR_RUN_ID: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
PR_RESULT_DIR: ${{ runner.temp }}/thread-transfer/pr
|
||||
BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }}
|
||||
BASELINE_MATCHES_BASE: ${{ steps.resolve.outputs.baseline_matches_base }}
|
||||
BASELINE_RUN_ID: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
BASELINE_RESULT_DIR: ${{ runner.temp }}/thread-transfer/main
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.publish({ github, context, core });
|
||||
@@ -0,0 +1,246 @@
|
||||
# Plan: Thread Lineage And Lazy Context Transfer
|
||||
|
||||
## Summary
|
||||
|
||||
Implement the shared backend foundation for forking, provider handoff, merge-back, and future subagents without forcing provider selection at fork time. The first slice should create cheap app-level fork lineage and defer expensive context materialization until a run starts and the target provider is known.
|
||||
|
||||
Architecture reference: `docs/orchestration-v2/thread-lineage-and-context-transfer.md`.
|
||||
|
||||
## Goals
|
||||
|
||||
- Support user-created fork threads for exploration.
|
||||
- Keep fork creation provider-neutral and cheap.
|
||||
- Reuse the same source-point/context-transfer model for provider switching, merge-back, and future subagents.
|
||||
- Prefer native same-provider fork at first dispatch when available.
|
||||
- Fall back to portable context only when native transfer is unavailable or target provider differs.
|
||||
- Keep all behavior replayable through V2 events/projections.
|
||||
|
||||
## Non-Goals For First Slice
|
||||
|
||||
- Full portable context generation quality.
|
||||
- Cross-provider adapter implementation beyond the data/runtime hook.
|
||||
- Merge-back UI.
|
||||
- Native or custom subagent orchestration.
|
||||
- Forking from actively streaming provider state.
|
||||
- Backward compatibility with old dev databases.
|
||||
|
||||
## Core Data Model
|
||||
|
||||
Add schema/contracts for:
|
||||
|
||||
```ts
|
||||
type ContextTransferType =
|
||||
| "fork"
|
||||
| "provider_handoff"
|
||||
| "merge_back"
|
||||
| "subagent_spawn"
|
||||
| "subagent_result";
|
||||
|
||||
type ContextSourcePoint = {
|
||||
threadId: ThreadId;
|
||||
runId?: RunId;
|
||||
checkpointId?: CheckpointId;
|
||||
turnItemId?: TurnItemId;
|
||||
providerThreadRef?: NativeThreadRef;
|
||||
providerTurnRef?: NativeTurnRef;
|
||||
};
|
||||
|
||||
type ContextTransferStatus =
|
||||
| "pending"
|
||||
| "resolved_native"
|
||||
| "resolved_portable"
|
||||
| "failed"
|
||||
| "consumed"
|
||||
| "superseded";
|
||||
```
|
||||
|
||||
Persist:
|
||||
|
||||
- `orchestration_v2_projection_context_transfers`
|
||||
- optional later portable handoff payload columns/table if the existing context handoff projection is not enough
|
||||
|
||||
For the first slice, `ContextTransfer` is required. Materialized `ContextHandoff` payloads can be deferred until portable context is implemented.
|
||||
|
||||
## Events
|
||||
|
||||
Add V2 events:
|
||||
|
||||
- `context-transfer.created`
|
||||
- `context-transfer.updated`
|
||||
- possibly `context-handoff.created` later
|
||||
|
||||
Do not emit provider-native fork details as app identity. Native fork refs belong in the transfer resolution payload and provider thread refs.
|
||||
|
||||
## Commands
|
||||
|
||||
Add:
|
||||
|
||||
```ts
|
||||
type ThreadForkCommand = {
|
||||
type: "thread.fork";
|
||||
commandId: CommandId;
|
||||
sourceThreadId: ThreadId;
|
||||
targetThreadId: ThreadId;
|
||||
sourcePoint:
|
||||
| { type: "latest_stable" }
|
||||
| { type: "run"; runId: RunId }
|
||||
| { type: "checkpoint"; checkpointId: CheckpointId };
|
||||
title?: string;
|
||||
createdAt: string;
|
||||
};
|
||||
```
|
||||
|
||||
First-slice policy:
|
||||
|
||||
- `latest_stable` resolves to latest completed run checkpoint.
|
||||
- explicit completed run/checkpoint is accepted.
|
||||
- active run source is rejected or resolved to latest stable checkpoint; choose one policy and test it.
|
||||
- target thread starts idle.
|
||||
- no provider session/thread is created by `thread.fork`.
|
||||
|
||||
## Runtime Hook
|
||||
|
||||
Add a provider-neutral start-context resolver used by run startup:
|
||||
|
||||
```ts
|
||||
resolveStartContext({
|
||||
threadId,
|
||||
runId,
|
||||
provider,
|
||||
modelSelection,
|
||||
userMessage,
|
||||
}): Effect<StartContextResolution, StartContextResolutionError>
|
||||
```
|
||||
|
||||
Resolution order:
|
||||
|
||||
1. No pending transfer targeting the thread/run: normal run start.
|
||||
2. Pending fork transfer and same provider with native fork support: resolve native fork.
|
||||
3. Pending transfer requiring portable context: return explicit unsupported/stub result in first slice, or build minimal portable context if cheap.
|
||||
4. Failed resolution: fail command before provider side effects.
|
||||
|
||||
The resolver should be called before provider thread creation/startTurn so the adapter can decide whether to create, resume, or native-fork provider state.
|
||||
|
||||
## Codex Native Fork Path
|
||||
|
||||
Investigate the app-server native fork API in `effect-codex-app-server` and Codex docs/probes.
|
||||
|
||||
Implementation target:
|
||||
|
||||
- use native fork only when source provider is Codex and source native refs are strong;
|
||||
- create or bind a new `ProviderThread` for the forked native thread;
|
||||
- when the source point is an earlier completed Codex provider turn, fork the latest native thread first and then rollback the forked native thread by later terminal provider turns;
|
||||
- mark `ContextTransfer.status = resolved_native` and then `consumed` when the first run starts;
|
||||
- preserve source app thread lineage separately from native thread refs.
|
||||
|
||||
If native API details are not clean, land the data model and resolver first with native fork marked unsupported, then add Codex native fork in a follow-up.
|
||||
|
||||
## Portable Context Fallback
|
||||
|
||||
The first slice should define the fallback boundary even if it does not fully implement high-quality summarization.
|
||||
|
||||
Minimum viable fallback:
|
||||
|
||||
- detect cross-provider fork/handoff need;
|
||||
- create failed/unsupported transfer resolution with a clear command error, or
|
||||
- generate a deterministic minimal context handoff from app projection if we want a usable MVP.
|
||||
|
||||
Do not silently concatenate hidden summaries into the user message without a `ContextTransfer`/`ContextHandoff` record.
|
||||
|
||||
## Merge-Back Preparation
|
||||
|
||||
Do not implement merge-back in the first slice, but keep model support:
|
||||
|
||||
- `ContextTransfer.type = "merge_back"`
|
||||
- `basePoint` on transfer
|
||||
- source thread may differ from target thread
|
||||
|
||||
The later merge-back command should create a transfer from fork latest stable point back to source thread and consume it with the next user message.
|
||||
|
||||
## Subagent Preparation
|
||||
|
||||
Do not implement subagents in this slice, but keep model support:
|
||||
|
||||
- `createdBy: "agent"`
|
||||
- `type: "subagent_spawn"` and `"subagent_result"`
|
||||
- source/target thread relationship fields
|
||||
|
||||
Native subagent ingestion can later map provider-native child refs into the same graph. Cross-provider app-owned subagents can later create child app threads using the same transfer primitive.
|
||||
|
||||
## Projection And Debugger
|
||||
|
||||
Backend projection first:
|
||||
|
||||
- expose thread lineage in thread projection;
|
||||
- expose context transfers in debug projection;
|
||||
- expose transfer status and resolution strategy.
|
||||
|
||||
Debugger after backend:
|
||||
|
||||
- fork button/control from stable source point;
|
||||
- show thread lineage/source point;
|
||||
- show pending/resolved/failed transfers;
|
||||
- show native vs portable resolution.
|
||||
|
||||
Do not build debugger controls before the backend projection is authoritative.
|
||||
|
||||
## Tests
|
||||
|
||||
Use `bun run test`, not `bun test`.
|
||||
|
||||
Required backend tests:
|
||||
|
||||
- `thread.fork` from latest completed checkpoint creates target thread and pending transfer.
|
||||
- fork command is idempotent through command receipts.
|
||||
- fork does not create provider session/thread eagerly.
|
||||
- first run on same-provider fork invokes native resolution path when capability exists.
|
||||
- unsupported native fork falls back or fails according to explicit policy.
|
||||
- active-run fork policy is deterministic.
|
||||
- replay/recovery preserves target thread lineage and pending transfer.
|
||||
|
||||
Add test provider layers only at external service boundaries. Do not mock core orchestration policy.
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Add contract schemas and ids for context transfers/source points.
|
||||
2. Add migration/projection table for context transfers.
|
||||
3. Add event store/projection handling for transfer events.
|
||||
4. Add `thread.fork` command policy and orchestrator path.
|
||||
5. Add tests for cheap idle fork creation and recovery.
|
||||
6. Add start-context resolver interface.
|
||||
7. Wire resolver into run startup with no-op behavior.
|
||||
8. Add Codex native fork capability investigation and adapter path.
|
||||
9. Add tests for same-provider native fork resolution.
|
||||
10. Add debug projection surface after backend behavior is stable.
|
||||
|
||||
## Validation
|
||||
|
||||
Before considering the slice complete:
|
||||
|
||||
- `bun fmt`
|
||||
- `bun lint`
|
||||
- `bun typecheck`
|
||||
- targeted backend tests with `bun run test`
|
||||
|
||||
If backend code changes are included, tests must cover the new orchestration behavior before the task is considered done.
|
||||
|
||||
## Implementation Status
|
||||
|
||||
Implemented in this slice:
|
||||
|
||||
- context transfer ids, schemas, JSON codecs, events, and projection storage
|
||||
- app-thread lineage on thread creation and fork creation
|
||||
- `thread.fork` command using `latest_stable`, explicit run, or explicit checkpoint source points
|
||||
- cheap idle fork creation with no eager provider session/thread/run
|
||||
- Codex same-provider native `thread/fork` resolution on first target dispatch
|
||||
- Codex native fork-from-earlier-run resolution with `thread/fork` plus fork-local `thread/rollback`
|
||||
- transfer status progression through `pending`, `resolved_native`, and `consumed`
|
||||
- command receipt idempotency for duplicate fork commands
|
||||
- replay-backed integration coverage for lazy fork creation and native Codex fork consumption
|
||||
|
||||
Explicitly deferred:
|
||||
|
||||
- portable `ContextHandoff` materialization for cross-provider forks/provider handoff
|
||||
- merge-back command/runtime
|
||||
- subagent spawn/result runtime
|
||||
- debugger controls for creating/inspecting transfers
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,3 +12,4 @@
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
21. `21-orchestration-v2-application-integration.md`
|
||||
@@ -114,7 +114,6 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
|
||||
- Never make a PR unless the developer explicitly asks you to do so.
|
||||
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
|
||||
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
|
||||
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
|
||||
- UI changes need before/after images. Motion or timing needs a short video.
|
||||
- One concern per PR. If the description says "also", split it.
|
||||
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
|
||||
|
||||
@@ -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)
|
||||
- [Customize a project icon](./docs/user/project-settings.md)
|
||||
- [Appearance preferences](./docs/user/appearance.md)
|
||||
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
|
||||
- [Keeping app and server in sync](./docs/user/updating.md)
|
||||
- [Source control integrations](./docs/user/source-control.md)
|
||||
|
||||
@@ -95,6 +95,8 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.userDataDirName, "t3code");
|
||||
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha)");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.orElseSucceed((): string | null => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
|
||||
@@ -0,0 +1,999 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MAX_FAVICON_CANDIDATES,
|
||||
MAX_FAVICON_RESPONSE_BYTES,
|
||||
captureFavicon,
|
||||
selectFaviconCandidates,
|
||||
} from "./FaviconCapture.ts";
|
||||
|
||||
const PNG = "data:image/png;base64,cG5n";
|
||||
const SOURCE_PNG = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(SOURCE_PNG);
|
||||
SOURCE_PNG.writeUInt32BE(1, 16);
|
||||
SOURCE_PNG.writeUInt32BE(1, 20);
|
||||
const SOURCE_PNG_URL = `data:image/png;base64,${SOURCE_PNG.toString("base64")}`;
|
||||
|
||||
function sourceGif(
|
||||
width: number,
|
||||
height: number,
|
||||
frameWidth = width,
|
||||
frameHeight = height,
|
||||
additionalFrames: ReadonlyArray<{
|
||||
readonly left?: number;
|
||||
readonly top?: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}> = [],
|
||||
): Buffer {
|
||||
const frames = [{ width: frameWidth, height: frameHeight }, ...additionalFrames];
|
||||
const buffer = Buffer.alloc(13 + frames.length * 12 + 1);
|
||||
buffer.write("GIF89a", 0, "ascii");
|
||||
buffer.writeUInt16LE(width, 6);
|
||||
buffer.writeUInt16LE(height, 8);
|
||||
let offset = 13;
|
||||
for (const frame of frames) {
|
||||
buffer[offset] = 0x2c;
|
||||
buffer.writeUInt16LE(frame.left ?? 0, offset + 1);
|
||||
buffer.writeUInt16LE(frame.top ?? 0, offset + 3);
|
||||
buffer.writeUInt16LE(frame.width, offset + 5);
|
||||
buffer.writeUInt16LE(frame.height, offset + 7);
|
||||
offset += 10;
|
||||
buffer[offset] = 2;
|
||||
buffer[offset + 1] = 0;
|
||||
offset += 2;
|
||||
}
|
||||
buffer[offset] = 0x3b;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceJpeg(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: number | ReadonlyArray<number> = [],
|
||||
): Buffer {
|
||||
const frame = Buffer.from([
|
||||
0xff,
|
||||
0xd8,
|
||||
0xff,
|
||||
0xc0,
|
||||
0x00,
|
||||
0x07,
|
||||
0x08,
|
||||
height >>> 8,
|
||||
height & 0xff,
|
||||
width >>> 8,
|
||||
width & 0xff,
|
||||
]);
|
||||
const app1Segments = (typeof orientations === "number" ? [orientations] : orientations).map(
|
||||
(orientation) => sourceJpegExifSegment([orientation]),
|
||||
);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...app1Segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegApp1Segment(payload: Buffer): Buffer {
|
||||
const app1 = Buffer.alloc(4 + payload.byteLength);
|
||||
app1[0] = 0xff;
|
||||
app1[1] = 0xe1;
|
||||
app1.writeUInt16BE(payload.byteLength + 2, 2);
|
||||
payload.copy(app1, 4);
|
||||
return app1;
|
||||
}
|
||||
|
||||
function sourceJpegExifSegment(
|
||||
orientations: ReadonlyArray<number>,
|
||||
options?: {
|
||||
readonly byteOrder?: "II" | "MM";
|
||||
readonly magic?: number;
|
||||
readonly padding?: number;
|
||||
},
|
||||
): Buffer {
|
||||
const exif = Buffer.alloc(20 + orientations.length * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif[5] = options?.padding ?? 0;
|
||||
const littleEndian = options?.byteOrder !== "MM";
|
||||
exif.write(littleEndian ? "II" : "MM", 6, "ascii");
|
||||
const writeUInt16 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt16LE(value, offset) : exif.writeUInt16BE(value, offset);
|
||||
const writeUInt32 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt32LE(value, offset) : exif.writeUInt32BE(value, offset);
|
||||
writeUInt16(options?.magic ?? 42, 8);
|
||||
writeUInt32(8, 10);
|
||||
writeUInt16(orientations.length, 14);
|
||||
orientations.forEach((orientation, index) => {
|
||||
const entryOffset = 16 + index * 12;
|
||||
writeUInt16(0x0112, entryOffset);
|
||||
writeUInt16(3, entryOffset + 2);
|
||||
writeUInt32(1, entryOffset + 4);
|
||||
writeUInt16(orientation, entryOffset + 8);
|
||||
});
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegWithApp1Segments(
|
||||
width: number,
|
||||
height: number,
|
||||
segments: ReadonlyArray<Buffer>,
|
||||
): Buffer {
|
||||
const frame = sourceJpeg(width, height);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithOrientationEntries(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: ReadonlyArray<number>,
|
||||
): Buffer {
|
||||
return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer {
|
||||
const exif = sourceJpegExifSegment([6], { byteOrder });
|
||||
exif[10] = alias;
|
||||
exif[11] = alias;
|
||||
return sourceJpegWithApp1Segments(64, 32, [exif]);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfd(options: {
|
||||
readonly rootOrientation?: number;
|
||||
readonly subIfdFirst?: boolean;
|
||||
readonly subIfdOrientation: number;
|
||||
}): Buffer {
|
||||
const rootEntries = options.rootOrientation === undefined ? 1 : 2;
|
||||
const rootIfdOffset = 14;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
|
||||
const writeOrientation = (offset: number, orientation: number) => {
|
||||
exif.writeUInt16LE(0x0112, offset);
|
||||
exif.writeUInt16LE(3, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt16LE(orientation, offset + 8);
|
||||
};
|
||||
const writeSubIfdPointer = (offset: number) => {
|
||||
exif.writeUInt16LE(0x8769, offset);
|
||||
exif.writeUInt16LE(4, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, offset + 8);
|
||||
};
|
||||
|
||||
const firstRootEntryOffset = rootIfdOffset + 2;
|
||||
if (options.rootOrientation === undefined) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
} else if (options.subIfdFirst) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
writeOrientation(firstRootEntryOffset + 12, options.rootOrientation);
|
||||
} else {
|
||||
writeOrientation(firstRootEntryOffset, options.rootOrientation);
|
||||
writeSubIfdPointer(firstRootEntryOffset + 12);
|
||||
}
|
||||
|
||||
exif.writeUInt16LE(1, subIfdOffset);
|
||||
writeOrientation(subIfdOffset + 2, options.subIfdOrientation);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfdPointers(options: {
|
||||
readonly pointerCount: number;
|
||||
readonly subIfdEntries: number;
|
||||
}): Buffer {
|
||||
const { pointerCount, subIfdEntries } = options;
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset);
|
||||
for (let index = 0; index < subIfdEntries; index += 1) {
|
||||
const entryOffset = subIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(1, entryOffset);
|
||||
exif.writeUInt16LE(3, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
}
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer {
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + pointerCount * 2 + 2 + subIfdEntries * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset + index * 2 - 6, entryOffset + 8);
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset + index * 2);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceWebp(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.alloc(30);
|
||||
buffer.write("RIFF", 0, "ascii");
|
||||
buffer.write("WEBP", 8, "ascii");
|
||||
buffer.write("VP8X", 12, "ascii");
|
||||
buffer.writeUIntLE(width - 1, 24, 3);
|
||||
buffer.writeUIntLE(height - 1, 27, 3);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceIco(embedded: Buffer): Buffer {
|
||||
const buffer = Buffer.alloc(22 + embedded.byteLength);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(embedded.byteLength, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
embedded.copy(buffer, 22);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafePng(): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(4096, 16);
|
||||
buffer.writeUInt32BE(4096, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourcePng(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafeDib(): Buffer {
|
||||
const buffer = Buffer.alloc(40);
|
||||
buffer.writeUInt32LE(40, 0);
|
||||
buffer.writeInt32LE(4096, 4);
|
||||
buffer.writeInt32LE(4096, 8);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeWebContents(options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
}) {
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : PNG,
|
||||
);
|
||||
return {
|
||||
webContents: {
|
||||
session: { fetch },
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
} as never,
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
};
|
||||
}
|
||||
|
||||
const JPEG_LANDSCAPE_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
resizeHeight: 16,
|
||||
resizeWidth: 32,
|
||||
} as const;
|
||||
const JPEG_PORTRAIT_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
resizeHeight: 32,
|
||||
resizeWidth: 16,
|
||||
} as const;
|
||||
|
||||
async function expectJpegLayout(
|
||||
source: Buffer,
|
||||
layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT,
|
||||
): Promise<void> {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`);
|
||||
expect(code).toContain(layout.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
describe("selectFaviconCandidates", () => {
|
||||
it("filters and deduplicates before applying the candidate cap", () => {
|
||||
const valid = Array.from(
|
||||
{ length: MAX_FAVICON_CANDIDATES + 2 },
|
||||
(_, index) => `https://example.com/favicon-${index}.png`,
|
||||
);
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 64 }, () => "javascript:alert(1)"),
|
||||
valid[0]!,
|
||||
valid[0]!,
|
||||
...valid.slice(1),
|
||||
]),
|
||||
).toEqual(valid.slice(0, MAX_FAVICON_CANDIDATES));
|
||||
});
|
||||
|
||||
it("bounds raw candidate scanning independently of the usable-candidate cap", () => {
|
||||
const oversizedInvalid = `javascript:${"x".repeat(2_048)}`;
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 128 }, () => oversizedInvalid),
|
||||
"https://example.com/too-late.png",
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("captureFavicon", () => {
|
||||
it.each([
|
||||
{
|
||||
label: "same-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://example.com/favicon.png",
|
||||
credentials: "include",
|
||||
},
|
||||
{
|
||||
label: "cross-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://cdn.example.net/favicon.png",
|
||||
credentials: "omit",
|
||||
},
|
||||
])("uses the explicit credential policy for $label requests", async (testCase) => {
|
||||
const { webContents, fetch } = makeWebContents();
|
||||
const result = await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: testCase.pageUrl,
|
||||
candidates: [testCase.faviconUrl],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
testCase.faviconUrl,
|
||||
expect.objectContaining({ credentials: testCase.credentials, redirect: "error" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("decodes base64 and percent-encoded inline images without fetching", async () => {
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const percentEncodedPng = [...SOURCE_PNG]
|
||||
.map((byte) => `%${byte.toString(16).padStart(2, "0")}`)
|
||||
.join("");
|
||||
|
||||
for (const candidate of [SOURCE_PNG_URL, `data:image/png,${percentEncodedPng}`]) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("tries the next candidate after an ordinary rejection", async () => {
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(null, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("cancels a rejected response body before trying the next candidate", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(body, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("stops a pending fetch when its capture is aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: (_url, init) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
expect(await capture).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("ends candidate fallback when the overall capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: (url, init) => {
|
||||
if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 }));
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [
|
||||
"https://example.com/first.png",
|
||||
"https://example.com/second.png",
|
||||
"https://example.com/third.png",
|
||||
],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(timeout).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not publish a rasterization that completes after the capture deadline", async () => {
|
||||
const captureTimeoutController = new AbortController();
|
||||
const rasterTimeoutController = new AbortController();
|
||||
const timeout = vi
|
||||
.spyOn(AbortSignal, "timeout")
|
||||
.mockImplementation((milliseconds) =>
|
||||
milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal,
|
||||
);
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce());
|
||||
captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a stalled response body when the capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const cancel = vi.fn();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
cancel,
|
||||
}),
|
||||
{ headers: { "content-type": "image/png" } },
|
||||
),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects and cancels an oversized streamed response", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(MAX_FAVICON_RESPONSE_BYTES));
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () => new Response(body, { headers: { "content-type": "image/png" } }),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains bounded compatibility with common favicon formats", async () => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
for (const [mime, buffer] of [
|
||||
["image/gif", sourceGif(32, 32)],
|
||||
["image/jpeg", sourceJpeg(32, 32)],
|
||||
["image/webp", sourceWebp(32, 32)],
|
||||
["image/x-icon", sourceIco(SOURCE_PNG)],
|
||||
] as const) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:${mime};base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "landscape",
|
||||
source: sourcePng(64, 32),
|
||||
resizeWidth: 32,
|
||||
resizeHeight: 16,
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
},
|
||||
{
|
||||
label: "portrait",
|
||||
source: sourcePng(32, 64),
|
||||
resizeWidth: 16,
|
||||
resizeHeight: 32,
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
},
|
||||
])("preserves $label aspect ratio within the 32x32 output", async (testCase) => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`);
|
||||
expect(code).toContain('resizeQuality: "high"');
|
||||
expect(code).toContain(testCase.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
});
|
||||
|
||||
it.each([
|
||||
...[1, 2, 3, 4].map((orientation) => ({
|
||||
label: `keeps stored dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
...[5, 6, 7, 8].map((orientation) => ({
|
||||
label: `uses display dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is transposed",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [6, 1]),
|
||||
},
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is untransposed",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [1, 6]),
|
||||
},
|
||||
{
|
||||
label: "does not consult a later EXIF segment after an invalid orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "uses a later valid orientation in the same IFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithOrientationEntries(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "skips a non-EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("not-exif")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "skips an empty EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "stops after a malformed qualifying EXIF APP1 segment",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "ignores the EXIF padding byte",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]),
|
||||
},
|
||||
{
|
||||
label: "reads big-endian EXIF",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]),
|
||||
},
|
||||
{
|
||||
label: "matches Chromium for a nonstandard TIFF magic field",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit little-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xc9, "II"),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit big-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xcd, "MM"),
|
||||
},
|
||||
{
|
||||
label: "reads an orientation from a SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a SubIFD orientation before a later root orientation",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({
|
||||
rootOrientation: 1,
|
||||
subIfdFirst: true,
|
||||
subIfdOrientation: 6,
|
||||
}),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a root orientation before a later SubIFD orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "memoizes repeated aliases to the same SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }),
|
||||
]),
|
||||
},
|
||||
])("matches Chromium JPEG layout: $label", async ({ source, layout }) => {
|
||||
await expectJpegLayout(source, layout);
|
||||
});
|
||||
|
||||
it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => {
|
||||
const source = sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithOverlappingSubIfds(32, 32),
|
||||
]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects JPEGs with multiple frame headers before rasterization", async () => {
|
||||
const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unsafe PNG size before rasterization", async () => {
|
||||
const buffer = makeUnsafePng();
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(new Uint8Array(buffer), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["GIF", "image/gif", sourceGif(4096, 4096)],
|
||||
["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)],
|
||||
["GIF later frame", "image/gif", sourceGif(1, 1, 1, 1, [{ width: 4096, height: 4096 }])],
|
||||
[
|
||||
"GIF cumulative frames",
|
||||
"image/gif",
|
||||
sourceGif(
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
Array.from({ length: 256 }, () => ({ width: 64, height: 64 })),
|
||||
),
|
||||
],
|
||||
["JPEG", "image/jpeg", sourceJpeg(4096, 4096)],
|
||||
["WebP", "image/webp", sourceWebp(4096, 4096)],
|
||||
["ICO with PNG", "image/x-icon", sourceIco(makeUnsafePng())],
|
||||
["ICO with DIB", "image/x-icon", sourceIco(makeUnsafeDib())],
|
||||
["SVG", "image/svg+xml", Buffer.from('<svg width="1" height="1"/>')],
|
||||
[
|
||||
"SVG with embedded bitmap",
|
||||
"image/svg+xml",
|
||||
Buffer.from(
|
||||
`<svg width="1" height="1"><image href="data:image/png;base64,${makeUnsafePng().toString("base64")}"/></svg>`,
|
||||
),
|
||||
],
|
||||
[
|
||||
"ICO invalid payload span",
|
||||
"image/x-icon",
|
||||
(() => {
|
||||
const buffer = Buffer.alloc(22);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(100, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
return buffer;
|
||||
})(),
|
||||
],
|
||||
])("rejects unsafe or unsupported %s before rasterization", async (_label, mime, buffer) => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const candidate = `data:${mime};base64,${buffer.toString("base64")}`;
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores output that is not a bounded PNG data URL", async () => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async () => "data:image/svg+xml;base64,c3Zn",
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("waits for physical rasterization settlement after a logical timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveOld!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveOld = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const timedOut = captureFavicon(input);
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
expect(await timedOut).toEqual({ kind: "timed-out" });
|
||||
|
||||
const newer = captureFavicon(input);
|
||||
await Promise.resolve();
|
||||
expect(executions).toBe(1);
|
||||
resolveOld(PNG);
|
||||
expect(await newer).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("ends candidate fallback after a rasterization timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce();
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("coalesces queued rasterizations so only the latest pending capture launches", async () => {
|
||||
let resolveFirst!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const first = captureFavicon(input);
|
||||
const superseded = captureFavicon(input);
|
||||
const newest = captureFavicon(input);
|
||||
|
||||
expect(executions).toBe(1);
|
||||
resolveFirst(PNG);
|
||||
expect(await first).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(await superseded).toEqual({ kind: "none" });
|
||||
expect(await newest).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,679 @@
|
||||
import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
|
||||
export const MAX_FAVICON_CANDIDATES = 8;
|
||||
export const MAX_FAVICON_HTTP_URL_LENGTH = 2_048;
|
||||
|
||||
const MAX_FAVICON_CANDIDATE_INPUT_UNITS = 262_144;
|
||||
const MIN_FAVICON_CANDIDATE_INPUT_UNITS = 256;
|
||||
const MAX_FAVICON_SOURCE_PIXELS = 1_048_576;
|
||||
const MAX_FAVICON_INLINE_URL_LENGTH = Math.ceil((MAX_FAVICON_RESPONSE_BYTES * 4) / 3) + 128;
|
||||
const FAVICON_CAPTURE_TIMEOUT_MS = 5_000;
|
||||
const FAVICON_RASTER_WORLD_ID = 1001;
|
||||
const FAVICON_RASTER_TIMEOUT_MS = 1_000;
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
|
||||
interface RasterizationGate {
|
||||
generation: number;
|
||||
launchAllowed?: Promise<void>;
|
||||
}
|
||||
|
||||
const rasterizationGates = new WeakMap<Electron.WebContents, RasterizationGate>();
|
||||
|
||||
async function waitForRasterLaunch(previous: Promise<void>, signal: AbortSignal): Promise<void> {
|
||||
if (signal.aborted) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const finish = () => {
|
||||
signal.removeEventListener("abort", finish);
|
||||
resolve();
|
||||
};
|
||||
signal.addEventListener("abort", finish, { once: true });
|
||||
void previous.then(finish);
|
||||
});
|
||||
}
|
||||
|
||||
export type FaviconCaptureResult =
|
||||
| { readonly kind: "captured"; readonly dataUrl: string }
|
||||
| { readonly kind: "none" }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
type RasterizationResult =
|
||||
| { readonly kind: "completed"; readonly value: unknown }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
export function safeHttpOrigin(url: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function selectFaviconCandidates(candidates: ReadonlyArray<string>): ReadonlyArray<string> {
|
||||
const selected: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
let inputUnits = 0;
|
||||
for (const candidate of candidates) {
|
||||
// Charge a minimum per entry so a large array of tiny malformed values is bounded too.
|
||||
inputUnits += Math.max(MIN_FAVICON_CANDIDATE_INPUT_UNITS, candidate.length);
|
||||
if (inputUnits > MAX_FAVICON_CANDIDATE_INPUT_UNITS) break;
|
||||
if (!isSupportedFaviconUrl(candidate) || seen.has(candidate)) continue;
|
||||
seen.add(candidate);
|
||||
selected.push(candidate);
|
||||
if (selected.length === MAX_FAVICON_CANDIDATES) break;
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
export async function captureFavicon(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageUrl: string;
|
||||
readonly candidates: ReadonlyArray<string>;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
if (!pageOrigin) return { kind: "none" };
|
||||
const captureTimeout = AbortSignal.timeout(FAVICON_CAPTURE_TIMEOUT_MS);
|
||||
const captureSignal = AbortSignal.any([input.signal, captureTimeout]);
|
||||
|
||||
for (const candidate of selectFaviconCandidates(input.candidates)) {
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
const captured = await captureCandidate({
|
||||
webContents: input.webContents,
|
||||
pageOrigin,
|
||||
candidate,
|
||||
signal: captureSignal,
|
||||
});
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
if (captured.kind === "captured" || captured.kind === "timed-out") return captured;
|
||||
}
|
||||
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
async function captureCandidate(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageOrigin: string;
|
||||
readonly candidate: string;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
try {
|
||||
const inline = parseInlineFavicon(input.candidate);
|
||||
if (inline) {
|
||||
return await normalizeFaviconBuffer(
|
||||
input.webContents,
|
||||
inline.mime,
|
||||
inline.buffer,
|
||||
input.signal,
|
||||
);
|
||||
}
|
||||
|
||||
const candidateOrigin = safeHttpOrigin(input.candidate);
|
||||
if (!candidateOrigin) return { kind: "none" };
|
||||
const response = await input.webContents.session.fetch(input.candidate, {
|
||||
credentials: candidateOrigin === input.pageOrigin ? "include" : "omit",
|
||||
redirect: "error",
|
||||
signal: input.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
return { kind: "none" };
|
||||
}
|
||||
const buffer = await readFaviconResponse(response, input.signal);
|
||||
if (!buffer || input.signal.aborted) return { kind: "none" };
|
||||
const mime = response.headers.get("content-type")?.split(";", 1)[0] ?? null;
|
||||
return await normalizeFaviconBuffer(input.webContents, mime, buffer, input.signal);
|
||||
} catch {
|
||||
return { kind: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
async function readFaviconResponse(
|
||||
response: Response,
|
||||
signal: AbortSignal,
|
||||
): Promise<Buffer | null> {
|
||||
const contentLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await response.body?.cancel();
|
||||
return null;
|
||||
}
|
||||
if (!response.body) {
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
return buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES ? buffer : null;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const cancelForAbort = () => {
|
||||
void reader.cancel(signal.reason).catch(() => undefined);
|
||||
};
|
||||
signal.addEventListener("abort", cancelForAbort, { once: true });
|
||||
if (signal.aborted) cancelForAbort();
|
||||
const chunks: Buffer[] = [];
|
||||
let byteLength = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const next = await reader.read();
|
||||
if (next.done) return Buffer.concat(chunks, byteLength);
|
||||
byteLength += next.value.byteLength;
|
||||
if (byteLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await reader.cancel();
|
||||
return null;
|
||||
}
|
||||
chunks.push(Buffer.from(next.value));
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener("abort", cancelForAbort);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function isSupportedFaviconUrl(url: string): boolean {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return false;
|
||||
if (/^data:/i.test(url)) return /^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(url);
|
||||
try {
|
||||
const protocol = new URL(url).protocol;
|
||||
return (
|
||||
(protocol === "http:" || protocol === "https:") && url.length <= MAX_FAVICON_HTTP_URL_LENGTH
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeInlineFaviconPayload(payload: string): Buffer | null {
|
||||
const decoded = Buffer.allocUnsafe(Buffer.byteLength(payload));
|
||||
let inputOffset = 0;
|
||||
let outputOffset = 0;
|
||||
while (inputOffset < payload.length) {
|
||||
const escapeOffset = payload.indexOf("%", inputOffset);
|
||||
const literalEnd = escapeOffset === -1 ? payload.length : escapeOffset;
|
||||
outputOffset += decoded.write(payload.slice(inputOffset, literalEnd), outputOffset, "utf8");
|
||||
if (escapeOffset === -1) break;
|
||||
const hex = payload.slice(escapeOffset + 1, escapeOffset + 3);
|
||||
if (!/^[0-9a-f]{2}$/i.test(hex)) return null;
|
||||
decoded[outputOffset] = Number.parseInt(hex, 16);
|
||||
outputOffset += 1;
|
||||
inputOffset = escapeOffset + 3;
|
||||
}
|
||||
return decoded.subarray(0, outputOffset);
|
||||
}
|
||||
|
||||
function parseInlineFavicon(
|
||||
url: string,
|
||||
): { readonly buffer: Buffer; readonly mime: string } | null {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return null;
|
||||
const match = /^data:(image\/[a-z0-9.+-]+)((?:;[^,]*)?),(.*)$/is.exec(url);
|
||||
if (!match) return null;
|
||||
const mime = match[1]?.toLowerCase();
|
||||
const parameters = match[2]
|
||||
?.split(";")
|
||||
.filter(Boolean)
|
||||
.map((parameter) => parameter.toLowerCase());
|
||||
const payload = match[3];
|
||||
if (!mime || !parameters || !payload) return null;
|
||||
const base64 = parameters.at(-1) === "base64";
|
||||
if (parameters.includes("base64") && !base64) return null;
|
||||
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
if (base64) {
|
||||
if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null;
|
||||
buffer = Buffer.from(payload, "base64");
|
||||
if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const decoded = decodeInlineFaviconPayload(payload);
|
||||
if (!decoded) return null;
|
||||
buffer = decoded;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
|
||||
? { buffer, mime }
|
||||
: null;
|
||||
}
|
||||
|
||||
interface ImageDimensions {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
function safeDimensions(dimensions: ImageDimensions | null): dimensions is ImageDimensions {
|
||||
return (
|
||||
dimensions !== null &&
|
||||
Number.isSafeInteger(dimensions.width) &&
|
||||
Number.isSafeInteger(dimensions.height) &&
|
||||
dimensions.width > 0 &&
|
||||
dimensions.height > 0 &&
|
||||
dimensions.width * dimensions.height <= MAX_FAVICON_SOURCE_PIXELS
|
||||
);
|
||||
}
|
||||
|
||||
function pngDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
|
||||
return null;
|
||||
}
|
||||
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
|
||||
}
|
||||
|
||||
function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
|
||||
let offset = startOffset;
|
||||
while (offset < buffer.byteLength) {
|
||||
const blockLength = buffer[offset]!;
|
||||
offset += 1;
|
||||
if (blockLength === 0) return offset;
|
||||
if (offset + blockLength > buffer.byteLength) return null;
|
||||
offset += blockLength;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function gifDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
|
||||
return null;
|
||||
}
|
||||
const logicalWidth = buffer.readUInt16LE(6);
|
||||
const logicalHeight = buffer.readUInt16LE(8);
|
||||
if (!safeDimensions({ width: logicalWidth, height: logicalHeight })) return null;
|
||||
const packed = buffer[10]!;
|
||||
let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
|
||||
if (offset > buffer.byteLength) return null;
|
||||
let width = logicalWidth;
|
||||
let height = logicalHeight;
|
||||
let frameCount = 0;
|
||||
let framePixels = 0;
|
||||
while (offset < buffer.byteLength) {
|
||||
const marker = buffer[offset];
|
||||
if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
|
||||
if (marker === 0x2c) {
|
||||
if (offset + 10 > buffer.byteLength) return null;
|
||||
const left = buffer.readUInt16LE(offset + 1);
|
||||
const top = buffer.readUInt16LE(offset + 3);
|
||||
const frameWidth = buffer.readUInt16LE(offset + 5);
|
||||
const frameHeight = buffer.readUInt16LE(offset + 7);
|
||||
if (frameWidth === 0 || frameHeight === 0) return null;
|
||||
framePixels += frameWidth * frameHeight;
|
||||
if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
|
||||
width = Math.max(width, left + frameWidth);
|
||||
height = Math.max(height, top + frameHeight);
|
||||
if (!safeDimensions({ width, height })) return null;
|
||||
const framePacked = buffer[offset + 9]!;
|
||||
offset += 10;
|
||||
if ((framePacked & 0x80) !== 0) {
|
||||
offset += 3 * 2 ** ((framePacked & 0x07) + 1);
|
||||
}
|
||||
if (offset >= buffer.byteLength) return null;
|
||||
const minimumCodeSize = buffer[offset]!;
|
||||
if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
|
||||
offset += 1;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
frameCount += 1;
|
||||
continue;
|
||||
}
|
||||
if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset + 2);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface JpegExifMetadata {
|
||||
readonly complete: boolean;
|
||||
readonly orientation: number | null;
|
||||
}
|
||||
|
||||
function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
|
||||
if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
|
||||
return null;
|
||||
}
|
||||
const metadataWithoutOrientation = (): JpegExifMetadata => ({
|
||||
complete: true,
|
||||
orientation: null,
|
||||
});
|
||||
if (segment.byteLength < 14) return metadataWithoutOrientation();
|
||||
const tiffOffset = 6;
|
||||
const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
|
||||
const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
|
||||
if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
|
||||
const readUInt16 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 2 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
|
||||
};
|
||||
const readUInt32 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 4 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
|
||||
};
|
||||
const relativeIfdOffset = readUInt32(tiffOffset + 4);
|
||||
if (relativeIfdOffset === null) return metadataWithoutOrientation();
|
||||
// Keep untrusted metadata parsing linear even when IFD pointers overlap.
|
||||
let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
|
||||
const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
|
||||
type IfdOrientation = number | null | typeof budgetExhausted;
|
||||
const subIfdOrientationByOffset = new Map<number, number | null>();
|
||||
const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
|
||||
if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
|
||||
return subIfdOrientationByOffset.get(ifdOffset) ?? null;
|
||||
}
|
||||
const entryCount = readUInt16(ifdOffset);
|
||||
if (entryCount === null) return null;
|
||||
let result: IfdOrientation = null;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (remainingIfdEntryVisits === 0) return budgetExhausted;
|
||||
remainingIfdEntryVisits -= 1;
|
||||
const entryOffset = ifdOffset + 2 + index * 12;
|
||||
if (entryOffset + 12 > segment.byteLength) break;
|
||||
const tag = readUInt16(entryOffset);
|
||||
const type = readUInt16(entryOffset + 2);
|
||||
const count = readUInt32(entryOffset + 4);
|
||||
if (tag === 0x0112 && type === 3 && count === 1) {
|
||||
const orientation = readUInt16(entryOffset + 8);
|
||||
if (orientation !== null && orientation >= 1 && orientation <= 8) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
} else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
|
||||
const relativeSubIfdOffset = readUInt32(entryOffset + 8);
|
||||
if (relativeSubIfdOffset !== null) {
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
|
||||
if (orientation === budgetExhausted) return budgetExhausted;
|
||||
if (orientation !== null) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
|
||||
return result;
|
||||
};
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
|
||||
return orientation === budgetExhausted
|
||||
? { complete: false, orientation: null }
|
||||
: { complete: true, orientation };
|
||||
}
|
||||
|
||||
function jpegDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
|
||||
const startOfFrameMarkers = new Set([
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
|
||||
]);
|
||||
let offset = 2;
|
||||
let dimensions: ImageDimensions | null = null;
|
||||
let exifMetadata: JpegExifMetadata | null = null;
|
||||
while (offset + 3 < buffer.byteLength) {
|
||||
if (buffer[offset] !== 0xff) {
|
||||
offset += 1;
|
||||
continue;
|
||||
}
|
||||
while (buffer[offset] === 0xff) offset += 1;
|
||||
const marker = buffer[offset];
|
||||
offset += 1;
|
||||
if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
|
||||
if (offset + 1 >= buffer.byteLength) return null;
|
||||
const length = buffer.readUInt16BE(offset);
|
||||
if (length < 2 || offset + length > buffer.byteLength) return null;
|
||||
if (marker === 0xe1 && exifMetadata === null) {
|
||||
exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
|
||||
}
|
||||
if (startOfFrameMarkers.has(marker)) {
|
||||
if (length < 7) return null;
|
||||
if (dimensions !== null) return null;
|
||||
dimensions = {
|
||||
height: buffer.readUInt16BE(offset + 3),
|
||||
width: buffer.readUInt16BE(offset + 5),
|
||||
};
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
if (!dimensions) return null;
|
||||
if (exifMetadata?.complete === false) return null;
|
||||
const orientation = exifMetadata?.orientation;
|
||||
return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
|
||||
? { width: dimensions.height, height: dimensions.width }
|
||||
: dimensions;
|
||||
}
|
||||
|
||||
function webpDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 30 ||
|
||||
buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
|
||||
buffer.subarray(8, 12).toString("ascii") !== "WEBP"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const kind = buffer.subarray(12, 16).toString("ascii");
|
||||
if (kind === "VP8X") {
|
||||
return {
|
||||
width: 1 + buffer.readUIntLE(24, 3),
|
||||
height: 1 + buffer.readUIntLE(27, 3),
|
||||
};
|
||||
}
|
||||
if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(26) & 0x3fff,
|
||||
height: buffer.readUInt16LE(28) & 0x3fff,
|
||||
};
|
||||
}
|
||||
if (kind === "VP8L" && buffer[20] === 0x2f) {
|
||||
return {
|
||||
width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
|
||||
height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function dibDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 12) return null;
|
||||
const headerSize = buffer.readUInt32LE(0);
|
||||
if (headerSize === 12) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(4),
|
||||
height: buffer.readUInt16LE(6),
|
||||
};
|
||||
}
|
||||
if (headerSize < 40 || buffer.byteLength < 12) return null;
|
||||
return {
|
||||
width: Math.abs(buffer.readInt32LE(4)),
|
||||
height: Math.abs(buffer.readInt32LE(8)),
|
||||
};
|
||||
}
|
||||
|
||||
function icoDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 22 ||
|
||||
buffer.readUInt16LE(0) !== 0 ||
|
||||
(buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const count = buffer.readUInt16LE(4);
|
||||
if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = 6 + index * 16;
|
||||
width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
|
||||
height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
|
||||
if (!safeDimensions({ width, height })) return null;
|
||||
const byteLength = buffer.readUInt32LE(offset + 8);
|
||||
const imageOffset = buffer.readUInt32LE(offset + 12);
|
||||
if (
|
||||
byteLength === 0 ||
|
||||
imageOffset < 6 + count * 16 ||
|
||||
imageOffset > buffer.byteLength ||
|
||||
byteLength > buffer.byteLength - imageOffset
|
||||
)
|
||||
return null;
|
||||
const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
|
||||
const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
|
||||
if (!safeDimensions(embeddedDimensions)) return null;
|
||||
}
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function sourceDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
return (
|
||||
pngDimensions(buffer) ??
|
||||
gifDimensions(buffer) ??
|
||||
jpegDimensions(buffer) ??
|
||||
webpDimensions(buffer) ??
|
||||
icoDimensions(buffer)
|
||||
);
|
||||
}
|
||||
|
||||
async function normalizeFaviconBuffer(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
signal: AbortSignal,
|
||||
): Promise<FaviconCaptureResult> {
|
||||
const declaredMime = mime?.trim().toLowerCase() || null;
|
||||
const normalizedMime =
|
||||
declaredMime === "application/x-icon"
|
||||
? "image/x-icon"
|
||||
: declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
|
||||
? null
|
||||
: declaredMime;
|
||||
const dimensions = sourceDimensions(buffer);
|
||||
if (
|
||||
(normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
|
||||
normalizedMime === "image/svg+xml" ||
|
||||
buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
|
||||
!safeDimensions(dimensions)
|
||||
) {
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
const rasterized = await rasterizeFavicon(
|
||||
webContents,
|
||||
normalizedMime,
|
||||
buffer,
|
||||
dimensions,
|
||||
signal,
|
||||
);
|
||||
if (rasterized.kind === "timed-out") return rasterized;
|
||||
return typeof rasterized.value === "string" &&
|
||||
rasterized.value.startsWith("data:image/png;base64,") &&
|
||||
rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
|
||||
? { kind: "captured", dataUrl: rasterized.value }
|
||||
: { kind: "none" };
|
||||
}
|
||||
|
||||
async function rasterizeFavicon(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
dimensions: ImageDimensions,
|
||||
signal: AbortSignal,
|
||||
): Promise<RasterizationResult> {
|
||||
const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
|
||||
rasterizationGates.set(webContents, gate);
|
||||
const generation = ++gate.generation;
|
||||
const previousLaunchAllowed = gate.launchAllowed;
|
||||
if (previousLaunchAllowed) {
|
||||
await waitForRasterLaunch(previousLaunchAllowed, signal);
|
||||
}
|
||||
if (signal.aborted || generation !== gate.generation) {
|
||||
return { kind: "completed", value: null };
|
||||
}
|
||||
|
||||
const payload = buffer.toString("base64");
|
||||
const blobType = mime ?? "";
|
||||
const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
|
||||
const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
|
||||
const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
|
||||
const drawX = (32 - decodeWidth) / 2;
|
||||
const drawY = (32 - decodeHeight) / 2;
|
||||
const code = `
|
||||
(() => {
|
||||
const rasterize = async () => {
|
||||
try {
|
||||
const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
|
||||
const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
|
||||
resizeWidth: ${decodeWidth},
|
||||
resizeHeight: ${decodeHeight},
|
||||
resizeQuality: "high",
|
||||
});
|
||||
try {
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
|
||||
return null;
|
||||
}
|
||||
const canvas = new OffscreenCanvas(32, 32);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return null;
|
||||
context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
|
||||
const blob = await canvas.convertToBlob({ type: "image/png" });
|
||||
const output = new Uint8Array(await blob.arrayBuffer());
|
||||
let binary = "";
|
||||
for (const byte of output) binary += String.fromCharCode(byte);
|
||||
return "data:image/png;base64," + btoa(binary);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return rasterize();
|
||||
})()
|
||||
`;
|
||||
|
||||
const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
|
||||
{ code },
|
||||
]);
|
||||
|
||||
const result = new Promise<RasterizationResult>((resolve, reject) => {
|
||||
// Electron cannot cancel isolated-world execution. This timeout ends only
|
||||
// the logical attempt; renderer work may finish after a newer attempt starts.
|
||||
const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
|
||||
let settled = false;
|
||||
const finish = (complete: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
timeout.removeEventListener("abort", onTimeout);
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
complete();
|
||||
};
|
||||
const onTimeout = () => {
|
||||
finish(() => resolve({ kind: "timed-out" }));
|
||||
};
|
||||
const onAbort = () => {
|
||||
finish(() => resolve({ kind: "completed", value: null }));
|
||||
};
|
||||
timeout.addEventListener("abort", onTimeout, { once: true });
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
void execution.then(
|
||||
(value) => {
|
||||
finish(() => resolve({ kind: "completed", value }));
|
||||
},
|
||||
(cause: unknown) => {
|
||||
finish(() => reject(cause));
|
||||
},
|
||||
);
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
// The logical timeout does not cancel Electron's renderer work. Keep the
|
||||
// gate closed until that physical execution actually settles.
|
||||
const launchAllowed = execution.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
gate.launchAllowed = launchAllowed;
|
||||
void launchAllowed.then(() => {
|
||||
if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
|
||||
});
|
||||
return await result;
|
||||
}
|
||||
@@ -186,6 +186,102 @@ const makeTestPreviewWebContents = (
|
||||
capturePage,
|
||||
}) as never;
|
||||
|
||||
const TEST_FAVICON = "data:image/png;base64,cG5n";
|
||||
|
||||
const makeSourcePng = (width = 1, height = 1): Buffer => {
|
||||
const buffer = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(buffer);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
};
|
||||
|
||||
const makeFaviconWebContents = (options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly id?: number;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
readonly url?: string;
|
||||
}) => {
|
||||
const sourcePng = makeSourcePng();
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
let currentUrl = options?.url ?? "http://localhost:3200/";
|
||||
let destroyed = false;
|
||||
let loading = false;
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(sourcePng), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON,
|
||||
);
|
||||
const reload = vi.fn();
|
||||
const loadURL = vi.fn(async (url: string) => {
|
||||
currentUrl = url;
|
||||
});
|
||||
const off = vi.fn();
|
||||
const debuggerOff = vi.fn();
|
||||
const webContents = {
|
||||
id: options?.id ?? 42,
|
||||
isDestroyed: () => destroyed,
|
||||
getType: () => "webview",
|
||||
getURL: () => currentUrl,
|
||||
getTitle: () => "Preview",
|
||||
isLoading: () => loading,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
reload,
|
||||
reloadIgnoringCache: vi.fn(),
|
||||
loadURL,
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off,
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
session: { fetch },
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: debuggerOff,
|
||||
},
|
||||
};
|
||||
return {
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
debuggerOff,
|
||||
listeners,
|
||||
loadURL,
|
||||
off,
|
||||
reload,
|
||||
setDestroyed: (value: boolean) => {
|
||||
destroyed = value;
|
||||
},
|
||||
setLoading: (value: boolean) => {
|
||||
loading = value;
|
||||
},
|
||||
setUrl: (url: string) => {
|
||||
currentUrl = url;
|
||||
},
|
||||
webContents: webContents as never,
|
||||
};
|
||||
};
|
||||
|
||||
const settle = function* (until: () => boolean) {
|
||||
for (let attempt = 0; attempt < 30 && !until(); attempt++) {
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
};
|
||||
|
||||
const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
|
||||
const listeners = new Map<string, () => void>();
|
||||
const send = vi.fn();
|
||||
@@ -257,6 +353,32 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("rejects a destroyed webview during registration", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const getType = vi.fn(() => "webview" as const);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => true,
|
||||
getType,
|
||||
} as never);
|
||||
yield* manager.createTab("tab_destroyed_registration");
|
||||
|
||||
const exit = yield* Effect.exit(manager.registerWebview("tab_destroyed_registration", 42));
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
|
||||
_tag: "PreviewWebContentsNotFoundError",
|
||||
tabId: "tab_destroyed_registration",
|
||||
webContentsId: 42,
|
||||
});
|
||||
}
|
||||
expect(getType).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
@@ -375,6 +497,488 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("detaches a destroyed webview instead of navigating it", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_destroyed_navigation");
|
||||
yield* manager.registerWebview("tab_destroyed_navigation", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_navigation", "dark");
|
||||
preview.setDestroyed(true);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_navigation", "https://example.com/");
|
||||
|
||||
expect(preview.loadURL).not.toHaveBeenCalled();
|
||||
expect(preview.reload).not.toHaveBeenCalled();
|
||||
expect(preview.off).toHaveBeenCalled();
|
||||
expect(preview.debuggerOff).toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: null,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const previous = makeFaviconWebContents();
|
||||
const replacement = makeFaviconWebContents({ url: "https://example.com/" });
|
||||
let current = previous.webContents;
|
||||
let startReplacementRegistration: () => void = () => void 0;
|
||||
const replacementReady = new Promise<void>((resolve) => {
|
||||
startReplacementRegistration = resolve;
|
||||
});
|
||||
fromId.mockImplementation(() => current);
|
||||
yield* manager.createTab("tab_destroyed_replacement_race");
|
||||
yield* manager.registerWebview("tab_destroyed_replacement_race", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_replacement_race", "dark");
|
||||
const replacementRegistration = yield* Effect.promise(() => replacementReady).pipe(
|
||||
Effect.flatMap(() => manager.registerWebview("tab_destroyed_replacement_race", 42)),
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
previous.setDestroyed(true);
|
||||
previous.debuggerOff.mockImplementationOnce(() => {
|
||||
current = replacement.webContents;
|
||||
startReplacementRegistration();
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_replacement_race", "https://example.com/");
|
||||
const registrationExit = yield* Fiber.await(replacementRegistration);
|
||||
|
||||
expect(Exit.isSuccess(registrationExit)).toBe(true);
|
||||
expect(previous.off).toHaveBeenCalled();
|
||||
expect(replacement.off).not.toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: 42,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("publishes a canonical favicon origin while the page is loading", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents({
|
||||
url: `http://localhost:3200/${"x".repeat(3_000)}`,
|
||||
});
|
||||
preview.setLoading(true);
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_loading");
|
||||
yield* manager.registerWebview("tab_favicon_loading", 42);
|
||||
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(states.at(-1)?.favicon).toMatchObject({
|
||||
dataUrl: TEST_FAVICON,
|
||||
pageUrl: "http://localhost:3200",
|
||||
});
|
||||
expect(states.at(-1)?.favicon?.capturedAt).toEqual(expect.any(Number));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("shares an identical in-flight event and lets a changed event win", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFirst!: (response: Response) => void;
|
||||
const firstResponse = new Promise<Response>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
});
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: (url) =>
|
||||
url.endsWith("first.png")
|
||||
? firstResponse
|
||||
: Promise.resolve(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_latest");
|
||||
yield* manager.registerWebview("tab_favicon_latest", 42);
|
||||
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
resolveFirst(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(preview.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("allows an identical retry after an undecodable capture", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let rasterizations = 0;
|
||||
const preview = makeFaviconWebContents({
|
||||
rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_retry");
|
||||
yield* manager.registerWebview("tab_favicon_retry", 42);
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => rasterizations === 1);
|
||||
yield* settle(() => false);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(rasterizations).toBe(2);
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not publish a capture invalidated by navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_navigation");
|
||||
yield* manager.registerWebview("tab_favicon_navigation", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
preview.listeners.get("did-start-navigation")?.({
|
||||
isMainFrame: true,
|
||||
isSameDocument: false,
|
||||
} as never);
|
||||
preview.setUrl("https://example.com/");
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.some((state) => state.favicon !== undefined)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("retains a favicon when reloading the current URL without a new event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reload");
|
||||
yield* manager.registerWebview("tab_favicon_reload", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.navigate("tab_favicon_reload", "http://localhost:3200/");
|
||||
|
||||
expect(preview.reload).toHaveBeenCalledOnce();
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon after a confirmed cross-origin navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_origin");
|
||||
yield* manager.registerWebview("tab_favicon_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("https://example.com/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect(
|
||||
"retains the previous document icon across a failed cross-origin navigation",
|
||||
() =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_failed_origin");
|
||||
yield* manager.registerWebview("tab_favicon_failed_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.listeners.get("did-fail-load")?.(
|
||||
{} as never,
|
||||
-105 as never,
|
||||
"Name not resolved" as never,
|
||||
"https://unreachable.example/" as never,
|
||||
true as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "LoadFailed");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not resurrect an icon after a confirmed about:blank document", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_blank");
|
||||
yield* manager.registerWebview("tab_favicon_blank", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("about:blank");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Idle");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
|
||||
preview.setUrl("http://localhost:3200/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon when a replacement webview attaches", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) => {
|
||||
if (id === 42) return initial.webContents;
|
||||
if (id === 43) return replacement.webContents;
|
||||
return null;
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_replace");
|
||||
yield* manager.registerWebview("tab_favicon_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_replace", 43);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("ignores an old capture that completes after webview replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const initial = makeFaviconWebContents({
|
||||
id: 42,
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) =>
|
||||
id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null,
|
||||
);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_late_replace");
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => initial.fetch.mock.calls.length === 1);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 43);
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(
|
||||
states.some((state) => state.webContentsId === 43 && state.favicon !== undefined),
|
||||
).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("treats a reused WebContents id as a new attachment", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 42 });
|
||||
let active = initial.webContents;
|
||||
fromId.mockImplementation(() => active);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reused_id");
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
active = replacement.webContents;
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
expect(initial.off).toHaveBeenCalled();
|
||||
expect(replacement.listeners.has("page-favicon-updated")).toBe(true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("preserves a favicon when the active attachment registers again", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reregister");
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewFavicon,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -85,6 +87,7 @@ export interface PreviewTabState {
|
||||
pictureInPicture: boolean;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
favicon?: DesktopPreviewFavicon;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -346,7 +349,10 @@ type PreviewInputSignal =
|
||||
| { readonly kind: "key"; readonly key: string; readonly code: string };
|
||||
|
||||
interface ManagedListeners {
|
||||
readonly attachmentId: symbol;
|
||||
readonly cancelFaviconCapture: () => void;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly webContents: Electron.WebContents;
|
||||
}
|
||||
|
||||
type FrameCaptureConsumer = "picture-in-picture" | "recording";
|
||||
@@ -613,6 +619,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const emitIfCurrent = Effect.fn("PreviewManager.emitIfCurrent")(function* (
|
||||
tabId: string,
|
||||
state: PreviewTabState,
|
||||
) {
|
||||
if ((yield* SynchronizedRef.get(tabsRef)).get(tabId) === state) {
|
||||
yield* emit(tabId, state);
|
||||
}
|
||||
});
|
||||
|
||||
const update = Effect.fn("PreviewManager.update")(function* (
|
||||
tabId: string,
|
||||
patch: Partial<PreviewTabState>,
|
||||
@@ -1204,7 +1219,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
copy.delete(webContentsId);
|
||||
}),
|
||||
]);
|
||||
if (managed) yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
if (managed) {
|
||||
managed.cancelFaviconCapture();
|
||||
yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const isAppShortcut = (input: Electron.Input): boolean =>
|
||||
@@ -1268,8 +1286,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const attachmentId = Symbol();
|
||||
let documentId = 0;
|
||||
let nextRequestId = 0;
|
||||
let activeCapture: {
|
||||
readonly controller: AbortController;
|
||||
readonly documentId: number;
|
||||
readonly eventKey: string;
|
||||
readonly requestId: number;
|
||||
} | null = null;
|
||||
const cancelFaviconCapture = () => {
|
||||
documentId += 1;
|
||||
activeCapture?.controller.abort();
|
||||
activeCapture = null;
|
||||
};
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
confirmedNavigation = false,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
const zoomFactor = yield* attempt(
|
||||
@@ -1282,7 +1315,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
if (!current || current.webContentsId !== wc.id || webContents.fromId(wc.id) !== wc) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
@@ -1292,8 +1327,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const clearFavicon =
|
||||
confirmedNavigation &&
|
||||
current.favicon !== undefined &&
|
||||
safeHttpOrigin(current.favicon.pageUrl) !==
|
||||
safeHttpOrigin(navStatus.kind === "Idle" ? wc.getURL() : navStatus.url);
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
...(clearFavicon ? currentWithoutFavicon : current),
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
@@ -1307,10 +1348,109 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const syncNavigation = () => runFork(syncState(false, true));
|
||||
const syncInPageNavigation = () => runFork(syncState(false));
|
||||
const navigationStarted = (
|
||||
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
|
||||
) => {
|
||||
if (event.isMainFrame && !event.isSameDocument) cancelFaviconCapture();
|
||||
};
|
||||
const publishFavicon = Effect.fn("PreviewManager.publishFavicon")(function* (input: {
|
||||
readonly captureDocumentId: number;
|
||||
readonly dataUrl: string;
|
||||
readonly pageUrl: string;
|
||||
readonly requestId: number;
|
||||
}) {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
const managed = (yield* Ref.get(attachedRef)).get(wc.id);
|
||||
if (
|
||||
!pageOrigin ||
|
||||
wc.isDestroyed() ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
managed?.attachmentId !== attachmentId ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId ||
|
||||
safeHttpOrigin(wc.getURL()) !== pageOrigin
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const capturedAt = yield* currentMillis;
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (
|
||||
!current ||
|
||||
current.webContentsId !== wc.id ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId
|
||||
) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
favicon: { dataUrl: input.dataUrl, pageUrl: pageOrigin, capturedAt },
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
});
|
||||
const faviconUpdated = (_event: Event, rawCandidates: ReadonlyArray<string>): void => {
|
||||
const pageUrl = wc.getURL();
|
||||
if (!safeHttpOrigin(pageUrl)) return;
|
||||
const candidates = selectFaviconCandidates(rawCandidates);
|
||||
if (candidates.length === 0) return;
|
||||
const eventKey = JSON.stringify([pageUrl, ...candidates]);
|
||||
if (activeCapture?.eventKey === eventKey) return;
|
||||
activeCapture?.controller.abort();
|
||||
const captureDocumentId = documentId;
|
||||
const requestId = ++nextRequestId;
|
||||
const controller = new AbortController();
|
||||
activeCapture = { controller, documentId: captureDocumentId, eventKey, requestId };
|
||||
runFork(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
captureFavicon({ webContents: wc, pageUrl, candidates, signal: controller.signal }),
|
||||
catch: (cause) =>
|
||||
new PreviewOperationError({
|
||||
operation: "captureFavicon",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.kind === "captured"
|
||||
? publishFavicon({
|
||||
captureDocumentId,
|
||||
dataUrl: result.dataUrl,
|
||||
pageUrl,
|
||||
requestId,
|
||||
})
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
controller.signal.aborted
|
||||
? Effect.void
|
||||
: Effect.logDebug("Favicon capture failed.", { error, tabId, webContentsId: wc.id }),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (activeCapture?.requestId === requestId) activeCapture = null;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
@@ -1387,9 +1527,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
cancelFaviconCapture();
|
||||
wc.off("did-start-navigation", navigationStarted);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("page-favicon-updated", faviconUpdated as never);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
wc.off("did-fail-load", failed as never);
|
||||
@@ -1399,9 +1542,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-start-navigation", navigationStarted);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("page-favicon-updated", faviconUpdated as never);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
wc.on("did-fail-load", failed as never);
|
||||
@@ -1418,7 +1563,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* Ref.update(attachedRef, (attached) =>
|
||||
replaceMap(attached, (copy) => {
|
||||
copy.set(wc.id, { scope });
|
||||
copy.set(wc.id, { attachmentId, cancelFaviconCapture, scope, webContents: wc });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1561,6 +1706,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const mainWindow = yield* Ref.get(mainWindowRef);
|
||||
if (
|
||||
!wc ||
|
||||
wc.isDestroyed() ||
|
||||
wc.getType() !== "webview" ||
|
||||
(Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents)
|
||||
) {
|
||||
@@ -1568,7 +1714,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const currentAttachment = attached.get(webContentsId);
|
||||
if (tab.webContentsId === webContentsId && currentAttachment?.webContents === wc) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
@@ -1580,7 +1727,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return;
|
||||
}
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
tab.webContentsId != null &&
|
||||
(tab.webContentsId !== webContentsId || currentAttachment?.webContents !== wc)
|
||||
? tab.webContentsId
|
||||
: null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
@@ -1627,8 +1777,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
] as const;
|
||||
}
|
||||
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = {
|
||||
...current,
|
||||
...currentWithoutFavicon,
|
||||
webContentsId,
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
@@ -1707,6 +1858,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
pictureInPicture: current?.pictureInPicture ?? false,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
...(current?.favicon ? { favicon: current.favicon } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
@@ -1718,17 +1870,48 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* emit(tabId, pending);
|
||||
if (pending.webContentsId == null) return;
|
||||
const wc = webContents.fromId(pending.webContentsId);
|
||||
if (!wc) {
|
||||
const detached = { ...pending, webContentsId: null };
|
||||
yield* SynchronizedRef.update(tabsRef, (tabs) =>
|
||||
tabs.get(tabId)?.webContentsId !== pending.webContentsId
|
||||
? tabs
|
||||
: replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, detached);
|
||||
}),
|
||||
const webContentsId = pending.webContentsId;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) {
|
||||
const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
yield* withTabLifecycleLock(
|
||||
tabId,
|
||||
Effect.gen(function* () {
|
||||
const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
const currentWebContents = webContents.fromId(webContentsId);
|
||||
if (
|
||||
currentTab?.webContentsId !== webContentsId ||
|
||||
currentAttachment !== expectedAttachment ||
|
||||
(currentWebContents && !currentWebContents.isDestroyed())
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(webContentsId),
|
||||
detachListeners(webContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (current?.webContentsId !== webContentsId) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null };
|
||||
return [
|
||||
Option.some(next),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value);
|
||||
}),
|
||||
);
|
||||
yield* emit(tabId, detached);
|
||||
return;
|
||||
}
|
||||
if (wc.getURL() === url) {
|
||||
|
||||
@@ -30,8 +30,10 @@ const clientSettings: ClientSettings = {
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
planModeEnabled: false,
|
||||
persistComposerContextStrip: true,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarAutoSettleOnMerge: true,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
|
||||
@@ -229,15 +229,18 @@ const NODE_PTY_PROBE_SCRIPT = (
|
||||
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
// can't read inside app.asar, so confirm those deps are unpacked on the real
|
||||
// filesystem before reporting the backend healthy. "effect" is the framework
|
||||
// every server module imports; resolving it validates the whole node_modules
|
||||
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
|
||||
// report it accurately instead of letting the server crash on
|
||||
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
|
||||
// launch with no fallback).
|
||||
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
|
||||
// The WSL Node can't read inside app.asar, so confirm what the server needs is
|
||||
// unpacked on the real filesystem before reporting the backend healthy. Exit 3
|
||||
// marks this distinct from a node-pty prebuild problem so the caller can report
|
||||
// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
|
||||
// launch (which, in wsl-only mode, would just fail to launch with no fallback).
|
||||
//
|
||||
// The sentinel must be a package the CLI bundle leaves external. It used to be
|
||||
// "effect", back when the bundle externalized its runtime deps and the whole
|
||||
// node_modules tree was unpacked. The bundle now inlines its JS dependencies,
|
||||
// so "effect" no longer exists on disk and only the native packages do —
|
||||
// resolving node-pty is what actually validates the unpacked tree.
|
||||
try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
|
||||
@@ -462,16 +465,17 @@ const ensureNodePtyImpl = (
|
||||
} as const;
|
||||
}
|
||||
|
||||
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
|
||||
// filesystem — a packaging regression, since the server bundle needs its
|
||||
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
|
||||
// Windows and dual mode surfaces the reason inline, instead of the server
|
||||
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
|
||||
// The packages the server bundle leaves external (node-pty and the other
|
||||
// native addons) couldn't be resolved on the WSL filesystem — a packaging
|
||||
// regression, since those must be unpacked from the asar. Fatal so wsl-only
|
||||
// mode falls back to Windows and dual mode surfaces the reason inline,
|
||||
// instead of the server crash-looping on ERR_MODULE_NOT_FOUND once it
|
||||
// actually launches.
|
||||
if (probe.exitCode === 3) {
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
|
||||
'WSL server dependencies could not be loaded (for example "node-pty"). The native packages the server needs are not unpacked where the WSL distro\'s Node can read them — this is a packaging problem with this build. Please report it.',
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ const mobileEndorsementRows = [
|
||||
<div class="harness-mark"><img src="/harnesses/cursor_light.svg" alt="" /></div>
|
||||
<div class="harness-meta">
|
||||
<div class="harness-name">Cursor</div>
|
||||
<div class="harness-tag">cursor-agent</div>
|
||||
<div class="harness-tag">@cursor/sdk</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="harness">
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.3",
|
||||
version: "1.0.4",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
|
||||
+7
@@ -252,6 +252,9 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
|
||||
val textLength = editor.text?.length ?: 0
|
||||
val safeStart = start.coerceIn(0, textLength)
|
||||
val safeEnd = end.coerceIn(0, textLength)
|
||||
// Re-applying an unchanged selection resets the keyboard's suggestion
|
||||
// state, so a no-op assignment must be skipped.
|
||||
if (editor.selectionStart == safeStart && editor.selectionEnd == safeEnd) return
|
||||
editor.setSelection(safeStart, safeEnd)
|
||||
}
|
||||
|
||||
@@ -281,6 +284,10 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
|
||||
)
|
||||
|
||||
private fun emitSelectionChange(start: Int, end: Int) {
|
||||
// Caret moves advance the revision counter like text edits do: a
|
||||
// controlled payload computed before this move is stale and must fail the
|
||||
// revision guard instead of yanking the caret back mid-typing.
|
||||
nativeEventCount += 1
|
||||
onComposerSelectionChange(
|
||||
mapOf(
|
||||
"value" to editor.text.toString(),
|
||||
|
||||
@@ -489,6 +489,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
return
|
||||
}
|
||||
restoreBaseTypingAttributes()
|
||||
// UIKit moves the selection before textViewDidChange runs. Emitting here
|
||||
// would pair the post-edit text with a pre-edit revision counter, so let
|
||||
// the change event that follows carry both; only pure caret moves emit.
|
||||
guard self.textView.serializedText() == value else {
|
||||
return
|
||||
}
|
||||
emitSelection()
|
||||
}
|
||||
|
||||
@@ -774,8 +780,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
}
|
||||
|
||||
private func emitSelection() {
|
||||
// Caret moves advance the revision counter like text edits do: a
|
||||
// controlled payload computed before this move is stale and must fail the
|
||||
// revision guard instead of yanking the caret back mid-typing.
|
||||
let currentValue = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
nativeEventCount += 1
|
||||
onComposerSelectionChange([
|
||||
"value": currentValue,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
@@ -817,10 +827,16 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
NSMaxRange(nextRange) <= textView.attributedText.length else {
|
||||
return
|
||||
}
|
||||
self.requestedSelection = nil
|
||||
// Programmatically assigning selectedRange resets the keyboard's
|
||||
// autocorrect and predictive-text context even when the range is
|
||||
// unchanged, so a no-op assignment must be skipped.
|
||||
guard !NSEqualRanges(nextRange, textView.selectedRange) else {
|
||||
return
|
||||
}
|
||||
isApplyingControlledValue = true
|
||||
textView.selectedRange = nextRange
|
||||
isApplyingControlledValue = false
|
||||
self.requestedSelection = nil
|
||||
}
|
||||
|
||||
private func updatePlaceholderVisibility() {
|
||||
|
||||
@@ -4,16 +4,13 @@ import type { MarkdownNode } from "react-native-nitro-markdown/headless";
|
||||
|
||||
import { CopyTextButton } from "./CopyTextButton";
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownListItemBlocks,
|
||||
nativeMarkdownTextRuns,
|
||||
} from "./nativeMarkdownText";
|
||||
import { nativeMarkdownDocumentRuns, nativeMarkdownListItemBlocks } from "./nativeMarkdownText";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
MarkdownCodeHighlighter,
|
||||
MarkdownHighlightedToken,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "./SelectableMarkdownText.types";
|
||||
|
||||
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
|
||||
@@ -48,12 +45,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
|
||||
|
||||
function SelectableNode(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -322,6 +320,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
|
||||
|
||||
function NativeTable(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -359,7 +358,7 @@ function NativeTable(props: {
|
||||
}}
|
||||
>
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownTextRuns(cell).map((run) =>
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
@@ -376,6 +375,7 @@ function NativeTable(props: {
|
||||
|
||||
function NativeMarkdownImage(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -384,6 +384,7 @@ function NativeMarkdownImage(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -445,6 +446,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
|
||||
|
||||
function NativeMixedParagraph(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -455,6 +457,7 @@ function NativeMixedParagraph(props: {
|
||||
<NativeMarkdownImage
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -462,6 +465,7 @@ function NativeMixedParagraph(props: {
|
||||
<SelectableNode
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -473,6 +477,7 @@ function NativeMixedParagraph(props: {
|
||||
|
||||
function NativeList(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -534,6 +539,7 @@ function NativeList(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, childIndex)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -551,6 +557,7 @@ function NativeList(props: {
|
||||
|
||||
export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -566,6 +573,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -587,6 +595,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeTable
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -595,6 +604,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeMarkdownImage
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -624,6 +634,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -637,6 +648,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeList
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -647,12 +659,14 @@ export function NativeMarkdownBlock(props: {
|
||||
return (props.node.children ?? []).some((child) => child.type === "image") ? (
|
||||
<NativeMixedParagraph
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -673,6 +687,7 @@ export function NativeMarkdownBlock(props: {
|
||||
>
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -690,6 +705,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -703,6 +719,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
|
||||
@@ -69,6 +69,7 @@ export function SelectableMarkdownText({
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
skills={skills}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
|
||||
@@ -70,15 +70,22 @@ const EMPTY_CONTEXT: RunContext = {
|
||||
|
||||
const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
|
||||
|
||||
function decodeCodePoint(codePoint: number, entity: string): string {
|
||||
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
|
||||
return entity;
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
|
||||
function decodeHtmlEntitiesOnce(value: string): string {
|
||||
return value.replace(
|
||||
/&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
|
||||
(entity, decimal: string | undefined, hexadecimal: string | undefined) => {
|
||||
if (decimal) {
|
||||
return String.fromCodePoint(Number.parseInt(decimal, 10));
|
||||
return decodeCodePoint(Number.parseInt(decimal, 10), entity);
|
||||
}
|
||||
if (hexadecimal) {
|
||||
return String.fromCodePoint(Number.parseInt(hexadecimal, 16));
|
||||
return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
|
||||
}
|
||||
switch (entity.toLowerCase()) {
|
||||
case "&":
|
||||
@@ -661,6 +668,7 @@ function appendDocumentBlock(
|
||||
function containsRichBlock(node: MarkdownNode): boolean {
|
||||
if (
|
||||
node.type === "code_block" ||
|
||||
node.type === "blockquote" ||
|
||||
node.type === "table" ||
|
||||
node.type === "image" ||
|
||||
node.type === "horizontal_rule" ||
|
||||
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.view.View
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
private val iconView = HeaderIconView(context)
|
||||
private val onTriggered by EventDispatcher()
|
||||
|
||||
init {
|
||||
isClickable = true
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
onTriggered(emptyMap<String, Any>())
|
||||
}
|
||||
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
|
||||
fun setLabel(label: String) {
|
||||
contentDescription = label
|
||||
}
|
||||
|
||||
fun setSystemImage(systemImage: String) {
|
||||
iconView.systemImage = systemImage
|
||||
}
|
||||
}
|
||||
|
||||
private class HeaderIconView(context: Context) : View(context) {
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.parseColor("#6B7280")
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeWidth = 3f * resources.displayMetrics.density
|
||||
style = Paint.Style.STROKE
|
||||
}
|
||||
|
||||
var systemImage: String = "gearshape"
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val size = minOf(width, height).toFloat()
|
||||
if (systemImage == "square.and.pencil") {
|
||||
drawNewTask(canvas, cx, cy, size)
|
||||
} else {
|
||||
drawSettings(canvas, cx, cy, size)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val radius = size * 0.12f
|
||||
canvas.drawCircle(cx, cy, radius, paint)
|
||||
for (index in 0 until 8) {
|
||||
val angle = Math.PI * index / 4.0
|
||||
val inner = size * 0.19f
|
||||
val outer = size * 0.27f
|
||||
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
|
||||
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
|
||||
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
|
||||
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
|
||||
canvas.drawLine(sx, sy, ex, ey, paint)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val left = cx - size * 0.2f
|
||||
val top = cy - size * 0.16f
|
||||
val right = cx + size * 0.14f
|
||||
val bottom = cy + size * 0.2f
|
||||
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
|
||||
canvas.drawLine(
|
||||
cx - size * 0.02f,
|
||||
cy + size * 0.13f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
canvas.drawLine(
|
||||
cx + size * 0.17f,
|
||||
cy - size * 0.2f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
}
|
||||
}
|
||||
-11
@@ -32,16 +32,5 @@ class T3NativeControlsModule : Module() {
|
||||
?.resolve("t3-showcase-ready")
|
||||
?.writeText(scene)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3HeaderButtonView: ExpoView {
|
||||
private static let size: CGFloat = 44
|
||||
private static let symbolSize: CGFloat = 18
|
||||
|
||||
private let button = UIButton(type: .system)
|
||||
private var systemImage = "circle"
|
||||
|
||||
let onTriggered = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
isAccessibilityElement = false
|
||||
button.frame = bounds
|
||||
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
|
||||
addSubview(button)
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
public override var intrinsicContentSize: CGSize {
|
||||
CGSize(width: Self.size, height: Self.size)
|
||||
}
|
||||
|
||||
public func setLabel(_ label: String) {
|
||||
button.accessibilityLabel = label
|
||||
}
|
||||
|
||||
public func setSystemImage(_ systemImage: String) {
|
||||
guard self.systemImage != systemImage else {
|
||||
return
|
||||
}
|
||||
self.systemImage = systemImage
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
private func applyConfiguration() {
|
||||
var configuration: UIButton.Configuration
|
||||
if #available(iOS 26.0, *) {
|
||||
configuration = .glass()
|
||||
configuration.cornerStyle = .capsule
|
||||
} else {
|
||||
configuration = .plain()
|
||||
}
|
||||
|
||||
configuration.baseForegroundColor = .label
|
||||
configuration.contentInsets = .zero
|
||||
configuration.image = UIImage(systemName: systemImage)
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
|
||||
pointSize: Self.symbolSize,
|
||||
weight: .regular
|
||||
)
|
||||
button.configuration = configuration
|
||||
}
|
||||
|
||||
@objc private func handlePress() {
|
||||
onTriggered()
|
||||
}
|
||||
}
|
||||
@@ -87,16 +87,5 @@ public final class T3NativeControlsModule: Module {
|
||||
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
|
||||
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
+103
-35
@@ -11,7 +11,7 @@ import {
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
@@ -39,6 +39,15 @@ import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
|
||||
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
|
||||
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
|
||||
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
|
||||
import {
|
||||
NewTaskBranchPickerRouteScreen,
|
||||
NewTaskEnvironmentPickerRouteScreen,
|
||||
} from "./features/threads/NewTaskContextPickerScreens";
|
||||
import {
|
||||
ExistingThreadSettingsRouteProvider,
|
||||
ExistingThreadSettingsRouteScreen,
|
||||
NewTaskThreadSettingsRouteScreen,
|
||||
} from "./features/threads/ThreadSettingsSheet";
|
||||
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
|
||||
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
|
||||
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
|
||||
@@ -62,17 +71,15 @@ import {
|
||||
} from "./features/sharing/incoming-share-presentation";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import {
|
||||
FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
NATIVE_SHEET_SURFACE_COLOR,
|
||||
NATIVE_SHEET_SURFACE_CONTENT_STYLE,
|
||||
} from "./native/sheet-surface";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
|
||||
// background stay STATIC config while still adapting to appearance changes.
|
||||
const SHEET_BACKGROUND_COLOR =
|
||||
Platform.OS === "ios"
|
||||
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
|
||||
: undefined;
|
||||
|
||||
type AppScreenOptions = NativeStackNavigationOptions & {
|
||||
readonly unstable_navigationItemStyle?: "editor";
|
||||
};
|
||||
@@ -91,8 +98,8 @@ const GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerShown: true,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? { backgroundColor: "transparent" }
|
||||
: SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
: NATIVE_SHEET_SURFACE_COLOR !== undefined
|
||||
? { backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
@@ -109,10 +116,10 @@ const SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
NATIVE_SHEET_SURFACE_COLOR !== undefined
|
||||
? // native-stack types this as `string`, but the native side accepts any
|
||||
// ColorValue including DynamicColorIOS.
|
||||
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
{ backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: false,
|
||||
@@ -125,6 +132,14 @@ const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
// A native glass header for a sheet screen whose primary child is a scroll
|
||||
// view. The centered sheet title stays stable while UIKit supplies scroll-edge
|
||||
// fading from that child.
|
||||
const SHEET_GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
headerBackVisible: false,
|
||||
@@ -238,9 +253,16 @@ const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
|
||||
const NewTaskSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "NewTask",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
// Sheets read better with the iOS-default centered title (no editor style).
|
||||
unstable_navigationItemStyle: undefined,
|
||||
...SHEET_GLASS_HEADER_OPTIONS,
|
||||
// The form-sheet host owns the one opaque adaptive surface. Child screens
|
||||
// and the navigation bar stay transparent over it, avoiding visible color
|
||||
// slabs as view controllers move horizontally.
|
||||
contentStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
|
||||
// UIKit's default push adds a dimming shadow and independently transitions
|
||||
// the navigation bar. Both read as mismatched sheet backgrounds here.
|
||||
// simple_push retains native push/pop gestures without either artifact.
|
||||
animation: Platform.OS === "ios" ? "simple_push" : undefined,
|
||||
animationDuration: Platform.OS === "ios" ? 350 : undefined,
|
||||
},
|
||||
screens: {
|
||||
NewTask: createNativeStackScreen({
|
||||
@@ -253,9 +275,39 @@ const NewTaskSheetStack = createNativeStackNavigator({
|
||||
NewTaskDraft: createNativeStackScreen({
|
||||
screen: NewTaskDraftRouteScreen,
|
||||
linking: "draft",
|
||||
// The draft composer has no scroll view for glass to sample; a solid
|
||||
// header also lays the content out below the bar (no manual inset).
|
||||
options: SHEET_SOLID_HEADER_OPTIONS,
|
||||
options: {
|
||||
headerBackVisible: false,
|
||||
title: "",
|
||||
},
|
||||
}),
|
||||
NewTaskEnvironment: createNativeStackScreen({
|
||||
screen: NewTaskEnvironmentPickerRouteScreen,
|
||||
linking: "draft/environment",
|
||||
options: {
|
||||
title: "Environment",
|
||||
},
|
||||
}),
|
||||
NewTaskBranch: createNativeStackScreen({
|
||||
screen: NewTaskBranchPickerRouteScreen,
|
||||
linking: "draft/branch",
|
||||
options: {
|
||||
title: "Branch",
|
||||
},
|
||||
}),
|
||||
ThreadSettings: createNativeStackScreen({
|
||||
screen: NewTaskThreadSettingsRouteScreen,
|
||||
linking: "draft/settings",
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [1],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
AddProject: createNativeStackScreen({
|
||||
screen: AddProjectSourceRoute,
|
||||
@@ -294,6 +346,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"SettingsLegal",
|
||||
"SettingsSheet",
|
||||
"ThreadReviewComment",
|
||||
"ThreadSettingsSheet",
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -356,9 +409,11 @@ function RootStackLayout(props: {
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
<ExistingThreadSettingsRouteProvider>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ExistingThreadSettingsRouteProvider>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
@@ -440,7 +495,9 @@ export const RootStack = createNativeStackNavigator({
|
||||
options: {
|
||||
// Android cannot host the keyboard-driven comment composer inside a
|
||||
// formSheet; use a full-screen modal there instead.
|
||||
presentation: Platform.OS === "android" ? "fullScreenModal" : "formSheet",
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "fullScreenModal" as const }
|
||||
: FORM_SHEET_PRESENTATION_OPTIONS),
|
||||
sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.55, 0.92],
|
||||
sheetGrabberVisible: Platform.OS !== "android",
|
||||
},
|
||||
@@ -450,10 +507,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
linking: `${THREAD_LINKING_PREFIX}/files`,
|
||||
options: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR }
|
||||
: undefined,
|
||||
contentStyle: NATIVE_SHEET_SURFACE_CONTENT_STYLE,
|
||||
title: "Files",
|
||||
},
|
||||
}),
|
||||
@@ -462,11 +516,25 @@ export const RootStack = createNativeStackNavigator({
|
||||
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadSettingsSheet: createNativeStackScreen({
|
||||
screen: ExistingThreadSettingsRouteScreen,
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [1],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
GitOverview: createNativeStackScreen({
|
||||
screen: GitOverviewSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -475,7 +543,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitCommitSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -484,7 +552,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitBranchesSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -493,7 +561,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitConfirmSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.45, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -509,7 +577,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.7, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
@@ -532,7 +600,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.6, 0.95],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -547,7 +615,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const, headerShown: false }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
@@ -557,7 +625,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "connections/new",
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -577,7 +645,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
|
||||
@@ -3,14 +3,9 @@ import { Image } from "expo-image";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3_CODE_BRAND_MARK_SOURCE } from "./brandAssets";
|
||||
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
const BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
const DEFAULT_STAGE_LABEL =
|
||||
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
|
||||
|
||||
@@ -22,7 +17,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
return (
|
||||
<View className="flex-row items-center gap-3">
|
||||
<Image
|
||||
source={BRAND_MARK_SOURCE}
|
||||
source={T3_CODE_BRAND_MARK_SOURCE}
|
||||
accessibilityIgnoresInvertColors
|
||||
style={{
|
||||
width: iconSize,
|
||||
|
||||
+65
-5
@@ -17,11 +17,73 @@ import { cn } from "../lib/cn";
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { SymbolView } from "./AppSymbol";
|
||||
|
||||
export const COMPOSER_TOOLBAR_CONTROL_HEIGHT = 44;
|
||||
export const COMPOSER_TOOLBAR_GAP = 8;
|
||||
export const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
|
||||
const COMPOSER_TOOLBAR_GAP = 8;
|
||||
const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
|
||||
const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4;
|
||||
|
||||
/**
|
||||
* Quiet inline composer control used inside cards and their context rows.
|
||||
* Unlike ComposerToolbarButton, this does not draw another pill inside the
|
||||
* composer surface, so model and workspace controls read as part of the card.
|
||||
*/
|
||||
export function ComposerInlineControl(props: {
|
||||
readonly accessibilityHint?: string;
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly disabled?: boolean;
|
||||
readonly emphasized?: boolean;
|
||||
readonly icon?: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly iconNode?: ReactNode;
|
||||
readonly label: string;
|
||||
readonly maxWidth?: number;
|
||||
readonly onPress?: () => void;
|
||||
readonly selected?: boolean;
|
||||
readonly static?: boolean;
|
||||
readonly chevronDirection?: "down" | "right";
|
||||
readonly showChevron?: boolean;
|
||||
}) {
|
||||
const iconColor = useThemeColor(
|
||||
props.emphasized || props.selected ? "--color-icon" : "--color-icon-muted",
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityHint={props.accessibilityHint}
|
||||
accessibilityRole={props.static ? undefined : "button"}
|
||||
accessibilityState={
|
||||
props.static ? undefined : { disabled: props.disabled, selected: props.selected }
|
||||
}
|
||||
className="h-11 flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"
|
||||
disabled={props.disabled || props.static}
|
||||
onPress={props.onPress}
|
||||
style={{ maxWidth: props.maxWidth ?? 190, opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
{props.iconNode ? (
|
||||
<View className="size-4 shrink-0 items-center justify-center">{props.iconNode}</View>
|
||||
) : props.icon ? (
|
||||
<SymbolView name={props.icon} size={16} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-sm font-t3-medium",
|
||||
props.emphasized || props.selected ? "text-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
{props.showChevron === false ? null : (
|
||||
<SymbolView
|
||||
name={props.chevronDirection === "right" ? "chevron.right" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerToolbarRow(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly paddingBottom?: number;
|
||||
@@ -247,5 +309,3 @@ export function ComposerToolbarButton(props: {
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export const ComposerToolbarTrigger = ComposerToolbarButton;
|
||||
@@ -5,16 +5,19 @@ import {
|
||||
useColorScheme,
|
||||
View,
|
||||
type ColorValue,
|
||||
type StyleProp,
|
||||
type ViewProps,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
export interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
|
||||
interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
|
||||
readonly children: ReactNode;
|
||||
readonly glassEffectStyle?: "clear" | "regular" | "none";
|
||||
readonly tintColor?: ColorValue;
|
||||
readonly chrome?: "default" | "none";
|
||||
/** Styling used only when native Liquid Glass is unavailable. */
|
||||
readonly fallbackStyle?: StyleProp<ViewStyle>;
|
||||
}
|
||||
|
||||
export function GlassSurface({
|
||||
@@ -22,6 +25,7 @@ export function GlassSurface({
|
||||
glassEffectStyle = "regular",
|
||||
chrome = "default",
|
||||
tintColor,
|
||||
fallbackStyle,
|
||||
style,
|
||||
...props
|
||||
}: GlassSurfaceProps) {
|
||||
@@ -67,7 +71,7 @@ export function GlassSurface({
|
||||
}
|
||||
|
||||
return (
|
||||
<View {...props} style={[surfaceStyle, style]}>
|
||||
<View {...props} style={[surfaceStyle, fallbackStyle, style]}>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import Constants from "expo-constants";
|
||||
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
|
||||
export const T3_CODE_BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
@@ -1,5 +1,16 @@
|
||||
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
|
||||
import { ORCHESTRATION_CACHE_SCHEMA_VERSION } from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadDetailSnapshot,
|
||||
type VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
@@ -7,6 +18,125 @@ 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,
|
||||
titleRegeneration: {
|
||||
requestId: CommandId.make("title-regeneration-1"),
|
||||
startedAt: NOW,
|
||||
},
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
archivedThreads: [],
|
||||
};
|
||||
const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
|
||||
snapshotSequence: 4,
|
||||
projection: {
|
||||
thread: {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
providerInstanceId: PROVIDER_INSTANCE_ID,
|
||||
modelSelection: {
|
||||
instanceId: PROVIDER_INSTANCE_ID,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
rootThreadId: THREAD_ID,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: NOW,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
subagentActivations: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: NOW,
|
||||
},
|
||||
};
|
||||
const REFS: VcsListRefsResult = {
|
||||
refs: [
|
||||
{
|
||||
@@ -28,13 +158,16 @@ function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey:
|
||||
|
||||
function makeDatabase() {
|
||||
const values = new Map<string, string>();
|
||||
const schemaVersions = new Map<string, number>();
|
||||
const removed: Array<string> = [];
|
||||
const database = MobileDatabase.of({
|
||||
loadCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
|
||||
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
|
||||
saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
|
||||
Effect.sync(() => {
|
||||
values.set(cacheId(environmentId, kind, cacheKey), payload);
|
||||
const id = cacheId(environmentId, kind, cacheKey);
|
||||
values.set(id, payload);
|
||||
schemaVersions.set(id, schemaVersion);
|
||||
}),
|
||||
removeCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.sync(() => {
|
||||
@@ -59,10 +192,40 @@ function makeDatabase() {
|
||||
loadPreferencesJson: Effect.succeed(Option.none()),
|
||||
savePreferencesJson: () => Effect.void,
|
||||
});
|
||||
return { database, removed, values };
|
||||
return { database, removed, schemaVersions, values };
|
||||
}
|
||||
|
||||
describe("mobile SQLite environment cache store", () => {
|
||||
it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
|
||||
|
||||
yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
|
||||
yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
|
||||
|
||||
const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
|
||||
const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
|
||||
|
||||
expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
|
||||
expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
);
|
||||
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("round-trips schema-validated VCS refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import {
|
||||
ConnectionPersistenceError,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ServerConfig,
|
||||
VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -16,25 +13,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
// makes pre-pagination clients discard the record instead of decoding a
|
||||
// partial thread as complete (rollback safety).
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
|
||||
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,
|
||||
@@ -48,13 +29,17 @@ const StoredVcsRefs = Schema.Struct({
|
||||
});
|
||||
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredShellSnapshot),
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredThreadSnapshot),
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
|
||||
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredServerConfig),
|
||||
);
|
||||
@@ -130,12 +115,12 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
),
|
||||
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
|
||||
const payload = yield* encodeStoredShellSnapshot({
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "shell", "snapshot", ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
|
||||
}),
|
||||
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
|
||||
@@ -153,15 +138,15 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
}),
|
||||
),
|
||||
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
|
||||
const threadId = snapshot.thread.id;
|
||||
const threadId = snapshot.projection.thread.id;
|
||||
const payload = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "thread", threadId, ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
|
||||
}),
|
||||
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
|
||||
import {
|
||||
boundedThreadSnapshotLoaderLayer,
|
||||
threadHistoryControllerLayer,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -15,7 +18,11 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
|
||||
const snapshotLoaderLayer = Layer.mergeAll(
|
||||
boundedThreadSnapshotLoaderLayer,
|
||||
shellSnapshotLoaderLayer,
|
||||
threadHistoryControllerLayer,
|
||||
);
|
||||
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
|
||||
@@ -17,6 +17,7 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as CatalogStore from "./catalog-store";
|
||||
|
||||
function targetPersistenceError(
|
||||
|
||||
@@ -20,12 +20,15 @@ import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
loadAgentAwarenessRegistrationRecord,
|
||||
loadOrCreateAgentAwarenessDeviceId,
|
||||
loadPreferences,
|
||||
saveAgentAwarenessRegistrationRecord,
|
||||
} from "../../persistence/imperative";
|
||||
import type { Preferences } from "../../persistence/mobile-preferences";
|
||||
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
|
||||
import {
|
||||
AgentAwarenessOperationError,
|
||||
__resetAgentAwarenessRemoteRegistrationForTest,
|
||||
armAgentAwarenessLiveActivityForLocalWork,
|
||||
getAgentAwarenessRegistrationStatus,
|
||||
mergeAgentAwarenessRegistrationPreferences,
|
||||
refreshActiveLiveActivityRemoteRegistration,
|
||||
@@ -43,6 +46,13 @@ import * as Notifications from "expo-notifications";
|
||||
const secureStore = vi.hoisted(() => new Map<string, string>());
|
||||
const widgetMocks = vi.hoisted(() => ({
|
||||
getInstances: vi.fn(() => []),
|
||||
start: vi.fn(() => ({})),
|
||||
}));
|
||||
const environmentConfigsMock = vi.hoisted(() => ({
|
||||
configs: new Map<
|
||||
string,
|
||||
{ environment: { capabilities: { agentActivityPublishing?: boolean } } }
|
||||
>(),
|
||||
}));
|
||||
const backgroundRuntime = vi.hoisted(() => ({
|
||||
pending: [] as Array<{
|
||||
@@ -77,9 +87,22 @@ vi.mock("expo-widgets", () => ({
|
||||
vi.mock("../../widgets/AgentActivity", () => ({
|
||||
default: {
|
||||
getInstances: widgetMocks.getInstances,
|
||||
start: widgetMocks.start,
|
||||
},
|
||||
}));
|
||||
|
||||
// The state modules pull the whole connection stack (and native expo modules)
|
||||
// into the import graph; the arming gate only needs the configs map.
|
||||
vi.mock("../../state/atom-registry", () => ({
|
||||
appAtomRegistry: {
|
||||
get: () => environmentConfigsMock.configs,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../state/server", () => ({
|
||||
environmentServerConfigsAtom: Symbol("environmentServerConfigsAtom"),
|
||||
}));
|
||||
|
||||
vi.mock("expo-notifications", () => ({
|
||||
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
|
||||
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
|
||||
@@ -227,6 +250,8 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
|
||||
widgetMocks.getInstances.mockReset();
|
||||
widgetMocks.getInstances.mockReturnValue([]);
|
||||
widgetMocks.start.mockClear();
|
||||
environmentConfigsMock.configs.clear();
|
||||
});
|
||||
|
||||
it("preserves disabled Live Activity preferences in relay registrations", () => {
|
||||
@@ -856,4 +881,55 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
},
|
||||
);
|
||||
|
||||
it("skips the Live Activity seed when the environment reports publishing disabled", async () => {
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
vi.mocked(loadPreferences).mockResolvedValueOnce({
|
||||
liveActivitiesEnabled: true,
|
||||
} as Preferences);
|
||||
environmentConfigsMock.configs.set("env-1", {
|
||||
environment: { capabilities: { agentActivityPublishing: false } },
|
||||
});
|
||||
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
threadTitle: "Fix the flaky test",
|
||||
projectTitle: "t3code",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(widgetMocks.start).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("seeds the Live Activity for publishing and pre-capability environments", async () => {
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
environmentConfigsMock.configs.set("env-publishing", {
|
||||
environment: { capabilities: { agentActivityPublishing: true } },
|
||||
});
|
||||
|
||||
vi.mocked(loadPreferences).mockResolvedValueOnce({
|
||||
liveActivitiesEnabled: true,
|
||||
} as Preferences);
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: "env-publishing" as EnvironmentId,
|
||||
threadTitle: "Fix the flaky test",
|
||||
projectTitle: "t3code",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
|
||||
|
||||
// An environment without the capability may run an older server that
|
||||
// still publishes; only an explicit false skips the seed.
|
||||
widgetMocks.start.mockClear();
|
||||
vi.mocked(loadPreferences).mockResolvedValueOnce({
|
||||
liveActivitiesEnabled: true,
|
||||
} as Preferences);
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: "env-pre-capability" as EnvironmentId,
|
||||
threadTitle: "Fix the flaky test",
|
||||
projectTitle: "t3code",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import type { Preferences } from "../../persistence/mobile-preferences";
|
||||
import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
@@ -448,18 +450,38 @@ function unregisterDeviceWithRelay(input: {
|
||||
});
|
||||
}
|
||||
|
||||
// The environment descriptor advertises whether agent-activity publishes
|
||||
// currently leave that server (`capabilities.agentActivityPublishing`). Only
|
||||
// an explicit false skips the seed card: older servers omit the capability
|
||||
// but may still publish.
|
||||
function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.agentActivityPublishing !== false
|
||||
);
|
||||
}
|
||||
|
||||
// Arms the lock-screen card the moment the user starts agent work from this
|
||||
// phone, while the app is still foregrounded and the fresh activity's token
|
||||
// can be registered immediately. The seeded row is a best-effort placeholder;
|
||||
// the relay's registration replay repaints it with the authoritative
|
||||
// aggregate within seconds. No-ops when a card is already armed.
|
||||
// aggregate within seconds. No-ops when a card is already armed, and skips
|
||||
// environments that report publishing disabled — the seed would sit on
|
||||
// "Connecting" forever with no update ever arriving to repaint or end it.
|
||||
export function armAgentAwarenessLiveActivityForLocalWork(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadTitle: string;
|
||||
readonly projectTitle: string;
|
||||
}): void {
|
||||
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
|
||||
return;
|
||||
}
|
||||
if (!environmentPublishesAgentActivity(input.environmentId)) {
|
||||
logRegistrationDebug("live activity arming skipped; environment does not publish", {
|
||||
environmentId: input.environmentId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
void loadPreferences()
|
||||
.catch(() => null)
|
||||
.then((preferences) => {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
import { makeRawThreadShell } from "../../test-fixtures";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
@@ -22,42 +24,30 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
|
||||
readonly branch?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
|
||||
return makeRawThreadShell({
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
|
||||
});
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { CameraView, useCameraPermissions } from "expo-camera";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -11,12 +11,13 @@ import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ErrorBanner } from "../../components/ErrorBanner";
|
||||
import { ConnectionSheetButton } from "./ConnectionSheetButton";
|
||||
import { extractPairingUrlFromQrPayload } from "./pairing";
|
||||
import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { buildPairingUrl, parsePairingUrl } from "./pairing";
|
||||
|
||||
type ConnectionsNewRouteParams = {
|
||||
readonly mode?: string;
|
||||
readonly pairingUrl?: string;
|
||||
readonly autoConnect?: string;
|
||||
};
|
||||
|
||||
export function ConnectionsNewRouteScreen({
|
||||
@@ -30,6 +31,13 @@ export function ConnectionsNewRouteScreen({
|
||||
} = useRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const params = route.params ?? {};
|
||||
// Deep-link prefill exists for development automation only. A production
|
||||
// link must not arrive with attacker-chosen host and token already filled.
|
||||
const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
|
||||
const shouldAutoConnect =
|
||||
__DEV__ &&
|
||||
routePairingUrl.length > 0 &&
|
||||
(params.autoConnect === "1" || params.autoConnect === "true");
|
||||
const insets = useSafeAreaInsets();
|
||||
const [hostInput, setHostInput] = useState("");
|
||||
const [codeInput, setCodeInput] = useState("");
|
||||
@@ -37,6 +45,7 @@ export function ConnectionsNewRouteScreen({
|
||||
const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
|
||||
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
|
||||
const [scannerLocked, setScannerLocked] = useState(false);
|
||||
const attemptedAutoConnectRef = useRef<string | null>(null);
|
||||
|
||||
const headerIconColor = useThemeColor("--color-icon");
|
||||
|
||||
@@ -48,6 +57,16 @@ export function ConnectionsNewRouteScreen({
|
||||
setCodeInput(code);
|
||||
}, [connectionPairingUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (routePairingUrl.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { host, code } = parsePairingUrl(routePairingUrl);
|
||||
setHostInput(host);
|
||||
setCodeInput(code);
|
||||
}, [routePairingUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (pairingConnectionError) {
|
||||
setIsSubmitting(false);
|
||||
@@ -116,22 +135,38 @@ export function ConnectionsNewRouteScreen({
|
||||
[onChangeConnectionPairingUrl, scannerLocked],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
setIsSubmitting(true);
|
||||
|
||||
const pairingUrl = buildPairingUrl(hostInput, codeInput);
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
const result = await onConnectPress(pairingUrl);
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
if (navigation.canGoBack()) {
|
||||
navigation.goBack();
|
||||
} else {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
const connectAndClose = useCallback(
|
||||
async (pairingUrl: string, replaceWithHome: boolean) => {
|
||||
setIsSubmitting(true);
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
try {
|
||||
const result = await onConnectPress(pairingUrl);
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
if (replaceWithHome || !navigation.canGoBack()) {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
} else {
|
||||
navigation.goBack();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
} else {
|
||||
setIsSubmitting(false);
|
||||
},
|
||||
[navigation, onChangeConnectionPairingUrl, onConnectPress],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
await connectAndClose(buildPairingUrl(hostInput, codeInput), false);
|
||||
}, [codeInput, connectAndClose, hostInput]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
|
||||
return;
|
||||
}
|
||||
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, navigation]);
|
||||
|
||||
attemptedAutoConnectRef.current = routePairingUrl;
|
||||
void connectAndClose(routePairingUrl, true);
|
||||
}, [connectAndClose, routePairingUrl, shouldAutoConnect]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
|
||||
@@ -8,6 +8,7 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import {
|
||||
buildFileTree,
|
||||
@@ -123,7 +124,7 @@ export function FileTreeBrowser(props: {
|
||||
const insets = useSafeAreaInsets();
|
||||
// Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
|
||||
// observed adjustedContentInset bottom (~102) seen in the native trace.
|
||||
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 44 : 0;
|
||||
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + IOS_NAV_BAR_HEIGHT : 0;
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
|
||||
const controlledSelectedPathRef = useRef(controlledSelectedPath);
|
||||
|
||||
@@ -356,6 +356,7 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
onSearchTextChange: props.onSearchQueryChange,
|
||||
placeholder: "Search",
|
||||
searchTextChangeId: "home-search-text",
|
||||
showsSearchDismissButton: true,
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
|
||||
import { checkForAppUpdateOnLaunch, startAppUpdateForegroundRecheck } from "../updates/app-updates";
|
||||
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
@@ -34,6 +34,7 @@ export function HomeRouteScreen() {
|
||||
|
||||
useEffect(() => {
|
||||
void checkForAppUpdateOnLaunch();
|
||||
startAppUpdateForegroundRecheck();
|
||||
}, []);
|
||||
|
||||
const {
|
||||
@@ -45,6 +46,7 @@ export function HomeRouteScreen() {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -186,6 +188,7 @@ export function HomeRouteScreen() {
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() =>
|
||||
|
||||
@@ -115,6 +115,7 @@ interface HomeScreenProps {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -189,7 +190,7 @@ function deriveEmptyState(props: {
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
detail: "Create a task to start a new coding runtime in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
@@ -206,6 +207,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const autoSettleOnMerge =
|
||||
!AsyncResult.isSuccess(preferencesResult) ||
|
||||
preferencesResult.value.autoSettleOnMerge !== false;
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
@@ -482,8 +486,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
// the partition works directly off live shells — no snapshot merging or
|
||||
// optimistic holds.
|
||||
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
|
||||
// closed PR auto-settles its thread on the next partition (mirrors web).
|
||||
// PR states stream in per-row. The next partition applies the configured
|
||||
// merge rule and the always-on close rule, matching web.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
@@ -538,6 +542,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onUnpinThread],
|
||||
);
|
||||
const handleRegenerateThreadTitle = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onRegenerateThreadTitle(thread);
|
||||
},
|
||||
[props.onRegenerateThreadTitle],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -615,6 +625,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order (reorder-capable threads only) for the
|
||||
// Move up/down position flags. Computed from all shells, not the rendered
|
||||
// list, so search/scope filtering never disables or misdirects a move.
|
||||
@@ -649,6 +668,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
@@ -660,6 +680,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
@@ -793,7 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
@@ -811,6 +832,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -842,6 +865,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleRegenerateThreadTitle,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
@@ -863,6 +887,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Items,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
@@ -967,6 +992,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery={props.searchQuery}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onDeleteThread={props.onDeleteThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -988,6 +1015,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleRegenerateThreadTitle,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
@@ -998,6 +1026,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
@@ -1072,7 +1101,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 session." />
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding runtime." />
|
||||
)
|
||||
) : null;
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
import {
|
||||
presentThreadShell,
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
@@ -32,29 +34,41 @@ function makeProject(id: string, title: string): EnvironmentProject {
|
||||
};
|
||||
}
|
||||
|
||||
const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z");
|
||||
|
||||
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
id: ThreadId.make(id),
|
||||
const threadId = ThreadId.make(id);
|
||||
return presentThreadShell(environmentId, {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: `Thread ${id}`,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: threadTimestamp,
|
||||
updatedAt: threadTimestamp,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
}
|
||||
|
||||
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -30,25 +31,21 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { ProviderInstanceId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
|
||||
import { threadCanArchive } from "./threadArchive";
|
||||
|
||||
function runtime(
|
||||
status: ThreadRuntimeSummary["status"],
|
||||
activeRunId: ThreadRuntimeSummary["activeRunId"],
|
||||
): ThreadRuntimeSummary {
|
||||
return {
|
||||
status,
|
||||
activeRunId,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
providerName: "codex",
|
||||
lastError: null,
|
||||
updatedAt: "2026-07-28T10:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("threadCanArchive", () => {
|
||||
it("blocks provider-active work", () => {
|
||||
const activeRunId = RunId.make("run-live");
|
||||
expect(threadCanArchive(runtime("preparing", activeRunId))).toBe(false);
|
||||
expect(threadCanArchive(runtime("starting", activeRunId))).toBe(false);
|
||||
expect(threadCanArchive(runtime("running", activeRunId))).toBe(false);
|
||||
});
|
||||
|
||||
it("only allows queued work when no provider run remains active", () => {
|
||||
const activeRunId = RunId.make("run-live");
|
||||
expect(threadCanArchive(runtime("queued", null))).toBe(true);
|
||||
expect(threadCanArchive(runtime("queued", activeRunId))).toBe(false);
|
||||
});
|
||||
|
||||
it("allows post-provider waiting work despite a retained active run id", () => {
|
||||
const staleActiveRunId = RunId.make("run-finished");
|
||||
expect(threadCanArchive(runtime("waiting", null))).toBe(true);
|
||||
expect(threadCanArchive(runtime("waiting", staleActiveRunId))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
|
||||
|
||||
/**
|
||||
* Archiving may discard queued work, but it must not detach a provider while
|
||||
* that provider is still executing a turn.
|
||||
*/
|
||||
export function threadCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
|
||||
if (runtime?.status === "queued") {
|
||||
return runtime.activeRunId === null;
|
||||
}
|
||||
return (
|
||||
runtime?.status !== "preparing" &&
|
||||
runtime?.status !== "starting" &&
|
||||
runtime?.status !== "running"
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { environmentThreadShells, 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). */
|
||||
@@ -48,6 +49,15 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsTitleRegeneration(
|
||||
environmentId: EnvironmentThreadShell["environmentId"],
|
||||
) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadTitleRegeneration === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -119,13 +129,9 @@ function useThreadActionExecutor(
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (
|
||||
action === "archive" &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
// The server cancels queued runs on archive. Only an actual provider
|
||||
// turn still needs the user to interrupt it first.
|
||||
if (action === "archive" && !threadCanArchive(thread.runtime)) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
@@ -227,13 +233,18 @@ export function useThreadListActions(): {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly regenerateThreadTitle: (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 updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -405,6 +416,47 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[unpinMutation],
|
||||
);
|
||||
const regenerateThreadTitle = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (
|
||||
thread.titleRegeneration != null ||
|
||||
titleRegenerationInFlightThreadKeys.current.has(key)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
titleRegenerationInFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const result = await updateThreadMetadata({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, regenerateTitle: true },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread title could not be regenerated.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
titleRegenerationInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[updateThreadMetadata],
|
||||
);
|
||||
|
||||
// Move up / Move down for the pinned block. Computed against the CANONICAL
|
||||
// keyed pinned order (not the rendered list), so the move is valid even
|
||||
@@ -497,6 +549,7 @@ export function useThreadListActions(): {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,10 @@ export function subscribeToHardwareKeyboardCommandRegistrations(listener: () =>
|
||||
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
|
||||
const commandHandlers = handlers.get(command);
|
||||
if (!commandHandlers) return false;
|
||||
for (const handler of [...commandHandlers].toReversed()) {
|
||||
const handlersInRegistrationOrder = Array.from(commandHandlers);
|
||||
for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) {
|
||||
const handler = handlersInRegistrationOrder[index];
|
||||
if (!handler) continue;
|
||||
if (handler() !== false) return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -11,6 +11,9 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
*/
|
||||
export const NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED = NATIVE_LIQUID_GLASS_SUPPORTED;
|
||||
|
||||
/** Clearance for scroll content that must come to rest above the floating toolbar. */
|
||||
export const NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET = 56;
|
||||
|
||||
type NativeMailSearchToolbarInput = Omit<
|
||||
HeaderBarButtonMailSearchToolbarItem,
|
||||
"type" | "useFallbackSearchField"
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
inferProjectTitleFromPath,
|
||||
} from "@t3tools/client-runtime/state/projects";
|
||||
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
|
||||
@@ -402,13 +402,12 @@ function SourceControlRow(props: {
|
||||
icon={icon}
|
||||
isFirst={props.isFirst}
|
||||
onPress={() =>
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectRepository",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectRepository", {
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
source: props.source,
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
@@ -498,12 +497,11 @@ export function AddProjectSourceScreen() {
|
||||
}
|
||||
isFirst
|
||||
onPress={() =>
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectLocal",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectLocal", {
|
||||
environmentId: selectedEnvironment.environmentId,
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
|
||||
@@ -547,10 +545,18 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
if (existing) {
|
||||
Alert.alert("Project already exists", existing.title);
|
||||
navigation.dispatch(
|
||||
StackActions.replace("NewTaskDraft", {
|
||||
environmentId: existing.environmentId,
|
||||
projectId: existing.id,
|
||||
title: existing.title,
|
||||
CommonActions.reset({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: existing.environmentId,
|
||||
projectId: existing.id,
|
||||
title: existing.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
return;
|
||||
@@ -561,7 +567,6 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
projectId,
|
||||
workspaceRoot,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
const result = await createProject({
|
||||
environmentId: environment.environmentId,
|
||||
@@ -571,10 +576,18 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
return result;
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("NewTaskDraft", {
|
||||
environmentId: environment.environmentId,
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(workspaceRoot),
|
||||
CommonActions.reset({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: environment.environmentId,
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(workspaceRoot),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
@@ -612,15 +625,14 @@ export function AddProjectRepositoryScreen(props: {
|
||||
const provider = addProjectRemoteSourceProvider(source);
|
||||
if (!provider) {
|
||||
const remoteUrl = repositoryInput.trim();
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectDestination",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectDestination", {
|
||||
environmentId: environment.environmentId,
|
||||
source,
|
||||
remoteUrl,
|
||||
repositoryTitle: remoteUrl,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
@@ -636,15 +648,14 @@ export function AddProjectRepositoryScreen(props: {
|
||||
setError(errorMessage(Cause.squash(result.cause)));
|
||||
} else {
|
||||
const repository = result.value;
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "AddProjectDestination",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("AddProjectDestination", {
|
||||
environmentId: environment.environmentId,
|
||||
source,
|
||||
remoteUrl: repository.sshUrl,
|
||||
repositoryTitle: repository.nameWithOwner,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
setIsSubmitting(false);
|
||||
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
|
||||
|
||||
@@ -39,6 +39,7 @@ import { environmentCatalog } from "../../connection/catalog";
|
||||
import { useEnvironmentPresentation } from "../../state/presentation";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import {
|
||||
@@ -277,9 +278,11 @@ function ReviewFileNavigator({
|
||||
// The nested native header is translucent; start the list below it so
|
||||
// the scroll-edge effect can sample the content (same treatment as
|
||||
// FileTreeBrowser in the Files pane).
|
||||
paddingTop: Platform.OS === "ios" ? insets.top + 44 + 8 : 8,
|
||||
paddingTop: Platform.OS === "ios" ? insets.top + IOS_NAV_BAR_HEIGHT + 8 : 8,
|
||||
}}
|
||||
scrollIndicatorInsets={Platform.OS === "ios" ? { top: insets.top + 44 } : undefined}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios" ? { top: insets.top + IOS_NAV_BAR_HEIGHT } : undefined
|
||||
}
|
||||
renderItem={renderFile}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MessageId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type ReviewDiffPreviewSource,
|
||||
} from "@t3tools/contracts";
|
||||
import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
|
||||
import {
|
||||
buildReviewListItems,
|
||||
@@ -18,9 +14,9 @@ import {
|
||||
} from "./reviewModel";
|
||||
|
||||
function makeCheckpoint(
|
||||
input: Partial<OrchestrationCheckpointSummary> &
|
||||
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
|
||||
): OrchestrationCheckpointSummary {
|
||||
input: Partial<ThreadCheckpointSummary> &
|
||||
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
|
||||
): ThreadCheckpointSummary {
|
||||
return {
|
||||
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
|
||||
status: "ready",
|
||||
@@ -52,12 +48,12 @@ describe("buildReviewSectionItems", () => {
|
||||
it("keeps one chip per checkpoint and appends git sources", () => {
|
||||
const checkpoints = [
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-1"),
|
||||
runId: RunId.make("run-1"),
|
||||
checkpointTurnCount: 1,
|
||||
completedAt: "2026-04-01T00:00:00.000Z",
|
||||
}),
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("run-2"),
|
||||
checkpointTurnCount: 2,
|
||||
completedAt: "2026-04-02T00:00:00.000Z",
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
|
||||
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
|
||||
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Order from "effect/Order";
|
||||
@@ -128,11 +129,11 @@ export type ReviewParsedDiff =
|
||||
readonly notice: string | null;
|
||||
};
|
||||
|
||||
function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
return `Turn ${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
const fileCount = checkpoint.files.length;
|
||||
if (checkpoint.status !== "ready") {
|
||||
return `Diff ${checkpoint.status}`;
|
||||
@@ -141,8 +142,8 @@ function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string
|
||||
}
|
||||
|
||||
function compareCheckpointTurnCountDescending(
|
||||
left: OrchestrationCheckpointSummary,
|
||||
right: OrchestrationCheckpointSummary,
|
||||
left: ThreadCheckpointSummary,
|
||||
right: ThreadCheckpointSummary,
|
||||
): -1 | 0 | 1 {
|
||||
if (left.checkpointTurnCount === right.checkpointTurnCount) {
|
||||
return 0;
|
||||
@@ -151,7 +152,7 @@ function compareCheckpointTurnCountDescending(
|
||||
return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
|
||||
}
|
||||
|
||||
const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
|
||||
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
|
||||
compareCheckpointTurnCountDescending,
|
||||
);
|
||||
|
||||
@@ -510,14 +511,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
|
||||
}
|
||||
|
||||
export function getReviewSectionIdForCheckpoint(
|
||||
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
|
||||
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
|
||||
): string {
|
||||
return `turn:${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
export function getReadyReviewCheckpoints(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): ReadonlyArray<OrchestrationCheckpointSummary> {
|
||||
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
return pipe(
|
||||
checkpoints,
|
||||
Arr.filter((checkpoint) => checkpoint.status === "ready"),
|
||||
@@ -526,7 +527,7 @@ export function getReadyReviewCheckpoints(
|
||||
}
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
deriveThreadCheckpointSummaries,
|
||||
type ThreadCheckpointSummary,
|
||||
} from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { useCheckpointDiff } from "../../state/queries";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { reviewEnvironment } from "../../state/review";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import {
|
||||
buildReviewSectionItems,
|
||||
@@ -30,7 +34,7 @@ export function useReviewSections(input: {
|
||||
}) {
|
||||
const { environmentId, reviewCache, threadId } = input;
|
||||
const enabled = input.enabled ?? true;
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const selectedThread = useSelectedThreadProjection();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const diffPreview = useEnvironmentQuery(
|
||||
enabled && environmentId !== undefined && selectedThreadCwd !== null
|
||||
@@ -49,8 +53,11 @@ export function useReviewSections(input: {
|
||||
}, [diffPreview.data, reviewCache.threadKey]);
|
||||
|
||||
const readyCheckpoints = useMemo(
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
() =>
|
||||
getReadyReviewCheckpoints(
|
||||
selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
|
||||
),
|
||||
[selectedThread],
|
||||
);
|
||||
const checkpointBySectionId = useMemo(
|
||||
() =>
|
||||
@@ -59,7 +66,7 @@ export function useReviewSections(input: {
|
||||
getReviewSectionIdForCheckpoint(checkpoint),
|
||||
checkpoint,
|
||||
]),
|
||||
) as Record<string, OrchestrationCheckpointSummary>,
|
||||
) as Record<string, ThreadCheckpointSummary>,
|
||||
[readyCheckpoints],
|
||||
);
|
||||
const reviewSections = useMemo(
|
||||
|
||||
@@ -522,9 +522,21 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const autoSettleOnMerge =
|
||||
!AsyncResult.isSuccess(preferencesResult) ||
|
||||
preferencesResult.value.autoSettleOnMerge !== false;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
<SettingsSwitchRow
|
||||
icon="arrow.triangle.branch"
|
||||
label="Auto-settle merged threads"
|
||||
value={autoSettleOnMerge}
|
||||
onValueChange={(value) => savePreferences({ autoSettleOnMerge: value })}
|
||||
/>
|
||||
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
|
||||
</SettingsSection>
|
||||
);
|
||||
@@ -537,7 +549,10 @@ function GeneralSettingsSection() {
|
||||
*/
|
||||
function LegacySettingsSection() {
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const preferences = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const planModeEnabled =
|
||||
AsyncResult.isSuccess(preferences) && preferences.value.planModeEnabled === true;
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
@@ -548,10 +563,16 @@ function LegacySettingsSection() {
|
||||
value={!threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
|
||||
/>
|
||||
<SettingsSwitchRow
|
||||
icon="hammer"
|
||||
label="Plan Mode"
|
||||
value={planModeEnabled}
|
||||
onValueChange={(value) => savePreferences({ planModeEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
Brings back the original grouped thread list. The default list is flat, in creation order:
|
||||
active work renders as cards; settled threads collapse to compact rows.
|
||||
Opt into retired interfaces kept for compatibility. Plan Mode restores the Build/Plan
|
||||
control; otherwise every task runs in Build mode.
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
@@ -587,7 +608,10 @@ function AppSettingsSection() {
|
||||
if (updateInFlight.current) return;
|
||||
updateInFlight.current = true;
|
||||
try {
|
||||
// The user asked for this restart by tapping the version row, so it may
|
||||
// apply immediately instead of prompting.
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
onFailure: (message) => Alert.alert("Update failed", message),
|
||||
onStateChange: setUpdateState,
|
||||
});
|
||||
@@ -610,11 +634,15 @@ function AppSettingsSection() {
|
||||
? "Checking…"
|
||||
: updateState === "downloading"
|
||||
? "Downloading…"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
: // "ready" appears only when this check joined an in-flight background-mode
|
||||
// check; that download installs at the next backgrounding.
|
||||
updateState === "ready"
|
||||
? "Update ready"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
|
||||
const versionRow = (
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ComposerToolbarButton,
|
||||
ComposerToolbarRow,
|
||||
ComposerToolbarScroller,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
} from "../../components/ComposerToolbar";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
useKnownTerminalSessions,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
@@ -172,7 +172,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
const params = props.route.params;
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const selectedThreadDetail = useSelectedThreadProjection();
|
||||
const selectedThreadDetailWorktreePath =
|
||||
selectedThreadDetail?.projection.thread.worktreePath ?? null;
|
||||
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const routeThreadIdRaw = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentId = routeEnvironmentIdRaw
|
||||
@@ -283,13 +285,13 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
activeSessionLocation: activeKnownSession?.state.summary ?? null,
|
||||
workspaceRoot: selectedThreadProject.workspaceRoot,
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetailWorktreePath,
|
||||
});
|
||||
}, [
|
||||
activeKnownSession?.state.summary,
|
||||
pendingLaunch,
|
||||
selectedThread,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThreadDetailWorktreePath,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
]);
|
||||
const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger";
|
||||
import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -6,6 +5,7 @@ import { memo } from "react";
|
||||
import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
export type ComposerCommandItem =
|
||||
| {
|
||||
@@ -56,33 +56,14 @@ function PopoverSurface(props: {
|
||||
...props.style,
|
||||
};
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<LiquidGlassView
|
||||
effect="clear"
|
||||
interactive={false}
|
||||
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
|
||||
colorScheme={props.isDarkMode ? "dark" : "light"}
|
||||
style={baseStyle}
|
||||
>
|
||||
{props.children}
|
||||
</LiquidGlassView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
baseStyle,
|
||||
{
|
||||
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
|
||||
borderWidth: 1,
|
||||
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
|
||||
},
|
||||
]}
|
||||
<GlassSurface
|
||||
glassEffectStyle="clear"
|
||||
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
|
||||
style={baseStyle}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
</GlassSurface>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,13 @@ import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanim
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { APP_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { GitActionProgress } from "../../state/use-vcs-action-state";
|
||||
|
||||
const OVERLAY_LAYOUT_TRANSITION = LinearTransition.duration(220);
|
||||
const OVERLAY_TOP_GAP = 8;
|
||||
const AnimatedLiquidGlassView = Animated.createAnimatedComponent(LiquidGlassView);
|
||||
|
||||
export function GitActionProgressOverlay(props: {
|
||||
@@ -52,7 +54,7 @@ export function GitActionProgressOverlay(props: {
|
||||
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
|
||||
exiting={FadeOut.duration(150)}
|
||||
className="absolute inset-x-3 z-[100]"
|
||||
style={{ top: insets.top + 48 }}
|
||||
style={{ top: insets.top + APP_BAR_HEIGHT + OVERLAY_TOP_GAP }}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<Pressable onPress={handlePress}>
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Switch,
|
||||
TextInput,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { vcsEnvironment } from "../../state/vcs";
|
||||
import {
|
||||
createNativeMailSearchToolbarItem,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
|
||||
} from "../layout/native-mail-search-toolbar";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
|
||||
|
||||
function SelectionRow(props: {
|
||||
readonly icon?: "arrow.triangle.branch" | "desktopcomputer";
|
||||
readonly onPress: () => void;
|
||||
readonly disabled?: boolean;
|
||||
readonly selected: boolean;
|
||||
readonly isLast?: boolean;
|
||||
readonly subtitle?: string;
|
||||
readonly title: string;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
const checkmarkColor = useThemeColor("--color-icon");
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}
|
||||
accessibilityRole="radio"
|
||||
accessibilityState={{ checked: props.selected }}
|
||||
className={cn(
|
||||
"min-h-14 flex-row items-center gap-3 bg-card px-4 py-3 active:bg-subtle",
|
||||
!props.isLast && "border-b border-border-subtle",
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
onPress={props.onPress}
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
{props.icon ? (
|
||||
<SymbolView name={props.icon} size={17} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
|
||||
{props.title}
|
||||
</Text>
|
||||
{props.subtitle ? (
|
||||
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
|
||||
{props.subtitle}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{props.selected ? (
|
||||
<SymbolView
|
||||
name="checkmark"
|
||||
size={16}
|
||||
tintColor={checkmarkColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function ToggleRow(props: {
|
||||
readonly title: string;
|
||||
readonly value: boolean;
|
||||
readonly onValueChange: (value: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="min-h-14 flex-row items-center gap-3 bg-card px-4 py-3">
|
||||
<Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
|
||||
{props.title}
|
||||
</Text>
|
||||
<Switch
|
||||
accessibilityLabel={props.title}
|
||||
onValueChange={props.onValueChange}
|
||||
value={props.value}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function BranchSelectionRow(props: {
|
||||
readonly badge: string | null;
|
||||
readonly branch: VcsRef;
|
||||
readonly disabled: boolean;
|
||||
readonly isFirst: boolean;
|
||||
readonly isLast: boolean;
|
||||
readonly onSelect: (branch: VcsRef) => void;
|
||||
readonly selected: boolean;
|
||||
}) {
|
||||
const onPress = useCallback(() => props.onSelect(props.branch), [props.branch, props.onSelect]);
|
||||
|
||||
return (
|
||||
<View
|
||||
className={cn(
|
||||
props.isFirst && "overflow-hidden rounded-t-2xl",
|
||||
props.isLast && "overflow-hidden rounded-b-2xl",
|
||||
)}
|
||||
>
|
||||
<SelectionRow
|
||||
icon="arrow.triangle.branch"
|
||||
disabled={props.disabled}
|
||||
isLast={props.isLast}
|
||||
onPress={onPress}
|
||||
selected={props.selected}
|
||||
subtitle={props.badge ? props.badge.toUpperCase() : undefined}
|
||||
title={props.branch.name}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function PickerSurface(props: { readonly children: ReactNode }) {
|
||||
return <View className="overflow-hidden rounded-2xl bg-card">{props.children}</View>;
|
||||
}
|
||||
|
||||
export function NewTaskEnvironmentPickerRouteScreen() {
|
||||
const flow = useNewTaskFlow();
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerShown: Platform.OS !== "android",
|
||||
title: "Environment",
|
||||
}}
|
||||
/>
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidScreenHeader title="Environment" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{
|
||||
paddingBottom: Math.max(insets.bottom, 16) + 16,
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<PickerSurface>
|
||||
{flow.environments.map((environment, index) => (
|
||||
<SelectionRow
|
||||
key={String(environment.environmentId)}
|
||||
icon="desktopcomputer"
|
||||
isLast={index === flow.environments.length - 1}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
flow.selectEnvironment(environment.environmentId);
|
||||
navigation.goBack();
|
||||
}}
|
||||
selected={flow.selectedEnvironmentId === environment.environmentId}
|
||||
title={environment.environmentLabel}
|
||||
/>
|
||||
))}
|
||||
</PickerSurface>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function NewTaskBranchPickerRouteScreen() {
|
||||
const flow = useNewTaskFlow();
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const placeholderColor = useThemeColor("--color-placeholder");
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const fontFamily = useFontFamily("regular");
|
||||
const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
|
||||
const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
|
||||
const selectingBranchNameRef = useRef<string | null>(null);
|
||||
const allowSelectionNavigationRef = useRef(false);
|
||||
const mountedRef = useRef(true);
|
||||
const screenTitle = flow.workspaceMode === "worktree" ? "Base branch" : "Branch";
|
||||
const usesNativeMailSearchToolbar = Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
|
||||
const selectedBranchName =
|
||||
flow.selectedBranchName ??
|
||||
flow.availableBranches.find((branch) => branch.current)?.name ??
|
||||
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
const branchListContentStyle = useMemo(
|
||||
() => ({
|
||||
paddingBottom: usesNativeMailSearchToolbar
|
||||
? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
|
||||
: Platform.OS === "ios"
|
||||
? 16
|
||||
: Math.max(insets.bottom, 16) + 16,
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 12,
|
||||
}),
|
||||
[insets.bottom, usesNativeMailSearchToolbar],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
flow.setBranchQuery("");
|
||||
};
|
||||
}, [flow.setBranchQuery]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
navigation.addListener("beforeRemove", (event) => {
|
||||
if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}),
|
||||
[navigation],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
async (branch: VcsRef) => {
|
||||
if (selectingBranchNameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
selectingBranchNameRef.current = branch.name;
|
||||
void Haptics.selectionAsync();
|
||||
|
||||
try {
|
||||
let selectedBranch = branch;
|
||||
const needsCheckout = shouldCheckoutNewTaskBranch({
|
||||
branchIsCurrent: branch.current,
|
||||
branchWorktreePath: branch.worktreePath,
|
||||
workspaceMode: flow.workspaceMode,
|
||||
});
|
||||
if (needsCheckout && flow.selectedProject) {
|
||||
setSwitchingBranchName(branch.name);
|
||||
const result = await switchRef({
|
||||
environmentId: flow.selectedProject.environmentId,
|
||||
input: {
|
||||
cwd: flow.selectedProject.workspaceRoot,
|
||||
refName: branch.name,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
Alert.alert(
|
||||
"Could not switch branch",
|
||||
error instanceof Error ? error.message : "The branch could not be checked out.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
selectedBranch = {
|
||||
...branch,
|
||||
current: true,
|
||||
isRemote: false,
|
||||
name: result.value.refName ?? branch.name,
|
||||
};
|
||||
}
|
||||
|
||||
// The checkout has already changed the repository. Persist the matching
|
||||
// draft selection even if the native sheet was dismissed while the
|
||||
// command was in flight; only visible-screen work is focus-gated below.
|
||||
flow.selectBranch(selectedBranch);
|
||||
if (!mountedRef.current || !navigation.isFocused()) {
|
||||
return;
|
||||
}
|
||||
flow.setBranchQuery("");
|
||||
allowSelectionNavigationRef.current = true;
|
||||
navigation.goBack();
|
||||
} finally {
|
||||
selectingBranchNameRef.current = null;
|
||||
allowSelectionNavigationRef.current = false;
|
||||
if (mountedRef.current) {
|
||||
setSwitchingBranchName(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
flow.selectBranch,
|
||||
flow.selectedProject,
|
||||
flow.setBranchQuery,
|
||||
flow.workspaceMode,
|
||||
navigation,
|
||||
switchRef,
|
||||
],
|
||||
);
|
||||
|
||||
const renderBranch = useCallback(
|
||||
({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
|
||||
<BranchSelectionRow
|
||||
badge={branchBadgeLabel({ branch: item, project: flow.selectedProject })}
|
||||
branch={item}
|
||||
disabled={switchingBranchName !== null}
|
||||
isFirst={index === 0}
|
||||
isLast={index === flow.filteredBranches.length - 1}
|
||||
onSelect={selectBranch}
|
||||
selected={selectedBranchName === item.name}
|
||||
/>
|
||||
),
|
||||
[
|
||||
flow.filteredBranches.length,
|
||||
flow.selectedProject,
|
||||
selectBranch,
|
||||
selectedBranchName,
|
||||
switchingBranchName,
|
||||
],
|
||||
);
|
||||
|
||||
const branchListHeader =
|
||||
flow.workspaceMode === "worktree" ? (
|
||||
<View className="mb-3 overflow-hidden rounded-2xl">
|
||||
<ToggleRow
|
||||
onValueChange={flow.setStartFromOrigin}
|
||||
title="Start from origin"
|
||||
value={flow.startFromOrigin}
|
||||
/>
|
||||
</View>
|
||||
) : null;
|
||||
|
||||
const branchContent =
|
||||
flow.filteredBranches.length === 0 ? (
|
||||
<ScrollView
|
||||
className="flex-1 bg-sheet"
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 12 }}
|
||||
scrollEnabled={false}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{branchListHeader}
|
||||
<View
|
||||
className="flex-1 items-center justify-center gap-3 px-4"
|
||||
style={{
|
||||
marginBottom: usesNativeMailSearchToolbar
|
||||
? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
|
||||
: 0,
|
||||
}}
|
||||
>
|
||||
{flow.branchesLoading ? <ActivityIndicator /> : null}
|
||||
<Text className="text-center text-sm text-foreground-muted">
|
||||
{flow.branchesLoading
|
||||
? "Loading branches…"
|
||||
: flow.branchesError
|
||||
? flow.branchesError
|
||||
: flow.branchQuery
|
||||
? "No matching branches"
|
||||
: "No branches available"}
|
||||
</Text>
|
||||
{!flow.branchesLoading && flow.branchesError ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
className="rounded-full bg-card px-4 py-2 active:opacity-70"
|
||||
onPress={flow.loadBranches}
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-foreground">Try again</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</ScrollView>
|
||||
) : (
|
||||
<LegendList
|
||||
alwaysBounceVertical={false}
|
||||
automaticallyAdjustsScrollIndicatorInsets
|
||||
automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
|
||||
className="flex-1 bg-sheet"
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={branchListContentStyle}
|
||||
data={flow.filteredBranches}
|
||||
keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyExtractor={(branch) =>
|
||||
`${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
|
||||
}
|
||||
ListHeaderComponent={branchListHeader}
|
||||
ListFooterComponent={
|
||||
flow.branchesFetchingNextPage ? (
|
||||
<View className="items-center py-4">
|
||||
<ActivityIndicator />
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
onEndReached={flow.hasMoreBranches ? flow.loadMoreBranches : undefined}
|
||||
onEndReachedThreshold={0.35}
|
||||
renderItem={renderBranch}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
);
|
||||
|
||||
if (Platform.OS === "android") {
|
||||
return (
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title={screenTitle} onBack={() => navigation.goBack()} />
|
||||
<View className="px-4 pb-2 pt-3">
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="h-11 rounded-xl bg-card px-4 text-base text-foreground"
|
||||
onChangeText={flow.setBranchQuery}
|
||||
placeholder="Find a branch"
|
||||
placeholderTextColor={placeholderColor}
|
||||
style={{ color: foregroundColor, fontFamily }}
|
||||
value={flow.branchQuery}
|
||||
/>
|
||||
</View>
|
||||
{branchContent}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerShown: true,
|
||||
title: screenTitle,
|
||||
unstable_headerToolbarItems: usesNativeMailSearchToolbar
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
onSearchTextChange: flow.setBranchQuery,
|
||||
placeholder: "Find a branch",
|
||||
searchTextChangeId: "new-task-branch-search-text",
|
||||
showsSearchDismissButton: true,
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
headerSearchBarOptions: usesNativeMailSearchToolbar
|
||||
? undefined
|
||||
: {
|
||||
allowToolbarIntegration: true,
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Find a branch",
|
||||
onChangeText: (event) => {
|
||||
flow.setBranchQuery(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
flow.setBranchQuery("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
{usesNativeMailSearchToolbar ? null : (
|
||||
<NativeHeaderToolbar placement="bottom">
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
{branchContent}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
StackActions,
|
||||
useFocusEffect,
|
||||
useNavigation,
|
||||
usePreventRemove,
|
||||
} from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Platform, Pressable, ScrollView, View, useColorScheme } from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
@@ -11,30 +16,32 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||
|
||||
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import {
|
||||
ComposerInlineControl,
|
||||
ComposerToolbarButton,
|
||||
ComposerToolbarRow,
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
} from "../../components/ComposerToolbar";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ComposerSurface } from "./ThreadComposer";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
import {
|
||||
useThreadSettingsSheetPresentation,
|
||||
type NavigationWithFinishTransitioning,
|
||||
} from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import {
|
||||
clearComposerDraftContent,
|
||||
@@ -44,26 +51,38 @@ import {
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
|
||||
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { resolveDraftProjectSelection } from "./new-task-project-selection";
|
||||
import {
|
||||
resolveNewTaskBranchLabel,
|
||||
resolveNewTaskWorkspaceLabel,
|
||||
} from "./new-task-context-presentation";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
function formatWorkspaceLabel(input: {
|
||||
readonly workspaceMode: string;
|
||||
readonly currentBranchName: string | null;
|
||||
readonly selectedBranchName: string | null;
|
||||
}): string {
|
||||
const branchName = input.selectedBranchName ?? input.currentBranchName;
|
||||
if (input.workspaceMode === "worktree") {
|
||||
return branchName ? `New worktree · ${branchName}` : "New worktree";
|
||||
function NewTaskWorkspaceIcon(props: {
|
||||
readonly workspaceMode: "local" | "worktree";
|
||||
readonly worktreePath: string | null;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
if (props.workspaceMode === "local" && props.worktreePath === null) {
|
||||
return <SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />;
|
||||
}
|
||||
return branchName ? `Current · ${branchName}` : "Current checkout";
|
||||
|
||||
return (
|
||||
<View className="size-4">
|
||||
<SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />
|
||||
<View className="absolute -right-1 -bottom-1">
|
||||
<SymbolView name="arrow.triangle.branch" size={9} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function NewTaskDraftScreen(props: {
|
||||
@@ -90,7 +109,8 @@ export function NewTaskDraftScreen(props: {
|
||||
const insets = useSafeAreaInsets();
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const controlsBottomPadding = Math.max(insets.bottom, 10);
|
||||
const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
|
||||
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
@@ -108,6 +128,49 @@ export function NewTaskDraftScreen(props: {
|
||||
editorRef: promptInputRef,
|
||||
isEditorFocused: isComposerFocused,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (Platform.OS !== "ios") {
|
||||
return;
|
||||
}
|
||||
|
||||
navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });
|
||||
}, [isKeyboardVisible, navigation]);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (Platform.OS === "ios") {
|
||||
navigation.getParent()?.setOptions({ gestureEnabled: true });
|
||||
}
|
||||
};
|
||||
}, [navigation]);
|
||||
const settingsRoutePresentedRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = true;
|
||||
navigation.dispatch(StackActions.push("ThreadSettings"));
|
||||
}, [navigation, settingsSheetPresentation.isVisible]);
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = false;
|
||||
settingsSheetPresentation.onDismissed();
|
||||
}, [settingsSheetPresentation.onDismissed]),
|
||||
);
|
||||
useEffect(
|
||||
() =>
|
||||
// UIKit's completion callback for the sheet dismissal, surfaced by the
|
||||
// native-stack patch. This is when the queued keyboard restore runs.
|
||||
(navigation as unknown as NavigationWithFinishTransitioning).addListener(
|
||||
"finishTransitioning",
|
||||
settingsSheetPresentation.onStackTransitionsFinished,
|
||||
),
|
||||
[navigation, settingsSheetPresentation.onStackTransitionsFinished],
|
||||
);
|
||||
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
|
||||
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
|
||||
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
|
||||
@@ -227,9 +290,9 @@ export function NewTaskDraftScreen(props: {
|
||||
}, [props.pendingTaskId, cancelEditingPendingTask]);
|
||||
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const projectUnderlineColor = useThemeColor("--color-foreground-muted");
|
||||
const regularFontFamily = useFontFamily("regular");
|
||||
const bodyText = useScaledTextRole("body");
|
||||
const headlineText = useScaledTextRole("headline");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
|
||||
|
||||
@@ -315,7 +378,7 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
flow.loadBranches();
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -517,121 +580,6 @@ export function NewTaskDraftScreen(props: {
|
||||
shareImportAttempt,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
// Android starts with the collapsed composer pill (like an open thread)
|
||||
// and only expands/focuses when tapped.
|
||||
if (!selectedProject || Platform.OS === "android") {
|
||||
return;
|
||||
}
|
||||
|
||||
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
|
||||
const interaction = InteractionManager.runAfterInteractions(() => {
|
||||
focusFrame = requestAnimationFrame(() => {
|
||||
// The delayed focus can land after the settings sheet opened, which
|
||||
// would pop the keyboard underneath its modal.
|
||||
if (!settingsSheetPresentation.isActiveRef.current) {
|
||||
promptInputRef.current?.focus();
|
||||
} else {
|
||||
settingsSheetPresentation.restoreFocusAfterSave();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
interaction.cancel();
|
||||
if (focusFrame !== null) {
|
||||
cancelAnimationFrame(focusFrame);
|
||||
}
|
||||
};
|
||||
}, [
|
||||
selectedProject,
|
||||
settingsSheetPresentation.isActiveRef,
|
||||
settingsSheetPresentation.restoreFocusAfterSave,
|
||||
]);
|
||||
|
||||
const environmentMenuActions = useMemo(
|
||||
() =>
|
||||
flow.environments.map((environment) => ({
|
||||
id: `environment:${environment.environmentId}`,
|
||||
title: environment.environmentLabel,
|
||||
attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,
|
||||
state:
|
||||
flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
|
||||
})),
|
||||
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
|
||||
);
|
||||
|
||||
const providerOptionDescriptors = useMemo(
|
||||
() =>
|
||||
resolveProviderOptionDescriptors({
|
||||
capabilities: flow.selectedModelOption?.capabilities,
|
||||
selections: flow.selectedModel?.options,
|
||||
}),
|
||||
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
|
||||
);
|
||||
|
||||
const workspaceMenuActions = useMemo(() => {
|
||||
const branchActions =
|
||||
flow.availableBranches.length === 0
|
||||
? [
|
||||
{
|
||||
id: "workspace:branch:none",
|
||||
title: flow.branchesLoading ? "Loading branches…" : "No branches available",
|
||||
attributes: { disabled: true },
|
||||
},
|
||||
]
|
||||
: flow.availableBranches.slice(0, 12).map((branch) => {
|
||||
const badge = branchBadgeLabel({
|
||||
branch,
|
||||
project: flow.selectedProject,
|
||||
});
|
||||
|
||||
return {
|
||||
id: `workspace:branch:${branch.name}`,
|
||||
title: branch.name,
|
||||
subtitle: badge ? badge.toUpperCase() : undefined,
|
||||
state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
|
||||
};
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
id: "workspace:mode",
|
||||
title: "Mode",
|
||||
subtitle: flow.workspaceMode === "local" ? "Current checkout" : "New worktree",
|
||||
subactions: (["local", "worktree"] as const).map((value) => ({
|
||||
id: `workspace:mode:${value}`,
|
||||
title: value === "local" ? "Current checkout" : "New worktree",
|
||||
state: flow.workspaceMode === value ? ("on" as const) : undefined,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "workspace:branch",
|
||||
title: "Branch",
|
||||
subtitle: flow.selectedBranchName ?? "Choose branch",
|
||||
subactions: branchActions,
|
||||
},
|
||||
...(flow.workspaceMode === "worktree"
|
||||
? [
|
||||
{
|
||||
id: "workspace:start-from-origin",
|
||||
title: "Start from origin",
|
||||
subtitle: "Base the worktree on the latest origin branch",
|
||||
image: "arrow.triangle.pull",
|
||||
state: flow.startFromOrigin ? ("on" as const) : undefined,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
}, [
|
||||
flow.availableBranches,
|
||||
flow.branchesLoading,
|
||||
flow.selectedBranchName,
|
||||
flow.selectedProject,
|
||||
flow.startFromOrigin,
|
||||
flow.workspaceMode,
|
||||
]);
|
||||
|
||||
const selectedEnvironmentLabel =
|
||||
flow.environments.find(
|
||||
(environment) => environment.environmentId === flow.selectedEnvironmentId,
|
||||
@@ -640,50 +588,17 @@ export function NewTaskDraftScreen(props: {
|
||||
flow.availableBranches.find((branch) => branch.current)?.name ??
|
||||
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: flow.selectedModelOption?.label ?? "Model",
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
const selectedBranchName = flow.selectedBranchName ?? currentBranchName;
|
||||
const selectedBranchLabel = resolveNewTaskBranchLabel({
|
||||
branchName: selectedBranchName,
|
||||
startFromOrigin: flow.startFromOrigin,
|
||||
workspaceMode: flow.workspaceMode,
|
||||
});
|
||||
const workspaceLabel = useMemo(
|
||||
() =>
|
||||
formatWorkspaceLabel({
|
||||
currentBranchName,
|
||||
selectedBranchName: flow.selectedBranchName,
|
||||
workspaceMode: flow.workspaceMode,
|
||||
}),
|
||||
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
|
||||
);
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
|
||||
return;
|
||||
}
|
||||
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
|
||||
}
|
||||
|
||||
function handleWorkspaceMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("workspace:mode:")) {
|
||||
flow.setWorkspaceMode(
|
||||
event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (event === "workspace:start-from-origin") {
|
||||
flow.setStartFromOrigin(!flow.startFromOrigin);
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("workspace:branch:")) {
|
||||
const branchName = event.slice("workspace:branch:".length);
|
||||
const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
|
||||
if (branch) {
|
||||
flow.selectBranch(branch);
|
||||
}
|
||||
}
|
||||
}
|
||||
const workspaceLabel = resolveNewTaskWorkspaceLabel({
|
||||
workspaceMode: flow.workspaceMode,
|
||||
worktreePath: flow.selectedWorktreePath,
|
||||
});
|
||||
const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
|
||||
|
||||
async function handlePickImages(): Promise<void> {
|
||||
if (isIncomingShareTransferPending) {
|
||||
@@ -733,7 +648,9 @@ export function NewTaskDraftScreen(props: {
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const interactionMode = flow.planModeEnabled
|
||||
? (draft.interactionMode ?? flow.interactionMode)
|
||||
: "default";
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
@@ -793,7 +710,11 @@ export function NewTaskDraftScreen(props: {
|
||||
// -only Activity start. If creation fails, the token registration's replay
|
||||
// finds no work and ends the card within seconds.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
|
||||
environmentId: selectedProject.environmentId,
|
||||
threadTitle: deriveThreadTitleSeed({
|
||||
text: initialMessageText,
|
||||
attachments: draft.attachments,
|
||||
}),
|
||||
projectTitle: selectedProject.title,
|
||||
});
|
||||
const result = await createProjectThread({
|
||||
@@ -851,7 +772,7 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
if (!selectedProject) {
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
@@ -866,11 +787,6 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
const isAndroid = Platform.OS === "android";
|
||||
const isDarkMode = colorScheme === "dark";
|
||||
// Android expansion follows native editor focus so relayout cannot race
|
||||
// the touch gesture that opens the keyboard.
|
||||
// The settings sheet dismisses the keyboard, so its flag keeps the Android
|
||||
// draft composer expanded through the blur (mirrors ThreadComposer).
|
||||
const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;
|
||||
const canStart =
|
||||
Boolean(flow.selectedProject) &&
|
||||
Boolean(flow.selectedModel) &&
|
||||
@@ -882,235 +798,279 @@ export function NewTaskDraftScreen(props: {
|
||||
const promptEditor = (
|
||||
<ComposerEditor
|
||||
ref={promptInputRef}
|
||||
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
|
||||
// forces the iOS keyboard bring-up during the formSheet present
|
||||
// animation and stalls it. The runAfterInteractions effect above focuses
|
||||
// the editor once the transition settles instead.
|
||||
// The context-first screen intentionally opens with the keyboard closed.
|
||||
// Focusing is a user action, so presenting the form sheet has one motion.
|
||||
autoFocus={false}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
multiline
|
||||
scrollEnabled={isExpanded}
|
||||
scrollEnabled
|
||||
value={flow.prompt}
|
||||
skills={flow.selectedProviderSkills}
|
||||
onChangeText={flow.setPrompt}
|
||||
onFocus={() => setIsComposerFocused(true)}
|
||||
onBlur={() => setIsComposerFocused(false)}
|
||||
onPasteImages={(uris) => void handleNativePasteImages(uris)}
|
||||
placeholder={`Describe a coding task in ${selectedProject.title}`}
|
||||
// Same collapsed centering as ThreadComposer: native vertical gravity
|
||||
// in a pill-height box.
|
||||
singleLineCentered={!isExpanded}
|
||||
contentInsetVertical={isAndroid ? 0 : undefined}
|
||||
style={
|
||||
isAndroid
|
||||
? isExpanded
|
||||
? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }
|
||||
: { height: 36 }
|
||||
: { flex: 1, minHeight: 0 }
|
||||
}
|
||||
textStyle={
|
||||
isAndroid
|
||||
? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }
|
||||
: headlineText
|
||||
}
|
||||
placeholder="Ask anything…"
|
||||
singleLineCentered={false}
|
||||
contentInsetVertical={0}
|
||||
style={{
|
||||
minHeight: 72,
|
||||
maxHeight: 160,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
}}
|
||||
textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
|
||||
/>
|
||||
);
|
||||
|
||||
const toolbarPills = (
|
||||
<>
|
||||
<ComposerToolbarButton
|
||||
icon="plus"
|
||||
onPress={() => void handlePickImages()}
|
||||
const closeNewTask = () => {
|
||||
void KeyboardController.dismiss({ animated: true });
|
||||
const parentNavigation = navigation.getParent();
|
||||
if (parentNavigation) {
|
||||
parentNavigation.goBack();
|
||||
return;
|
||||
}
|
||||
navigation.goBack();
|
||||
};
|
||||
const chooseProject = () => {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
promptInputRef.current?.blur();
|
||||
void KeyboardController.dismiss({ animated: true });
|
||||
navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
|
||||
};
|
||||
const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
promptInputRef.current?.blur();
|
||||
void KeyboardController.dismiss({ animated: true });
|
||||
navigation.dispatch(StackActions.push(routeName));
|
||||
};
|
||||
|
||||
const hero = (
|
||||
<View className="items-center gap-6 px-6" testID="new-task-hero">
|
||||
<View className="w-full items-center gap-1.5">
|
||||
<Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
|
||||
What should we build
|
||||
</Text>
|
||||
<View className="max-w-full flex-row items-center justify-center">
|
||||
<Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
|
||||
<Pressable
|
||||
accessibilityHint="Opens the project picker"
|
||||
accessibilityLabel={`Change project from ${selectedProject.title}`}
|
||||
accessibilityRole="button"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
onPress={chooseProject}
|
||||
className="min-w-0 max-w-[250px] active:opacity-65"
|
||||
style={{
|
||||
borderBottomColor: projectUnderlineColor,
|
||||
borderBottomWidth: 1,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
className="text-2xl font-t3-medium tracking-tight text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{selectedProject.title}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
|
||||
chevronDirection="right"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="desktopcomputer"
|
||||
label={`on ${selectedEnvironmentLabel}`}
|
||||
maxWidth={260}
|
||||
onPress={
|
||||
flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined
|
||||
}
|
||||
showChevron={flow.environments.length > 1}
|
||||
static={flow.environments.length <= 1}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
const heroViewport = (
|
||||
<View className="flex-1" collapsable={false}>
|
||||
<ScrollView
|
||||
alwaysBounceVertical={isKeyboardVisible}
|
||||
className="flex-1"
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
contentContainerClassName="grow items-center pb-[236px] pt-12 ios:pt-[72px]"
|
||||
keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
testID="new-task-hero-scroll"
|
||||
>
|
||||
{hero}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
|
||||
const workspaceControls = (
|
||||
<View className="flex-row items-center gap-1 px-2">
|
||||
<ComposerInlineControl
|
||||
accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
|
||||
accessibilityLabel={workspaceLabel}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={
|
||||
<NewTaskWorkspaceIcon
|
||||
workspaceMode={flow.workspaceMode}
|
||||
worktreePath={flow.selectedWorktreePath}
|
||||
/>
|
||||
}
|
||||
label={workspaceLabel}
|
||||
maxWidth={flow.workspaceMode === "local" ? 220 : 148}
|
||||
onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
|
||||
showChevron={false}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
/>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
|
||||
chevronDirection="right"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
icon="arrow.triangle.branch"
|
||||
label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
|
||||
maxWidth={190}
|
||||
onPress={() => openContextPicker("NewTaskBranch")}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={environmentMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Environment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="desktopcomputer"
|
||||
label={selectedEnvironmentLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={workspaceMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Workspace"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
label={workspaceLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
</>
|
||||
</View>
|
||||
);
|
||||
|
||||
const settingsSheet = (
|
||||
<ThreadSettingsSheet
|
||||
visible={settingsSheetPresentation.isVisible}
|
||||
onClose={settingsSheetPresentation.close}
|
||||
onDismissed={settingsSheetPresentation.onDismissed}
|
||||
providerGroups={flow.providerGroups}
|
||||
selectedModel={flow.selectedModel}
|
||||
onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
|
||||
optionDescriptors={providerOptionDescriptors}
|
||||
onUpdateOptionSelections={flow.setSelectedModelOptions}
|
||||
runtimeMode={flow.runtimeMode}
|
||||
onUpdateRuntimeMode={flow.setRuntimeMode}
|
||||
/>
|
||||
);
|
||||
const composerDock = (
|
||||
<View className="bg-sheet px-4 pt-1" style={{ paddingBottom: controlsBottomPadding }}>
|
||||
<View className="pb-1">{workspaceControls}</View>
|
||||
|
||||
const startButton = (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={
|
||||
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
|
||||
}
|
||||
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
|
||||
onPress={() => void handleStart()}
|
||||
variant="primary"
|
||||
showChevron={false}
|
||||
disabled={!canStart}
|
||||
/>
|
||||
<ComposerSurface
|
||||
animateLayout={false}
|
||||
isDarkMode={isDarkMode}
|
||||
style={{
|
||||
borderRadius: 26,
|
||||
minHeight: 140,
|
||||
overflow: "hidden",
|
||||
paddingBottom: 6,
|
||||
paddingHorizontal: 14,
|
||||
paddingTop: 14,
|
||||
}}
|
||||
>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
imageBorderRadius={16}
|
||||
imageSize={72}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{promptEditor}
|
||||
|
||||
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={sheetFadeOpaque}
|
||||
fadeTransparent={sheetFadeTransparent}
|
||||
contentPaddingRight={8}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="plus"
|
||||
onPress={() => void handlePickImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel="Model and reasoning settings"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
emphasized
|
||||
iconNode={
|
||||
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={flow.selectedModelOption?.label ?? "Choose model"}
|
||||
maxWidth={152}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{flow.planModeEnabled ? (
|
||||
<ComposerInlineControl
|
||||
accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
|
||||
accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
emphasized
|
||||
icon={
|
||||
flow.interactionMode === "plan"
|
||||
? { ios: "list.bullet.clipboard", android: "auto_awesome" }
|
||||
: { ios: "hammer", android: "construction" }
|
||||
}
|
||||
label={flow.interactionMode === "plan" ? "Plan" : "Build"}
|
||||
onPress={() =>
|
||||
flow.setInteractionMode(flow.interactionMode === "plan" ? "default" : "plan")
|
||||
}
|
||||
showChevron={false}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerToolbarScroller>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={
|
||||
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
|
||||
}
|
||||
disabled={!canStart}
|
||||
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
|
||||
onPress={() => void handleStart()}
|
||||
showChevron={false}
|
||||
variant="primary"
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
</ComposerSurface>
|
||||
</View>
|
||||
);
|
||||
|
||||
if (isAndroid) {
|
||||
// The draft is a thread that doesn't exist yet, so it mirrors the thread
|
||||
// page: in-screen header, empty feed canvas above, and the same floating
|
||||
// composer chrome as ThreadComposer (collapsed pill → expanded card).
|
||||
//
|
||||
// Composer positioning mirrors ThreadDetailScreen's floating overlay
|
||||
// (KeyboardStickyView, absolute bottom overlay) rather than
|
||||
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
|
||||
// resolves the composer's on-screen frame via a native
|
||||
// viewPositionInWindow measurement, which this app's Android
|
||||
// edge-to-edge setup (KeyboardProvider's native content-view margin
|
||||
// handling neutralizes windowSoftInputMode="adjustResize" while active)
|
||||
// makes unreliable — the composer stayed under the keyboard instead of
|
||||
// translating above it. KeyboardStickyView sticks directly to the
|
||||
// animated keyboard height instead, sidestepping that measurement.
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
|
||||
|
||||
<View className="flex-1" />
|
||||
<AndroidScreenHeader title="New task" onBack={closeNewTask} />
|
||||
{heroViewport}
|
||||
|
||||
<KeyboardStickyView
|
||||
enabled={isKeyboardVisible}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
offset={{ closed: 0, opened: keyboardOpenedOffset }}
|
||||
>
|
||||
<View
|
||||
className="px-4 pt-2"
|
||||
style={{
|
||||
paddingBottom: controlsBottomPadding,
|
||||
experimental_backgroundImage: isDarkMode
|
||||
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
|
||||
}}
|
||||
>
|
||||
<ComposerSurface
|
||||
isDarkMode={isDarkMode}
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
borderRadius: 20,
|
||||
overflow: "hidden",
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
}
|
||||
: {
|
||||
borderRadius: 999,
|
||||
overflow: "hidden",
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingLeft: 18,
|
||||
paddingRight: 5,
|
||||
paddingVertical: 5,
|
||||
}
|
||||
}
|
||||
>
|
||||
{isExpanded && flow.attachments.length > 0 ? (
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={
|
||||
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>
|
||||
{!isExpanded ? (
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canStart}
|
||||
onPress={() => void handleStart()}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{isExpanded ? (
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}
|
||||
fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}
|
||||
>
|
||||
{toolbarPills}
|
||||
</ComposerToolbarScroller>
|
||||
{startButton}
|
||||
</ComposerToolbarRow>
|
||||
) : null}
|
||||
</View>
|
||||
{composerDock}
|
||||
</KeyboardStickyView>
|
||||
{settingsSheet}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
|
||||
<View className="flex-1 bg-sheet" collapsable={false}>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerBackVisible: false,
|
||||
headerShadowVisible: false,
|
||||
title: "",
|
||||
}}
|
||||
/>
|
||||
<NativeHeaderToolbar placement="left">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Cancel new task"
|
||||
label="Cancel"
|
||||
onPress={closeNewTask}
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>
|
||||
|
||||
<View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View className="px-4 pt-3">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
imageSize={88}
|
||||
imageBorderRadius={20}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={sheetFadeOpaque}
|
||||
fadeTransparent={sheetFadeTransparent}
|
||||
>
|
||||
{toolbarPills}
|
||||
</ComposerToolbarScroller>
|
||||
{startButton}
|
||||
</ComposerToolbarRow>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
{heroViewport}
|
||||
<KeyboardStickyView
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: keyboardOpenedOffset }}
|
||||
>
|
||||
{composerDock}
|
||||
</KeyboardStickyView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import {
|
||||
StackActions,
|
||||
useIsFocused,
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -14,10 +19,10 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { getProjectScopeSelectionTarget } from "./new-task-project-selection";
|
||||
|
||||
type NewTaskRouteParams = {
|
||||
readonly incomingShareId?: string | string[];
|
||||
@@ -80,7 +85,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
|
||||
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
|
||||
const projects = useProjects();
|
||||
const { projectScopes } = useNewTaskFlow();
|
||||
const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const navigation = useNavigation();
|
||||
const isFocused = useIsFocused();
|
||||
@@ -88,7 +93,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const { getShare, releaseShareReservation } = useIncomingShare();
|
||||
const routeShareId = Array.isArray(route.params?.incomingShareId)
|
||||
? route.params.incomingShareId[0]
|
||||
@@ -126,27 +130,22 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
return;
|
||||
}
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
const state = navigation.getState();
|
||||
const previousRoute = state?.routes[state.index - 1];
|
||||
if (previousRoute?.name === "NewTaskDraft") {
|
||||
setProject(project);
|
||||
navigation.goBack();
|
||||
return;
|
||||
}
|
||||
|
||||
navigation.dispatch(
|
||||
StackActions.push("NewTaskDraft", {
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
incomingShareId: incomingShare?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function toggleGroup(groupKey: string): void {
|
||||
setExpandedGroupKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(groupKey)) {
|
||||
next.delete(groupKey);
|
||||
} else {
|
||||
next.add(groupKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -169,15 +168,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
return;
|
||||
}
|
||||
resumedDestinationKeyRef.current = destinationKey;
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
navigation.dispatch(
|
||||
StackActions.push("NewTaskDraft", {
|
||||
environmentId: reservedDestinationProject.environmentId,
|
||||
projectId: reservedDestinationProject.id,
|
||||
title: reservedDestinationProject.title,
|
||||
incomingShareId: incomingShare.id,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
}, [incomingShare, isFocused, navigation, reservedDestinationProject]);
|
||||
|
||||
return (
|
||||
@@ -196,7 +194,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
{
|
||||
accessibilityLabel: "Add project",
|
||||
icon: "plus",
|
||||
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
|
||||
onPress: () => navigation.dispatch(StackActions.push("AddProject")),
|
||||
},
|
||||
]
|
||||
: []
|
||||
@@ -223,7 +221,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
{catalogState.hasReadyEnvironment ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
@@ -263,7 +261,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
) : (
|
||||
<Pressable
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
Add new project
|
||||
@@ -275,22 +273,15 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{projectScopes.map((scope, scopeIndex) => {
|
||||
const hasMultipleProjects = scope.projects.length > 1;
|
||||
const expanded = expandedGroupKeys.has(scope.key);
|
||||
const singleProject = hasMultipleProjects ? null : scope.projects[0];
|
||||
const selectionTarget = getProjectScopeSelectionTarget(scope, selectedEnvironmentId);
|
||||
return (
|
||||
<View
|
||||
key={scope.key}
|
||||
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
|
||||
>
|
||||
<Pressable
|
||||
disabled={singleProject !== null && reservedDestinationProject !== null}
|
||||
onPress={() => {
|
||||
if (singleProject) {
|
||||
void selectProject(singleProject);
|
||||
} else {
|
||||
toggleGroup(scope.key);
|
||||
}
|
||||
}}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(selectionTarget)}
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3.5"
|
||||
>
|
||||
<View className="h-7 w-7 items-center justify-center">
|
||||
@@ -311,52 +302,16 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
>
|
||||
{hasMultipleProjects
|
||||
? `${scope.projects.length} workspaces`
|
||||
: singleProject?.workspaceRoot}
|
||||
: selectionTarget.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
{hasMultipleProjects && expanded
|
||||
? scope.projects.map((project) => (
|
||||
<Pressable
|
||||
key={scopedProjectKey(project.environmentId, project.id)}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(project)}
|
||||
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
faviconPath={project.faviconPath}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
/>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-sm font-t3-bold text-foreground">
|
||||
{project.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{project.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
))
|
||||
: null}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -6,9 +6,9 @@ import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export interface PendingApprovalCardProps {
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
|
||||
// behind this card, so a translucent surface bleeds messages through it.
|
||||
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 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -29,17 +31,23 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
{props.approval.detail}
|
||||
</Text>
|
||||
) : null}
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
|
||||
@@ -48,7 +56,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
|
||||
import type { RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
|
||||
import Animated, {
|
||||
@@ -55,14 +56,14 @@ export interface PendingUserInputCardProps {
|
||||
readonly onInputFocusChange?: (focused: boolean) => void;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
requestId: RuntimeRequestId,
|
||||
question: ThreadUserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -89,6 +90,9 @@ const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
const questionCount = props.pendingUserInput.questions.length;
|
||||
// V2 runtime requests carry response capability: a dead provider process
|
||||
// cannot accept answers, so the card reads-only until the run restarts.
|
||||
const canRespond = props.pendingUserInput.responseCapability === "live";
|
||||
|
||||
const cardCoverage = props.cardCoverage;
|
||||
const barHeightRef = useRef(0);
|
||||
@@ -247,6 +251,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
showsVerticalScrollIndicator
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{!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 (
|
||||
@@ -263,6 +273,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
disabled={!canRespond}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
@@ -292,6 +303,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
editable={canRespond}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
@@ -311,7 +323,9 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
|
||||
)}
|
||||
disabled={
|
||||
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
!canRespond ||
|
||||
props.answers === null ||
|
||||
props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
}
|
||||
onPress={() => void props.onSubmit()}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import { buildThreadActivityInspector } from "../../lib/threadActivityInspector";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useV2ItemSupport } from "../../state/v2-item-support";
|
||||
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
|
||||
|
||||
export function ThreadActivityInspector(props: {
|
||||
readonly activity: ThreadFeedActivity;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly iconColor: ColorValue;
|
||||
readonly workspaceRoot?: string | null;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
const row = props.activity.projectedItem;
|
||||
const support = useV2ItemSupport({
|
||||
environmentId: props.environmentId,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
});
|
||||
const model = useMemo(
|
||||
() => buildThreadActivityInspector(props.activity, support, props.currentThreadId),
|
||||
[props.activity, props.currentThreadId, support],
|
||||
);
|
||||
const revertCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, {
|
||||
label: "checkpoint rollback",
|
||||
reportFailure: true,
|
||||
});
|
||||
const [rollingBack, setRollingBack] = useState(false);
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<View className="flex-row flex-wrap gap-x-4 gap-y-2 rounded-lg border border-neutral-300/50 bg-black/[0.025] p-2.5 dark:border-white/[0.1] dark:bg-white/[0.025]">
|
||||
{model.fields.map((field) => (
|
||||
<View key={`${field.label}:${field.value}`} className="min-w-[42%] flex-1 gap-0.5">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
{field.label}
|
||||
</Text>
|
||||
<Text selectable className="text-2xs leading-4 text-foreground">
|
||||
{field.value}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
|
||||
{model.blocks.map((block) => (
|
||||
<View key={`${block.label}:${block.value}`} className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
{block.label}
|
||||
</Text>
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ maxHeight: 240 }}
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-2xs leading-[17px] text-foreground-muted"
|
||||
style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}
|
||||
>
|
||||
{block.value}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
))}
|
||||
|
||||
{model.fileLinks.length > 0 ? (
|
||||
<View className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Files
|
||||
</Text>
|
||||
{model.fileLinks.map((link) => {
|
||||
const relativePath =
|
||||
resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
|
||||
(link.path.startsWith("/") ? null : link.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={`${link.path}:${link.line ?? 0}:${link.label}`}
|
||||
accessibilityRole={relativePath ? "link" : undefined}
|
||||
disabled={relativePath === null}
|
||||
onPress={() => {
|
||||
if (!relativePath) return;
|
||||
void Haptics.selectionAsync();
|
||||
navigation.navigate(
|
||||
"ThreadFile",
|
||||
buildThreadActivityFileParams({
|
||||
environmentId: props.environmentId,
|
||||
currentThreadId: props.currentThreadId,
|
||||
activitySourceThreadId: row.sourceThreadId,
|
||||
relativePath,
|
||||
line: link.line,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="doc.text"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
|
||||
{link.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{model.webLinks.length > 0 ? (
|
||||
<View className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Sources
|
||||
</Text>
|
||||
{model.webLinks.map((link) => (
|
||||
<Pressable
|
||||
key={link.url}
|
||||
accessibilityRole="link"
|
||||
onPress={() => void Linking.openURL(link.url)}
|
||||
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="arrow.up.right.square"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
|
||||
{link.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{model.rollbackTarget ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Roll back to this checkpoint"
|
||||
disabled={rollingBack}
|
||||
onPress={() => {
|
||||
setRollingBack(true);
|
||||
void Haptics.selectionAsync();
|
||||
void revertCheckpoint({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
threadId: model.rollbackTarget!.threadId,
|
||||
checkpointId: model.rollbackTarget!.checkpointId,
|
||||
scopeId: model.rollbackTarget!.scopeId,
|
||||
},
|
||||
}).finally(() => setRollingBack(false));
|
||||
}}
|
||||
className="min-h-10 flex-row items-center justify-center gap-2 rounded-lg border border-neutral-300/60 px-3 py-2 dark:border-white/[0.12]"
|
||||
>
|
||||
<SymbolView
|
||||
name={rollingBack ? "hourglass" : "arrow.counterclockwise"}
|
||||
size={14}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="font-t3-medium text-xs text-foreground">
|
||||
{rollingBack ? "Rolling back…" : "Roll back to checkpoint"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
|
||||
<View className="gap-1 border-t border-neutral-300/50 pt-2 dark:border-white/[0.1]">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Structured details
|
||||
</Text>
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ maxHeight: 280 }}
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-2xs leading-[17px] text-foreground-muted"
|
||||
style={{ fontFamily: "ui-monospace" }}
|
||||
>
|
||||
{model.structuredDetails}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
serializeComposerFileLink,
|
||||
type ComposerTrigger,
|
||||
} from "@t3tools/shared/composerTrigger";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
@@ -41,18 +41,19 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
import {
|
||||
ComposerEditor,
|
||||
type ComposerEditorHandle,
|
||||
type ComposerEditorSelection,
|
||||
} from "../../components/ComposerEditor";
|
||||
import {
|
||||
ComposerInlineControl,
|
||||
ComposerToolbarButton,
|
||||
ComposerToolbarRow,
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
} from "../../components/ComposerToolbar";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
@@ -63,15 +64,17 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import {
|
||||
applyProviderOptionSelection,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import { buildThreadSettingsMenu } from "./thread-settings-menu";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
import {
|
||||
type ExistingThreadSettingsRouteSession,
|
||||
useExistingThreadSettingsRoutePresentation,
|
||||
} from "./ThreadSettingsSheet";
|
||||
import {
|
||||
useThreadSettingsSheetPresentation,
|
||||
type NavigationWithFinishTransitioning,
|
||||
} from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
/**
|
||||
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
|
||||
@@ -83,7 +86,7 @@ export const COMPOSER_COLLAPSED_CHROME = 60;
|
||||
* Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
|
||||
* Used by the parent to compute the larger feed bottom inset when the composer is focused.
|
||||
*/
|
||||
export const COMPOSER_EXPANDED_CHROME = 174;
|
||||
export const COMPOSER_EXPANDED_CHROME = 156;
|
||||
|
||||
export interface ThreadComposerProps {
|
||||
readonly draftMessage: string;
|
||||
@@ -100,10 +103,11 @@ export interface ThreadComposerProps {
|
||||
* are on screen while they reconcile with the server.
|
||||
*/
|
||||
readonly threadSyncPhase?: "loading" | "syncing" | null;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectCwd: string | null;
|
||||
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
|
||||
@@ -123,8 +127,8 @@ export interface ThreadComposerProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* The pill / card container — renders as LiquidGlassView on supported
|
||||
* iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
|
||||
* The pill / card container — renders with Expo's native GlassView on supported
|
||||
* iOS 26+ devices and keeps the existing opaque fallback elsewhere.
|
||||
* Exported so NewTaskDraftScreen can render the same composer chrome.
|
||||
*/
|
||||
// One timing for every piece of the expanded↔compact morph so the surface,
|
||||
@@ -140,6 +144,8 @@ export function ComposerSurface(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly style: ViewStyle;
|
||||
readonly isDarkMode: boolean;
|
||||
/** Existing thread composers morph between pill and card layouts. */
|
||||
readonly animateLayout?: boolean;
|
||||
}) {
|
||||
// Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself
|
||||
// (needed to clip content to the pill shape) would clip the shadow on iOS.
|
||||
@@ -152,35 +158,26 @@ export function ComposerSurface(props: {
|
||||
elevation: 10,
|
||||
};
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<LiquidGlassView
|
||||
effect="regular"
|
||||
interactive
|
||||
colorScheme={props.isDarkMode ? "dark" : "light"}
|
||||
style={props.style}
|
||||
>
|
||||
{props.children}
|
||||
</LiquidGlassView>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<View
|
||||
style={[
|
||||
props.style,
|
||||
{
|
||||
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
|
||||
borderWidth: 1,
|
||||
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
|
||||
},
|
||||
]}
|
||||
<Animated.View
|
||||
layout={props.animateLayout === false ? undefined : COMPOSER_LAYOUT_TRANSITION}
|
||||
style={shadowStyle}
|
||||
>
|
||||
<GlassSurface
|
||||
chrome="none"
|
||||
fallbackStyle={{
|
||||
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
|
||||
borderWidth: 1,
|
||||
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
|
||||
}}
|
||||
glassEffectStyle="regular"
|
||||
// The composer is a passive material containing interactive controls.
|
||||
// Expo GlassView defaults to non-interactive and both layouts share it.
|
||||
tintColor="transparent"
|
||||
style={props.style}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
</GlassSurface>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@@ -271,6 +268,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
});
|
||||
|
||||
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
|
||||
const navigation = useNavigation();
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const bodyText = useScaledTextRole("body");
|
||||
@@ -281,14 +279,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
editorRef: inputRef,
|
||||
isEditorFocused: isFocused,
|
||||
});
|
||||
const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
|
||||
const settingsRoutePresentedRef = useRef(false);
|
||||
const wasExpandedBeforePreviewRef = useRef(false);
|
||||
const inFlightThreadIdsRef = useRef(new Set<string>());
|
||||
const { onExpandedChange } = props;
|
||||
|
||||
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
|
||||
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
|
||||
// Opening and closing count as active so the composer stays expanded while
|
||||
// focus moves between its native editor and the settings modal.
|
||||
// Opening and presentation count as active so the composer stays expanded
|
||||
// while focus moves between its native editor and the settings picker.
|
||||
const isExpanded = isFocused || settingsSheetPresentation.isActive;
|
||||
const canSend = hasContent;
|
||||
|
||||
@@ -324,9 +324,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
setIsFocused(false);
|
||||
onEditorFocusChange?.(false);
|
||||
}, [onEditorFocusChange]);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
const showStopAction = props.canStopThread;
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
|
||||
@@ -334,7 +332,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
: "Send";
|
||||
const currentModelSelection = props.selectedThread.modelSelection;
|
||||
const currentRuntimeMode = props.selectedThread.runtimeMode;
|
||||
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
|
||||
const connectionStatus = composerConnectionStatus({
|
||||
connectionError: props.connectionError,
|
||||
connectionState: props.connectionState,
|
||||
@@ -544,6 +541,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
// after the send so its preference read and native Activity start don't
|
||||
// contend with the queued-message feedback on the tap frame.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: props.environmentId,
|
||||
threadTitle: props.selectedThread.title,
|
||||
projectTitle: props.environmentLabel ?? "T3 Code",
|
||||
});
|
||||
@@ -626,67 +624,71 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}),
|
||||
[currentModelOption?.capabilities, currentModelSelection.options],
|
||||
);
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
|
||||
// iOS gets a native menu on the trigger pill: the everyday adjustments
|
||||
// apply without resigning the keyboard, while "All Settings…" (and the
|
||||
// Android trigger) still route through the sheet, which must dismiss it.
|
||||
const settingsMenu = useMemo(
|
||||
() =>
|
||||
Platform.OS === "ios"
|
||||
? buildThreadSettingsMenu({
|
||||
providerGroups: threadProviderGroups,
|
||||
selectedModel: currentModelSelection,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
})
|
||||
: null,
|
||||
[threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = props.onUpdateModelSelection;
|
||||
const onUpdateRuntimeMode = props.onUpdateRuntimeMode;
|
||||
const handleSettingsMenuAction = useCallback(
|
||||
(eventId: string) => {
|
||||
const event = settingsMenu?.events.get(eventId);
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
switch (event.type) {
|
||||
case "select-model":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection(event.option.selection);
|
||||
return;
|
||||
case "set-option": {
|
||||
const options = applyProviderOptionSelection(providerOptionDescriptors, {
|
||||
id: event.optionId,
|
||||
value: event.value,
|
||||
});
|
||||
if (options) {
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection({ ...currentModelSelection, options });
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "set-runtime":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateRuntimeMode(event.mode);
|
||||
return;
|
||||
}
|
||||
},
|
||||
const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
|
||||
() => ({
|
||||
ownerId: settingsOwnerId,
|
||||
providerGroups: threadProviderGroups,
|
||||
selectedModel: currentModelSelection,
|
||||
onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
onUpdateOptionSelections: (options) =>
|
||||
props.onUpdateModelSelection({ ...currentModelSelection, options }),
|
||||
runtimeMode: currentRuntimeMode,
|
||||
onUpdateRuntimeMode: props.onUpdateRuntimeMode,
|
||||
}),
|
||||
[
|
||||
currentModelSelection,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
currentRuntimeMode,
|
||||
props.onUpdateModelSelection,
|
||||
props.onUpdateRuntimeMode,
|
||||
providerOptionDescriptors,
|
||||
settingsMenu,
|
||||
settingsOwnerId,
|
||||
threadProviderGroups,
|
||||
],
|
||||
);
|
||||
const openSettings = useCallback(() => {
|
||||
settingsRoutePresentation.present(settingsRouteSession);
|
||||
settingsSheetPresentation.open();
|
||||
}, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (settingsSheetPresentation.isActive) {
|
||||
settingsRoutePresentation.present(settingsRouteSession);
|
||||
}
|
||||
}, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = true;
|
||||
navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
|
||||
}, [navigation, settingsSheetPresentation.isVisible]);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = false;
|
||||
settingsSheetPresentation.onDismissed();
|
||||
settingsRoutePresentation.clear(settingsOwnerId);
|
||||
}, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
// UIKit's completion callback for the sheet dismissal, surfaced by the
|
||||
// native-stack patch. This is when the queued keyboard restore runs.
|
||||
(navigation as unknown as NavigationWithFinishTransitioning).addListener(
|
||||
"finishTransitioning",
|
||||
settingsSheetPresentation.onStackTransitionsFinished,
|
||||
),
|
||||
[navigation, settingsSheetPresentation.onStackTransitionsFinished],
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
@@ -739,10 +741,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
borderRadius: 20,
|
||||
borderRadius: 26,
|
||||
minHeight: 140,
|
||||
overflow: "hidden" as const,
|
||||
paddingBottom: 6,
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
paddingTop: 14,
|
||||
}
|
||||
: {
|
||||
borderRadius: 999,
|
||||
@@ -792,7 +796,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
minHeight: 80,
|
||||
minHeight: 72,
|
||||
maxHeight: 160,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
@@ -841,15 +845,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{isExpanded ? (
|
||||
// Toolbar row — matches draft page layout (expanded only)
|
||||
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
{isExpanded ? (
|
||||
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={toolbarFadeOpaque}
|
||||
fadeTransparent={toolbarFadeTransparent}
|
||||
contentPaddingRight={8}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
@@ -857,31 +858,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
{settingsMenu ? (
|
||||
<ControlPillMenu
|
||||
actions={settingsMenu.actions}
|
||||
onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
) : (
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
)}
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel="Model and reasoning settings"
|
||||
emphasized
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
maxWidth={152}
|
||||
onPress={openSettings}
|
||||
/>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
@@ -901,8 +887,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
showChevron={false}
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{/* Queue count */}
|
||||
{props.queueCount > 0 ? (
|
||||
@@ -915,21 +901,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
) : null}
|
||||
</Animated.View>
|
||||
|
||||
<ThreadSettingsSheet
|
||||
visible={settingsSheetPresentation.isVisible}
|
||||
onClose={settingsSheetPresentation.close}
|
||||
onDismissed={settingsSheetPresentation.onDismissed}
|
||||
providerGroups={threadProviderGroups}
|
||||
selectedModel={currentModelSelection}
|
||||
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
|
||||
optionDescriptors={providerOptionDescriptors}
|
||||
onUpdateOptionSelections={(options) =>
|
||||
props.onUpdateModelSelection({ ...currentModelSelection, options })
|
||||
}
|
||||
runtimeMode={currentRuntimeMode}
|
||||
onUpdateRuntimeMode={props.onUpdateRuntimeMode}
|
||||
/>
|
||||
|
||||
<ImageViewing
|
||||
images={previewImageUri ? [{ uri: previewImageUri }] : []}
|
||||
imageIndex={0}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
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 { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
RuntimeRequestId,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import {
|
||||
memo,
|
||||
@@ -58,11 +58,14 @@ import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
PendingUserInputDraftAnswer,
|
||||
ThreadFeedEntry,
|
||||
ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
@@ -76,31 +79,35 @@ import {
|
||||
COMPOSER_EXPANDED_CHROME,
|
||||
ThreadComposer,
|
||||
} from "./ThreadComposer";
|
||||
import { ThreadFeed } from "./ThreadFeed";
|
||||
import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
|
||||
import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
|
||||
import { ThreadQueueControl } from "./ThreadQueueControl";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
|
||||
export interface ThreadDetailScreenProps {
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly screenTone: StatusTone;
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly activityRun: ThreadFeedLatestRun | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
|
||||
/** Progressive history controls for oversized mobile thread opens. */
|
||||
readonly historyControls?: ThreadFeedHistoryControls;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
@@ -121,16 +128,16 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
requestId: RuntimeRequestId,
|
||||
question: ThreadUserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -298,7 +305,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
// keyboard animations coherent. Collapse state is keyed by request id so a
|
||||
// new request re-expands automatically.
|
||||
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
|
||||
useState<ApprovalRequestId | null>(null);
|
||||
useState<RuntimeRequestId | null>(null);
|
||||
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
|
||||
const userInputCollapsed =
|
||||
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
|
||||
@@ -456,6 +463,39 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
|
||||
const lastDispatchedVisitRef = useRef<string | null>(null);
|
||||
const selectedThreadId = props.selectedThread.id;
|
||||
const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
|
||||
const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
|
||||
useEffect(() => {
|
||||
// Records the server-side visited watermark while the thread is on
|
||||
// screen (mirror of web ChatView), so the "Done" marker clears on every
|
||||
// device. Field absent → the server predates visited tracking.
|
||||
if (selectedThreadLastVisitedAt === undefined) return;
|
||||
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
|
||||
if (Number.isNaN(threadUpdatedAtMs)) return;
|
||||
const lastVisitedAtMs = selectedThreadLastVisitedAt
|
||||
? Date.parse(selectedThreadLastVisitedAt)
|
||||
: NaN;
|
||||
if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
|
||||
// Dedupe per watermark — the effect re-runs before the command echo lands.
|
||||
const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
|
||||
if (lastDispatchedVisitRef.current === dispatchKey) return;
|
||||
lastDispatchedVisitRef.current = dispatchKey;
|
||||
void visitThread({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
|
||||
});
|
||||
}, [
|
||||
props.environmentId,
|
||||
selectedThreadId,
|
||||
selectedThreadKey,
|
||||
selectedThreadLastVisitedAt,
|
||||
selectedThreadUpdatedAt,
|
||||
visitThread,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
@@ -589,7 +629,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
threadTitle={props.selectedThread.title}
|
||||
latestRun={props.activityRun}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
@@ -598,12 +639,18 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
historyControls={props.historyControls}
|
||||
topAccessory={
|
||||
<ThreadRelationshipsBanner
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
/>
|
||||
}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
onEndFollowEnabledChange={setEndFollowEnabled}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
@@ -668,6 +715,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<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"
|
||||
@@ -727,6 +779,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
canStopThread={props.canStopThread}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import {
|
||||
ThreadId,
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -27,6 +35,7 @@ import {
|
||||
} from "react-native-nitro-markdown";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Image,
|
||||
Linking,
|
||||
Platform,
|
||||
@@ -47,6 +56,7 @@ import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
@@ -74,6 +84,7 @@ import {
|
||||
import { buildReviewParsedDiff } from "../review/reviewModel";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import {
|
||||
resolveMarkdownFontSizes,
|
||||
resolveNativeMarkdownTypography,
|
||||
@@ -86,8 +97,9 @@ import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons
|
||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
type ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
@@ -102,7 +114,17 @@ 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 WIDE_MARKDOWN_BLOCK_OPTIONS = {
|
||||
includeOrderedLists: Platform.OS === "android",
|
||||
} as const;
|
||||
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
@@ -135,14 +157,22 @@ function isFreshTimestamp(input: string): boolean {
|
||||
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
|
||||
}
|
||||
|
||||
export interface ThreadFeedHistoryControls {
|
||||
readonly hasMoreHistory: boolean;
|
||||
readonly loading: boolean;
|
||||
readonly error: string | null;
|
||||
readonly onLoadEarlier: () => void;
|
||||
}
|
||||
|
||||
export interface ThreadFeedProps {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly threadTitle: string;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly latestRun: ThreadFeedLatestRun | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
@@ -150,17 +180,98 @@ export interface ThreadFeedProps {
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly historyControls?: ThreadFeedHistoryControls;
|
||||
readonly topAccessory?: ReactNode;
|
||||
readonly contentMaxWidth?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
readonly loading: boolean;
|
||||
readonly onLoadEarlier: () => void;
|
||||
} | null;
|
||||
}
|
||||
|
||||
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: {
|
||||
@@ -816,15 +927,16 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
|
||||
function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
readonly unsettledTurnId: RunId | null;
|
||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleWorkGroup: (groupId: string) => void;
|
||||
readonly onToggleWorkRow: (rowId: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onToggleWorkRow: (rowId: string, anchorKey?: string) => void;
|
||||
readonly onToggleTurnFold: (runId: RunId) => void;
|
||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||
readonly onMarkdownLinkPress: (href: string) => void;
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
@@ -833,6 +945,7 @@ function renderFeedEntry(
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly reviewCommentBubbleWidth: number;
|
||||
readonly userBubbleMaxWidth: number;
|
||||
readonly threadTitle: string;
|
||||
},
|
||||
) {
|
||||
const entry = info.item;
|
||||
@@ -842,12 +955,12 @@ function renderFeedEntry(
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
if (entry.type === "run-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: entry.expanded }}
|
||||
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
||||
onPress={() => props.onToggleTurnFold(entry.runId)}
|
||||
hitSlop={4}
|
||||
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
@@ -888,11 +1001,11 @@ function renderFeedEntry(
|
||||
// children during the unclamped pass and never moves them once the width
|
||||
// is clamped, so the paragraphs around the block end up drawn on top of
|
||||
// each other. Pinning the width removes that pass.
|
||||
const hasWideBlock = hasWideMarkdownBlock(message.text);
|
||||
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
message.turnId === props.unsettledTurnId;
|
||||
message.runId === props.unsettledTurnId;
|
||||
const showAssistantMeta =
|
||||
message.role === "assistant" &&
|
||||
props.terminalAssistantMessageIds.has(message.id) &&
|
||||
@@ -901,11 +1014,17 @@ function renderFeedEntry(
|
||||
|
||||
if (isUser) {
|
||||
const enterAnimated = isFreshTimestamp(message.createdAt);
|
||||
const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
|
||||
return (
|
||||
<Animated.View
|
||||
className="mb-5 items-end"
|
||||
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
|
||||
>
|
||||
{message.createdBy === "agent" ? (
|
||||
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
Sent by another agent
|
||||
</Text>
|
||||
) : null}
|
||||
<View
|
||||
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
|
||||
style={{
|
||||
@@ -940,6 +1059,30 @@ function renderFeedEntry(
|
||||
})}
|
||||
</View>
|
||||
<View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
|
||||
{intentBadge ? (
|
||||
<View
|
||||
accessible
|
||||
accessibilityRole="text"
|
||||
accessibilityLabel={intentBadge.accessibilityLabel}
|
||||
className={cn(
|
||||
"rounded-full border px-1.5 py-0.5",
|
||||
intentBadge.tone === "queued"
|
||||
? "border-amber-500/25 bg-amber-500/10 dark:border-amber-400/25 dark:bg-amber-400/10"
|
||||
: "border-sky-500/25 bg-sky-500/10 dark:border-sky-400/25 dark:bg-sky-400/10",
|
||||
)}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-2xs tracking-wide",
|
||||
intentBadge.tone === "queued"
|
||||
? "text-amber-700 dark:text-amber-300"
|
||||
: "text-sky-700 dark:text-sky-300",
|
||||
)}
|
||||
>
|
||||
{intentBadge.label}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
||||
{timestampLabel}
|
||||
</Text>
|
||||
@@ -1001,6 +1144,12 @@ function renderFeedEntry(
|
||||
})}
|
||||
{showAssistantMeta ? (
|
||||
<View className="mt-1 flex-row items-center gap-1">
|
||||
<AssistantForkButton
|
||||
environmentId={props.environmentId}
|
||||
iconColor={iconSubtleColor}
|
||||
projectedItem={message.projectedItem}
|
||||
sourceTitle={props.threadTitle}
|
||||
/>
|
||||
<CopyTextButton
|
||||
accessibilityLabel="Copy message"
|
||||
text={message.text}
|
||||
@@ -1021,10 +1170,15 @@ function renderFeedEntry(
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
copiedRowId={props.copiedRowId}
|
||||
currentThreadId={props.threadId}
|
||||
environmentId={props.environmentId}
|
||||
expanded={props.expandedWorkGroups[entry.id] ?? false}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={(rowId) => props.onToggleWorkRow(rowId, entry.id)}
|
||||
workspaceRoot={props.workspaceRoot}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1293,6 +1447,41 @@ function compactFileName(filePath: string): string {
|
||||
return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
|
||||
}
|
||||
|
||||
function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) {
|
||||
const mutedColor = useThemeColor("--color-icon-subtle");
|
||||
const accentColor = useThemeColor("--color-primary");
|
||||
if (!props.hasMoreHistory && props.error === null) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<View className="mb-3 items-center gap-1.5 px-2">
|
||||
{props.hasMoreHistory ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Load earlier activity"
|
||||
disabled={props.loading}
|
||||
onPress={props.onLoadEarlier}
|
||||
className="min-h-9 flex-row items-center justify-center gap-2 rounded-full border border-border/60 bg-surface/80 px-4 py-2 disabled:opacity-50"
|
||||
>
|
||||
{props.loading ? (
|
||||
<ActivityIndicator size="small" color={accentColor} />
|
||||
) : (
|
||||
<SymbolView name="chevron.up" size={12} tintColor={accentColor} type="monochrome" />
|
||||
)}
|
||||
<Text className="text-sm font-medium text-foreground">
|
||||
{props.loading ? "Loading earlier activity…" : "Load earlier activity"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{props.error !== null ? (
|
||||
<Text className="text-center text-xs" style={{ color: mutedColor }}>
|
||||
{props.error}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadFeedPlaceholder(props: {
|
||||
readonly bottomInset: number;
|
||||
readonly detail: string;
|
||||
@@ -1327,10 +1516,10 @@ 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 userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
@@ -1338,11 +1527,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
const [viewportHeight, setViewportHeight] = useState(0);
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
// Live-follow latch. LegendList's maintainScrollAtEnd alone re-pins the feed
|
||||
// whenever the viewport drifts back inside its geometric threshold, which
|
||||
// yanked users off history they were reading every time a stream chunk grew
|
||||
// a row. Follow breaks when the user scrolls up and away, and re-arms only
|
||||
// when the list actually returns to the end (or on send / thread switch).
|
||||
// Live-follow latch (#5566). LegendList's maintainScrollAtEnd alone re-pins
|
||||
// the feed whenever the viewport drifts back inside its geometric threshold,
|
||||
// which yanked users off history they were reading every time a stream chunk
|
||||
// grew a row. Follow breaks when the user scrolls up and away, and re-arms
|
||||
// only when the list actually returns to the end (or on send / thread switch).
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
// A "user scroll session" spans from drag start through the end of its
|
||||
@@ -1370,7 +1559,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
readonly expandedTurnIds: ReadonlySet<RunId>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
@@ -1392,7 +1581,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const userBubbleMaxWidth = contentWidth * 0.85;
|
||||
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
|
||||
const insets = useSafeAreaInsets();
|
||||
const topContentInset = props.contentTopInset ?? insets.top + 44;
|
||||
const topContentInset = props.contentTopInset ?? insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const bottomContentInset = props.contentBottomInset ?? 18;
|
||||
const usesNativeAutomaticInsets =
|
||||
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
|
||||
@@ -1405,7 +1594,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// header-providing screen) and fall back to the standard iOS bar height.
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext);
|
||||
const anchorTopInset = usesNativeAutomaticInsets
|
||||
? navigationHeaderHeight || insets.top + 44
|
||||
? navigationHeaderHeight || insets.top + IOS_NAV_BAR_HEIGHT
|
||||
: topContentInset;
|
||||
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
@@ -1443,6 +1632,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1452,6 +1642,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1544,22 +1735,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
|
||||
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
|
||||
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
// Thread identity is env-scoped: two environments can hold the same
|
||||
// ThreadId, and keying resets (or the list mount) on the bare id would
|
||||
// carry stale scroll/follow state across an environment switch.
|
||||
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
|
||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||
// re-arm follow regardless of where the user had scrolled before.
|
||||
@@ -1576,31 +1755,31 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
|
||||
|
||||
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 handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
|
||||
const presentedFeed = useMemo(
|
||||
() =>
|
||||
deriveThreadFeedPresentation(
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
props.latestRun,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
new Set(
|
||||
Object.entries(expandedWorkGroups)
|
||||
.filter(([, expanded]) => expanded)
|
||||
.map(([groupId]) => groupId),
|
||||
),
|
||||
props.activeWorkStartedAt,
|
||||
),
|
||||
[
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
],
|
||||
[expandedTurnIds, expandedWorkGroups, props.activeWorkStartedAt, props.feed, props.latestRun],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
@@ -1629,29 +1808,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[presentedFeed, props.anchorMessageId, anchorTopInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
const terminalIdsByTurn = new Map<RunId, string>();
|
||||
for (const entry of props.feed) {
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
|
||||
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
|
||||
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
|
||||
}
|
||||
}
|
||||
return new Set(terminalIdsByTurn.values());
|
||||
}, [props.feed]);
|
||||
const unsettledTurnId =
|
||||
props.latestTurn &&
|
||||
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
if (!props.latestTurn || !previous) {
|
||||
previousLatestTurnRef.current = props.latestRun;
|
||||
if (!props.latestRun || !previous) {
|
||||
return;
|
||||
}
|
||||
if (props.latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
|
||||
const interruptedTurnId = props.latestTurn.turnId;
|
||||
if (props.latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && props.latestRun.status === "interrupted") {
|
||||
const interruptedTurnId = props.latestRun.runId;
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
|
||||
@@ -1660,14 +1835,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return;
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
if (!current.expandedTurnIds.has(previous.turnId)) {
|
||||
if (!current.expandedTurnIds.has(previous.runId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
}, [props.latestTurn]);
|
||||
}, [props.latestRun]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1748,8 +1923,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleWorkRow = useCallback(
|
||||
(rowId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
||||
(rowId: string, anchorKey?: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
@@ -1762,14 +1937,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
(runId: RunId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
next.add(runId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
@@ -1794,7 +1969,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const getFixedItemSize = useCallback(
|
||||
(entry: ThreadFeedEntry) => {
|
||||
switch (entry.type) {
|
||||
case "turn-fold":
|
||||
case "run-fold":
|
||||
return TURN_FOLD_HEIGHT;
|
||||
case "work-toggle":
|
||||
return WORK_GROUP_TOGGLE_HEIGHT;
|
||||
@@ -1817,7 +1992,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
(info: { item: ThreadFeedEntry; index: number }) =>
|
||||
renderFeedEntry(info, {
|
||||
environmentId: props.environmentId,
|
||||
threadId: props.threadId,
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1833,10 +2010,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
userBubbleMaxWidth,
|
||||
threadTitle: props.threadTitle,
|
||||
skills: props.skills,
|
||||
workspaceRoot: props.workspaceRoot,
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1853,7 +2033,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onToggleWorkGroup,
|
||||
onToggleWorkRow,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.threadTitle,
|
||||
props.skills,
|
||||
props.workspaceRoot,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1983,17 +2166,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
ListHeaderComponent={
|
||||
<>
|
||||
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
|
||||
{props.loadEarlier != null ? (
|
||||
<Pressable
|
||||
onPress={props.loadEarlier.onLoadEarlier}
|
||||
disabled={props.loadEarlier.loading}
|
||||
className="items-center py-2"
|
||||
>
|
||||
<Text className="text-xs text-foreground-secondary">
|
||||
{props.loadEarlier.loading ? "Loading earlier turns…" : "Load earlier turns"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
{props.historyControls ? (
|
||||
<ThreadFeedLoadEarlierControl {...props.historyControls} />
|
||||
) : null}
|
||||
{props.topAccessory}
|
||||
</>
|
||||
}
|
||||
contentContainerStyle={{
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
@@ -29,6 +30,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadSearch } from "../../state/queries";
|
||||
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
@@ -211,8 +213,13 @@ function ThreadNavigationSidebarPane(
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const autoSettleOnMerge =
|
||||
!AsyncResult.isSuccess(preferencesResult) ||
|
||||
preferencesResult.value.autoSettleOnMerge !== false;
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -410,8 +417,8 @@ function ThreadNavigationSidebarPane(
|
||||
|
||||
// Thread List v2 (beta) support — same model as the compact Home list
|
||||
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
|
||||
// PR states stream in per-row; merged/closed PRs auto-settle their thread
|
||||
// on the next partition.
|
||||
// PR states stream in per-row. The next partition applies the configured
|
||||
// merge rule and the always-on close rule.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
@@ -505,6 +512,15 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order for Move up/down flags — computed from
|
||||
// all shells so search/scope filtering never disables a valid move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
@@ -536,6 +552,7 @@ function ThreadNavigationSidebarPane(
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
@@ -547,6 +564,7 @@ function ThreadNavigationSidebarPane(
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
autoSettleOnMerge,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
@@ -927,7 +945,7 @@ function ThreadNavigationSidebarPane(
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
@@ -950,6 +968,8 @@ function ThreadNavigationSidebarPane(
|
||||
onSelectThread={handleSelectThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onArchiveThread={archiveThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -1067,6 +1087,8 @@ function ThreadNavigationSidebarPane(
|
||||
fullSwipeWidth={props.width - 20}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -1103,6 +1125,7 @@ function ThreadNavigationSidebarPane(
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
regenerateThreadTitle,
|
||||
props.onNewThreadInProject,
|
||||
props.searchQuery,
|
||||
props.selectedThreadKey,
|
||||
@@ -1110,6 +1133,7 @@ function ThreadNavigationSidebarPane(
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
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";
|
||||
import {
|
||||
buildCancelQueuedRunCommand,
|
||||
resolveThreadQueueRowControls,
|
||||
} from "./threadQueueControlPresentation";
|
||||
|
||||
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 cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "cancel 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);
|
||||
};
|
||||
|
||||
const dismiss = async (runId: RunId) => {
|
||||
setBusyRunId(runId);
|
||||
void Haptics.selectionAsync();
|
||||
await cancel(
|
||||
buildCancelQueuedRunCommand({
|
||||
environmentId: props.environmentId,
|
||||
runId,
|
||||
threadId: props.threadId,
|
||||
}),
|
||||
);
|
||||
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) => {
|
||||
const controls = resolveThreadQueueRowControls({
|
||||
busy: busyRunId !== null,
|
||||
canPromoteToSteer: workflow.canPromoteToSteer,
|
||||
canReorder: workflow.canReorder,
|
||||
index,
|
||||
queuedCount: workflow.queuedRuns.length,
|
||||
text,
|
||||
});
|
||||
|
||||
return (
|
||||
<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}>
|
||||
{controls.displayText}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message up"
|
||||
disabled={!controls.canMoveUp}
|
||||
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={!controls.canMoveDown}
|
||||
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={!controls.canSteer}
|
||||
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>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={controls.dismissAccessibilityLabel}
|
||||
disabled={!controls.canDismiss}
|
||||
onPress={() => void dismiss(run.id)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="xmark" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
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(
|
||||
// Subagent edges come from the projection, not from thread shells, so
|
||||
// they survive the shell filtering and would point at threads the
|
||||
// client no longer receives — rendering as "Unavailable", and taking
|
||||
// over the banner headline when they sort first.
|
||||
immediateThreadRelationships(graph, props.threadId).filter(
|
||||
(relationship) => relationship.edge.kind !== "subagent",
|
||||
),
|
||||
(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: "SettingsContent",
|
||||
params: { 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -8,10 +8,6 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
requestOlderThreadTurns,
|
||||
threadHasOlderTurns,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -75,6 +71,7 @@ import {
|
||||
ThreadInspectorContentStack,
|
||||
type ThreadInspectorMode,
|
||||
} from "./thread-inspector-content-stack";
|
||||
import { isInternalSubagentThread } from "./threadVisibility";
|
||||
|
||||
interface ThreadInspectorSelection {
|
||||
readonly routeThreadIdentity: string | null;
|
||||
@@ -130,6 +127,58 @@ function ThreadUnavailableScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
function SubagentThreadRedirect({
|
||||
environmentId,
|
||||
parentThreadId,
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly parentThreadId: ThreadId | null;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
useEffect(() => {
|
||||
if (parentThreadId === null) {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
return;
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
environmentId,
|
||||
threadId: parentThreadId,
|
||||
}),
|
||||
);
|
||||
}, [environmentId, navigation, parentThreadId]);
|
||||
return <OpeningThreadLoadingScreen />;
|
||||
}
|
||||
|
||||
// Thread selection resolves on its own tick after the connection reports
|
||||
// available, and a hidden subagent thread's redirect depends on that
|
||||
// selection landing. Deciding "unavailable" the instant the connection is
|
||||
// ready flashes the error screen over what is actually a redirect (or a
|
||||
// late-arriving shell); the decision must wait out this window first.
|
||||
const UNAVAILABLE_DECISION_DELAY_MS = 1_500;
|
||||
|
||||
function useThreadUnavailableDecision(routeThreadKey: string | null, connectionReady: boolean) {
|
||||
const [decision, setDecision] = useState<{
|
||||
readonly key: string | null;
|
||||
readonly decided: boolean;
|
||||
}>({ key: routeThreadKey, decided: false });
|
||||
// A navigation reuses this mounted screen, and an effect-based reset leaves
|
||||
// the previous route's fired decision visible for one render — exactly the
|
||||
// flash the delay exists to prevent. Reset synchronously during render.
|
||||
if (decision.key !== routeThreadKey) {
|
||||
setDecision({ key: routeThreadKey, decided: false });
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!connectionReady) return;
|
||||
const timer = setTimeout(
|
||||
() => setDecision({ key: routeThreadKey, decided: true }),
|
||||
UNAVAILABLE_DECISION_DELAY_MS,
|
||||
);
|
||||
return () => clearTimeout(timer);
|
||||
}, [routeThreadKey, connectionReady]);
|
||||
return decision.key === routeThreadKey && decision.decided;
|
||||
}
|
||||
|
||||
export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
|
||||
const { state: workspaceState } = useWorkspaceState();
|
||||
const { connectionState } = useRemoteConnectionStatus();
|
||||
@@ -150,6 +199,11 @@ export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
|
||||
? null
|
||||
: scopedThreadKey(selectedThread.environmentId, selectedThread.id);
|
||||
const selectedThreadDetailState = useSelectedThreadDetailState();
|
||||
const stillHydrating =
|
||||
workspaceState.isLoadingConnections ||
|
||||
routeConnectionState === "connecting" ||
|
||||
routeConnectionState === "reconnecting";
|
||||
const unavailableDecided = useThreadUnavailableDecision(routeThreadKey, !stillHydrating);
|
||||
|
||||
if (environmentId === null || threadIdRaw === null) {
|
||||
return <OpeningThreadLoadingScreen />;
|
||||
@@ -160,15 +214,21 @@ export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
|
||||
// loading placeholder while messages fetch, and the composer's connection
|
||||
// pill reports connecting/reconnecting/syncing status.
|
||||
if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
|
||||
// Internal subagent threads are hidden from user-facing lists; a deep
|
||||
// link or stale selection still lands here, so send it to the parent
|
||||
// thread instead of exposing the hidden transcript.
|
||||
if (isInternalSubagentThread(selectedThread)) {
|
||||
return (
|
||||
<SubagentThreadRedirect
|
||||
environmentId={selectedThread.environmentId}
|
||||
parentThreadId={selectedThread.lineage.parentThreadId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
|
||||
}
|
||||
|
||||
const stillHydrating =
|
||||
workspaceState.isLoadingConnections ||
|
||||
routeConnectionState === "connecting" ||
|
||||
routeConnectionState === "reconnecting";
|
||||
|
||||
if (stillHydrating) {
|
||||
if (stillHydrating || !unavailableDecided) {
|
||||
return <OpeningThreadLoadingScreen />;
|
||||
}
|
||||
|
||||
@@ -194,26 +254,36 @@ function ThreadRouteContent(
|
||||
useThreadSelection();
|
||||
const selectedThreadDetailState = props.selectedThreadDetailState;
|
||||
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
|
||||
// "Load earlier turns" header state for windowed (paginated) thread loads.
|
||||
const loadEarlierTurns = useMemo(() => {
|
||||
if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
loading:
|
||||
selectedThreadDetailState.page._tag === "Some" &&
|
||||
selectedThreadDetailState.page.value.loadingOlder,
|
||||
onLoadEarlier: () => {
|
||||
requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
|
||||
},
|
||||
};
|
||||
}, [selectedThread, selectedThreadDetailState]);
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
|
||||
label: "load earlier thread history",
|
||||
reportFailure: false,
|
||||
});
|
||||
const historyControls = useMemo(() => {
|
||||
const history = selectedThreadDetailState.history;
|
||||
if (!selectedThread) {
|
||||
return undefined;
|
||||
}
|
||||
if (!history.hasMoreHistory && history.error === null) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
hasMoreHistory: history.hasMoreHistory,
|
||||
loading: history.loading,
|
||||
error: history.error,
|
||||
onLoadEarlier: () => {
|
||||
void loadEarlierHistory({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: { threadId: selectedThread.id },
|
||||
});
|
||||
},
|
||||
};
|
||||
}, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
|
||||
const navigation = useNavigation();
|
||||
const params = props.route.params;
|
||||
const environmentIdRaw = firstRouteParam(params.environmentId);
|
||||
@@ -325,7 +395,7 @@ function ThreadRouteContent(
|
||||
}),
|
||||
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
|
||||
);
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
|
||||
const handleReconnectEnvironment = useCallback(() => {
|
||||
if (!environmentId) {
|
||||
return;
|
||||
@@ -479,23 +549,17 @@ function ThreadRouteContent(
|
||||
void navigation.navigate("Connections");
|
||||
}, [navigation]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
(selectedThread.session?.status !== "running" &&
|
||||
selectedThread.session?.status !== "starting")
|
||||
) {
|
||||
if (!selectedThread || composer.interruptibleRunId === null) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
...(selectedThread.session.activeTurnId
|
||||
? { turnId: selectedThread.session.activeTurnId }
|
||||
: {}),
|
||||
runId: composer.interruptibleRunId,
|
||||
},
|
||||
});
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
}, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
|
||||
|
||||
const handleOpenTerminal = useCallback(
|
||||
(nextTerminalId?: string | null) => {
|
||||
@@ -773,6 +837,7 @@ function ThreadRouteContent(
|
||||
connectionError={routeConnectionError}
|
||||
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
activityRun={composer.selectedThreadActivityRun}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
@@ -784,8 +849,9 @@ function ThreadRouteContent(
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
loadEarlier={loadEarlierTurns}
|
||||
historyControls={historyControls}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
canStopThread={composer.interruptibleRunId !== null}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { resolvePendingTaskInteractionMode } from "./legacy-plan-mode";
|
||||
|
||||
describe("resolvePendingTaskInteractionMode", () => {
|
||||
it("preserves a queued plan task while the preference is still loading", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: false,
|
||||
planModeEnabled: false,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: "plan",
|
||||
}),
|
||||
).toBe("plan");
|
||||
});
|
||||
|
||||
it("forces build mode once the disabled preference has loaded", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: true,
|
||||
planModeEnabled: false,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: "plan",
|
||||
}),
|
||||
).toBe("default");
|
||||
});
|
||||
|
||||
it("keeps a fresh draft in build mode while the preference is loading", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: false,
|
||||
planModeEnabled: false,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: undefined,
|
||||
}),
|
||||
).toBe("default");
|
||||
});
|
||||
|
||||
it("honors the draft's mode when the plan preference is enabled", () => {
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: true,
|
||||
planModeEnabled: true,
|
||||
draftInteractionMode: "plan",
|
||||
queuedInteractionMode: undefined,
|
||||
}),
|
||||
).toBe("plan");
|
||||
expect(
|
||||
resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: true,
|
||||
planModeEnabled: true,
|
||||
draftInteractionMode: undefined,
|
||||
queuedInteractionMode: "plan",
|
||||
}),
|
||||
).toBe("default");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
type ProviderInteractionMode,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export function resolveLegacyPlanModeEnabled(input: {
|
||||
readonly loaded: boolean;
|
||||
readonly preference: boolean | undefined;
|
||||
}): boolean {
|
||||
return input.loaded && input.preference === true;
|
||||
}
|
||||
|
||||
export function resolvePendingTaskInteractionMode(input: {
|
||||
readonly preferenceLoaded: boolean;
|
||||
readonly planModeEnabled: boolean;
|
||||
readonly draftInteractionMode: ProviderInteractionMode | undefined;
|
||||
readonly queuedInteractionMode: ProviderInteractionMode | undefined;
|
||||
}): ProviderInteractionMode {
|
||||
if (input.planModeEnabled) {
|
||||
return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
}
|
||||
if (!input.preferenceLoaded) {
|
||||
// Only an existing queued task may retain its previous mode while the
|
||||
// preference is unknown. A fresh draft still defaults to Build so a stale
|
||||
// persisted Plan selection cannot bypass a disabled preference at launch.
|
||||
return input.queuedInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
}
|
||||
return DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
resolveNewTaskBranchWorktreePath,
|
||||
resolveNewTaskBranchLabel,
|
||||
resolveNewTaskLocalWorkspaceSelection,
|
||||
} from "./new-task-context-presentation";
|
||||
|
||||
describe("resolveNewTaskLocalWorkspaceSelection", () => {
|
||||
it("waits for refs instead of carrying a worktree base into Current checkout", () => {
|
||||
expect(
|
||||
resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: [],
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
awaitsCurrentBranch: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("adopts the checkout's current branch once refs load", () => {
|
||||
expect(
|
||||
resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: [
|
||||
{ name: "feature/worktree-base", current: false, worktreePath: "/worktree" },
|
||||
{ name: "main", current: true, worktreePath: "/repo" },
|
||||
],
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
awaitsCurrentBranch: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries the worktree path when the current branch lives in another worktree", () => {
|
||||
expect(
|
||||
resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: [
|
||||
{ name: "feature/split", current: true, worktreePath: "/repo/.t3/worktrees/split" },
|
||||
{ name: "main", current: false, worktreePath: "/repo" },
|
||||
],
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "feature/split",
|
||||
worktreePath: "/repo/.t3/worktrees/split",
|
||||
awaitsCurrentBranch: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveNewTaskBranchWorktreePath", () => {
|
||||
it("moves Current checkout to the selected existing worktree", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "local",
|
||||
projectCwd: "/repo",
|
||||
branchWorktreePath: "/repo/.t3/worktrees/feature",
|
||||
}),
|
||||
).toBe("/repo/.t3/worktrees/feature");
|
||||
});
|
||||
|
||||
it("keeps the project checkout represented by a null override", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "local",
|
||||
projectCwd: "/repo",
|
||||
branchWorktreePath: "/repo",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("does not reuse an existing worktree while creating a new one", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "worktree",
|
||||
projectCwd: "/repo",
|
||||
branchWorktreePath: "/repo/.t3/worktrees/feature",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveNewTaskBranchLabel", () => {
|
||||
it("shows the checked-out branch without a base-ref prefix", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: "feature/mobile",
|
||||
startFromOrigin: true,
|
||||
workspaceMode: "local",
|
||||
}),
|
||||
).toBe("feature/mobile");
|
||||
});
|
||||
|
||||
it("labels a local worktree base with From", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: "main",
|
||||
startFromOrigin: false,
|
||||
workspaceMode: "worktree",
|
||||
}),
|
||||
).toBe("From main");
|
||||
});
|
||||
|
||||
it("labels a remote worktree base with From origin", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: "main",
|
||||
startFromOrigin: true,
|
||||
workspaceMode: "worktree",
|
||||
}),
|
||||
).toBe("From origin/main");
|
||||
});
|
||||
|
||||
it("prompts when no branch is available", () => {
|
||||
expect(
|
||||
resolveNewTaskBranchLabel({
|
||||
branchName: null,
|
||||
startFromOrigin: true,
|
||||
workspaceMode: "worktree",
|
||||
}),
|
||||
).toBe("Choose branch");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
export function resolveNewTaskWorkspaceLabel(input: {
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
readonly worktreePath: string | null;
|
||||
}): "Current checkout" | "Current worktree" | "New worktree" {
|
||||
if (input.workspaceMode === "worktree") {
|
||||
return "New worktree";
|
||||
}
|
||||
return input.worktreePath ? "Current worktree" : "Current checkout";
|
||||
}
|
||||
|
||||
export function resolveNewTaskBranchWorktreePath(input: {
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
readonly projectCwd: string;
|
||||
readonly branchWorktreePath: string | null | undefined;
|
||||
}): string | null {
|
||||
if (
|
||||
input.workspaceMode === "worktree" ||
|
||||
!input.branchWorktreePath ||
|
||||
input.branchWorktreePath === input.projectCwd
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return input.branchWorktreePath;
|
||||
}
|
||||
|
||||
export function resolveNewTaskLocalWorkspaceSelection(input: {
|
||||
readonly branches: ReadonlyArray<{
|
||||
readonly name: string;
|
||||
readonly current: boolean;
|
||||
readonly worktreePath?: string | null;
|
||||
}>;
|
||||
readonly projectCwd: string;
|
||||
}): {
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly awaitsCurrentBranch: boolean;
|
||||
} {
|
||||
const currentBranch = input.branches.find((branch) => branch.current) ?? null;
|
||||
if (!currentBranch) {
|
||||
return {
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
awaitsCurrentBranch: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
branch: currentBranch.name,
|
||||
worktreePath: resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode: "local",
|
||||
projectCwd: input.projectCwd,
|
||||
branchWorktreePath: currentBranch.worktreePath,
|
||||
}),
|
||||
awaitsCurrentBranch: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveNewTaskBranchLabel(input: {
|
||||
readonly branchName: string | null;
|
||||
readonly startFromOrigin: boolean;
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
}): string {
|
||||
if (!input.branchName) {
|
||||
return "Choose branch";
|
||||
}
|
||||
|
||||
if (input.workspaceMode === "local") {
|
||||
return input.branchName;
|
||||
}
|
||||
|
||||
const baseRef = input.startFromOrigin ? `origin/${input.branchName}` : input.branchName;
|
||||
return `From ${baseRef}`;
|
||||
}
|
||||
|
||||
export function shouldCheckoutNewTaskBranch(input: {
|
||||
readonly branchIsCurrent: boolean;
|
||||
readonly branchWorktreePath: string | null | undefined;
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
}): boolean {
|
||||
return input.workspaceMode === "local" && !input.branchIsCurrent && !input.branchWorktreePath;
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import { useEnvironmentQuery } from "../../state/query";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
clearComposerDraft,
|
||||
copyComposerDraftContentIfEmpty,
|
||||
getComposerDraftSnapshot,
|
||||
isComposerDraftEmpty,
|
||||
removeComposerDraftAttachment,
|
||||
@@ -50,7 +51,7 @@ import {
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
|
||||
import {
|
||||
flattenQueuedThreadMessages,
|
||||
threadOutboxManager,
|
||||
@@ -74,10 +75,16 @@ import {
|
||||
type HomeProjectScope,
|
||||
} from "../home/homeThreadList";
|
||||
import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
|
||||
import { resolvePendingTaskInteractionMode } from "./legacy-plan-mode";
|
||||
import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
|
||||
import {
|
||||
resolveNewTaskBranchWorktreePath,
|
||||
resolveNewTaskLocalWorkspaceSelection,
|
||||
} from "./new-task-context-presentation";
|
||||
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
|
||||
const BRANCH_SEARCH_DEBOUNCE_MS = 150;
|
||||
|
||||
function pendingTaskDraftKey(messageId: string): string {
|
||||
return `pending-task:${messageId}`;
|
||||
@@ -96,14 +103,6 @@ function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {
|
||||
return message?.creation !== undefined ? message : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null {
|
||||
if (!branch.worktreePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return branch.worktreePath === project.workspaceRoot ? null : branch.worktreePath;
|
||||
}
|
||||
|
||||
export function branchBadgeLabel(input: {
|
||||
readonly branch: VcsRef;
|
||||
readonly project: EnvironmentProject | null;
|
||||
@@ -117,9 +116,6 @@ export function branchBadgeLabel(input: {
|
||||
if (input.branch.isDefault) {
|
||||
return "default";
|
||||
}
|
||||
if (input.branch.isRemote) {
|
||||
return "remote";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -139,9 +135,13 @@ type NewTaskFlowContextValue = {
|
||||
readonly submitting: boolean;
|
||||
readonly branchQuery: string;
|
||||
readonly branchesLoading: boolean;
|
||||
readonly branchesError: string | null;
|
||||
readonly branchesFetchingNextPage: boolean;
|
||||
readonly hasMoreBranches: boolean;
|
||||
readonly availableBranches: ReadonlyArray<VcsRef>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly planModeEnabled: boolean;
|
||||
readonly expandedProvider: string | null;
|
||||
readonly environments: ReadonlyArray<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -175,7 +175,8 @@ type NewTaskFlowContextValue = {
|
||||
readonly clearAttachments: () => void;
|
||||
readonly setSubmitting: (value: boolean) => void;
|
||||
readonly setBranchQuery: (value: string) => void;
|
||||
readonly loadBranches: () => Promise<void>;
|
||||
readonly loadBranches: () => void;
|
||||
readonly loadMoreBranches: () => void;
|
||||
readonly setRuntimeMode: (value: RuntimeMode) => void;
|
||||
readonly setInteractionMode: (value: ProviderInteractionMode) => void;
|
||||
readonly setSelectedModelOptions: (
|
||||
@@ -191,6 +192,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const threads = useThreadShells();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const groupingSettings = useMobileProjectGroupingSettings();
|
||||
const { enabled: planModeEnabled, loaded: planModePreferenceLoaded } = useLegacyPlanModeState();
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
@@ -219,6 +221,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
|
||||
const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
|
||||
// Mirrors `editingPendingTask` synchronously so the unmount flush cannot act
|
||||
// on a task whose editing session already ended this render.
|
||||
const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
|
||||
@@ -229,6 +232,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setExpandedProvider(null);
|
||||
pendingLocalBranchSyncDraftKeysRef.current.clear();
|
||||
const editing = editingPendingTaskRef.current;
|
||||
editingPendingTaskRef.current = null;
|
||||
setEditingPendingTask(null);
|
||||
@@ -395,7 +399,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
|
||||
true;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
const interactionMode = planModeEnabled
|
||||
? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)
|
||||
: DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
// Stored selections only count while their provider is usable on the
|
||||
// server; otherwise the server's default model wins instead of silently
|
||||
@@ -521,18 +527,24 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
}
|
||||
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
|
||||
}, [selectedProjectDraftKey]);
|
||||
const debouncedBranchQuery = useDebouncedValue(branchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
|
||||
const branchTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: selectedProject?.environmentId ?? null,
|
||||
// `|| null` also skips the stand-in project's empty workspaceRoot.
|
||||
cwd: selectedProject?.workspaceRoot || null,
|
||||
query: null,
|
||||
query: debouncedBranchQuery,
|
||||
}),
|
||||
[selectedProject?.environmentId, selectedProject?.workspaceRoot],
|
||||
[debouncedBranchQuery, selectedProject?.environmentId, selectedProject?.workspaceRoot],
|
||||
);
|
||||
const branchState = useBranches(branchTarget);
|
||||
const branchesLoading = branchState.isPending;
|
||||
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
|
||||
const branchState = usePaginatedBranches(branchTarget);
|
||||
const branchSearchIsDebouncing = branchQuery.trim() !== debouncedBranchQuery.trim();
|
||||
const branchesLoading =
|
||||
branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);
|
||||
const branchesFetchingNextPage = branchState.isFetchingNextPage;
|
||||
const hasMoreBranches =
|
||||
branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
|
||||
const allBranchRefs = branchState.refs;
|
||||
const availableBranches = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
@@ -554,11 +566,21 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
);
|
||||
}, [availableBranches, branchQuery]);
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
}, []);
|
||||
const setProject = useCallback(
|
||||
(project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
const nextDraftKey = `new-task:${nextProjectKey}`;
|
||||
if (
|
||||
selectedProjectDraftKey?.startsWith("new-task:") &&
|
||||
selectedProjectDraftKey !== nextDraftKey
|
||||
) {
|
||||
void copyComposerDraftContentIfEmpty(selectedProjectDraftKey, nextDraftKey);
|
||||
}
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const selectEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => {
|
||||
@@ -596,28 +618,86 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const localSelection = resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: availableBranches,
|
||||
projectCwd: selectedProject.workspaceRoot,
|
||||
});
|
||||
if (mode === "local" && localSelection.awaitsCurrentBranch) {
|
||||
pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
|
||||
} else {
|
||||
pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
branch: mode === "local" ? localSelection.branch : selectedBranchName,
|
||||
worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
[
|
||||
availableBranches,
|
||||
draftStartFromOrigin,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
selectedWorktreePath,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
workspaceMode !== "local" ||
|
||||
!selectedProject ||
|
||||
!selectedProjectDraftKey ||
|
||||
!pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const localSelection = resolveNewTaskLocalWorkspaceSelection({
|
||||
branches: availableBranches,
|
||||
projectCwd: selectedProject.workspaceRoot,
|
||||
});
|
||||
if (localSelection.awaitsCurrentBranch) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: "local",
|
||||
branch: localSelection.branch,
|
||||
worktreePath: localSelection.worktreePath,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
}, [
|
||||
availableBranches,
|
||||
draftStartFromOrigin,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
worktreePath: resolveNewTaskBranchWorktreePath({
|
||||
workspaceMode,
|
||||
projectCwd: selectedProject.workspaceRoot,
|
||||
branchWorktreePath: branch.worktreePath,
|
||||
}),
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
@@ -643,7 +723,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
const loadMoreBranches = branchState.loadNext;
|
||||
const loadBranches = useCallback(() => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
@@ -767,7 +848,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
attachments: draft.attachments,
|
||||
modelSelection: draftModelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: draft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
interactionMode: resolvePendingTaskInteractionMode({
|
||||
preferenceLoaded: planModePreferenceLoaded,
|
||||
planModeEnabled,
|
||||
draftInteractionMode: draft.interactionMode,
|
||||
queuedInteractionMode: editingPendingTask?.interactionMode,
|
||||
}),
|
||||
creation: {
|
||||
projectId: selectedProject.id,
|
||||
...(projectTitle !== undefined ? { projectTitle } : {}),
|
||||
@@ -792,6 +878,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
planModeEnabled,
|
||||
planModePreferenceLoaded,
|
||||
startFromOrigin,
|
||||
workspaceMode,
|
||||
],
|
||||
@@ -904,9 +992,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
submitting,
|
||||
branchQuery,
|
||||
branchesLoading,
|
||||
branchesError: branchState.error,
|
||||
branchesFetchingNextPage,
|
||||
hasMoreBranches,
|
||||
availableBranches,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
planModeEnabled,
|
||||
expandedProvider,
|
||||
environments,
|
||||
selectedProject,
|
||||
@@ -935,6 +1027,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSubmitting,
|
||||
setBranchQuery,
|
||||
loadBranches,
|
||||
loadMoreBranches,
|
||||
setRuntimeMode,
|
||||
setInteractionMode,
|
||||
setSelectedModelOptions,
|
||||
@@ -946,6 +1039,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
beginEditingPendingTask,
|
||||
branchQuery,
|
||||
branchesLoading,
|
||||
branchState.error,
|
||||
branchesFetchingNextPage,
|
||||
buildPendingTaskMessage,
|
||||
cancelEditingPendingTask,
|
||||
editingPendingTask,
|
||||
@@ -954,7 +1049,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
filteredBranches,
|
||||
finishEditingPendingTask,
|
||||
interactionMode,
|
||||
planModeEnabled,
|
||||
loadBranches,
|
||||
loadMoreBranches,
|
||||
projectScopes,
|
||||
modelOptions,
|
||||
prompt,
|
||||
@@ -963,6 +1060,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
reset,
|
||||
runtimeMode,
|
||||
selectedBranchName,
|
||||
hasMoreBranches,
|
||||
selectedEnvironmentId,
|
||||
selectedModel,
|
||||
selectedModelKey,
|
||||
|
||||
@@ -5,12 +5,13 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import type { HomeProjectScope } from "../home/homeThreadList";
|
||||
import {
|
||||
getOnlySelectableProject,
|
||||
getProjectScopeSelectionTarget,
|
||||
resolveDraftProjectSelection,
|
||||
} from "./new-task-project-selection";
|
||||
|
||||
function makeProject(id: string): EnvironmentProject {
|
||||
function makeProject(id: string, environmentId = "environment"): EnvironmentProject {
|
||||
return {
|
||||
environmentId: EnvironmentId.make("environment"),
|
||||
environmentId: EnvironmentId.make(environmentId),
|
||||
id: ProjectId.make(id),
|
||||
title: id,
|
||||
workspaceRoot: `/work/${id}`,
|
||||
@@ -41,9 +42,25 @@ describe("getOnlySelectableProject", () => {
|
||||
expect(getOnlySelectableProject([makeScope([project])])).toBe(project);
|
||||
});
|
||||
|
||||
it("does not auto-select a representative when one group has multiple clones", () => {
|
||||
it("selects the representative when one logical project has multiple workspaces", () => {
|
||||
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
|
||||
expect(getOnlySelectableProject([makeScope(projects)])).toBeNull();
|
||||
expect(getOnlySelectableProject([makeScope(projects)])).toBe(projects[0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProjectScopeSelectionTarget", () => {
|
||||
it("keeps the current environment when it hosts the selected logical project", () => {
|
||||
const projects = [makeProject("t3code-mac", "mac"), makeProject("t3code-server", "server")];
|
||||
expect(getProjectScopeSelectionTarget(makeScope(projects), EnvironmentId.make("server"))).toBe(
|
||||
projects[1],
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the representative when the current environment does not host the project", () => {
|
||||
const projects = [makeProject("t3code-mac", "mac"), makeProject("t3code-server", "server")];
|
||||
expect(getProjectScopeSelectionTarget(makeScope(projects), EnvironmentId.make("other"))).toBe(
|
||||
projects[0],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,10 +80,11 @@ describe("resolveDraftProjectSelection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the picker for multiple physical projects in one logical group", () => {
|
||||
it("selects one logical project even when it has multiple physical workspaces", () => {
|
||||
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
|
||||
expect(resolveDraftProjectSelection(null, projects, [makeScope(projects)])).toEqual({
|
||||
kind: "pick",
|
||||
kind: "select",
|
||||
project: projects[0],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import type { HomeProjectScope } from "../home/homeThreadList";
|
||||
|
||||
export type DraftProjectSelectionResolution =
|
||||
type DraftProjectSelectionResolution =
|
||||
| { readonly kind: "preserve" }
|
||||
| { readonly kind: "select"; readonly project: EnvironmentProject }
|
||||
| { readonly kind: "pick" };
|
||||
|
||||
export function getProjectScopeSelectionTarget(
|
||||
scope: HomeProjectScope,
|
||||
preferredEnvironmentId: EnvironmentId | null,
|
||||
): EnvironmentProject {
|
||||
return (
|
||||
scope.projects.find((project) => project.environmentId === preferredEnvironmentId) ??
|
||||
scope.representative
|
||||
);
|
||||
}
|
||||
|
||||
export function getOnlySelectableProject(
|
||||
projectScopes: ReadonlyArray<HomeProjectScope>,
|
||||
): EnvironmentProject | null {
|
||||
const onlyScope = projectScopes.length === 1 ? projectScopes[0] : null;
|
||||
return onlyScope?.projects.length === 1 ? (onlyScope.projects[0] ?? null) : null;
|
||||
return onlyScope?.representative ?? null;
|
||||
}
|
||||
|
||||
export function resolveDraftProjectSelection(
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { View } from "react-native";
|
||||
|
||||
import { T3HeaderButton } from "../../native/T3HeaderButton.android";
|
||||
import type { SidebarHeaderActionsProps } from "./sidebar-header-actions";
|
||||
|
||||
export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
|
||||
return (
|
||||
<View className="h-11 flex-row gap-1">
|
||||
<T3HeaderButton
|
||||
accessibilityLabel="Open settings"
|
||||
icon="gearshape"
|
||||
onPress={props.onOpenSettings}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
|
||||
import type { HomeGroupDisplayAction } from "../home/homeListItems";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import { resolveThreadStatus } from "./threadPresentation";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
|
||||
@@ -430,6 +431,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
@@ -451,7 +454,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
|
||||
props;
|
||||
const status = resolveThreadStatus(thread);
|
||||
const pr = useThreadPr(thread, props.projectCwd);
|
||||
const timestamp = relativeTime(
|
||||
@@ -471,6 +475,21 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
THREAD_ROW_MENU_ACTIONS[0]!,
|
||||
...buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
THREAD_ROW_MENU_ACTIONS[1]!,
|
||||
],
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const primaryAction = useMemo(
|
||||
() => ({
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
@@ -483,9 +502,10 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete],
|
||||
[handleArchive, handleDelete, handleRegenerateTitle],
|
||||
);
|
||||
|
||||
const statusPill = effectiveStatus ? (
|
||||
@@ -674,7 +694,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
// ControlPillMenu injects onLongPress into the row and anchors the
|
||||
// token-styled dropdown to it; taps and swipes are untouched.
|
||||
<ControlPillMenu
|
||||
actions={THREAD_ROW_MENU_ACTIONS}
|
||||
actions={menuActions}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
|
||||
@@ -27,11 +27,13 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import {
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
threadHasUnseenCompletion,
|
||||
type ThreadListV2Status,
|
||||
} from "./threadListV2";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
@@ -58,6 +60,8 @@ const STATUS_LABEL_BY_STATUS: Partial<
|
||||
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
|
||||
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
|
||||
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
|
||||
// Colorless like the web sidebar: parked on background work, not "act now".
|
||||
waiting: { label: "Waiting", className: "text-foreground-tertiary" },
|
||||
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
|
||||
};
|
||||
|
||||
@@ -65,8 +69,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
// Menus keep lifecycle and title regeneration together. Archive keeps its
|
||||
// own surface (thread screen / settings) rather than crowding v2 rows.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
@@ -341,6 +345,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly fullSwipeWidth?: number;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
@@ -355,6 +360,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly snoozeSupported: boolean;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: boolean;
|
||||
/** False on servers that predate thread title regeneration. */
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
/** False on servers that predate thread.pin.reorder. Gates the pinned
|
||||
Move up / Move down menu items. */
|
||||
readonly pinReorderSupported?: boolean;
|
||||
@@ -365,8 +372,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly canMovePinnedDown?: 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
|
||||
merged/closed work (mirrors web's onChangeRequestState). */
|
||||
/** Reports this row's live PR state for the partition's merge and close
|
||||
rules. Mirrors web's onChangeRequestState. */
|
||||
readonly onChangeRequestState?: (
|
||||
threadKey: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
@@ -384,6 +391,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onRegenerateThreadTitle,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
@@ -413,10 +421,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
// "Done" marks a completion the user has not opened yet — same emerald
|
||||
// label as the web sidebar, sourced from the server-side visited watermark
|
||||
// so checking a thread on any device clears it everywhere.
|
||||
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
|
||||
const statusLabel =
|
||||
STATUS_LABEL_BY_STATUS[status] ??
|
||||
(isUnread ? { label: "Done", className: "text-emerald-700 dark:text-emerald-300" } : undefined);
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleSnooze = useCallback(
|
||||
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
|
||||
@@ -506,6 +524,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
props.pinningSupported,
|
||||
],
|
||||
);
|
||||
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
@@ -516,13 +542,31 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
() => [
|
||||
CARD_MENU_ACTIONS[0]!,
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
...CARD_MENU_ACTIONS.slice(1),
|
||||
],
|
||||
[pinMenuItem, titleRegenerationMenuItems],
|
||||
);
|
||||
const slimMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const snoozedMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const legacyMenuActions = useMemo<MenuAction[]>(
|
||||
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -534,6 +578,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
|
||||
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: nativeEvent.event,
|
||||
@@ -549,6 +594,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleRegenerateTitle,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
@@ -677,7 +723,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</View>
|
||||
) : null}
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
{status === "failed" && thread.runtime?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
@@ -687,7 +733,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
{thread.runtime.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
/* "branch · machine" share one truncating line. The machine sits
|
||||
@@ -890,11 +936,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
snoozedRow
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
? snoozedMenuActions
|
||||
: !props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
? legacyMenuActions
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
? slimMenuActions
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: cardMenuActions
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";
|
||||
|
||||
function modelOption(
|
||||
model: string,
|
||||
overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},
|
||||
): ModelOption {
|
||||
const providerKey = overrides.providerKey ?? "codex";
|
||||
return {
|
||||
key: `${providerKey}:${model}`,
|
||||
label: model,
|
||||
subtitle: providerKey,
|
||||
providerKey,
|
||||
providerLabel: providerKey === "codex" ? "Codex" : "Claude",
|
||||
providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",
|
||||
isDefault: overrides.isDefault ?? false,
|
||||
isLegacy: overrides.isLegacy ?? false,
|
||||
capabilities: null,
|
||||
selection: {
|
||||
instanceId: ProviderInstanceId.make(providerKey),
|
||||
model,
|
||||
options: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function group(models: ReadonlyArray<ModelOption>): ProviderGroup {
|
||||
const first = models[0];
|
||||
if (!first) {
|
||||
throw new Error("group requires at least one model");
|
||||
}
|
||||
return {
|
||||
providerKey: first.providerKey,
|
||||
providerLabel: first.providerLabel,
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
const effortDescriptor: ProviderOptionDescriptor = {
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium", isDefault: true },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "ultrathink", label: "Ultrathink" },
|
||||
{ id: "ultracode", label: "Ultracode" },
|
||||
],
|
||||
currentValue: "high",
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
};
|
||||
|
||||
const fastModeDescriptor: ProviderOptionDescriptor = {
|
||||
id: "fastMode",
|
||||
label: "Fast mode",
|
||||
type: "boolean",
|
||||
currentValue: false,
|
||||
};
|
||||
|
||||
function baseInput() {
|
||||
const models = [
|
||||
modelOption("gpt-current", { isDefault: true }),
|
||||
modelOption("gpt-next"),
|
||||
modelOption("gpt-old", { isLegacy: true }),
|
||||
];
|
||||
return {
|
||||
providerGroups: [group(models)],
|
||||
selectedModel: models[0]?.selection ?? null,
|
||||
optionDescriptors: [effortDescriptor, fastModeDescriptor],
|
||||
runtimeMode: "auto",
|
||||
} as const;
|
||||
}
|
||||
|
||||
function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {
|
||||
return id === undefined ? undefined : menu.events.get(id);
|
||||
}
|
||||
|
||||
describe("buildThreadSettingsMenu", () => {
|
||||
it("orders the top level as model, options, runtime", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.map((action) => action.title)).toEqual([
|
||||
"Model",
|
||||
"Reasoning",
|
||||
"Fast mode",
|
||||
"Runtime",
|
||||
]);
|
||||
});
|
||||
|
||||
it("summarizes the current choice on each submenu row", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");
|
||||
expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");
|
||||
expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");
|
||||
});
|
||||
|
||||
it("checkmarks the selected model and resolves selection events", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const current = modelItems.find((action) => action.title === "gpt-current");
|
||||
expect(current?.state).toBe("on");
|
||||
expect(current?.subtitle).toBe("Default");
|
||||
expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");
|
||||
|
||||
const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);
|
||||
expect(event?.type).toBe("select-model");
|
||||
expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");
|
||||
});
|
||||
|
||||
it("folds unselected legacy models behind a nested submenu", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"Legacy Models",
|
||||
]);
|
||||
expect(
|
||||
modelItems
|
||||
.find((action) => action.title === "Legacy Models")
|
||||
?.subactions?.map((action) => action.title),
|
||||
).toEqual(["gpt-old"]);
|
||||
});
|
||||
|
||||
it("keeps a selected legacy model in the main list", () => {
|
||||
const input = baseInput();
|
||||
const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...input,
|
||||
selectedModel: legacy?.selection ?? null,
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"gpt-old",
|
||||
]);
|
||||
expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");
|
||||
});
|
||||
|
||||
it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],
|
||||
});
|
||||
|
||||
const reasoning = menu.actions.find((action) => action.title === "Reasoning");
|
||||
expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);
|
||||
// The hidden value stays visible as the current summary; it just can't be
|
||||
// picked from the phone.
|
||||
expect(reasoning?.subtitle).toBe("Ultracode");
|
||||
expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves select-option and runtime events with checkmarked current values", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");
|
||||
expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "effort",
|
||||
value: "low",
|
||||
});
|
||||
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");
|
||||
expect(
|
||||
eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),
|
||||
).toEqual({ type: "set-runtime", mode: "full-access" });
|
||||
});
|
||||
|
||||
it("toggles boolean options with the inverted current value", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const fastMode = menu.actions.find((action) => action.title === "Fast mode");
|
||||
expect(fastMode?.state).toBe("off");
|
||||
expect(fastMode?.subactions).toBeUndefined();
|
||||
expect(eventFor(menu, fastMode?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: true,
|
||||
});
|
||||
|
||||
const enabled = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],
|
||||
});
|
||||
const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");
|
||||
expect(enabledRow?.state).toBe("on");
|
||||
expect(eventFor(enabled, enabledRow?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the menu presented only for top-level toggles", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
// Root-level boolean toggles refresh in place with clean chrome, so they
|
||||
// keep the menu presented.
|
||||
expect(
|
||||
menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,
|
||||
).toBe(true);
|
||||
|
||||
// Picks inside nested submenus close the menu: staying presented leaves
|
||||
// the submenu on screen with an expanded-submenu header, and the
|
||||
// bottom-anchored collapse back out drops by the levels' height delta.
|
||||
const expected = undefined;
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(
|
||||
(action) => action.subactions === undefined,
|
||||
);
|
||||
expect(nestedPicks.length).toBeGreaterThan(0);
|
||||
expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("sections models by provider only when multiple groups are offered", () => {
|
||||
const codexModels = [modelOption("gpt-current", { isDefault: true })];
|
||||
const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];
|
||||
const menu = buildThreadSettingsMenu({
|
||||
providerGroups: [group(codexModels), group(claudeModels)],
|
||||
selectedModel: codexModels[0]?.selection ?? null,
|
||||
optionDescriptors: [],
|
||||
runtimeMode: "auto",
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(
|
||||
modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),
|
||||
).toEqual([
|
||||
{ title: "Codex", inline: true },
|
||||
{ title: "Claude", inline: true },
|
||||
]);
|
||||
const claudeSection = modelItems.find((action) => action.title === "Claude");
|
||||
expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);
|
||||
});
|
||||
|
||||
const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {
|
||||
const types = new Set<ThreadSettingsMenuEvent["type"]>();
|
||||
for (const event of menu.events.values()) {
|
||||
types.add(event.type);
|
||||
}
|
||||
return types;
|
||||
};
|
||||
|
||||
it("registers an event for every leaf action id", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
const leafIds: string[] = [];
|
||||
const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {
|
||||
for (const item of items) {
|
||||
if (Array.isArray(item.subactions) && item.subactions.length > 0) {
|
||||
collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);
|
||||
} else if (item.id !== undefined) {
|
||||
leafIds.push(item.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
collect(menu.actions);
|
||||
|
||||
for (const id of leafIds) {
|
||||
expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();
|
||||
}
|
||||
expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));
|
||||
});
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
|
||||
import {
|
||||
getProviderOptionCurrentLabel,
|
||||
getProviderOptionCurrentValue,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
export function selectableChoices(
|
||||
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
|
||||
) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
|
||||
export type ThreadSettingsMenuEvent =
|
||||
| { readonly type: "select-model"; readonly option: ModelOption }
|
||||
| { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }
|
||||
| { readonly type: "set-runtime"; readonly mode: RuntimeMode };
|
||||
|
||||
export type ThreadSettingsMenu = {
|
||||
readonly actions: MenuAction[];
|
||||
/** Menu action id → the change it applies, for the onPressAction dispatch. */
|
||||
readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Native menu replacement for the thread settings sheet (model, select and
|
||||
* boolean provider options, runtime mode). The menu presents from the
|
||||
* composer pill without resigning the keyboard, so adjusting settings never
|
||||
* bounces focus. A thread is bound to one harness, so the menu covers the
|
||||
* sheet's full surface for existing threads; the sheet remains the Android
|
||||
* and new-task-draft surface.
|
||||
*
|
||||
* Selections apply immediately — the sheet's stage-then-Save flow only exists
|
||||
* because the sheet batches a model change with its option edits.
|
||||
*/
|
||||
export function buildThreadSettingsMenu(input: {
|
||||
readonly providerGroups: ReadonlyArray<ProviderGroup>;
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}): ThreadSettingsMenu {
|
||||
const events = new Map<string, ThreadSettingsMenuEvent>();
|
||||
const actions: MenuAction[] = [];
|
||||
|
||||
const isSelected = (option: ModelOption) =>
|
||||
option.selection.instanceId === input.selectedModel?.instanceId &&
|
||||
option.selection.model === input.selectedModel.model;
|
||||
|
||||
// Only top-level leaves (boolean toggles) keep the menu presented (iOS
|
||||
// 16+): the root refreshes in place with clean chrome. Picks inside nested
|
||||
// submenus close the menu — keeping the submenu presented renders an
|
||||
// expanded-submenu header with no way to pop back to the root, and the
|
||||
// bottom-anchored collapse back out travels the levels' height difference.
|
||||
const keepPresented = { keepsMenuPresented: true } as const;
|
||||
|
||||
const modelAction = (option: ModelOption, id: string): MenuAction => {
|
||||
events.set(id, { type: "select-model", option });
|
||||
return {
|
||||
id,
|
||||
title: option.label,
|
||||
...(option.isDefault ? { subtitle: "Default" } : {}),
|
||||
state: isSelected(option) ? "on" : "off",
|
||||
};
|
||||
};
|
||||
|
||||
const modelItems: MenuAction[] = [];
|
||||
const legacyItems: MenuAction[] = [];
|
||||
let selectedModelLabel: string | undefined;
|
||||
input.providerGroups.forEach((group, groupIndex) => {
|
||||
const groupItems: MenuAction[] = [];
|
||||
group.models.forEach((option, modelIndex) => {
|
||||
if (isSelected(option)) {
|
||||
selectedModelLabel = option.label;
|
||||
}
|
||||
const id = `model:${groupIndex}:${modelIndex}`;
|
||||
// A highlighted legacy model stays in the main list (mirroring the
|
||||
// sheet) so the checkmark isn't hidden behind the Legacy fold.
|
||||
if (option.isLegacy && !isSelected(option)) {
|
||||
legacyItems.push(modelAction(option, id));
|
||||
} else {
|
||||
groupItems.push(modelAction(option, id));
|
||||
}
|
||||
});
|
||||
if (groupItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
// A thread is bound to one harness, so provider sections only appear for
|
||||
// multi-group callers (the new-task draft, if it ever adopts the menu).
|
||||
if (input.providerGroups.length > 1) {
|
||||
modelItems.push({
|
||||
id: `model-group:${groupIndex}`,
|
||||
title: group.providerLabel,
|
||||
displayInline: true,
|
||||
subactions: groupItems,
|
||||
});
|
||||
} else {
|
||||
modelItems.push(...groupItems);
|
||||
}
|
||||
});
|
||||
if (legacyItems.length > 0) {
|
||||
modelItems.push({
|
||||
id: "legacy-models",
|
||||
title: "Legacy Models",
|
||||
subactions: legacyItems,
|
||||
});
|
||||
}
|
||||
if (modelItems.length > 0) {
|
||||
actions.push({
|
||||
id: "model",
|
||||
title: "Model",
|
||||
...(selectedModelLabel === undefined
|
||||
? input.selectedModel
|
||||
? { subtitle: input.selectedModel.model }
|
||||
: {}
|
||||
: { subtitle: selectedModelLabel }),
|
||||
subactions: modelItems,
|
||||
});
|
||||
}
|
||||
|
||||
for (const descriptor of input.optionDescriptors) {
|
||||
if (descriptor.type === "boolean") {
|
||||
const id = `option:${descriptor.id}`;
|
||||
events.set(id, {
|
||||
type: "set-option",
|
||||
optionId: descriptor.id,
|
||||
value: !(descriptor.currentValue ?? false),
|
||||
});
|
||||
actions.push({
|
||||
id,
|
||||
title: descriptor.label,
|
||||
state: descriptor.currentValue ? "on" : "off",
|
||||
attributes: keepPresented,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const currentValue = getProviderOptionCurrentValue(descriptor);
|
||||
const choices = selectableChoices(descriptor).map((choice): MenuAction => {
|
||||
const id = `option:${descriptor.id}:${choice.id}`;
|
||||
events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.id === currentValue ? "on" : "off",
|
||||
};
|
||||
});
|
||||
if (choices.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const currentLabel = getProviderOptionCurrentLabel(descriptor);
|
||||
actions.push({
|
||||
id: `option:${descriptor.id}`,
|
||||
title: descriptor.label,
|
||||
...(currentLabel === undefined ? {} : { subtitle: currentLabel }),
|
||||
subactions: choices,
|
||||
});
|
||||
}
|
||||
|
||||
const runtimeLabel = RUNTIME_MODE_CHOICES.find(
|
||||
(choice) => choice.mode === input.runtimeMode,
|
||||
)?.label;
|
||||
actions.push({
|
||||
id: "runtime",
|
||||
title: "Runtime",
|
||||
...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),
|
||||
subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {
|
||||
const id = `runtime:${choice.mode}`;
|
||||
events.set(id, { type: "set-runtime", mode: choice.mode });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.mode === input.runtimeMode ? "on" : "off",
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
return { actions, events };
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { selectableChoices } from "./thread-settings-options";
|
||||
|
||||
const effortDescriptor: Extract<ProviderOptionDescriptor, { type: "select" }> = {
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium", isDefault: true },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "ultrathink", label: "Ultrathink" },
|
||||
{ id: "ultracode", label: "Ultracode" },
|
||||
],
|
||||
currentValue: "high",
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
};
|
||||
|
||||
describe("selectableChoices", () => {
|
||||
it("hides prompt-injected and workflow-trigger choices, keeping declared order", () => {
|
||||
expect(selectableChoices(effortDescriptor).map((choice) => choice.id)).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
}> = [
|
||||
{
|
||||
mode: "approval-required",
|
||||
label: "Supervised",
|
||||
description: "Ask before commands and file changes.",
|
||||
},
|
||||
{
|
||||
mode: "auto-accept-edits",
|
||||
label: "Auto-accept edits",
|
||||
description: "Auto-approve edits, ask before other actions.",
|
||||
},
|
||||
{
|
||||
mode: "auto",
|
||||
label: "Auto",
|
||||
description: "Supported providers approve routine actions; others still ask.",
|
||||
},
|
||||
{
|
||||
mode: "full-access",
|
||||
label: "Full access",
|
||||
description: "Allow commands and edits without prompts.",
|
||||
},
|
||||
];
|
||||
|
||||
export function selectableChoices(
|
||||
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
|
||||
) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts";
|
||||
|
||||
import type { ModelOption } from "../../lib/modelOptions";
|
||||
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
import { modelMatchesCatalogQuery, pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
|
||||
function modelOption(
|
||||
model: string,
|
||||
@@ -28,6 +28,26 @@ function modelOption(
|
||||
}
|
||||
|
||||
describe("thread settings sheet state", () => {
|
||||
it("matches visible model and provider terms", () => {
|
||||
const model = modelOption("gpt-next");
|
||||
|
||||
expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "NEXT" })).toBe(true);
|
||||
expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "codex" })).toBe(true);
|
||||
expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "claude" })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("treats whitespace-only catalog searches as empty", () => {
|
||||
expect(
|
||||
modelMatchesCatalogQuery({
|
||||
model: modelOption("gpt-next"),
|
||||
providerLabel: "Codex",
|
||||
query: " ",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("clears staging when the applied model is pressed", () => {
|
||||
expect(
|
||||
pendingModelAfterPress({
|
||||
|
||||
@@ -1,5 +1,24 @@
|
||||
import type { ModelOption } from "../../lib/modelOptions";
|
||||
|
||||
/** Match the terms a user can actually see or recognize in the model picker. */
|
||||
export function modelMatchesCatalogQuery(input: {
|
||||
readonly model: ModelOption;
|
||||
readonly providerLabel: string;
|
||||
readonly query: string;
|
||||
}): boolean {
|
||||
const query = input.query.trim().toLocaleLowerCase();
|
||||
if (query.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return [
|
||||
input.model.label,
|
||||
input.model.subtitle,
|
||||
input.model.selection.model,
|
||||
input.providerLabel,
|
||||
].some((value) => value.toLocaleLowerCase().includes(query));
|
||||
}
|
||||
|
||||
/** Preserve staged provider options when the highlighted model is tapped again. */
|
||||
export function pendingModelAfterPress(input: {
|
||||
readonly current: ModelOption | null;
|
||||
@@ -11,3 +30,18 @@ export function pendingModelAfterPress(input: {
|
||||
}
|
||||
return input.current?.key === input.pressed.key ? input.current : input.pressed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Primary and selected providers start open; all other catalogs start closed.
|
||||
* A user's disclosure tap inverts that default until the picker is dismissed.
|
||||
*/
|
||||
export function providerSectionIsCollapsed(input: {
|
||||
readonly defaultExpanded: boolean;
|
||||
readonly hasExpansionOverride: boolean;
|
||||
readonly isNarrowed: boolean;
|
||||
}): boolean {
|
||||
if (input.isNarrowed) {
|
||||
return false;
|
||||
}
|
||||
return input.defaultExpanded ? input.hasExpansionOverride : !input.hasExpansionOverride;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
|
||||
describe("buildThreadTitleRegenerationMenuItems", () => {
|
||||
it("hides regeneration when the environment does not advertise support", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("offers regeneration for a supported environment", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows and disables the pending state", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerating…",
|
||||
image: "arrow.clockwise",
|
||||
attributes: { disabled: true },
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
|
||||
export function buildThreadTitleRegenerationMenuItems(input: {
|
||||
readonly supported: boolean;
|
||||
readonly isRegenerating: boolean;
|
||||
}): MenuAction[] {
|
||||
if (!input.supported) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
||||
|
||||
describe("thread work log overflow labels", () => {
|
||||
it("describes tool-only groups as tool calls", () => {
|
||||
expect(threadWorkLogOverflowNoun(true, 1)).toBe("tool call");
|
||||
expect(threadWorkLogOverflowNoun(true, 2)).toBe("tool calls");
|
||||
});
|
||||
|
||||
it("describes mixed groups as log entries", () => {
|
||||
expect(threadWorkLogOverflowNoun(false, 1)).toBe("log entry");
|
||||
expect(threadWorkLogOverflowNoun(false, 2)).toBe("log entries");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
export function threadWorkLogOverflowNoun(
|
||||
onlyToolRows: boolean,
|
||||
count: number,
|
||||
): "tool call" | "tool calls" | "log entry" | "log entries" {
|
||||
if (onlyToolRows) {
|
||||
return count === 1 ? "tool call" : "tool calls";
|
||||
}
|
||||
return count === 1 ? "log entry" : "log entries";
|
||||
}
|
||||
@@ -1,14 +1,21 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Image } from "expo-image";
|
||||
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
|
||||
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import Animated, { FadeIn } from "react-native-reanimated";
|
||||
import { ThreadActivityInspector } from "./ThreadActivityInspector";
|
||||
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
create: {
|
||||
@@ -71,6 +78,79 @@ 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 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 === "fork") {
|
||||
targetThreadId =
|
||||
item.targetThreadId === row.sourceThreadId && item.source.type === "run"
|
||||
? item.source.threadId
|
||||
: item.targetThreadId;
|
||||
label = targetThreadId === item.targetThreadId ? "Open forked thread" : "Open parent thread";
|
||||
}
|
||||
|
||||
if (targetThreadId === null) return null;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
accessibilityLabel={label}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: props.environmentId,
|
||||
threadId: targetThreadId,
|
||||
});
|
||||
}}
|
||||
className="mx-2 mb-2 min-h-9 flex-row items-center justify-center gap-1.5 rounded-lg border border-neutral-300/50 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
<Text className="font-t3-medium text-2xs text-foreground">{label}</Text>
|
||||
<SymbolView name="arrow.right" size={11} tintColor={props.iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
// Entering fades only for rows created moments ago: rows remount whenever the
|
||||
// list scrolls them back into view, and old rows must not replay an entrance.
|
||||
const FRESH_ROW_WINDOW_MS = 3_000;
|
||||
@@ -122,10 +202,15 @@ export function collapsedWorkLogHeight(
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly expanded: boolean;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleGroup: () => void;
|
||||
readonly onToggleRow: (rowId: string) => void;
|
||||
readonly workspaceRoot?: string | null;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
@@ -138,10 +223,15 @@ export function ThreadWorkLog(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows =
|
||||
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
work log
|
||||
@@ -149,17 +239,21 @@ export function ThreadWorkLog(props: {
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{rows.map((row) => {
|
||||
{visibleRows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.canExpand;
|
||||
const fullDetail = expanded ? row.getFullDetail() : null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
const detail = compactActivityDetail(row.detail);
|
||||
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
|
||||
const textIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
key={row.id}
|
||||
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
|
||||
className={cn(
|
||||
row.prominent &&
|
||||
"mb-2 overflow-hidden rounded-xl border border-neutral-300/60 bg-card dark:border-white/[0.1]",
|
||||
)}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole={canExpand ? "button" : undefined}
|
||||
@@ -181,30 +275,24 @@ export function ThreadWorkLog(props: {
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0"
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="min-h-8 flex-row items-center gap-1.5">
|
||||
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
|
||||
<SymbolView
|
||||
name={workRowSymbolName(row.icon)}
|
||||
size={13}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||
<WorkRowIcon row={row} iconSubtleColor={props.iconSubtleColor} />
|
||||
</View>
|
||||
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-foreground",
|
||||
iconIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
textIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
)}
|
||||
>
|
||||
{row.summary}
|
||||
</Text>
|
||||
{row.detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
|
||||
{detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {detail}</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
|
||||
@@ -248,28 +336,63 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
{fullDetail ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
className="max-h-60"
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="font-mono text-2xs leading-normal text-foreground-muted"
|
||||
>
|
||||
{fullDetail}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
{expanded && canExpand ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ThreadActivityInspector
|
||||
activity={row}
|
||||
currentThreadId={props.currentThreadId}
|
||||
environmentId={props.environmentId}
|
||||
iconColor={props.iconSubtleColor}
|
||||
workspaceRoot={props.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
{row.prominent ? (
|
||||
<ThreadActivityThreadLink
|
||||
activity={row}
|
||||
environmentId={props.environmentId}
|
||||
iconColor={props.iconSubtleColor}
|
||||
/>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded
|
||||
? `Show fewer ${overflowNoun}`
|
||||
: `Show ${hiddenCount} previous ${overflowNoun}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleGroup();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="h-5 w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={13}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded
|
||||
? `Show fewer ${overflowNoun}`
|
||||
: `+${hiddenCount} previous ${overflowNoun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -283,48 +406,36 @@ export function ThreadWorkGroupToggle(props: {
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const noun = props.onlyToolActivities
|
||||
? props.hiddenCount === 1
|
||||
? "tool call"
|
||||
: "tool calls"
|
||||
: props.hiddenCount === 1
|
||||
? "log entry"
|
||||
: "log entries";
|
||||
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
|
||||
const expandedLabel = props.onlyToolActivities
|
||||
? "Show fewer tool calls"
|
||||
: "Show fewer log entries";
|
||||
const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-1 px-1">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
||||
accessibilityLabel={
|
||||
props.expanded ? `Show fewer ${noun}` : `Show ${props.hiddenCount} previous ${noun}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggle();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5"
|
||||
>
|
||||
<View className="h-[18px] w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={
|
||||
props.expanded
|
||||
? { ios: "chevron.up", android: "keyboard_arrow_up" }
|
||||
: { ios: "chevron.down", android: "keyboard_arrow_down" }
|
||||
}
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={12}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
||||
{props.expanded ? `Show fewer ${noun}` : `+${props.hiddenCount} previous ${noun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
|
||||
|
||||
describe("thread activity file navigation", () => {
|
||||
it("keeps inherited activity file links on the currently selected thread", () => {
|
||||
const sourceThreadId = ThreadId.make("source-thread");
|
||||
const currentThreadId = ThreadId.make("current-thread");
|
||||
|
||||
const params = buildThreadActivityFileParams({
|
||||
environmentId: EnvironmentId.make("environment"),
|
||||
currentThreadId,
|
||||
activitySourceThreadId: sourceThreadId,
|
||||
relativePath: "apps/mobile/src/index.ts",
|
||||
line: 12,
|
||||
});
|
||||
|
||||
expect(params).toEqual({
|
||||
environmentId: "environment",
|
||||
threadId: "current-thread",
|
||||
path: ["apps", "mobile", "src", "index.ts"],
|
||||
line: "12",
|
||||
});
|
||||
});
|
||||
});
|
||||
Loaded 100 of 1160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user