Compare commits

..
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 36f6d76bd5 fix: harden upload lifecycle from second review round
- Unique per-request .part suffix so concurrent POSTs of one token
  cannot interleave into a shared temp file.
- xhr.timeout on uploads: a stalled POST now fails into the retryable
  state instead of blocking send (and pick-and-send) forever.
- Cross-environment re-upload keeps the old environment's copy until
  the new upload succeeds (supersedes), so a failed re-upload never
  destroys the only server copy.
- The plan follow-up branch releases attached images before clearing
  the composer instead of orphaning their pending files.
- Mobile: a mixed text+image clipboard still pastes its text while
  attach is disabled, and the image drop is surfaced.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-13 18:17:01 -07:00
Theo BrowneandClaude Fable 5 03196ef7ad fix: address review findings on upload-on-attach
Real bugs from Macroscope and Bugbot, all verified against source:

- awaitAttachmentUploads consulted only live jobs, so an upload that
  settled before the await lost its result and a ready image could drop
  from a pick-and-send message. Terminal states are now kept in a
  settled map that cancel/release clean up.
- Stashing cancelled in-flight uploads before the localStorage write was
  confirmed; a quota failure stranded chips in uploading forever.
  Cancellation now happens only after the write lands.
- Retargeting a draft to another environment overwrote a reload-restored
  attachment's ready state with a dead failed state. The mismatch is now
  derived (never written), so switching back recovers the attachment,
  and re-uploads release the old environment's bytes first.
- The turn-start failure path restored chips from the pre-await
  snapshot, resurrecting uploading states no job would ever advance.
- The "images were not attached" toast could fire when no message was
  sent; it now waits for the turn to actually start.
- Removing a preview annotation or discarding a draft leaked the upload
  and its server-side bytes; both now release like chip removal.
- Mobile paste drops now surface the needs-an-update banner instead of
  a console.warn.
- Normalizer error mappings keep their PlatformError causes; the dead
  unstructured AttachmentUploadRequestError is deleted; the sweep test
  no longer reads the real clock (effect-diagnostics CI failure).

Also folds the rebase onto main: the new moveComposerPromptAndImages
draft-carry now merges the unified image list, and in-flight uploads are
retargeted to the destination draft so moved chips keep their progress.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-13 18:03:23 -07:00
Theo BrowneandClaude Fable 5 f695b6f5bf feat: upload composer images on attach
Attachments used to ride the turn-start command as base64 data URLs:
send carried the bytes, the stash re-encoded them into localStorage,
and a 10MB image meant a 14M-char string in a single ws frame.

Images now upload the moment they are attached. A ws RPC mints a
pending-<uuid> id plus a signed, expiring upload URL (mirroring signed
asset GETs, so it works against any environment); the browser POSTs the
compressed bytes to it with progress and abort; the turn-start command
carries id references only. The Normalizer renames pending files to
their thread segment at send, resolving by uuid so retries after a
partial send are idempotent. Never-sent uploads are deleted on chip
removal and swept after 30 days.

Breaking: the dataUrl upload variant is deleted with no compatibility
path. RN mobile compiles with image attach gated off behind
IMAGE_ATTACH_ENABLED and tells the user an update is needed; drafts and
stash persist id references (v9/v3 storage, old payloads purged).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-13 17:51:12 -07:00
t3-code[bot]andcodex 5304f3e9d4 chore(mobile): bump app version to 1.0.4
Co-authored-by: codex <[email protected]>
2026-08-14 00:01:09 +00:00
85389b9883 Nest mobile task settings in bottom sheets (#6224)
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-13 23:59:27 +00:00
Theo Browne db1507e986 feat: allow disabling auto-settle on merge (#5880) 2026-08-13 16:18:15 -07:00
Rakshith Bhat 96bfa67b3d fix(web): align the snoozed thread wake icon (#6215) 2026-08-13 18:14:24 -04:00
Taylor Bombay 5ff3a03ada fix(web): align sidebar wordmark label (#6086) 2026-08-13 18:14:13 -04:00
t3-code[bot]andmaria 23d45d914e fix(web): restore default stage artwork colors (#6535)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-13 18:04:24 -04:00
Paul van DykandClaude Opus 5 bad1143b02 fix(mobile): show a real settings cog in the Android sidebar header (#6520)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-13 20:41:17 +00:00
Adamulek123andJulius Marminge 92d4a2e996 fix(web): scope pull request errors to their environment (#6490)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 20:40:21 +00:00
Utkarsh Patil 2fab18e289 fix(web): show unlinked icon when viewport aspect ratio is unlocked (#6509) 2026-08-13 16:03:48 -04:00
1b16ed663f fix(web): avoid Clerk close button overlap (#6442)
Co-authored-by: t3-code[bot] <236186684+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-13 15:08:28 -04:00
SimoneandSimone 83ad26c3a3 fix(mobile): prevent invalid HTML entities from crashing markdown (#6495)
Co-authored-by: Simone <[email protected]>
2026-08-13 15:08:13 -04:00
Chris Deeming fd51561b4e fix(mobile): extend blockquotes across wrapped lines (#6482) 2026-08-13 20:00:03 +02:00
Julius Marminge 9e201941aa Remove rebase requirement before opening PR (#6479) 2026-08-13 15:04:42 +00:00
t3-code[bot]andJulius Marminge 2ab188f1c0 fix: ignore pull request actions in latency tracker (#6476)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 14:51:31 +00:00
maria 9513e62e24 Add bil0000 to VOUCHED contributors list (#6462) 2026-08-13 14:26:36 +00:00
Bilal Bakr 97db94c9bf fix(web): keep pull request panel within viewport (#6451) 2026-08-13 08:45:33 -04:00
Exotic 5015d7cf9f fix(web): keep turn minimap stable as composer grows (#6414) 2026-08-13 15:30:37 +05:30
Nick Anisimov df19f6cfe3 fix(server): align Codex collaboration prompts (#6432) 2026-08-13 10:31:53 +02:00
Dominic RoyandClaude Fable 5 6bc6cb6be4 fix(web): keep diff file lists scrollable past expanded files (#6423)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 20:11:53 -07:00
Theo BrowneandClaude Fable 5 1e59b4c400 fix(web): keep the typed prompt when a draft changes repo (#6393)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 16:26:27 -07:00
t3-code[bot]andUtkarsh Patil 33f9705926 fix(web): make reset zoom hover visible (#6385)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 19:13:35 -04:00
Dominic Roy da6253b3dd web/settings: fix source control scan on relay environments (#6230) 2026-08-12 16:13:06 -07:00
129 changed files with 6847 additions and 3535 deletions

No files matched your search

+16 -16
View File
@@ -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
View File
@@ -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."
+1
View File
@@ -38,3 +38,4 @@ github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
github:bil0000
-1
View File
@@ -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.
@@ -32,6 +32,7 @@ const clientSettings: ClientSettings = {
planModeEnabled: false,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
+1 -1
View File
@@ -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.
@@ -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 "&amp;":
@@ -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" ||
@@ -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
)
}
}
@@ -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
View File
@@ -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,
}),
@@ -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;
+6 -2
View File
@@ -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>
);
@@ -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">
@@ -356,6 +356,7 @@ function IosHomeHeader(props: HomeHeaderProps) {
onSearchTextChange: props.onSearchQueryChange,
placeholder: "Search",
searchTextChangeId: "home-search-text",
showsSearchDismissButton: true,
}),
],
}
+7 -2
View File
@@ -207,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);
@@ -483,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());
@@ -665,6 +668,7 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
@@ -676,6 +680,7 @@ export function HomeScreen(props: HomeScreenProps) {
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
@@ -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;
@@ -571,10 +577,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 +626,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 +649,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]);
@@ -95,12 +95,15 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
const handleNativePaste = useNativePaste((uris) => {
void (async () => {
try {
const images = await convertPastedImagesToAttachments({
const pasted = await convertPastedImagesToAttachments({
uris,
existingCount: attachments.length,
});
if (images.length > 0) {
setAttachments((current) => [...current, ...images]);
if (pasted.images.length > 0) {
setAttachments((current) => [...current, ...pasted.images]);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
}
} catch (error) {
console.error("[review comment] error converting pasted images", error);
@@ -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>
);
@@ -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";
@@ -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,7 +16,6 @@ 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,
@@ -19,22 +23,24 @@ import {
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,
@@ -48,22 +54,37 @@ import { 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 {
setPendingConnectionError,
useRemoteConnectionStatus,
} from "../../state/use-remote-environment-registry";
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 +111,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 +130,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 +292,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 +380,7 @@ export function NewTaskDraftScreen(props: {
return;
}
loadedBranchesProjectKeyRef.current = projectKey;
void flow.loadBranches();
flow.loadBranches();
}, [flow.loadBranches, selectedProject]);
useEffect(() => {
@@ -517,121 +582,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 +590,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) {
@@ -693,17 +610,23 @@ export function NewTaskDraftScreen(props: {
if (result.images.length > 0) {
flow.appendAttachments(result.images);
}
if (result.error) {
setPendingConnectionError(result.error);
}
}
const handleNativePasteImages = useCallback(
async (uris: ReadonlyArray<string>) => {
try {
const images = await convertPastedImagesToAttachments({
const pasted = await convertPastedImagesToAttachments({
uris,
existingCount: flow.attachments.length,
});
if (images.length > 0) {
flow.appendAttachments(images);
if (pasted.images.length > 0) {
flow.appendAttachments(pasted.images);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
}
} catch (error) {
console.error("[native paste] error converting images", error);
@@ -733,7 +656,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 (
@@ -851,7 +776,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 +791,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 +802,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,3 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type {
EnvironmentId,
MessageId,
@@ -14,7 +13,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 +40,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 +63,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 +85,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;
@@ -123,8 +125,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 +142,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 +156,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 +266,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 +277,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;
@@ -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,
@@ -626,67 +623,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 +740,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 +795,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
style={
isExpanded
? {
minHeight: 80,
minHeight: 72,
maxHeight: 160,
paddingHorizontal: 4,
paddingVertical: 4,
@@ -841,15 +844,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 +857,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 +886,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
showChevron={false}
/>
</ComposerToolbarRow>
</Animated.View>
) : null}
) : null}
</ComposerSurface>
{/* Queue count */}
{props.queueCount > 0 ? (
@@ -915,21 +900,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}
@@ -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";
@@ -214,6 +216,10 @@ function ThreadNavigationSidebarPane(
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(
@@ -411,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());
@@ -546,6 +552,7 @@ function ThreadNavigationSidebarPane(
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
@@ -557,6 +564,7 @@ function ThreadNavigationSidebarPane(
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
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>
);
}
@@ -369,8 +369,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,
@@ -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;
}
@@ -263,6 +263,21 @@ describe("sortThreadsForListV2", () => {
});
describe("buildThreadListV2Items", () => {
it("keeps a merged thread active when auto-settle on merge is off", () => {
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
const layout = buildThreadListV2Items({
threads: [merged],
environmentId: null,
searchQuery: "",
changeRequestStateByKey: new Map([[`${environmentId}:${merged.id}`, "merged"]]),
autoSettleOnMerge: false,
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["merged"]);
expect(layout.settledCount).toBe(0);
});
it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -306,9 +306,8 @@ export function buildThreadListV2ListItems(input: {
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
* the default is fixed here rather than user-configurable.
* the settled recency tail, matching the web v2 list. Mobile stores these
* auto-settle preferences per device.
*/
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
@@ -329,6 +328,7 @@ export function buildThreadListV2Items(input: {
contract as settlementEnvironmentIds. */
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
readonly autoSettleOnMerge?: boolean;
/** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */
@@ -349,6 +349,7 @@ export function buildThreadListV2Items(input: {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const autoSettleOnMerge = input.autoSettleOnMerge ?? true;
const query = input.searchQuery.trim().toLocaleLowerCase();
const projectKeys = input.projectRefs
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
@@ -405,7 +406,12 @@ export function buildThreadListV2Items(input: {
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
effectiveSettled(thread, {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
settled.push(thread);
} else {
@@ -0,0 +1,26 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { mobilePreferencesAtom } from "../../state/preferences";
import { resolveLegacyPlanModeEnabled } from "./legacy-plan-mode";
/**
* Mobile preferences are device-local, matching the desktop client setting.
* Keep the legacy composer mode hidden until the preference has loaded and is
* explicitly enabled.
*/
export function useLegacyPlanModeEnabled(): boolean {
return useLegacyPlanModeState().enabled;
}
export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded: boolean } {
const preferences = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferences);
return {
enabled: resolveLegacyPlanModeEnabled({
loaded,
preference: loaded ? preferences.value.planModeEnabled : undefined,
}),
loaded,
};
}
@@ -14,7 +14,10 @@ import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { threadEnvironment } from "../../state/threads";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import {
droppedAttachmentsWarning,
type DraftComposerImageAttachment,
} from "../../lib/composerImages";
import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
import { randomHex } from "../../lib/uuid";
@@ -84,7 +87,11 @@ export function useCreateProjectThread() {
);
return AsyncResult.failure(result.cause);
}
setPendingConnectionError(null);
// Legacy drafts can still carry data-url images. `thread.turn.start` now
// only accepts uploaded attachment ids, which mobile cannot mint yet, so
// those images are dropped and the user is told rather than left to
// assume they were sent. Null clears the banner when there are none.
setPendingConnectionError(droppedAttachmentsWarning(input.initialAttachments.length));
return mapAtomCommandResult(result, () =>
scopeThreadRef(input.project.environmentId, threadId),
@@ -3,14 +3,46 @@ import { KeyboardController } from "react-native-keyboard-controller";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
export type ThreadSettingsSheetCloseReason = "save" | "dismiss";
type PresentationPhase = "closed" | "opening" | "visible" | "closing";
type PresentationPhase = "closed" | "opening" | "visible";
/**
* Keeps the custom native composer and the settings modal from owning focus at
* the same time. Opening waits for the keyboard dismissal to finish, while
* focus restoration waits for the modal's dismissal callback.
* The navigator-level UIKit completion event added by the repo's
* `@react-navigation/native-stack` patch; absent from upstream event maps.
*/
export type NavigationWithFinishTransitioning = {
readonly addListener: (type: "finishTransitioning", callback: () => void) => () => void;
};
/**
* How long after the dismissal's state change the keyboard starts rising, so
* its ~250ms show overlaps the tail of the sheet's ~500ms travel the way
* UIKit apps choreograph it. This is aesthetics, not correctness: without
* keepFocus-style inputView overrides a show started mid-dismissal completes
* cleanly, so a slower device merely gets more overlap — no failure mode.
* The navigator's `finishTransitioning` event (UIKit's real completion
* callback, surfaced by the repo's native-stack patch) additionally bounds
* the restore at the true landing moment should this timer ever lag it.
*/
const SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS = 300;
/**
* A JS-initiated dismissal pops state before its animation runs; a
* gesture-driven one animates natively first and pops afterwards, with the
* navigator's completion event landing a few dozen milliseconds before the
* pop. A completion this fresh at pop time therefore means the sheet is
* already gone and the keyboard should return immediately. The two orderings
* are separated by the sheet's full ~500ms travel, so this window is a
* classification with wide margin, not an animation race.
*/
const NATIVE_DISMISSAL_ECHO_WINDOW_MS = 150;
/**
* Keeps the custom native composer and the settings sheet from owning focus at
* the same time. Opening resigns the editor cleanly; a dismissal re-focuses it
* once the sheet has fully landed. A plain blur/focus pair costs one keyboard
* animation each way — keepFocus-style inputView overrides are avoided because
* removing them forces UIKit to reload input views, replaying the keyboard's
* show as a visible collapse/re-open.
*/
export function useThreadSettingsSheetPresentation(input: {
readonly editorRef: RefObject<ComposerEditorHandle | null>;
@@ -19,18 +51,36 @@ export function useThreadSettingsSheetPresentation(input: {
const [phase, setPhase] = useState<PresentationPhase>("closed");
const isActiveRef = useRef(false);
const isMountedRef = useRef(true);
const isEditorFocusedRef = useRef(input.isEditorFocused);
const openingIdRef = useRef(0);
const restoreFocusOnSaveRef = useRef(false);
const shouldRestoreAfterDismissRef = useRef(false);
const focusRestoreIdRef = useRef(0);
const restoreFocusAfterDismissRef = useRef(false);
const restorePendingRef = useRef(false);
const lastStackTransitionFinishedAtRef = useRef(0);
const dismissRestoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const clearDismissRestoreTimer = useCallback(() => {
if (dismissRestoreTimerRef.current !== null) {
clearTimeout(dismissRestoreTimerRef.current);
dismissRestoreTimerRef.current = null;
}
}, []);
useEffect(
() => () => {
useEffect(() => {
isEditorFocusedRef.current = input.isEditorFocused;
}, [input.isEditorFocused]);
useEffect(() => {
// React Strict Mode and Fast Refresh both run an effect cleanup/setup
// cycle without recreating refs. Re-arm the mounted guard on every setup.
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
isActiveRef.current = false;
openingIdRef.current += 1;
},
[],
);
focusRestoreIdRef.current += 1;
clearDismissRestoreTimer();
};
}, [clearDismissRestoreTimer]);
const open = useCallback(() => {
if (isActiveRef.current) {
@@ -38,61 +88,107 @@ export function useThreadSettingsSheetPresentation(input: {
}
isActiveRef.current = true;
restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible();
shouldRestoreAfterDismissRef.current = false;
focusRestoreIdRef.current += 1;
clearDismissRestoreTimer();
restorePendingRef.current = false;
restoreFocusAfterDismissRef.current = input.isEditorFocused || KeyboardController.isVisible();
setPhase("opening");
const openingId = openingIdRef.current + 1;
openingIdRef.current = openingId;
// Keyboard.dismiss() only tracks React Native TextInputs. The composer is
// a custom native text view, so explicitly resign its first responder too.
// Start the keyboard transition before the custom native editor resigns
// first responder, then present the sheet on the next frame. The sheet and
// keyboard animate together instead of serializing two native transitions.
void KeyboardController.dismiss({ animated: true });
input.editorRef.current?.blur();
void KeyboardController.dismiss().then(() => {
requestAnimationFrame(() => {
if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {
return;
}
setPhase("visible");
});
}, [input.editorRef, input.isEditorFocused]);
}, [clearDismissRestoreTimer, input.editorRef, input.isEditorFocused]);
const close = useCallback((reason: ThreadSettingsSheetCloseReason) => {
if (!isActiveRef.current) {
const restoreEditorFocus = useCallback(() => {
const focusRestoreId = focusRestoreIdRef.current + 1;
focusRestoreIdRef.current = focusRestoreId;
let attemptsRemaining = 20;
// Restoration runs after the dismissal transition, so the first attempt
// normally succeeds; the retries are insurance against UIKit briefly
// refusing first-responder status right at the transition boundary.
const restoreFocus = () => {
if (
!isMountedRef.current ||
focusRestoreIdRef.current !== focusRestoreId ||
isEditorFocusedRef.current ||
attemptsRemaining <= 0
) {
return;
}
attemptsRemaining -= 1;
input.editorRef.current?.focus();
setTimeout(restoreFocus, 50);
};
requestAnimationFrame(restoreFocus);
}, [input.editorRef]);
/** Runs the queued restore once — whichever completion signal arrives first. */
const runPendingDismissalRestore = useCallback(() => {
if (!restorePendingRef.current) {
return;
}
restorePendingRef.current = false;
clearDismissRestoreTimer();
// A reopened sheet owns focus again; drop the stale restore request.
if (!isMountedRef.current || isActiveRef.current) {
return;
}
restoreEditorFocus();
}, [clearDismissRestoreTimer, restoreEditorFocus]);
openingIdRef.current += 1;
shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current;
setPhase("closing");
}, []);
/**
* Marks the sheet closed and queues the keyboard's return for the moment
* the dismissal transition actually completes: the sheet slides away over a
* resting composer, then the keyboard lifts it in one continuous motion.
*/
const onDismissed = useCallback(() => {
const shouldRestoreFocus = shouldRestoreAfterDismissRef.current;
shouldRestoreAfterDismissRef.current = false;
restoreFocusOnSaveRef.current = false;
isActiveRef.current = false;
setPhase("closed");
if (shouldRestoreFocus) {
input.editorRef.current?.focus();
if (!restoreFocusAfterDismissRef.current) {
return;
}
}, [input.editorRef]);
restoreFocusAfterDismissRef.current = false;
restorePendingRef.current = true;
clearDismissRestoreTimer();
if (Date.now() - lastStackTransitionFinishedAtRef.current <= NATIVE_DISMISSAL_ECHO_WINDOW_MS) {
// A stack transition finished just before this pop reached JS: the pop
// is the state echo of a gesture-driven dismissal whose animation has
// already completed. The sheet is gone — bring the keyboard back now.
runPendingDismissalRestore();
return;
}
dismissRestoreTimerRef.current = setTimeout(() => {
dismissRestoreTimerRef.current = null;
runPendingDismissalRestore();
}, SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS);
}, [clearDismissRestoreTimer, runPendingDismissalRestore]);
// The new-task screen can have an autofocus queued before the sheet opens.
// Preserve that intent for Save without allowing it to focus under the modal.
const restoreFocusAfterSave = useCallback(() => {
if (isActiveRef.current) {
restoreFocusOnSaveRef.current = true;
}
}, []);
/** Wire to the navigator's `finishTransitioning` event. */
const onStackTransitionsFinished = useCallback(() => {
lastStackTransitionFinishedAtRef.current = Date.now();
runPendingDismissalRestore();
}, [runPendingDismissalRestore]);
return {
isActive: phase !== "closed",
isActiveRef,
isVisible: phase === "visible",
open,
close,
onDismissed,
restoreFocusAfterSave,
onStackTransitionsFinished,
} as const;
}
+26 -56
View File
@@ -1,5 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
const files = new Map<string, { base64: string; deleted: boolean }>();
@@ -38,33 +37,22 @@ vi.mock("./uuid", () => ({
import {
convertPastedImagesToAttachments,
droppedAttachmentsWarning,
isOwnedPastedImageUri,
toUploadChatImageAttachments,
} from "./composerImages";
describe("toUploadChatImageAttachments", () => {
it("strips client draft id and previewUri for the startTurn wire shape", () => {
expect(
toUploadChatImageAttachments([
{
id: "client-draft-id",
type: "image",
name: "pasted-image.png",
mimeType: "image/png",
sizeBytes: 12,
dataUrl: "data:image/png;base64,AA==",
previewUri: "file:///tmp/preview.png",
},
]),
).toEqual([
{
type: "image",
name: "pasted-image.png",
mimeType: "image/png",
sizeBytes: 12,
dataUrl: "data:image/png;base64,AA==",
},
]);
describe("droppedAttachmentsWarning", () => {
it("stays quiet when a message carries no legacy images", () => {
expect(droppedAttachmentsWarning(0)).toBeNull();
});
it("names how many legacy images were left behind", () => {
expect(droppedAttachmentsWarning(1)).toBe(
"1 image was not sent. Image attach needs an app update.",
);
expect(droppedAttachmentsWarning(3)).toBe(
"3 images were not sent. Image attach needs an app update.",
);
});
});
@@ -83,42 +71,24 @@ describe("native pasted image cleanup", () => {
expect(isOwnedPastedImageUri("https://example.com/t3-composer-paste/id.png")).toBe(false);
});
it("converts owned files to data-backed previews and deletes the source", async () => {
const uri =
// Image attach is off until mobile implements upload-on-attach, so pasted
// images produce no attachment. Temp-file cleanup must still happen.
it("attaches nothing and deletes owned temp files, leaving user files alone", async () => {
const owned =
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
files.set(uri, { base64: "aGVsbG8=", deleted: false });
const userOwned = "file:///private/var/mobile/photos/library.png";
files.set(owned, { base64: "aGVsbG8=", deleted: false });
files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
const attachments = await convertPastedImagesToAttachments({
uris: [uri],
const pasted = await convertPastedImagesToAttachments({
uris: [owned, userOwned],
existingCount: 0,
});
expect(attachments).toEqual([
expect.objectContaining({
dataUrl: "data:image/png;base64,aGVsbG8=",
previewUri: "data:image/png;base64,aGVsbG8=",
}),
]);
expect(files.get(uri)?.deleted).toBe(true);
});
it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
const rejected =
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
const overflow =
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
const userOwned = "file:///private/var/mobile/photos/library.png";
files.set(rejected, { base64: "", deleted: false });
files.set(overflow, { base64: "aGVsbG8=", deleted: false });
files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
await convertPastedImagesToAttachments({
uris: [rejected, overflow, userOwned],
existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
});
expect(files.get(rejected)?.deleted).toBe(true);
expect(files.get(overflow)?.deleted).toBe(true);
expect(pasted.images).toEqual([]);
// The drop is surfaced to callers, not just logged.
expect(pasted.error).toContain("app update");
expect(files.get(owned)?.deleted).toBe(true);
expect(files.get(userOwned)?.deleted).toBe(false);
});
});
+61 -18
View File
@@ -1,29 +1,46 @@
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type UploadChatImageAttachment,
} from "@t3tools/contracts";
import { estimateBase64ByteSize } from "./base64";
import { uuidv4 } from "./uuid";
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
/**
* Local-only draft shape. It used to extend the contracts upload type, but
* `thread.turn.start` now carries id references to already-uploaded blobs, so
* `dataUrl` never reaches the wire and lives purely in mobile draft storage.
*/
export interface DraftComposerImageAttachment {
readonly id: string;
readonly previewUri: string;
readonly type: "image";
readonly name: string;
readonly mimeType: string;
readonly sizeBytes: number;
readonly dataUrl: string;
}
/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */
export function toUploadChatImageAttachments(
attachments: ReadonlyArray<DraftComposerImageAttachment>,
): ReadonlyArray<UploadChatImageAttachment> {
return attachments.map((attachment) => ({
type: attachment.type,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
dataUrl: attachment.dataUrl,
}));
export const IMAGE_ATTACH_UNAVAILABLE_MESSAGE = "Image attach needs an app update.";
/**
* Copy for legacy draft/outbox images that predate the contract change and so
* cannot be sent. Returns null when there is nothing to warn about.
*/
export function droppedAttachmentsWarning(count: number): string | null {
if (count <= 0) {
return null;
}
const subject = count === 1 ? "1 image was" : `${count} images were`;
return `${subject} not sent. ${IMAGE_ATTACH_UNAVAILABLE_MESSAGE}`;
}
/**
* Mobile has no upload-on-attach implementation yet (web shipped first), and
* the old data-url path is gone from the contract. Capture stays disabled
* until the mobile port lands; flip this back on with that change.
*/
const IMAGE_ATTACH_ENABLED: boolean = false;
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
async function loadImagePicker() {
@@ -46,6 +63,10 @@ export async function pickComposerImages(input: { readonly existingCount: number
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
readonly error: string | null;
}> {
if (!IMAGE_ATTACH_ENABLED) {
return { images: [], error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
}
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
if (remainingSlots <= 0) {
return {
@@ -137,7 +158,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
if (await clipboard.hasImageAsync()) {
if ((await clipboard.hasImageAsync()) && IMAGE_ATTACH_ENABLED) {
if (remainingSlots <= 0) {
return {
images: [],
@@ -181,14 +202,26 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
};
}
// Reached with attach disabled even when the clipboard holds an image:
// mixed copy payloads (common on iOS) must still paste their text, with
// the image drop surfaced rather than silently swallowed.
if (await clipboard.hasStringAsync()) {
const text = await clipboard.getStringAsync();
const droppedImage = !IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync());
return {
images: [],
text: text.length > 0 ? text : null,
error: text.length > 0 ? null : "Clipboard is empty.",
error: droppedImage
? IMAGE_ATTACH_UNAVAILABLE_MESSAGE
: text.length > 0
? null
: "Clipboard is empty.",
};
}
if (!IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync())) {
// Image-only clipboard while attach is disabled.
return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
}
return {
images: [],
@@ -234,9 +267,19 @@ export function isOwnedPastedImageUri(uri: string): boolean {
export async function convertPastedImagesToAttachments(input: {
readonly uris: ReadonlyArray<string>;
readonly existingCount: number;
}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
}): Promise<{
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
/** Set when pasted images were dropped; callers surface it like a pick error. */
readonly error: string | null;
}> {
const { File } = await import("expo-file-system");
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
// Zero slots while attach is disabled: the loop below still runs so owned
// temporary paste files are deleted, but nothing is decoded or attached.
const remainingSlots = IMAGE_ATTACH_ENABLED
? PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount
: 0;
const error =
!IMAGE_ATTACH_ENABLED && input.uris.length > 0 ? IMAGE_ATTACH_UNAVAILABLE_MESSAGE : null;
const results: DraftComposerImageAttachment[] = [];
for (const [index, uri] of input.uris.entries()) {
@@ -277,5 +320,5 @@ export async function convertPastedImagesToAttachments(input: {
}
}
return results;
return { images: results, error };
}
+69 -1
View File
@@ -126,6 +126,22 @@ describe("nativeMarkdownTextRuns", () => {
]);
});
it.each([
["&#128512;", "😀"],
["&#x1f680;", "🚀"],
["&#9999999999;", "&#9999999999;"],
["&#x110000;", "&#x110000;"],
["&amp;#9999999999;", "&#9999999999;"],
["&amp;#x110000;", "&#x110000;"],
])("normalizes numeric entity %s without throwing", (content, expected) => {
const node: MarkdownNode = {
type: "paragraph",
children: [{ type: "text", content }],
};
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: expected }]);
});
it("reads inline content from nested text nodes", () => {
const node: MarkdownNode = {
type: "paragraph",
@@ -173,6 +189,25 @@ describe("nativeMarkdownDocumentRuns", () => {
]);
});
it("decorates known skill references inside blockquotes", () => {
const node: MarkdownNode = {
type: "blockquote",
children: [
{
type: "paragraph",
children: [{ type: "text", content: "Use $ui for this." }],
},
],
};
expect(nativeMarkdownDocumentRuns(node, [{ name: "ui", displayName: "UI" }])).toContainEqual({
text: "$ui",
role: "body",
skillName: "ui",
skillLabel: "UI",
});
});
it("leaves unknown skill-like text unchanged", () => {
const node: MarkdownNode = {
type: "document",
@@ -328,7 +363,7 @@ describe("nativeMarkdownDocumentRuns", () => {
]);
});
it("includes quotes and fenced code in the same selectable string", () => {
it("preserves quotes and fenced code in document runs", () => {
const node: MarkdownNode = {
type: "document",
children: [
@@ -414,6 +449,39 @@ describe("nativeMarkdownListItemBlocks", () => {
});
describe("nativeMarkdownDocumentChunks", () => {
it("renders plain blockquotes as rich blocks so their marker spans wrapped lines", () => {
const blockquote: MarkdownNode = {
type: "blockquote",
beg: 0,
end: 120,
children: [
{
type: "paragraph",
children: [
{
type: "text",
content:
"Persistent random per-result keys are the strongest design, even when this text wraps.",
},
],
},
],
};
expect(
nativeMarkdownDocumentChunks({
type: "document",
children: [blockquote],
}),
).toEqual([
{
kind: "rich",
key: "rich:blockquote:0:120",
node: blockquote,
},
]);
});
it("keeps headings and plain lists in one selectable document", () => {
const document: MarkdownNode = {
type: "document",
@@ -8,7 +8,7 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
import type { DraftComposerImageAttachment } from "./composerImages";
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
@@ -28,6 +28,11 @@ export interface ProjectThreadStartTurnSpec {
readonly messageId: string;
readonly createdAt: string;
readonly text: string;
/**
* Legacy data-url drafts only. `thread.turn.start` now takes id references
* to uploaded blobs, which mobile cannot mint yet, so these are dropped
* rather than sent. Callers surface `droppedAttachmentsWarning` to the user.
*/
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection: ModelSelection;
readonly runtimeMode: RuntimeMode;
@@ -55,7 +60,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
messageId: MessageId.make(spec.messageId),
role: "user" as const,
text: spec.text,
attachments: toUploadChatImageAttachments(spec.attachments),
attachments: [],
},
modelSelection: spec.modelSelection,
titleSeed: title,
@@ -1,26 +0,0 @@
import { requireNativeView } from "expo";
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
interface NativeHeaderButtonProps extends ViewProps {
readonly label: string;
readonly systemImage: "gearshape" | "square.and.pencil";
readonly onTriggered: (event: NativeSyntheticEvent<Record<string, never>>) => void;
}
const NativeHeaderButton = requireNativeView<NativeHeaderButtonProps>("T3NativeControls");
export function T3HeaderButton(props: {
readonly accessibilityLabel: string;
readonly icon: NativeHeaderButtonProps["systemImage"];
readonly onPress: () => void;
readonly style?: StyleProp<ViewStyle>;
}) {
return (
<NativeHeaderButton
label={props.accessibilityLabel}
onTriggered={props.onPress}
style={[{ width: 44, height: 44 }, props.style]}
systemImage={props.icon}
/>
);
}
+2 -2
View File
@@ -1,9 +1,9 @@
import { isLiquidGlassSupported } from "@callstack/liquid-glass";
import { isGlassEffectAPIAvailable } from "expo-glass-effect";
import { Platform } from "react-native";
import { supportsNativeLiquidGlass } from "../lib/native-glass-capability";
export const NATIVE_LIQUID_GLASS_SUPPORTED = supportsNativeLiquidGlass(
Platform.OS,
isLiquidGlassSupported,
isGlassEffectAPIAvailable(),
);
+28
View File
@@ -0,0 +1,28 @@
import { DynamicColorIOS, Platform, type ColorValue, type ViewStyle } from "react-native";
/**
* One opaque surface for content rendered inside a native form sheet.
*
* UIKit owns the outer sheet material and rounded corners. The presented route
* owns this surface so nested navigators never expose a differently colored
* native container while their screens move.
*/
export const NATIVE_SHEET_SURFACE_COLOR: ColorValue | undefined =
Platform.OS === "ios" ? DynamicColorIOS({ light: "#f2f2f7", dark: "#0e0e0e" }) : undefined;
export const NATIVE_SHEET_SURFACE_CONTENT_STYLE: ViewStyle | undefined =
NATIVE_SHEET_SURFACE_COLOR === undefined
? undefined
: { backgroundColor: NATIVE_SHEET_SURFACE_COLOR };
/**
* Paint the adaptive background on the presented screen itself. Nested stacks
* can stay transparent over this single surface, so a push never exposes an
* unpainted form-sheet host behind the moving child view controllers.
*/
export const FORM_SHEET_PRESENTATION_OPTIONS = {
presentation: "formSheet" as const,
...(NATIVE_SHEET_SURFACE_CONTENT_STYLE === undefined
? null
: { contentStyle: NATIVE_SHEET_SURFACE_CONTENT_STYLE }),
};
@@ -26,6 +26,7 @@ export interface Preferences {
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
readonly autoSettleOnMerge?: boolean;
/**
* Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
* no client-settings sync, so the legacy grouped thread list is opted into
@@ -34,6 +35,8 @@ export interface Preferences {
* default flat list — see `resolveThreadListV2Enabled`.
*/
readonly legacyThreadListEnabled?: boolean;
/** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */
readonly planModeEnabled?: boolean;
}
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
@@ -85,7 +88,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
autoSettleOnMerge?: boolean;
legacyThreadListEnabled?: boolean;
planModeEnabled?: boolean;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -122,9 +127,15 @@ function sanitizePreferences(parsed: Preferences): Preferences {
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.autoSettleOnMerge === "boolean") {
preferences.autoSettleOnMerge = parsed.autoSettleOnMerge;
}
if (typeof parsed.legacyThreadListEnabled === "boolean") {
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
}
if (typeof parsed.planModeEnabled === "boolean") {
preferences.planModeEnabled = parsed.planModeEnabled;
}
return preferences;
}
+122 -4
View File
@@ -1,14 +1,23 @@
import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts";
import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
import type {
EnvironmentId,
OrchestrationThread,
ThreadId,
VcsListRefsResult,
VcsRef,
} from "@t3tools/contracts";
import {
createThreadSearchResultsAtomFamily,
makeThreadSearchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { useAtomValue } from "@effect/atom-react";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
import { Atom } from "effect/unstable/reactivity";
import { useEffect, useMemo, useState } from "react";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useState } from "react";
import { appAtomRegistry } from "./atom-registry";
import { orchestrationEnvironment } from "./orchestration";
import { projectEnvironment } from "./projects";
import { useEnvironmentQuery } from "./query";
@@ -24,6 +33,8 @@ const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
const COMPOSER_PATH_SEARCH_LIMIT = 20;
const THREAD_SEARCH_DEBOUNCE_MS = 200;
const VCS_REF_LIST_LIMIT = 100;
const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
const INITIAL_BRANCH_CURSORS = [undefined] as const;
const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
matches: EMPTY_THREAD_SEARCH_MATCHES,
@@ -52,7 +63,7 @@ export interface ComposerPathSearchTarget {
readonly query: string | null;
}
function useDebouncedValue<A>(value: A, delayMs: number): A {
export function useDebouncedValue<A>(value: A, delayMs: number): A {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
@@ -125,6 +136,113 @@ export function useBranches(input: {
);
}
export function usePaginatedBranches(target: VcsRefTarget) {
const query = target.query?.trim() ?? "";
const targetKey =
target.environmentId !== null && target.cwd !== null
? JSON.stringify([target.environmentId, target.cwd, query])
: null;
const [pagination, setPagination] = useState<{
readonly targetKey: string | null;
readonly cursors: ReadonlyArray<number | undefined>;
}>({
targetKey,
cursors: INITIAL_BRANCH_CURSORS,
});
const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
const pageAtoms = useMemo(
() =>
target.environmentId !== null && target.cwd !== null
? cursors.map((cursor) =>
vcsEnvironment.listRefs({
environmentId: target.environmentId!,
input: {
cwd: target.cwd!,
...(query.length > 0 ? { query } : {}),
...(cursor === undefined ? {} : { cursor }),
limit: VCS_REF_LIST_LIMIT,
},
}),
)
: [],
[cursors, query, target.cwd, target.environmentId],
);
const pagesAtom = useMemo(
() =>
Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
),
[pageAtoms, targetKey],
);
const results = useAtomValue(pagesAtom);
const values = results.flatMap((result) => {
const value = Option.getOrNull(AsyncResult.value(result));
return value === null ? [] : [value];
});
const refs = new Map<string, VcsRef>();
for (const value of values) {
for (const ref of value.refs) {
refs.set(ref.name, ref);
}
}
const first = values[0] ?? null;
const last = values.at(-1) ?? null;
const data: VcsListRefsResult | null =
first === null || last === null
? null
: {
refs: [...refs.values()],
isRepo: first.isRepo,
hasPrimaryRemote: first.hasPrimaryRemote,
nextCursor: last.nextCursor,
totalCount: Math.max(...values.map((value) => value.totalCount)),
};
const lastResult = results.at(-1);
const isFetchingNextPage =
results.length > 1 &&
lastResult?.waiting === true &&
Option.isNone(AsyncResult.value(lastResult));
const failed = results.find((result) => result._tag === "Failure");
const error =
failed?._tag === "Failure"
? (() => {
const cause = Cause.squash(failed.cause);
return cause instanceof Error && cause.message.trim().length > 0
? cause.message
: "Failed to load refs.";
})()
: null;
const refresh = useCallback(() => {
const firstPage = pageAtoms[0];
setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
if (firstPage !== undefined) {
appAtomRegistry.refresh(firstPage);
}
}, [pageAtoms, targetKey]);
const loadNext = useCallback(() => {
if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
return;
}
setPagination((current) => {
const currentCursors =
current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
return currentCursors.includes(data.nextCursor!)
? { targetKey, cursors: currentCursors }
: { targetKey, cursors: [...currentCursors, data.nextCursor!] };
});
}, [data?.nextCursor, targetKey]);
return {
data,
refs: data?.refs ?? EMPTY_REFS,
error,
isPending: results.some((result) => result.waiting),
isFetchingNextPage,
refresh,
loadNext,
};
}
export function useComposerPathSearch(target: ComposerPathSearchTarget) {
const normalizedTarget = useMemo(
() => ({
@@ -1,10 +1,57 @@
import { afterEach, describe, expect, it } from "@effect/vitest";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { vi } from "vite-plus/test";
const composerDraftFileMocks = vi.hoisted(() => {
let document = "";
let releaseRead: (() => void) | null = null;
let readBarrier = Promise.resolve();
return {
blockRead() {
readBarrier = new Promise<void>((resolve) => {
releaseRead = resolve;
});
},
releaseRead() {
releaseRead?.();
releaseRead = null;
},
setDocument(value: unknown) {
document = JSON.stringify(value);
},
Directory: class {
create() {}
},
File: class {
exists = true;
create() {}
async text() {
await readBarrier;
return document;
}
write(value: string) {
document = value;
}
},
};
});
vi.mock("expo-file-system", () => ({
Directory: composerDraftFileMocks.Directory,
File: composerDraftFileMocks.File,
Paths: { document: "/documents" },
}));
import { appAtomRegistry } from "./atom-registry";
import {
clearComposerDraftContentState,
composerDraftsAtom,
copyComposerDraftContentIfEmpty,
copyComposerDraftContentState,
decodePersistedComposerDrafts,
type ComposerDraft,
getComposerDraftSnapshot,
@@ -165,6 +212,53 @@ describe("mobile composer drafts", () => {
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
});
it("carries unfinished content to a newly selected project without overwriting its settings", () => {
const sourceKey = "new-task:environment-1:project-1";
const targetKey = "new-task:environment-1:project-2";
const source: ComposerDraft = {
text: "Keep this task",
attachments: [],
importedShareIds: ["share-1"],
workspaceSelection: {
mode: "worktree",
branch: "feature/source",
worktreePath: null,
},
};
const target: ComposerDraft = {
text: "",
attachments: [],
runtimeMode: "approval-required",
};
expect(
copyComposerDraftContentState(
{ [sourceKey]: source, [targetKey]: target },
sourceKey,
targetKey,
),
).toEqual({
[sourceKey]: source,
[targetKey]: {
...target,
text: source.text,
attachments: source.attachments,
importedShareIds: source.importedShareIds,
},
});
});
it("does not overwrite unfinished content already stored for the selected project", () => {
const sourceKey = "new-task:environment-1:project-1";
const targetKey = "new-task:environment-1:project-2";
const drafts: Record<string, ComposerDraft> = {
[sourceKey]: { text: "Source task", attachments: [] },
[targetKey]: { text: "Target task", attachments: [] },
};
expect(copyComposerDraftContentState(drafts, sourceKey, targetKey)).toBe(drafts);
});
it("merges shared content into a project draft without duplicating retries", () => {
const draftKey = "new-task:environment-1:project-1";
const sharedAttachment = {
@@ -268,4 +362,35 @@ describe("mobile composer drafts", () => {
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
});
});
it("waits for persisted drafts before copying content between projects", async () => {
const sourceKey = "new-task:environment-1:project-1";
const targetKey = "new-task:environment-1:project-2";
const unrelatedKey = "environment-1:thread-1";
const source = { text: "Current task", attachments: [] } satisfies ComposerDraft;
const target = { text: "Persisted target", attachments: [] } satisfies ComposerDraft;
const unrelated = { text: "Keep me", attachments: [] } satisfies ComposerDraft;
composerDraftFileMocks.setDocument({
schemaVersion: 1,
drafts: {
[targetKey]: target,
[unrelatedKey]: unrelated,
},
});
composerDraftFileMocks.blockRead();
appAtomRegistry.set(composerDraftsAtom, { [sourceKey]: source });
const copy = copyComposerDraftContentIfEmpty(sourceKey, targetKey);
expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ [sourceKey]: source });
composerDraftFileMocks.releaseRead();
await copy;
expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
[sourceKey]: source,
[targetKey]: target,
[unrelatedKey]: unrelated,
});
});
});
+50 -1
View File
@@ -253,7 +253,11 @@ export function ensureComposerDraftsLoaded(): void {
function updateComposerDrafts(
update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
): void {
const next = update(appAtomRegistry.get(composerDraftsAtom));
const current = appAtomRegistry.get(composerDraftsAtom);
const next = update(current);
if (next === current) {
return;
}
appAtomRegistry.set(composerDraftsAtom, next);
schedulePersistComposerDrafts(next);
}
@@ -412,6 +416,51 @@ export function restoreComposerDraftSnapshotState(
return next;
}
export function copyComposerDraftContentState(
current: Record<string, ComposerDraft>,
sourceDraftKey: string,
targetDraftKey: string,
): Record<string, ComposerDraft> {
if (sourceDraftKey === targetDraftKey) {
return current;
}
const source = normalizeDraft(current[sourceDraftKey]);
const target = normalizeDraft(current[targetDraftKey]);
const sourceHasContent =
source.text.length > 0 ||
source.attachments.length > 0 ||
(source.importedShareIds?.length ?? 0) > 0;
const targetHasContent =
target.text.length > 0 ||
target.attachments.length > 0 ||
(target.importedShareIds?.length ?? 0) > 0;
if (!sourceHasContent || targetHasContent) {
return current;
}
return {
...current,
[targetDraftKey]: {
...target,
text: source.text,
attachments: source.attachments,
...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),
},
};
}
export async function copyComposerDraftContentIfEmpty(
sourceDraftKey: string,
targetDraftKey: string,
): Promise<void> {
ensureComposerDraftsLoaded();
if (loadPromise !== null) {
await loadPromise;
}
updateComposerDrafts((current) =>
copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),
);
}
function mergeComposerDraftText(existing: string, incoming: string): string {
if (incoming.length === 0) {
return existing;
@@ -238,12 +238,15 @@ export function useThreadComposerState() {
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
try {
const images = await convertPastedImagesToAttachments({
const pasted = await convertPastedImagesToAttachments({
uris,
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
});
if (images.length > 0) {
appendComposerDraftAttachments(threadKey, images);
if (pasted.images.length > 0) {
appendComposerDraftAttachments(threadKey, pasted.images);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
}
} catch (error) {
console.error("[native paste] error converting images", {
@@ -17,7 +17,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { scopedThreadKey } from "../lib/scopedEntities";
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
import { toUploadChatImageAttachments } from "../lib/composerImages";
import { droppedAttachmentsWarning } from "../lib/composerImages";
import { randomHex } from "../lib/uuid";
import { appAtomRegistry } from "./atom-registry";
import { useProjects, useThreadShells } from "./entities";
@@ -44,7 +44,10 @@ import {
useThreadOutboxMessages,
useThreadOutboxShellStatuses,
} from "./use-thread-outbox";
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
import {
setPendingConnectionError,
useRemoteConnectionStatus,
} from "./use-remote-environment-registry";
export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
Atom.keepAlive,
@@ -149,6 +152,14 @@ export function useThreadOutboxDrain(): void {
return false;
}
// Messages queued before the attachment contract change can still hold
// data-url images. They are never put on the wire, so tell the user the
// text went without them instead of dropping them silently.
const droppedWarning = droppedAttachmentsWarning(queuedMessage.attachments.length);
if (droppedWarning !== null) {
setPendingConnectionError(droppedWarning);
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
@@ -226,7 +237,7 @@ export function useThreadOutboxDrain(): void {
messageId: queuedMessage.messageId,
role: "user",
text: queuedMessage.text,
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
attachments: [],
},
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
@@ -0,0 +1,106 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { parseThreadSegmentFromAttachmentId } from "../attachmentStore.ts";
import {
deletePendingAttachment,
issueAttachmentUploadUrl,
storeAttachmentUpload,
validateAttachmentUploadToken,
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
} from "./AttachmentUpload.ts";
const testLayer = ServerSecretStore.layer.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-upload-" })),
Layer.provideMerge(NodeServices.layer),
);
const uploadInput = {
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 6,
} as const;
describe("AttachmentUpload", () => {
it.effect("mints a pending id and a token that validates round-trip", () =>
Effect.gen(function* () {
const issued = yield* issueAttachmentUploadUrl(uploadInput);
expect(parseThreadSegmentFromAttachmentId(issued.attachmentId)).toBe("pending");
expect(issued.relativeUrl.startsWith(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`)).toBe(true);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const claims = yield* validateAttachmentUploadToken(token);
expect(claims).toMatchObject({
kind: "attachment-upload",
attachmentId: issued.attachmentId,
mimeType: "image/png",
sizeBytes: 6,
});
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects a tampered token", () =>
Effect.gen(function* () {
const issued = yield* issueAttachmentUploadUrl(uploadInput);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const [payload, signature] = token.split(".");
const tampered = `${payload}x.${signature}`;
expect(yield* validateAttachmentUploadToken(tampered)).toBeNull();
expect(yield* validateAttachmentUploadToken("garbage")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("stores matching bytes and rejects a size mismatch", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const issued = yield* issueAttachmentUploadUrl(uploadInput);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const claims = yield* validateAttachmentUploadToken(token);
if (!claims) throw new Error("expected valid claims");
const short = yield* storeAttachmentUpload(claims, new Uint8Array([1, 2, 3]));
expect(short).toMatchObject({ ok: false, status: 400 });
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(6));
expect(stored).toEqual({ ok: true });
const finalPath = NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`);
expect(NodeFS.existsSync(finalPath)).toBe(true);
// No .part residue after a successful store (suffix is per-request).
const partResidue = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
entry.endsWith(".part"),
);
expect(partResidue).toEqual([]);
}).pipe(Effect.provide(testLayer)),
);
it.effect("deletes pending uploads idempotently but never thread-scoped files", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
const uuid = "00000000-0000-4000-8000-0000000000dd";
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${uuid}.png`);
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
yield* deletePendingAttachment(`pending-${uuid}`);
expect(NodeFS.existsSync(pendingPath)).toBe(false);
// Second delete is a no-op, not an error.
yield* deletePendingAttachment(`pending-${uuid}`);
const scopedUuid = "00000000-0000-4000-8000-0000000000ee";
const scopedPath = NodePath.join(config.attachmentsDir, `thread-1-${scopedUuid}.png`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
// A delete aimed at a claimed attachment must not remove it.
yield* deletePendingAttachment(`pending-${scopedUuid}`);
yield* deletePendingAttachment(`thread-1-${scopedUuid}`);
expect(NodeFS.existsSync(scopedPath)).toBe(true);
}).pipe(Effect.provide(testLayer)),
);
});
+221
View File
@@ -0,0 +1,221 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import {
ATTACHMENT_UPLOAD_URL_TTL_MS,
type AttachmentCreateUploadUrlInput,
AttachmentUploadSigningKeyError,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
createPendingAttachmentId,
findAttachmentPathByUuid,
parseAttachmentIdFromRelativePath,
parseAttachmentUuid,
parseThreadSegmentFromAttachmentId,
PENDING_ATTACHMENT_THREAD_SEGMENT,
} from "../attachmentStore.ts";
import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
signPayload,
timingSafeEqualBase64Url,
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import { inferImageExtension } from "../imageMime.ts";
export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
// Shares the asset-access secret: upload and asset claims are distinguished
// by their schema `kind`, so a token minted for one can never validate as
// the other, and one key covers both signing uses.
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const UploadClaimsSchema = Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment-upload"),
attachmentId: Schema.String,
mimeType: Schema.String,
/** Exact byte count the client committed to at mint time. */
sizeBytes: Schema.Number,
expiresAt: Schema.Number,
});
export type AttachmentUploadClaims = typeof UploadClaimsSchema.Type;
const UploadClaimsJson = Schema.fromJsonString(UploadClaimsSchema);
const decodeUploadClaimsOption = Schema.decodeUnknownOption(UploadClaimsJson);
const encodeUploadClaims = Schema.encodeSync(UploadClaimsJson);
// Plain function (not Effect) so the base64/JSON failure modes stay a simple
// null, mirroring AssetAccess.decodeClaims.
function decodeUploadClaims(encodedPayload: string): AttachmentUploadClaims | null {
try {
return Option.getOrNull(decodeUploadClaimsOption(base64UrlDecodeUtf8(encodedPayload)));
} catch {
return null;
}
}
const loadSigningSecret = Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
});
/**
* Mints the `pending-<uuid>` id and a signed, expiring upload URL for it.
* Called over the authenticated ws; the returned URL itself carries
* authorization (mirroring signed asset GET URLs), which is what lets the
* browser POST bytes to any environment without extra credential plumbing.
*/
export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
input: AttachmentCreateUploadUrlInput,
) {
const secret = yield* loadSigningSecret.pipe(
Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
);
const attachmentId = createPendingAttachmentId();
const expiresAt = (yield* Clock.currentTimeMillis) + ATTACHMENT_UPLOAD_URL_TTL_MS;
const encodedPayload = base64UrlEncode(
encodeUploadClaims({
version: 1,
kind: "attachment-upload",
attachmentId,
mimeType: input.mimeType.toLowerCase(),
sizeBytes: input.sizeBytes,
expiresAt,
}),
);
const token = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
return {
attachmentId,
relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${token}`,
expiresAt,
};
});
/** Verifies signature and expiry; null means "treat as not found". */
export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validateToken")(function* (
token: string,
) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) return null;
const secret = yield* loadSigningSecret.pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to load the attachment upload signing key.", { cause }),
),
Effect.orElseSucceed(() => null),
);
if (!secret) return null;
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) return null;
const claims = decodeUploadClaims(encodedPayload);
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
return claims;
});
export type StoreUploadResult =
| { readonly ok: true }
| { readonly ok: false; readonly status: number; readonly detail: string };
/**
* Persists validated upload bytes. Writes to `<id>.<ext>.part` first and
* renames on success, so a crashed or aborted upload can never leave a file
* that looks like a complete attachment. Re-running with the same token
* overwrites atomically, which makes client retries safe.
*/
export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
claims: AttachmentUploadClaims,
bytes: Uint8Array,
) {
if (bytes.byteLength !== claims.sizeBytes) {
return {
ok: false,
status: 400,
detail: `Body was ${bytes.byteLength} bytes, expected ${claims.sizeBytes}.`,
} satisfies StoreUploadResult;
}
const config = yield* ServerConfig.ServerConfig;
const extension = inferImageExtension({ mimeType: claims.mimeType });
const relativePath = `${claims.attachmentId}${extension}`;
const finalPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath,
});
// Unique per request: two concurrent POSTs of the same token must not
// interleave writes into one temp file. Both rename onto the final path
// atomically; last one wins with identical claims-validated content.
const partPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`,
});
if (!finalPath || !partPath) {
return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
}
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const writeResult = yield* Effect.gen(function* () {
yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
yield* fileSystem.writeFile(partPath, bytes);
yield* fileSystem.rename(partPath, finalPath);
}).pipe(
Effect.as({ ok: true } satisfies StoreUploadResult),
Effect.tapError((cause) =>
Effect.logError("Failed to persist attachment upload.", {
attachmentId: claims.attachmentId,
cause,
}),
),
Effect.orElseSucceed(
() =>
({
ok: false,
status: 500,
detail: "Failed to persist upload.",
}) satisfies StoreUploadResult,
),
);
return writeResult;
});
/**
* Deletes a never-sent upload. Idempotent, and refuses (as a silent no-op)
* anything already claimed by a thread: those files are owned by their
* message and only die with the thread.
*/
export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* (
attachmentId: string,
) {
if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
return;
}
const uuid = parseAttachmentUuid(attachmentId);
if (!uuid) return;
const config = yield* ServerConfig.ServerConfig;
const filePath = findAttachmentPathByUuid({ attachmentsDir: config.attachmentsDir, uuid });
if (!filePath) return;
const path = yield* Path.Path;
const foundId = parseAttachmentIdFromRelativePath(path.basename(filePath));
if (
!foundId ||
parseThreadSegmentFromAttachmentId(foundId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
) {
return;
}
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.remove(filePath).pipe(
Effect.catch(
() =>
// Raced with the sweep or a duplicate delete; idempotent by design.
Effect.void,
),
);
});
+160 -4
View File
@@ -7,10 +7,19 @@ import { describe, expect, it } from "vite-plus/test";
import {
createAttachmentId,
createPendingAttachmentId,
parseThreadSegmentFromAttachmentId,
planAttachmentClaim,
resolveAttachmentPathById,
sweepStalePendingAttachments,
toSafeThreadAttachmentSegment,
PENDING_ATTACHMENT_MAX_AGE_MS,
} from "./attachmentStore.ts";
function makeTempAttachmentsDir(): string {
return NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"));
}
describe("attachmentStore", () => {
it("sanitizes thread ids when creating attachment ids", () => {
const attachmentId = createAttachmentId("thread.folder/unsafe space");
@@ -45,11 +54,9 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
const attachmentsDir = makeTempAttachmentsDir();
try {
const attachmentId = "thread-1-attachment";
const attachmentId = "thread-1-00000000-0000-4000-8000-00000000000a";
const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
@@ -63,6 +70,155 @@ describe("attachmentStore", () => {
}
});
it("resolves a pending id to the renamed thread-scoped file after claim", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const uuid = "00000000-0000-4000-8000-00000000000b";
const scopedPath = NodePath.join(attachmentsDir, `thread-9-${uuid}.png`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
// Old signed asset URLs carry the pending id; they must keep resolving.
const resolved = resolveAttachmentPathById({
attachmentsDir,
attachmentId: `pending-${uuid}`,
});
expect(resolved).toBe(scopedPath);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("reserves the pending segment for uploads", () => {
expect(toSafeThreadAttachmentSegment("pending")).toBe("pending_thread");
const pendingId = createPendingAttachmentId();
expect(parseThreadSegmentFromAttachmentId(pendingId)).toBe("pending");
});
describe("planAttachmentClaim", () => {
const uuid = "00000000-0000-4000-8000-00000000000c";
it("plans a rename for a pending attachment", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.webp`);
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toEqual({
ok: true,
finalId: `thread-foo-${uuid}`,
currentPath: pendingPath,
finalPath: NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`),
alreadyScoped: false,
});
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("is idempotent when a retry references an already-renamed file", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const scopedPath = NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: true, alreadyScoped: true });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("refuses an attachment claimed by another thread", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
NodeFS.writeFileSync(
NodePath.join(attachmentsDir, `other-thread-${uuid}.png`),
Buffer.from("pixels"),
);
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: false });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("reports a missing attachment", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: false });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
describe("sweepStalePendingAttachments", () => {
it("deletes stale pending and partial files, keeps fresh and scoped ones", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const stalePending = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000001.png",
);
const freshPending = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000002.png",
);
const scoped = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000003.png",
);
const stalePart = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000004.png.part",
);
// Fixed epoch so the test never touches the real clock: files are
// stamped relative to `nowMs` below, not to wall time.
const nowMs = 1_800_000_000_000;
const freshMs = nowMs - 60_000;
const staleMs = nowMs - PENDING_ATTACHMENT_MAX_AGE_MS - 60_000;
for (const filePath of [stalePending, freshPending, scoped, stalePart]) {
NodeFS.writeFileSync(filePath, Buffer.from("x"));
}
NodeFS.utimesSync(freshPending, freshMs / 1000, freshMs / 1000);
NodeFS.utimesSync(stalePending, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(scoped, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(stalePart, staleMs / 1000, staleMs / 1000);
const swept = sweepStalePendingAttachments({
attachmentsDir,
nowMs,
});
expect(swept.deleted).toBe(2);
expect(NodeFS.existsSync(stalePending)).toBe(false);
expect(NodeFS.existsSync(stalePart)).toBe(false);
expect(NodeFS.existsSync(freshPending)).toBe(true);
expect(NodeFS.existsSync(scoped)).toBe(true);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
+175 -10
View File
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import type { ChatAttachment } from "@t3tools/contracts";
@@ -8,9 +9,8 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
import { inferImageExtension } from "./imageMime.ts";
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -19,6 +19,13 @@ const ATTACHMENT_ID_PATTERN = new RegExp(
"i",
);
/**
* Segment used for attachments uploaded before their thread exists
* (upload-on-attach). Files named `pending-<uuid>.<ext>` are re-scoped to the
* thread at turn start and swept when stale.
*/
export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
const segment = threadId
.trim()
@@ -31,9 +38,65 @@ export function toSafeThreadAttachmentSegment(threadId: string): string | null {
if (segment.length === 0) {
return null;
}
// `pending` is reserved for not-yet-sent uploads; a thread that slugged to
// it would have its attachments swept as orphans.
if (segment === PENDING_ATTACHMENT_THREAD_SEGMENT) {
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}_thread`;
}
return segment;
}
export function createPendingAttachmentId(): string {
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}`;
}
/** Extracts the trailing uuid from a `<segment>-<uuid>` attachment id. */
export function parseAttachmentUuid(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
return match?.[2]?.toLowerCase() ?? null;
}
/**
* Finds the on-disk file for an attachment uuid regardless of its current
* segment (`pending-` before send, thread-scoped after). The uuid is the
* stable identity: turn-start renames the file's segment but never the uuid,
* which is what keeps send retries and signed asset URLs working across the
* rename.
*/
export function findAttachmentPathByUuid(input: {
readonly attachmentsDir: string;
readonly uuid: string;
}): string | null {
const uuid = input.uuid.toLowerCase();
if (!new RegExp(`^${ATTACHMENT_ID_UUID_PATTERN}$`, "i").test(uuid)) {
return null;
}
let entries: string[];
try {
entries = NodeFS.readdirSync(input.attachmentsDir);
} catch {
return null;
}
const suffixPattern = new RegExp(`-${uuid}\\.[a-z0-9]{1,8}$`, "i");
for (const entry of entries) {
if (!suffixPattern.test(entry)) {
continue;
}
const resolved = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: entry,
});
if (resolved && NodeFS.existsSync(resolved)) {
return resolved;
}
}
return null;
}
export function createAttachmentId(threadId: string): string | null {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
@@ -80,20 +143,122 @@ export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
// Resolution is by uuid, not by exact id: a signed asset URL minted for a
// `pending-` id must keep working after turn start renames the file to its
// thread segment (draft previews hold such URLs across a send).
const uuid = parseAttachmentUuid(input.attachmentId);
if (!uuid) {
return null;
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
return findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
}
export type AttachmentClaimPlan =
| {
readonly ok: true;
readonly finalId: string;
readonly currentPath: string;
readonly finalPath: string;
/** True when a prior (possibly failed) send already renamed the file. */
readonly alreadyScoped: boolean;
}
| { readonly ok: false; readonly reason: string };
/**
* Plans the pending-to-thread re-scope for one referenced attachment at turn
* start. Pure path logic; the caller performs the rename. The uuid is matched
* against whatever segment the file currently has so retries after a partial
* send are idempotent, and a file already claimed by a different thread is
* refused rather than stolen.
*/
export function planAttachmentClaim(input: {
readonly attachmentsDir: string;
readonly threadId: string;
readonly attachmentId: string;
}): AttachmentClaimPlan {
const uuid = parseAttachmentUuid(input.attachmentId);
if (!uuid) {
return { ok: false, reason: "invalid attachment id" };
}
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
if (!threadSegment) {
return { ok: false, reason: "invalid thread id" };
}
const currentPath = findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
if (!currentPath) {
return { ok: false, reason: "attachment not found (removed or expired)" };
}
const fileName = NodePath.basename(currentPath);
const currentId = parseAttachmentIdFromRelativePath(fileName);
const currentSegment = currentId ? parseThreadSegmentFromAttachmentId(currentId) : null;
if (!currentSegment) {
return { ok: false, reason: "attachment file name is malformed" };
}
const extension = NodePath.extname(fileName);
const finalId = `${threadSegment}-${uuid}`;
if (currentSegment === threadSegment) {
return { ok: true, finalId, currentPath, finalPath: currentPath, alreadyScoped: true };
}
if (currentSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
return { ok: false, reason: "attachment belongs to another thread" };
}
const finalPath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${finalId}${extension}`,
});
if (!finalPath) {
return { ok: false, reason: "failed to resolve attachment path" };
}
return { ok: true, finalId, currentPath, finalPath, alreadyScoped: false };
}
export const PENDING_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
export const PARTIAL_UPLOAD_MAX_AGE_MS = 24 * 60 * 60 * 1000;
/**
* Deletes never-sent uploads (`pending-*`) past their retention window and
* half-written `*.part` files left by aborted uploads. Runs at server start;
* chip removal deletes eagerly, this is the backstop.
*/
export function sweepStalePendingAttachments(input: {
readonly attachmentsDir: string;
readonly nowMs: number;
}): { readonly deleted: number } {
let entries: string[];
try {
entries = NodeFS.readdirSync(input.attachmentsDir);
} catch {
return { deleted: 0 };
}
let deleted = 0;
for (const entry of entries) {
const isPartial = entry.endsWith(".part");
const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
if (!isPartial) {
const id = parseAttachmentIdFromRelativePath(entry);
const segment = id ? parseThreadSegmentFromAttachmentId(id) : null;
if (segment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
continue;
}
}
const resolved = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${normalizedId}${extension}`,
relativePath: entry,
});
if (maybePath && NodeFS.existsSync(maybePath)) {
return maybePath;
if (!resolved) {
continue;
}
try {
const stats = NodeFS.statSync(resolved);
if (input.nowMs - stats.mtimeMs > maxAgeMs) {
NodeFS.unlinkSync(resolved);
deleted += 1;
}
} catch {
// Raced with a concurrent delete or an unreadable entry; skip it.
}
}
return null;
return { deleted };
}
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
+2
View File
@@ -83,6 +83,8 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
[WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
+15
View File
@@ -6,6 +6,7 @@
*
* @module ServerConfig
*/
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -14,6 +15,8 @@ import * as LogLevel from "effect/LogLevel";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { sweepStalePendingAttachments } from "./attachmentStore.ts";
export const DEFAULT_PORT = 3773;
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
@@ -152,6 +155,18 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
],
{ concurrency: "unbounded" },
);
// Backstop GC for upload-on-attach: never-sent `pending-*` uploads and
// aborted `*.part` files. Eager deletes happen at chip removal; this covers
// crashed clients and abandoned drafts.
const nowMs = yield* Clock.currentTimeMillis;
const swept = sweepStalePendingAttachments({
attachmentsDir: derivedPaths.attachmentsDir,
nowMs,
});
if (swept.deleted > 0) {
yield* Effect.logInfo("Swept stale pending attachments.", { deleted: swept.deleted });
}
});
const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
+45
View File
@@ -28,6 +28,11 @@ import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import {
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
storeAttachmentUpload,
validateAttachmentUploadToken,
} from "./assets/AttachmentUpload.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
@@ -226,6 +231,46 @@ export const assetRouteLayer = HttpRouter.add(
}),
);
export const attachmentUploadRouteLayer = HttpRouter.add(
"POST",
`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
if (token.length === 0) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
// Invalid, tampered, and expired tokens are indistinguishable from
// missing ones on purpose, matching the signed asset GET route.
const claims = yield* validateAttachmentUploadToken(token);
if (!claims) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const contentLength = Number(request.headers["content-length"] ?? "");
if (!Number.isInteger(contentLength) || contentLength !== claims.sizeBytes) {
return HttpServerResponse.text("Content-Length must match the minted upload size.", {
status: 400,
});
}
const body = yield* request.arrayBuffer.pipe(Effect.orElseSucceed(() => null));
if (body === null) {
return HttpServerResponse.text("Failed to read the upload body.", { status: 400 });
}
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(body));
return stored.ok
? HttpServerResponse.empty({ status: 204 })
: HttpServerResponse.text(stored.detail, { status: stored.status });
}),
);
export const staticAndDevRouteLayer = HttpRouter.add(
"GET",
"*",
+9 -81
View File
@@ -1,92 +1,20 @@
import { describe, expect, it } from "vite-plus/test";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
import { inferImageExtension } from "./imageMime.ts";
describe("imageMime", () => {
it("parses base64 data URL with mime type", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
it("maps known image mime types to extensions", () => {
expect(inferImageExtension({ mimeType: "image/png" })).toBe(".png");
expect(inferImageExtension({ mimeType: "image/jpeg" })).toBe(".jpg");
expect(inferImageExtension({ mimeType: "IMAGE/WEBP" })).toBe(".webp");
});
it("parses base64 data URL with mime parameters", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
it("falls back to a safe file name extension", () => {
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.PNG" })).toBe(".png");
});
it("rejects non-base64 data URL", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
});
it("rejects missing mime type", () => {
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
});
it("parses base64 data URL with spaces in payload", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("rejects payload with characters outside the base64 alphabet", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
});
it("rejects structurally malformed base64", () => {
// '=' before the trailing padding position
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
// more than two padding characters
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
// length not a multiple of 4
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
});
it("accepts base64 with one or two trailing padding characters", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
mimeType: "image/png",
base64: "SGVsbA==",
});
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8h",
});
});
it("rejects empty and whitespace-only payloads", () => {
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
});
it("parses a case-insensitive scheme and mime type", () => {
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("parses a multi-megabyte payload from a deep call stack", () => {
// Regression: matching the payload with a regex borrowed the JS call
// stack, so a ~10 MB image parsed inside fiber execution threw
// "RangeError: Maximum call stack size exceeded".
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
const findMaxDepth = (depth: number): number => {
try {
return findMaxDepth(depth + 1);
} catch {
return depth;
}
};
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
expect(result?.mimeType).toBe("image/png");
expect(result?.base64.length).toBe(14_000_000);
it("falls back to .bin when nothing safe matches", () => {
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.exe" })).toBe(".bin");
});
it("does not read inherited keys from mime extension map", () => {
-83
View File
@@ -29,89 +29,6 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
".webp",
]);
// Whether `code` is a character the base64 payload may contain, aside from
// the whitespace handled separately below.
function isBase64Char(code: number): boolean {
return (
(code >= 0x61 && code <= 0x7a) || // a-z
(code >= 0x41 && code <= 0x5a) || // A-Z
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x2b || // +
code === 0x2f || // /
code === 0x3d // =
);
}
function isBase64Whitespace(code: number): boolean {
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
}
// Data URLs carry the full image payload, so this parser must never run a
// regex across the payload: V8's regex engine borrows the JS call stack, and
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
// execution) throws "Maximum call stack size exceeded".
export function parseBase64DataUrl(
dataUrl: string,
): { readonly mimeType: string; readonly base64: string } | null {
const trimmed = dataUrl.trim();
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
const commaIndex = trimmed.indexOf(",");
if (commaIndex === -1) return null;
const header = trimmed.slice(5, commaIndex);
if (header.length === 0) return null;
const headerParts: Array<string> = [];
for (const part of header.split(";")) {
const partTrimmed = part.trim();
if (partTrimmed.length > 0) {
headerParts.push(partTrimmed);
}
}
if (headerParts.length < 2) {
return null;
}
const trailingToken = headerParts.at(-1)?.toLowerCase();
if (trailingToken !== "base64") {
return null;
}
const mimeType = headerParts[0]?.toLowerCase();
if (!mimeType) return null;
const payload = trimmed.slice(commaIndex + 1);
const runs: Array<string> = [];
let runStart = -1;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (isBase64Char(code)) {
if (runStart === -1) runStart = index;
continue;
}
if (!isBase64Whitespace(code)) return null;
if (runStart !== -1) {
runs.push(payload.slice(runStart, index));
runStart = -1;
}
}
if (runStart !== -1) {
runs.push(payload.slice(runStart));
}
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
if (base64.length === 0 || base64.length % 4 !== 0) return null;
const firstPad = base64.indexOf("=");
if (firstPad !== -1) {
// '=' is only valid as one or two trailing padding characters; Node's
// decoder would otherwise silently truncate at the first '='.
if (base64.length - firstPad > 2) return null;
for (let index = firstPad; index < base64.length; index += 1) {
if (base64.charCodeAt(index) !== 0x3d) return null;
}
}
return { mimeType, base64 };
}
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
const key = input.mimeType.toLowerCase();
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
@@ -0,0 +1,138 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import {
type ClientOrchestrationCommand,
CommandId,
MessageId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { normalizeDispatchCommand } from "./Normalizer.ts";
const testLayer = Layer.mergeAll(
WorkspacePaths.layer,
ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-attachments-" }),
).pipe(Layer.provideMerge(NodeServices.layer));
const UUID = "00000000-0000-4000-8000-0000000000aa";
function turnStartCommand(attachment: {
readonly id: string;
readonly sizeBytes: number;
}): ClientOrchestrationCommand {
return {
type: "thread.turn.start",
commandId: CommandId.make("command-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-1"),
role: "user",
text: "look at this",
attachments: [
{
type: "image",
id: attachment.id,
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: attachment.sizeBytes,
},
],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: "2026-08-01T00:00:00.000Z",
};
}
describe("normalizeDispatchCommand attachments", () => {
it.effect("claims a pending upload: renames the file and rewrites the id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${UUID}.png`);
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(pendingPath, bytes);
const normalized = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
);
if (normalized.type !== "thread.turn.start") {
throw new Error("Expected a thread.turn.start command");
}
expect(normalized.message.attachments).toHaveLength(1);
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
expect(NodeFS.existsSync(pendingPath)).toBe(false);
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`))).toBe(
true,
);
}).pipe(Effect.provide(testLayer)),
);
it.effect("is idempotent when a retry references an already-claimed file", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`), bytes);
// The retry still carries the original pending id.
const normalized = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
);
if (normalized.type !== "thread.turn.start") {
throw new Error("Expected a thread.turn.start command");
}
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
}).pipe(Effect.provide(testLayer)),
);
it.effect("fails when the referenced upload does not exist", () =>
Effect.gen(function* () {
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 6 }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("not found");
}).pipe(Effect.provide(testLayer)),
);
it.effect("fails when the stored size does not match the reference", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(
NodePath.join(config.attachmentsDir, `pending-${UUID}.png`),
Buffer.from("pixels"),
);
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 999 }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("size");
}).pipe(Effect.provide(testLayer)),
);
it.effect("refuses an attachment already claimed by another thread", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `other-thread-${UUID}.png`), bytes);
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("another thread");
}).pipe(Effect.provide(testLayer)),
);
});
+36 -50
View File
@@ -1,18 +1,15 @@
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import {
type ClientOrchestrationCommand,
type IsoDateTime,
type OrchestrationCommand,
OrchestrationDispatchCommandError,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
import { planAttachmentClaim } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { parseBase64DataUrl } from "../imageMime.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const canonicalizeClientCommandTimestamps = (
@@ -48,7 +45,6 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
const receivedAt = DateTime.formatIso(yield* DateTime.now);
const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
@@ -104,67 +100,57 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
return canonicalCommand as OrchestrationCommand;
}
// Attachments arrive as id references to bytes already uploaded via the
// signed upload URL flow. Each `pending-<uuid>` file is renamed to its
// thread segment here; the uuid never changes, so signed asset URLs and
// send retries (which may reference an already-renamed file) keep working.
const normalizedAttachments = yield* Effect.forEach(
canonicalCommand.message.attachments,
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new OrchestrationDispatchCommandError({
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new OrchestrationDispatchCommandError({
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
const attachmentId = createAttachmentId(canonicalCommand.threadId);
if (!attachmentId) {
return yield* new OrchestrationDispatchCommandError({
message: "Failed to create a safe attachment id.",
});
}
const persistedAttachment = {
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
sizeBytes: bytes.byteLength,
};
const attachmentPath = resolveAttachmentPath({
const claimPlan = planAttachmentClaim({
attachmentsDir: serverConfig.attachmentsDir,
attachment: persistedAttachment,
threadId: canonicalCommand.threadId,
attachmentId: attachment.id,
});
if (!attachmentPath) {
if (!claimPlan.ok) {
return yield* new OrchestrationDispatchCommandError({
message: `Failed to resolve persisted path for '${attachment.name}'.`,
message: `Attachment '${attachment.name}' cannot be sent: ${claimPlan.reason}.`,
});
}
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
const stats = yield* fileSystem.stat(claimPlan.currentPath).pipe(
Effect.mapError(
() =>
(cause) =>
new OrchestrationDispatchCommandError({
message: `Failed to create attachment directory for '${attachment.name}'.`,
}),
),
);
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
Effect.mapError(
() =>
new OrchestrationDispatchCommandError({
message: `Failed to persist attachment '${attachment.name}'.`,
message: `Attachment '${attachment.name}' cannot be sent: attachment not found (removed or expired).`,
cause,
}),
),
);
if (Number(stats.size) !== attachment.sizeBytes) {
return yield* new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' cannot be sent: stored size does not match the reference.`,
});
}
return persistedAttachment;
if (!claimPlan.alreadyScoped) {
yield* fileSystem.rename(claimPlan.currentPath, claimPlan.finalPath).pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: `Failed to claim attachment '${attachment.name}' for this thread.`,
cause,
}),
),
);
}
return {
...attachment,
id: claimPlan.finalId,
mimeType: attachment.mimeType.toLowerCase(),
};
}),
{ concurrency: 1 },
);
@@ -120,7 +120,7 @@ Example:
plan content
</proposed_plan>
plan content should be human and agent digestible. The final plan must be plan-only and include:
plan content should be human and agent digestible. The final plan must be plan-only, concise by default, and include:
* A clear title
* A brief summary section
@@ -128,9 +128,17 @@ plan content should be human and agent digestible. The final plan must be plan-o
* Test cases and scenarios
* Explicit assumptions and defaults chosen where needed
When possible, prefer a compact structure with 3-5 short sections, usually: Summary, Key Changes or Implementation Changes, Test Plan, and Assumptions. Do not include a separate Scope section unless scope boundaries are genuinely important to avoid mistakes.
Prefer grouped implementation bullets by subsystem or behavior over file-by-file inventories. Mention files only when needed to disambiguate a non-obvious change, and avoid naming more than 3 paths unless extra specificity is necessary to prevent mistakes. Prefer behavior-level descriptions over symbol-by-symbol removal lists. For v1 feature-addition plans, do not invent detailed schema, validation, precedence, fallback, or wire-shape policy unless the request establishes it or it is needed to prevent a concrete implementation mistake; prefer the intended capability and minimum interface/behavior changes.
Keep bullets short and avoid explanatory sub-bullets unless they are needed to prevent ambiguity. Prefer the minimum detail needed for implementation safety, not exhaustive coverage. Within each section, compress related changes into a few high-signal bullets and omit branch-by-branch logic, repeated invariants, and long lists of unaffected behavior unless they are necessary to prevent a likely implementation mistake. Avoid repeated repo facts and irrelevant edge-case or rollout detail. For straightforward refactors, keep the plan to a compact summary, key edits, tests, and assumptions. If the user asks for more detail, then expand.
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
If the user stays in Plan mode and asks for revisions after a prior \`<proposed_plan>\`, any new \`<proposed_plan>\` must be a complete replacement. If the user indicates that the prior plan is not acceptable but does not provide enough information to produce a complete replacement, address the concern and continue planning without producing a \`<proposed_plan>\` block. If the follow-up neither requires changes nor calls the plan into question (e.g. clarifying question), answer it before the block, then reproduce the prior \`<proposed_plan>\` unchanged.
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
</collaboration_mode>`;
@@ -142,7 +150,7 @@ Your active mode changes only when new developer instructions with a different \
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
Use the \`request_user_input\` tool only when it is listed in the available tools for this turn.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
+2
View File
@@ -13,6 +13,7 @@ import * as ServerConfig from "./config.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
serverEnvironmentHttpApiLayer,
staticAndDevRouteLayer,
browserApiCorsLayer,
@@ -451,6 +452,7 @@ export const makeRoutesLayer = Layer.mergeAll(
),
otlpTracesProxyRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
),
+11
View File
@@ -88,6 +88,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
import { issueAssetUrl } from "./assets/AssetAccess.ts";
import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
@@ -1839,6 +1840,16 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.attachmentsCreateUploadUrl]: (input) =>
observeRpcEffect(WS_METHODS.attachmentsCreateUploadUrl, issueAttachmentUploadUrl(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.attachmentsDelete]: (input) =>
observeRpcEffect(
WS_METHODS.attachmentsDelete,
deletePendingAttachment(input.attachmentId),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.assetsCreateUrl]: (input) =>
observeRpcEffect(
WS_METHODS.assetsCreateUrl,
@@ -7,7 +7,7 @@ import {
type PreviewViewportSetting,
} from "@t3tools/contracts";
import { PREVIEW_VIEWPORT_PRESETS, resolvePreviewViewport } from "@t3tools/shared/previewViewport";
import { Link2, X } from "lucide-react";
import { Link2, Unlink2, X } from "lucide-react";
import { useState } from "react";
import { Button } from "~/components/ui/button";
@@ -310,7 +310,11 @@ export function BrowserDeviceToolbar({
onPointerDown={(event) => event.preventDefault()}
onClick={toggleAspectRatio}
>
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
{aspectRatio === null ? (
<Unlink2 className={cn(aspectRatio !== null && "text-foreground")} />
) : (
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
)}
</Button>
<Button
variant="ghost"
+9 -18
View File
@@ -233,23 +233,6 @@ export interface PullRequestDialogState {
key: number;
}
export function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result === "string") {
resolve(reader.result);
return;
}
reject(new Error("Could not read image data."));
});
reader.addEventListener("error", () => {
reject(reader.error ?? new Error("Failed to read image."));
});
reader.readAsDataURL(file);
});
}
export function resolveSendEnvMode(input: {
requestedEnvMode: DraftThreadEnvMode;
isGitRepo: boolean;
@@ -260,7 +243,7 @@ export function resolveSendEnvMode(input: {
export function cloneComposerImageForRetry(
image: ComposerImageAttachment,
): ComposerImageAttachment {
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
if (!image.file || typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
return image;
}
try {
@@ -275,6 +258,7 @@ export function cloneComposerImageForRetry(
export function deriveComposerSendState(options: {
prompt: string;
/** Uploaded attachments only — an image still in flight is not sendable content. */
imageCount: number;
terminalContexts: ReadonlyArray<TerminalContextDraft>;
/**
@@ -283,11 +267,17 @@ export function deriveComposerSendState(options: {
* contexts do: a prompt of just element chips is still a valid send.
*/
elementContextCount?: number;
/**
* Why attachments are blocking the send (uploading or failed), or null.
* Sending around an unsettled attachment would silently drop it.
*/
attachmentBlockReason?: string | null;
}): {
trimmedPrompt: string;
sendableTerminalContexts: TerminalContextDraft[];
expiredTerminalContextCount: number;
hasSendableContent: boolean;
attachmentBlockReason: string | null;
} {
const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
@@ -303,6 +293,7 @@ export function deriveComposerSendState(options: {
options.imageCount > 0 ||
sendableTerminalContexts.length > 0 ||
elementContextCount > 0,
attachmentBlockReason: options.attachmentBlockReason ?? null,
};
}
+51 -22
View File
@@ -27,6 +27,7 @@ import {
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import {
changeRequestAutoSettles,
effectiveSettled,
effectiveSnoozed,
threadWokeAt,
@@ -204,6 +205,8 @@ import {
useComposerDraftStore,
type DraftId,
} from "../composerDraftStore";
import { awaitAttachmentUploads, releaseComposerAttachment } from "../lib/attachmentUploadQueue";
import { readyAttachmentRefs, summarizeAttachmentUploads } from "../lib/attachmentUploadState";
import {
appendTerminalContextsToPrompt,
formatTerminalContextLabel,
@@ -306,7 +309,6 @@ import {
PullRequestDialogState,
cloneComposerImageForRetry,
deriveLockedProvider,
readFileAsDataUrl,
reconcileMountedTerminalThreadIds,
resolveThreadMetadataUpdateForNextTurn,
resolveSendEnvMode,
@@ -4101,6 +4103,7 @@ function ChatViewContent(props: ChatViewProps) {
// so the banner and the sidebar row never disagree.
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((settings) => settings.sidebarAutoSettleOnMerge);
const activeThreadPr = resolveThreadPr({
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
@@ -4141,15 +4144,14 @@ function ChatViewContent(props: ChatViewProps) {
if (activeThreadRef === null || activeThreadWokeAt === null) return;
markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt);
}, [activeThreadRef, activeThreadWokeAt, markThreadVisited]);
// Mirror of the sidebar's Woke pill for the open thread: same visit
// comparison, same merged/closed-PR suppression (finished work needs no
// wake-up call). Drives the dismissible composer banner below.
// Mirror of the sidebar's Woke pill for the open thread. It uses the same
// visit comparison and change request settle rule.
const activeThreadLastVisitedAt = useUiStateStore((store) =>
activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
);
const activeThreadWokeVisible = useMemo(() => {
if (activeThreadWokeAt === null) return false;
if (activeThreadPr?.state === "merged" || activeThreadPr?.state === "closed") return false;
if (changeRequestAutoSettles(activeThreadPr?.state, autoSettleOnMerge)) return false;
const wokeAtMs = Date.parse(activeThreadWokeAt);
if (Number.isNaN(wokeAtMs)) return false;
// Having the thread open counts as a visit at completedAt (the effect
@@ -4171,18 +4173,21 @@ function ChatViewContent(props: ChatViewProps) {
activeThreadLastVisitedAt,
activeThreadPr?.state,
activeThreadWokeAt,
autoSettleOnMerge,
]);
const activeThreadSettled = useMemo(() => {
if (activeThreadShell === null || !supportsSettlement) return false;
return effectiveSettled(activeThreadShell, {
now: `${nowMinute}:00.000Z`,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState: activeThreadPr?.state ?? null,
});
}, [
activeThreadPr?.state,
activeThreadShell,
autoSettleAfterDays,
autoSettleOnMerge,
nowMinute,
supportsSettlement,
]);
@@ -4957,7 +4962,9 @@ function ChatViewContent(props: ChatViewProps) {
hasSendableContent,
} = deriveComposerSendState({
prompt: promptForSend,
imageCount: composerImages.length,
// Only uploaded attachments count: an image still in flight (or failed)
// is not sendable content, and the composer blocks the send anyway.
imageCount: summarizeAttachmentUploads(composerImages, environmentId).ready,
terminalContexts: composerTerminalContexts,
elementContextCount:
composerElementContexts.length +
@@ -4970,6 +4977,12 @@ function ChatViewContent(props: ChatViewProps) {
planMarkdown: activeProposedPlan.planMarkdown,
});
promptRef.current = "";
// The follow-up sends text only; any attached images are being
// discarded with the rest of the composer, so their uploads and
// server-side bytes are released like a chip removal.
for (const image of composerImages) {
releaseComposerAttachment(image);
}
clearComposerDraftContent(composerDraftTarget);
composerRef.current?.resetCursorState();
await onSubmitPlanFollowUp({
@@ -5082,15 +5095,6 @@ function ChatViewContent(props: ChatViewProps) {
effort: ctxSelectedPromptEffort,
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
});
const turnAttachmentsPromise = Promise.all(
composerImagesSnapshot.map(async (image) => ({
type: "image" as const,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file),
})),
);
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: "image" as const,
id: image.id,
@@ -5202,13 +5206,26 @@ function ChatViewContent(props: ChatViewProps) {
}
}
const turnAttachmentsResult = await settlePromise(() => turnAttachmentsPromise);
if (failure === null && turnAttachmentsResult._tag === "Failure") {
failure = turnAttachmentsResult;
}
// Attachments ride the turn as id references to bytes that uploaded the
// moment they were attached. The composer blocks sending while an upload
// is in flight, but the preview "pick and send" gesture attaches and sends
// in one step, so wait for anything still running here.
const settledUploads = await awaitAttachmentUploads(
composerImagesSnapshot.map((image) => image.id),
);
const sendableImages = composerImagesSnapshot.map((image) => {
const settledUpload = settledUploads.get(image.id);
return settledUpload ? { ...image, upload: settledUpload } : image;
});
const turnAttachments = readyAttachmentRefs(sendableImages, environmentId);
const unsentImageNames = sendableImages
.filter(
(image) => image.upload.status !== "ready" || image.upload.environmentId !== environmentId,
)
.map((image) => image.name);
let turnStartSucceeded = false;
if (failure === null && turnAttachmentsResult._tag === "Success") {
if (failure === null) {
const bootstrap =
isLocalDraftThread || baseBranchForWorktree
? {
@@ -5248,7 +5265,7 @@ function ChatViewContent(props: ChatViewProps) {
messageId: messageIdForSend,
role: "user",
text: outgoingMessageText,
attachments: turnAttachmentsResult.value,
attachments: turnAttachments,
},
modelSelection: ctxSelectedModelSelection,
titleSeed: title,
@@ -5263,6 +5280,15 @@ function ChatViewContent(props: ChatViewProps) {
} else {
turnStartSucceeded = true;
acknowledgeActiveThreadWoke();
if (unsentImageNames.length > 0) {
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Some images were not attached",
description: `${unsentImageNames.join(", ")} did not finish uploading, so the message was sent without them.`,
}),
);
}
}
}
@@ -5286,7 +5312,10 @@ function ChatViewContent(props: ChatViewProps) {
return next.length === existing.length ? existing : next;
});
promptRef.current = promptForSend;
const retryComposerImages = composerImagesSnapshot.map(cloneComposerImageForRetry);
// `sendableImages` carries the settled upload states; the pre-await
// snapshot can still say `uploading` for a job that finished during
// the await and would restore chips no live job will ever advance.
const retryComposerImages = sendableImages.map(cloneComposerImageForRetry);
composerImagesRef.current = retryComposerImages;
composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
composerElementContextsRef.current = composerElementContextsSnapshot;
+31 -16
View File
@@ -19,6 +19,7 @@ import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-
import { CSS } from "@dnd-kit/utilities";
import {
canSnooze,
changeRequestAutoSettles,
effectiveSettled,
effectiveSnoozed,
threadWokeAt,
@@ -175,6 +176,7 @@ import {
type ComposerThreadDraftState,
type DraftSessionState,
} from "../composerDraftStore";
import { releaseComposerAttachment } from "../lib/attachmentUploadQueue";
// Settled-tail paging: recent history is the common lookup; the deep tail
// stays behind an explicit Show more.
@@ -441,10 +443,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
}) {
const { composer, draftId, onDiscard, onNavigate, session } = props;
const promptPreview = composer.prompt.trim().split("\n", 1)[0] ?? "";
// images mirrors persistedAttachments once rehydration finishes; before
// that only the persisted list is populated, hence max not sum.
const attachmentCount =
Math.max(composer.images.length, composer.persistedAttachments.length) +
composer.images.length +
composer.terminalContexts.length +
composer.elementContexts.length +
composer.previewAnnotations.length +
@@ -610,6 +610,14 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
]);
const handleDiscard = useCallback(
(draftId: DraftId) => {
// Discarding the draft abandons its attachments: stop in-flight
// uploads and free the server-side bytes before the store forgets
// them. (Server-side, only never-sent `pending-` files can be
// deleted, so this can never touch a sent thread's attachments.)
const draftImages = useComposerDraftStore.getState().getComposerDraft(draftId)?.images ?? [];
for (const image of draftImages) {
releaseComposerAttachment(image);
}
// The /draft/$draftId route redirects home on its own when the draft
// it renders disappears, so discarding the open draft needs no
// special-casing here.
@@ -657,6 +665,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
// False on environments whose server predates thread.settle/unsettle:
// the lifecycle affordances hide entirely rather than fail on click.
settlementSupported: boolean;
autoSettleOnMerge: boolean;
// Same contract for thread.snooze/unsnooze.
snoozeSupported: boolean;
// Renders the pin glyph. Pinned cards keep the full settle/snooze quick
@@ -765,17 +774,15 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
// deliberately static), so the pill has to carry the weight. Snoozing is
// an explicit act, so the pill clears only when the user re-engages:
// reading a completion-triggered wake, clicking the pill, sending a
// message, settling, archiving — or finishing the work outright (merged
// or closed PR). Timer wakes survive a mere visit. An unparseable visit
// timestamp counts as never-visited — corrupt local data must not eat
// the wake signal.
// message, settling, archiving, or a change request state that settles the
// thread. Timer wakes survive a mere visit. An unparseable visit timestamp
// counts as never-visited, so corrupt local data cannot eat the wake signal.
const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt);
const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt);
const isWoke =
wokeAtDate !== null &&
(lastVisitedDate === null || lastVisitedDate < wokeAtDate) &&
prState !== "merged" &&
prState !== "closed";
!changeRequestAutoSettles(prState, props.autoSettleOnMerge);
// In-flight rows (working, or waiting on approval/input) fade as a whole:
// there is nothing for the user to do yet, so prominence is reserved for
// rows that need a human — done (unread), read-but-unsettled, failed, and
@@ -851,8 +858,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
// Report the PR state up: the parent partitions rows with effectiveSettled,
// and a merged/closed PR auto-settles a thread — data only rows have.
// Report the PR state so the parent can apply the configured merge rule
// and the always-on close rule during partitioning.
useEffect(() => {
onChangeRequestState(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
@@ -1211,11 +1218,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
aria-label="Wake thread now"
onClick={handleUnsnoozeClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
"pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
isWoke && "group-hover/sidebar-row:static",
)}
>
<AlarmClockOffIcon className="size-3" />
<AlarmClockOffIcon className="mb-px size-3" />
</button>
)
) : !props.settlementSupported ? null : variantAction === "unsettle" ? (
@@ -1599,6 +1606,7 @@ export default function Sidebar() {
const { isMobile, setOpenMobile } = useSidebar();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
@@ -1801,8 +1809,8 @@ export default function Sidebar() {
// fresh clock whenever it recomputes.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
// closed PR auto-settles its 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());
@@ -1953,7 +1961,12 @@ export default function Sidebar() {
pinned.push(thread);
} else if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
effectiveSettled(thread, {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
settled.push(thread);
} else {
@@ -1988,6 +2001,7 @@ export default function Sidebar() {
};
}, [
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestStateByKey,
nowMinute,
scopedProjectKeys,
@@ -3532,6 +3546,7 @@ export default function Sidebar() {
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSettlement === true
}
autoSettleOnMerge={autoSettleOnMerge}
snoozeSupported={
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSnooze === true
@@ -144,10 +144,10 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(216 18) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop style={{ stopColor: "var(--stage-night-highlight)" }} stopOpacity="0.4" />
<stop style={{ stopColor: "var(--stage-night-glow-highlight)" }} stopOpacity="0.4" />
<stop
offset="0.5"
style={{ stopColor: "var(--stage-night-secondary)" }}
style={{ stopColor: "var(--stage-night-glow-secondary)" }}
stopOpacity="0.16"
/>
<stop offset="1" style={{ stopColor: "var(--stage-night-bottom)" }} stopOpacity="0" />
@@ -177,7 +177,7 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
))}
</g>
<g
style={{ stroke: "var(--stage-night-line)" }}
style={{ stroke: "var(--stage-night-sparkle)" }}
strokeLinecap="round"
strokeOpacity="0.7"
strokeWidth="0.6"
@@ -274,10 +274,10 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(474 44) rotate(166) scale(156 92)"
gradientUnits="userSpaceOnUse"
>
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.34" />
<stop style={{ stopColor: "var(--stage-art-celeste-highlight)" }} stopOpacity="0.34" />
<stop
offset="0.5"
style={{ stopColor: "var(--stage-art-secondary)" }}
style={{ stopColor: "var(--stage-art-celeste-secondary)" }}
stopOpacity="0.18"
/>
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
@@ -290,7 +290,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(704 18) rotate(145) scale(132 88)"
gradientUnits="userSpaceOnUse"
>
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.3" />
<stop style={{ stopColor: "var(--stage-art-violet-highlight)" }} stopOpacity="0.3" />
<stop
offset="0.52"
style={{ stopColor: "var(--stage-art-tertiary)" }}
@@ -301,7 +301,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
<pattern id={minorGridId} width="8" height="8" patternUnits="userSpaceOnUse">
<path
d="M8 0H0V8"
style={{ stroke: "var(--stage-art-line)" }}
style={{ stroke: "var(--stage-art-grid-line)" }}
strokeOpacity="0.14"
strokeWidth="0.5"
/>
@@ -309,7 +309,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
<pattern id={majorGridId} width="32" height="32" patternUnits="userSpaceOnUse">
<path
d="M32 0H0V32"
style={{ stroke: "var(--stage-art-line)" }}
style={{ stroke: "var(--stage-art-grid-line)" }}
strokeOpacity="0.26"
strokeWidth="0.6"
/>
+316 -249
View File
@@ -41,7 +41,7 @@ import {
replaceTextRange,
shouldSubmitComposerOnEnter,
} from "../../composer-logic";
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
import { deriveComposerSendState } from "../ChatView.logic";
import {
dataTransferHasComposerMention,
makeComposerMentionDragHandlers,
@@ -57,13 +57,27 @@ import {
} from "../../composerDraftStore";
import {
MAX_STASH_ENTRIES,
partitionStashAttachments,
usePromptStashStore,
type PromptStashEntry,
} from "../../promptStashStore";
import { ComposerStashBadge } from "./ComposerStashBadge";
import { ComposerStashMenu } from "./ComposerStashMenu";
import { compressImageForStash, compressImageToByteLimit } from "../../lib/imageCompression";
import { compressImageToByteLimit } from "../../lib/imageCompression";
import {
cancelAttachmentUpload,
releaseComposerAttachment,
retryAttachmentUpload,
startAttachmentUpload,
} from "../../lib/attachmentUploadQueue";
import {
ATTACHMENT_WRONG_ENVIRONMENT_REASON,
attachmentUploadBlockReason,
formatAttachmentUploadProgress,
isAttachmentInWrongEnvironment,
resolveAttachmentEnvironmentAction,
summarizeAttachmentUploads,
} from "../../lib/attachmentUploadState";
import { useAssetUrls } from "~/assets/assetUrls";
import { isCommandPaletteOpen } from "../../commandPaletteBus";
import { getTerminalFocusOwner } from "../../lib/terminalFocus";
import { resolveShortcutCommand } from "../../keybindings";
@@ -666,7 +680,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
setThreadError,
onExpandImage,
} = props;
const isSendDisabled = sendDisabledReason !== null;
// ------------------------------------------------------------------
// Store subscriptions (prompt / images / terminal contexts)
@@ -678,12 +691,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const composerElementContexts = composerDraft.elementContexts;
const composerPreviewAnnotations = composerDraft.previewAnnotations;
const composerReviewComments = composerDraft.reviewComments;
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
const setComposerDraftImageUpload = useComposerDraftStore((store) => store.setImageUpload);
const insertComposerDraftTerminalContext = useComposerDraftStore(
(store) => store.insertTerminalContext,
);
@@ -702,16 +715,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const removeComposerDraftReviewComment = useComposerDraftStore(
(store) => store.removeReviewComment,
);
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.clearPersistedAttachments,
);
const clearComposerDraftPromptAndImages = useComposerDraftStore(
(store) => store.clearComposerPromptAndImages,
);
const syncComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.syncPersistedAttachments,
);
const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
// ------------------------------------------------------------------
// Model state
@@ -974,12 +980,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const dragDepthRef = useRef(0);
const stashPulseKeyRef = useRef(0);
const stashPulseTimeoutRef = useRef<number | null>(null);
/**
* Snapshots currently being encoded, keyed by target+prompt+image ids.
* Keyed rather than boolean so a genuinely different prompt (or a different
* thread) can still be stashed while an earlier encode is running.
*/
const stashInFlightRef = useRef<Set<string>>(new Set());
/**
* Count of pasted images still being compressed, per thread. Reserved
* against the attachment limit so concurrent pastes can't overshoot it,
@@ -991,26 +991,35 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Derived: composer send state
// ------------------------------------------------------------------
const attachmentUploadSummary = useMemo(
() => summarizeAttachmentUploads(composerImages, environmentId),
[composerImages, environmentId],
);
const composerSendState = useMemo(
() =>
deriveComposerSendState({
prompt,
imageCount: composerImages.length,
imageCount: attachmentUploadSummary.ready,
terminalContexts: composerTerminalContexts,
elementContextCount:
composerElementContexts.length +
composerPreviewAnnotations.length +
composerReviewComments.length,
attachmentBlockReason: attachmentUploadBlockReason(attachmentUploadSummary),
}),
[
attachmentUploadSummary,
composerElementContexts.length,
composerImages.length,
composerPreviewAnnotations.length,
composerReviewComments.length,
composerTerminalContexts,
prompt,
],
);
// An unsettled attachment blocks the send just like a loading thread does:
// sending around it would silently drop an image the user can see attached.
const effectiveSendDisabledReason = sendDisabledReason ?? composerSendState.attachmentBlockReason;
const isSendDisabled = effectiveSendDisabledReason !== null;
// ------------------------------------------------------------------
// Derived: composer trigger / menu
@@ -1128,9 +1137,48 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
const nonPersistedComposerImageIdSet = useMemo(
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
// Attachments restored from a persisted draft have no blob preview: their
// bytes only exist on the server, so the thumbnail comes from a signed
// asset URL — the same flow sent-message attachments already use.
const restoredAttachmentIds = useMemo(
() =>
composerImages.flatMap((image) =>
image.previewUrl.length === 0 && image.upload.status === "ready"
? [image.upload.attachmentId]
: [],
),
[composerImages],
);
const restoredAttachmentResources = useMemo(
() =>
restoredAttachmentIds.map((attachmentId) => ({
_tag: "attachment" as const,
attachmentId,
})),
[restoredAttachmentIds],
);
const restoredAttachmentUrls = useAssetUrls(environmentId, restoredAttachmentResources);
const restoredAttachmentUrlById = useMemo(
() =>
new Map(
restoredAttachmentIds.flatMap((attachmentId, index) => {
const url = restoredAttachmentUrls[index];
return url ? [[attachmentId, url] as const] : [];
}),
),
[restoredAttachmentIds, restoredAttachmentUrls],
);
/** Chips as rendered: local blob preview when we have one, signed URL otherwise. */
const displayComposerImages = useMemo(
() =>
composerImages.map((image) => {
if (image.previewUrl.length > 0 || image.upload.status !== "ready") {
return image;
}
const previewUrl = restoredAttachmentUrlById.get(image.upload.attachmentId);
return previewUrl ? { ...image, previewUrl } : image;
}),
[composerImages, restoredAttachmentUrlById],
);
const isComposerApprovalState = activePendingApproval !== null;
@@ -1450,72 +1498,36 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);
// ------------------------------------------------------------------
// Image persist effect
// Attachment environment retargeting
// ------------------------------------------------------------------
// The bytes live in exactly one environment. When a draft is pointed at a
// different one, an attachment we still hold the File for is silently
// re-uploaded; the old environment's copy is released only after the new
// upload lands (`supersedes`), so a failed re-upload never destroys the
// only server copy. One restored after a reload has no File to re-send;
// its ready state is left intact and the mismatch is rendered and
// send-gated as a derived condition, so switching back recovers it.
useEffect(() => {
let cancelled = false;
void (async () => {
if (composerImages.length === 0) {
clearComposerDraftPersistedAttachments(composerDraftTarget);
return;
}
const getPersistedAttachmentsForThread = () =>
getComposerDraft(composerDraftTarget)?.persistedAttachments ?? [];
try {
const currentPersistedAttachments = getPersistedAttachmentsForThread();
const existingPersistedById = new Map(
currentPersistedAttachments.map((attachment) => [attachment.id, attachment]),
);
const stagedAttachmentById = new Map<string, PersistedComposerImageAttachment>();
await Promise.all(
composerImages.map(async (image) => {
try {
const dataUrl = await readFileAsDataUrl(image.file);
stagedAttachmentById.set(image.id, {
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl,
});
} catch {
const existingPersisted = existingPersistedById.get(image.id);
if (existingPersisted) {
stagedAttachmentById.set(image.id, existingPersisted);
for (const image of composerImages) {
if (resolveAttachmentEnvironmentAction(image, environmentId) === "reupload") {
const previousUpload = image.upload;
cancelAttachmentUpload(image.id);
startAttachmentUpload({
target: composerDraftTarget,
environmentId,
image,
...(previousUpload.status === "ready"
? {
supersedes: {
environmentId: previousUpload.environmentId,
attachmentId: previousUpload.attachmentId,
},
}
}
}),
);
const serialized = Array.from(stagedAttachmentById.values());
if (cancelled) return;
syncComposerDraftPersistedAttachments(composerDraftTarget, serialized);
} catch {
const currentImageIds = new Set(composerImages.map((image) => image.id));
const fallbackPersistedAttachments = getPersistedAttachmentsForThread();
const fallbackPersistedIds: Array<string> = [];
for (const attachment of fallbackPersistedAttachments) {
if (currentImageIds.has(attachment.id)) {
fallbackPersistedIds.push(attachment.id);
}
}
const fallbackPersistedIdSet = new Set(fallbackPersistedIds);
const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) =>
fallbackPersistedIdSet.has(attachment.id),
);
if (cancelled) return;
syncComposerDraftPersistedAttachments(composerDraftTarget, fallbackAttachments);
: {}),
});
}
})();
return () => {
cancelled = true;
};
}, [
composerDraftTarget,
clearComposerDraftPersistedAttachments,
composerImages,
getComposerDraft,
syncComposerDraftPersistedAttachments,
]);
}
}, [composerDraftTarget, composerImages, environmentId]);
// ------------------------------------------------------------------
// Callbacks: prompt change
@@ -1910,7 +1922,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const stashQueue = usePromptStashStore((state) => state.entries);
const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
useEffect(() => {
return () => {
@@ -1967,7 +1978,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
let unrestoredImageNames: string[] = [];
if (entry.attachments.length > 0) {
// Attachment bytes live in one environment. Restoring into a different
// one cannot reach them, so those come back as named drops.
const wrongEnvironmentImageNames = entry.attachments
.filter((attachment) => attachment.environmentId !== environmentId)
.map((attachment) => attachment.name);
const restorableAttachments = entry.attachments.filter(
(attachment) => attachment.environmentId === environmentId,
);
if (restorableAttachments.length > 0) {
const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
// The draft store also dedupes by mimeType+sizeBytes+name, so filter
// on the same key here. Counting a duplicate against capacity would
@@ -1982,7 +2001,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
0,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS - composerImagesRef.current.length,
);
const pending = entry.attachments.filter(
const pending = restorableAttachments.filter(
(attachment) =>
!existingIds.has(attachment.id) &&
!existingDedupKeys.has(
@@ -2003,18 +2022,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// prompt across threads and providers, so whatever the composer has
// selected right now stays selected.
// Each cause gets its own sentence so "too large" is never blamed for a
// file that actually failed to decode, or for one the composer simply
// had no room to take back.
// Each cause gets its own sentence so "still uploading" is never blamed
// for a file that actually failed, or for one the composer simply had no
// room to take back.
const missingImageReasons: string[] = [];
if (entry.droppedImageNames.length > 0) {
missingImageReasons.push(
`${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`,
`${entry.droppedImageNames.join(", ")} had not finished uploading when this prompt was saved.`,
);
}
if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) {
missingImageReasons.push(
`${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`,
`${entry.unreadableImageNames.join(", ")} failed to upload when this prompt was saved.`,
);
}
if (wrongEnvironmentImageNames.length > 0) {
missingImageReasons.push(
`${wrongEnvironmentImageNames.join(", ")} is not available in this environment.`,
);
}
if (unrestoredImageNames.length > 0) {
@@ -2042,6 +2066,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
addComposerDraftImages,
composerDraftTarget,
composerImagesRef,
environmentId,
promptRef,
setComposerDraftPrompt,
takeStashEntry,
@@ -2064,7 +2089,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[takeStashEntry],
);
const stashCurrentPrompt = useCallback(async () => {
const stashCurrentPrompt = useCallback(() => {
// Terminal-context placeholders reference live sessions the stash can't
// round-trip, so they are stripped from the stashed prompt.
const prompt = promptRef.current.split(INLINE_TERMINAL_CONTEXT_PLACEHOLDER).join("").trim();
@@ -2073,149 +2098,111 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
setIsStashMenuOpen((open) => !open);
return;
}
// A repeat ⌘S on the *same* still-unencoded snapshot would stash it
// twice. Guard on the snapshot itself rather than a bare boolean: once
// the composer has been cleared the user can type something genuinely
// new (or switch threads) while encoding continues, and that deserves its
// own entry.
const snapshotKey = `${String(composerDraftTarget)}${prompt}${images
.map((image) => image.id)
.join(",")}`;
if (stashInFlightRef.current.has(snapshotKey)) return;
stashInFlightRef.current.add(snapshotKey);
// Attachments are already on the server, so the entry is a handful of id
// references and the whole stash is one synchronous write. Anything that
// has not landed yet cannot be referenced and comes back as a named drop.
// Nothing is cancelled yet: if the write fails below, the composer (and
// its in-flight uploads) must be left exactly as they were.
const stashTarget = composerDraftTarget;
const entryId = randomUUID();
try {
// Persist the text-only entry *first*, then clear. Ordering matters in
// both directions: writing before clearing means a crash or closed tab
// mid-encode still leaves the prompt recoverable, while clearing before
// the async image work means edits typed during encoding are not wiped.
// Images are appended to the stored entry as they finish encoding.
const { evicted, written, durable } = stashEntryToQueue({
id: entryId,
createdAt: new Date().toISOString(),
prompt,
attachments: [],
droppedImageNames: [],
unreadableImageNames: [],
pendingImageCount: images.length,
});
// Clearing the composer is only safe once the write actually landed.
// If it was rejected (quota) the store has already rolled itself back,
// so leave the composer untouched rather than making it the second
// casualty of a reload.
if (!written) {
toastManager.add({
type: "error",
title: "Could not stash this prompt",
description:
"Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",
data: { hideCopyButton: true },
});
return;
}
// Written but only into the in-memory fallback (localStorage blocked):
// the entry is visible and restorable this session, so proceed with the
// clear, but say it won't survive a reload.
if (!durable) {
toastManager.add({
type: "warning",
title: "Stashed prompt will not survive a reload",
description:
"Browser storage is unavailable, so this stash is kept in memory only for this session.",
data: { hideCopyButton: true },
});
}
// Only the prompt and images are cleared — terminal/element contexts,
// preview annotations, and review comments are not stashable, so
// destroying them here would be unrecoverable.
promptRef.current = "";
clearComposerDraftPromptAndImages(stashTarget);
setComposerCursor(0);
setComposerTrigger(null);
pulseStashBadge();
if (evicted) {
toastManager.add({
type: "warning",
title: "Oldest stashed prompt discarded",
description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,
data: { hideCopyButton: true },
});
}
// Images are re-encoded for the stash rather than stored verbatim: the
// composer allows up to 10MB per image, but localStorage gives the whole
// origin ~5MB. Only the stashed copy shrinks; the live attachment (and
// anything sent without stashing) keeps the original file.
const candidateAttachments: PersistedComposerImageAttachment[] = [];
const oversizedImageNames: string[] = [];
const unreadableImageNames: string[] = [];
for (const image of images) {
const result = await compressImageForStash(image.file);
if (!result.ok) {
// "too large" and "could not be read" are distinct outcomes; the
// menu and restore toast report them separately.
(result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push(
image.name,
);
continue;
}
candidateAttachments.push({
const attachments: PersistedComposerImageAttachment[] = [];
const stillUploadingImages: ComposerImageAttachment[] = [];
const failedImageNames: string[] = [];
for (const image of images) {
if (image.upload.status === "ready") {
attachments.push({
id: image.id,
attachmentId: image.upload.attachmentId,
name: image.name,
mimeType: result.image.mimeType,
sizeBytes: result.image.sizeBytes,
dataUrl: result.image.dataUrl,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
environmentId: image.upload.environmentId,
});
continue;
}
const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);
if (image.upload.status === "failed") {
failedImageNames.push(image.name);
} else {
stillUploadingImages.push(image);
}
}
const stillUploadingImageNames = stillUploadingImages.map((image) => image.name);
const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
attachments: kept,
droppedImageNames: [...oversizedImageNames, ...droppedNames],
unreadableImageNames,
const { evicted, written, durable } = stashEntryToQueue({
id: randomUUID(),
createdAt: new Date().toISOString(),
prompt,
attachments,
droppedImageNames: stillUploadingImageNames,
unreadableImageNames: failedImageNames,
});
// Clearing the composer is only safe once the write actually landed.
// If it was rejected (quota) the store has already rolled itself back,
// so leave the composer untouched rather than making it the second
// casualty of a reload.
if (!written) {
toastManager.add({
type: "error",
title: "Could not stash this prompt",
description:
"Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",
data: { hideCopyButton: true },
});
return;
}
// Written but only into the in-memory fallback (localStorage blocked):
// the entry is visible and restorable this session, so proceed with the
// clear, but say it won't survive a reload.
if (!durable) {
toastManager.add({
type: "warning",
title: "Stashed prompt will not survive a reload",
description:
"Browser storage is unavailable, so this stash is kept in memory only for this session.",
data: { hideCopyButton: true },
});
}
// The write landed, so the composer is being cleared: uploads that could
// not be stashed (still in flight) are cancelled now, and failed ones lose
// their settled record. Doing this before the write would strand the
// chips in `uploading` forever on a rejected write.
for (const image of stillUploadingImages) {
cancelAttachmentUpload(image.id);
}
// Only the prompt and images are cleared — terminal/element contexts,
// preview annotations, and review comments are not stashable, so
// destroying them here would be unrecoverable.
promptRef.current = "";
clearComposerDraftPromptAndImages(stashTarget);
setComposerCursor(0);
setComposerTrigger(null);
pulseStashBadge();
if (evicted) {
toastManager.add({
type: "warning",
title: "Oldest stashed prompt discarded",
description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,
data: { hideCopyButton: true },
});
}
const unstashedImageNames = [...stillUploadingImageNames, ...failedImageNames];
if (unstashedImageNames.length > 0) {
toastManager.add({
type: "warning",
title: "Some images were not stashed",
description: `${unstashedImageNames.join(", ")} had not finished uploading, so ${unstashedImageNames.length === 1 ? "it was" : "they were"} not saved with the prompt.`,
data: { hideCopyButton: true },
});
if (attached) {
// The second phase can be rejected on its own: the text-only entry
// fit, but adding image payloads pushed past the quota. Disk would
// then still hold the phase-one entry with pendingImageCount set,
// which reads as an orphan after reload — so say so now. Gated on the
// entry write having been durable: on the in-memory fallback nothing
// is ever durable, and the session-only warning already covered it.
if (!imagesDurable && durable && images.length > 0) {
toastManager.add({
type: "warning",
title: "Stashed images were not saved",
description:
"The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.",
data: { hideCopyButton: true },
});
}
} else if (kept.length > 0) {
// The entry was restored or deleted before its images finished
// encoding, so they have nowhere to land. Say so rather than letting
// them evaporate.
toastManager.add({
type: "warning",
title: "Stashed images did not attach",
description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`,
data: { hideCopyButton: true },
});
}
} finally {
// Must clear on every path: a throw that left this set would wedge this
// snapshot's ⌘S until the composer remounts.
stashInFlightRef.current.delete(snapshotKey);
}
}, [
clearComposerDraftPromptAndImages,
composerDraftTarget,
composerImagesRef,
finalizeStashEntryImages,
promptRef,
pulseStashBadge,
stashEntryToQueue,
@@ -2339,6 +2326,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
sizeBytes: attachmentFile.size,
previewUrl,
file: attachmentFile,
upload: { status: "uploading", progress: 0 },
});
}
if (nextImages.length === 1 && nextImages[0]) {
@@ -2346,6 +2334,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
} else if (nextImages.length > 1) {
addComposerImagesToDraft(nextImages);
}
// Upload starts on attach, not on send: the URL is minted with the exact
// post-compression byte count, so this has to run after the ladder. Only
// images the store actually accepted are uploaded — a duplicate paste is
// deduped away and must not leave orphaned bytes on the server.
const acceptedImageIds = new Set(
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.images ?? []).map(
(image) => image.id,
),
);
for (const image of nextImages) {
if (!acceptedImageIds.has(image.id)) continue;
startAttachmentUpload({ target: composerDraftTarget, environmentId, image });
}
// Only failures are reported here. Success must not pass `null`: by
// now other work (a failed send, an overlapping paste) may have set a
// thread error this call knows nothing about, and clearing it would
@@ -2364,8 +2365,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
};
const removeComposerImage = (imageId: string) => {
removeComposerImageFromDraft(imageId);
const removeComposerImage = (image: ComposerImageAttachment) => {
// Abort an in-flight upload, and hand back an already-uploaded one so the
// server does not keep bytes nothing will ever reference.
releaseComposerAttachment(image);
removeComposerImageFromDraft(image.id);
};
/** Re-runs a failed upload. The File never left memory, so nothing is re-picked. */
const retryComposerImageUpload = (image: ComposerImageAttachment) => {
if (!image.file) {
return;
}
retryAttachmentUpload({ target: composerDraftTarget, environmentId, image });
};
// ------------------------------------------------------------------
@@ -2784,7 +2796,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showPlanFollowUpPrompt={false}
promptHasText={false}
isSendBusy={isSendBusy}
sendDisabledReason={sendDisabledReason}
sendDisabledReason={effectiveSendDisabledReason}
isConnecting={isConnecting}
isEnvironmentUnavailable={
environmentUnavailable !== null ||
@@ -2900,12 +2912,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerPreviewAnnotations.length > 0 && (
<ComposerPreviewAnnotationCards
annotations={composerPreviewAnnotations}
images={composerImages}
onRemove={(annotationId) =>
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
}
images={displayComposerImages}
onRemove={(annotationId) => {
// The annotation's screenshot is a composer image with a
// server-side upload behind it; removing the card must
// stop that upload / free those bytes like removing a
// chip does.
const annotationImage = displayComposerImages.find(
(image) => image.id === annotationId,
);
if (annotationImage) {
releaseComposerAttachment(annotationImage);
}
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId);
}}
onExpandImage={(imageId) => {
const preview = buildExpandedImagePreview(composerImages, imageId);
const preview = buildExpandedImagePreview(displayComposerImages, imageId);
if (preview) onExpandImage(preview);
}}
className="mb-3"
@@ -2941,12 +2963,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{!isComposerCollapsedMobile &&
!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
composerImages.some(
displayComposerImages.some(
(image) =>
!composerPreviewAnnotations.some((annotation) => annotation.id === image.id),
) && (
<div className="mb-3 flex flex-wrap gap-2">
{composerImages
{displayComposerImages
.filter(
(image) =>
!composerPreviewAnnotations.some(
@@ -2956,7 +2978,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
.map((image) => (
<div
key={image.id}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
className={cn(
"relative h-16 w-16 overflow-hidden rounded-lg border bg-background",
image.upload.status === "failed" ||
isAttachmentInWrongEnvironment(image, environmentId)
? "border-destructive/70"
: "border-border/80",
)}
>
{image.previewUrl ? (
<button
@@ -2964,7 +2992,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(composerImages, image.id);
const preview = buildExpandedImagePreview(
displayComposerImages,
image.id,
);
if (!preview) return;
onExpandImage(preview);
}}
@@ -2972,7 +3003,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<img
src={image.previewUrl}
alt={image.name}
className="h-full w-full object-cover"
className={cn(
"h-full w-full object-cover",
image.upload.status === "ready" &&
!isAttachmentInWrongEnvironment(image, environmentId)
? ""
: "opacity-40",
)}
/>
</button>
) : (
@@ -2980,16 +3017,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{image.name}
</div>
)}
{nonPersistedComposerImageIdSet.has(image.id) && (
{/* Progress is text, not a spinner: a chip that repaints
every frame is a real cost on a 120Hz display. */}
{image.upload.status === "uploading" && (
<span
className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 py-0.5 text-center text-[10px] tabular-nums text-secondary-label"
aria-label={`Uploading ${image.name}`}
>
{formatAttachmentUploadProgress(image.upload.progress)}
</span>
)}
{isAttachmentInWrongEnvironment(image, environmentId) && (
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label="Draft attachment may not persist"
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
>
<CircleAlertIcon className="size-3" />
<span className="pointer-events-auto absolute inset-x-0 bottom-0 truncate bg-background/85 px-1 py-0.5 text-center text-[10px] text-destructive">
{ATTACHMENT_WRONG_ENVIRONMENT_REASON}
</span>
}
/>
@@ -2997,8 +3040,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
side="top"
className="max-w-64 whitespace-normal leading-tight"
>
Draft attachment could not be saved locally and may be lost on
navigation.
This image was uploaded to a different environment. Switch back to
send it from there, or remove it.
</TooltipPopup>
</Tooltip>
)}
{image.upload.status === "failed" && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="absolute inset-x-0 bottom-0 cursor-pointer truncate bg-background/85 px-1 py-0.5 text-center text-[10px] text-destructive"
onClick={() => retryComposerImageUpload(image)}
aria-label={`Retry upload for ${image.name}`}
>
{image.upload.reason}
</button>
}
/>
<TooltipPopup
side="top"
className="max-w-64 whitespace-normal leading-tight"
>
{image.file
? "Upload failed. Click to try again, or remove the image."
: "This image is not available here. Remove it to send."}
</TooltipPopup>
</Tooltip>
)}
@@ -3006,7 +3073,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
variant="ghost"
size="icon-xs"
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
onClick={() => removeComposerImage(image.id)}
onClick={() => removeComposerImage(image)}
aria-label={`Remove ${image.name}`}
>
<XIcon />
@@ -3067,7 +3134,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showPlanFollowUpPrompt={false}
promptHasText={false}
isSendBusy={isSendBusy}
sendDisabledReason={sendDisabledReason}
sendDisabledReason={effectiveSendDisabledReason}
isConnecting={isConnecting}
isEnvironmentUnavailable={
environmentUnavailable !== null ||
@@ -3191,7 +3258,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showPlanFollowUpPrompt={pendingUserInputs.length === 0 && showPlanFollowUpPrompt}
promptHasText={prompt.trim().length > 0}
isSendBusy={isSendBusy}
sendDisabledReason={sendDisabledReason}
sendDisabledReason={effectiveSendDisabledReason}
isConnecting={isConnecting}
isEnvironmentUnavailable={
environmentUnavailable !== null ||
@@ -1,4 +1,4 @@
import { BookmarkIcon, XIcon } from "lucide-react";
import { BookmarkIcon, ImageIcon, XIcon } from "lucide-react";
import { memo, useEffect, useState } from "react";
import { formatRelativeTimeLabel } from "../../timestampFormat";
@@ -121,30 +121,18 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
onRestore(entry);
}}
>
{/* Stashed attachments are server-side ids now, so a
thumbnail would need a signed URL per entry per row.
The count carries the same information. */}
{entry.attachments.length > 0 ? (
<span className="flex shrink-0 items-center -space-x-1.5">
{entry.attachments.slice(0, 3).map((attachment) => (
<img
key={attachment.id}
src={attachment.dataUrl}
alt=""
aria-hidden="true"
className="size-5 rounded border border-border/70 object-cover"
/>
))}
</span>
<ImageIcon className="size-4 shrink-0 text-icon-muted" />
) : (
<BookmarkIcon className="size-4 shrink-0 text-icon-muted" />
)}
<span className="min-w-0 flex-1 truncate text-sm">
{stashEntrySnippet(entry)}
</span>
{entry.pendingImageCount ? (
<span className="shrink-0 text-[10px] text-secondary-label">
saving {entry.pendingImageCount} image
{entry.pendingImageCount === 1 ? "" : "s"}…
</span>
) : missingImageCount(entry) > 0 ? (
{missingImageCount(entry) > 0 ? (
<span className="shrink-0 text-[10px] text-warning-foreground">
{missingImageCount(entry)} image
{missingImageCount(entry) === 1 ? "" : "s"} dropped
@@ -115,8 +115,11 @@ export function DraftHeroHeadline({
return;
}
const project = entry.targetProject;
// Changing the repo of a draft moves the typed content along:
// the user started writing in the wrong project, not a new task.
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
replace: true,
carryComposerContent: true,
});
}}
>
@@ -610,7 +610,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
/>
<TimelineMinimap
items={minimapItems}
bottomInset={contentInsetEndAdjustment}
hasPersistentGutter={minimapHasPersistentGutter}
hitStripWidth={minimapHitStripWidth}
stripMap={minimapStripMap}
@@ -712,14 +711,12 @@ function timelineMinimapEventTargetsPreview(target: EventTarget): boolean {
}
function TimelineMinimap({
bottomInset,
hasPersistentGutter,
hitStripWidth,
items,
stripMap,
onSelect,
}: {
bottomInset: number;
hasPersistentGutter: boolean;
hitStripWidth: number;
items: ReadonlyArray<TimelineMinimapItem>;
@@ -779,19 +776,16 @@ function TimelineMinimap({
return null;
}
const safeBottomInset = Math.max(0, Math.ceil(bottomInset));
return (
<div
className={cn(
"group/minimap pointer-events-none absolute top-0 left-0 z-40 hidden w-18 [@media(pointer:fine)]:block",
"group/minimap pointer-events-none absolute inset-y-0 left-0 z-40 hidden w-18 [@media(pointer:fine)]:block",
hasPersistentGutter
? "opacity-100"
: "opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100",
)}
data-testid="timeline-minimap"
data-persistent-gutter={hasPersistentGutter ? "true" : "false"}
style={{ bottom: safeBottomInset }}
>
<div className="relative h-full w-full select-none">
<button
@@ -19,7 +19,7 @@ export function ClerkUserProfilePage({
}) {
return (
<div className={cn("w-full min-w-0 text-foreground", className)}>
<header className="flex flex-col gap-3 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
<header className="flex flex-col gap-3 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4 sm:pr-8">
<div className="min-w-0">
<h2 className="text-[1.0625rem] leading-6 font-semibold">{title}</h2>
{description ? (
@@ -44,7 +44,7 @@ describe("StyledDiffCodeView", () => {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
paddingTop: 0,
paddingBottom: 0,
paddingBottom: 8,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
});
@@ -304,11 +304,16 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
// Pierre uses its general file spacing as a fallback in expanded-file layout paths.
// Keep it zero alongside the explicit paddings or expanding the first file can
// Keep it zero alongside the explicit paddingTop or expanding the first file can
// reintroduce the library's default 8px gap above its header.
spacing: 0,
paddingTop: 0,
paddingBottom: 0,
// Unlike the gap above, the 8px under a file's last line is painted
// unconditionally by Pierre's stylesheet (`--diffs-gap-fallback`), so the metric has
// to count it: at zero every expanded file's virtual height ran 8px short of its
// rendered height, and the end of the list sat past the reachable scroll range —
// one clipped file row per expanded file above it.
paddingBottom: 8,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
}}
@@ -169,6 +169,7 @@ export function PreviewMoreMenu({
type="button"
onClick={callTab(bridge.resetZoom)}
aria-label="Reset zoom"
className="[:hover,[data-pressed]]:bg-foreground/10"
disabled={tabDisabled}
>
<RotateCcw />
@@ -1,6 +1,8 @@
import { jsx } from "react/jsx-runtime";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import { getPreviewPanelMaxWidth } from "./PreviewPanelShell";
import { getPreviewPanelMaxWidth, PreviewPanelShell } from "./PreviewPanelShell";
describe("getPreviewPanelMaxWidth", () => {
it("allows the panel to use 70% of an ultra-wide viewport without a pixel ceiling", () => {
@@ -10,4 +12,12 @@ describe("getPreviewPanelMaxWidth", () => {
it("rounds fractional CSS pixels down", () => {
expect(getPreviewPanelMaxWidth(2_001)).toBe(1_400);
});
it("keeps inline panels inside their containing workspace", () => {
const markup = renderToStaticMarkup(
jsx(PreviewPanelShell, { mode: "inline", defaultWidth: 1_000, children: "Panel" }),
);
expect(markup).toContain("max-w-full");
});
});
@@ -51,7 +51,7 @@ export function PreviewPanelShell(props: {
return (
<div
className={cn(
"relative flex h-full min-h-0 min-w-0 flex-col self-stretch bg-background",
"relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
isInline
? props.maximized
? "flex-1 border-l border-border"
@@ -19,6 +19,7 @@ import {
useThreadRecentHistory,
} from "~/browserHistoryStore";
import { type ComposerImageAttachment, useComposerDraftStore } from "~/composerDraftStore";
import { startAttachmentUpload } from "~/lib/attachmentUploadQueue";
import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
import { ensureLocalApi } from "~/localApi";
import {
@@ -576,10 +577,18 @@ export function PreviewView({
sizeBytes: screenshotFile.size,
previewUrl: annotation.screenshot.dataUrl,
file: screenshotFile,
upload: { status: "uploading", progress: 0 },
} satisfies ComposerImageAttachment)
: null;
if (image) {
addImage(threadRef, image);
// Element-pick screenshots upload exactly like a pasted image: the
// chip is live immediately, the bytes follow.
startAttachmentUpload({
target: threadRef,
environmentId: threadRef.environmentId,
image,
});
}
if (submission === "send") {
onSendAnnotation?.(annotation, image);
@@ -531,38 +531,11 @@ export function PullRequestDetailPanel({
// and at worst answer from it.
const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
const [refreshToken, setRefreshToken] = useState(0);
const refreshFromHost = useCallback(
async (showFeedback = false) => {
const toastId = showFeedback
? toastManager.add({
type: "loading",
title: "Refreshing pull request...",
})
: null;
const result = await invalidate({ environmentId, input: { reference } });
refreshDetail();
setRefreshToken((token) => token + 1);
if (toastId !== null) {
toastManager.update(
toastId,
result._tag === "Failure"
? {
type: "error",
title: "Could not refresh pull request",
description: readableFailure(
squashAtomCommandFailure(result),
"Try again in a moment.",
),
}
: {
type: "success",
title: "Pull request refreshed",
},
);
}
},
[environmentId, invalidate, reference, refreshDetail],
);
const refreshFromHost = useCallback(async () => {
await invalidate({ environmentId, input: { reference } });
refreshDetail();
setRefreshToken((token) => token + 1);
}, [environmentId, invalidate, reference, refreshDetail]);
// A refresh asked for by the page: the detail, and through the token below, the diff with it.
const appliedForcedToken = useRef(forcedRefreshToken);
useEffect(() => {
@@ -1170,10 +1143,7 @@ export function PullRequestDetailPanel({
<MoreHorizontalIcon className="size-4" />
</MenuTrigger>
<MenuPopup align="end" side="bottom" className="min-w-72">
<MenuItem
disabled={detailQuery.isPending}
onClick={() => void refreshFromHost(true)}
>
<MenuItem disabled={detailQuery.isPending} onClick={() => void refreshFromHost()}>
<RefreshCwIcon className="size-3.5" />
Refresh
</MenuItem>
@@ -3,7 +3,7 @@ import { CircleIcon } from "lucide-react";
import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
import { PullRequestFiltersMenu } from "./PullRequestListFilters";
import { PullRequestFiltersMenu, pullRequestProjectKey } from "./PullRequestListFilters";
function findValueChange(
node: ReactNode,
@@ -129,7 +129,7 @@ describe("pull request filters menu", () => {
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
radioGroup?.props.onValueChange(`${environmentId} ${projectId}`);
radioGroup?.props.onValueChange(pullRequestProjectKey({ id: projectId, environmentId }));
expect(onProject).not.toHaveBeenCalled();
radioGroup?.props.onValueChange("all");
@@ -159,7 +159,23 @@ describe("pull request filters menu", () => {
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
radioGroup?.props.onValueChange(`env-2 ${projectId}`);
radioGroup?.props.onValueChange(
pullRequestProjectKey({ id: projectId, environmentId: "env-2" as EnvironmentId }),
);
expect(onProject).toHaveBeenCalledWith(projectId, "env-2");
});
it("does not collide when environment and project ids contain spaces", () => {
expect(
pullRequestProjectKey({
environmentId: "a b" as EnvironmentId,
id: "c" as ProjectId,
}),
).not.toBe(
pullRequestProjectKey({
environmentId: "a" as EnvironmentId,
id: "b c" as ProjectId,
}),
);
});
});
@@ -122,10 +122,10 @@ const UNFILTERED_VALUE = "all";
* A project's own radio value, carrying the server along with the id: the id alone is only
* unique within its own server, so two rows sharing one would otherwise both read as checked.
*/
const projectMenuValue = (project: {
export const pullRequestProjectKey = (project: {
readonly id: ProjectId;
readonly environmentId: EnvironmentId;
}) => `${project.environmentId} ${project.id}`;
}) => JSON.stringify([project.environmentId, project.id]);
const DRAFT_OPTIONS = [
{ value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
@@ -247,7 +247,7 @@ export function PullRequestFiltersMenu({
* the reader is already choosing between projects, rather than as a count above the list
* that says something is missing without saying which.
*/
unavailable: ReadonlyMap<ProjectId, string>;
unavailable: ReadonlyMap<string, string>;
/** The environment comes with the project id, since picking a row picks a specific server's copy of it. */
onProject: (projectId: ProjectId | undefined, environmentId: EnvironmentId | undefined) => void;
}) {
@@ -350,7 +350,7 @@ export function PullRequestFiltersMenu({
value={
projectId === undefined || projectEnvironmentId === undefined
? ALL_PROJECTS_VALUE
: projectMenuValue({ id: projectId, environmentId: projectEnvironmentId })
: pullRequestProjectKey({ id: projectId, environmentId: projectEnvironmentId })
}
onValueChange={(next) => {
if (next === ALL_PROJECTS_VALUE) {
@@ -359,7 +359,7 @@ export function PullRequestFiltersMenu({
}
// The value carries both halves, since the id alone cannot tell two servers' rows
// apart once they share one.
const project = projects.find((candidate) => projectMenuValue(candidate) === next);
const project = projects.find((candidate) => pullRequestProjectKey(candidate) === next);
if (
project !== undefined &&
(project.id !== projectId || project.environmentId !== projectEnvironmentId)
@@ -379,14 +379,16 @@ export function PullRequestFiltersMenu({
as a broken menu rather than as a workspace with three unreadable repositories. */}
{projects
.toSorted(
(left, right) => Number(unavailable.has(left.id)) - Number(unavailable.has(right.id)),
(left, right) =>
Number(unavailable.has(pullRequestProjectKey(left))) -
Number(unavailable.has(pullRequestProjectKey(right))),
)
.map((project) => {
const reason = unavailable.get(project.id);
const reason = unavailable.get(pullRequestProjectKey(project));
return (
<MenuRadioItem
key={projectMenuValue(project)}
value={projectMenuValue(project)}
key={pullRequestProjectKey(project)}
value={pullRequestProjectKey(project)}
disabled={reason !== undefined}
title={reason}
>
@@ -1,4 +1,4 @@
import type { EnvironmentId, PullRequestListEntry } from "@t3tools/contracts";
import type { EnvironmentId, ProjectId, PullRequestListEntry } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -710,6 +710,20 @@ describe("merging the environments' own listings", () => {
);
});
it("keeps project errors scoped to the environment that reported them", () => {
const error = {
projectId: "project-1" as ProjectId,
projectTitle: "Web",
message: "Not signed in",
} as const;
const merged = mergePullRequestLists([
[ENV_1, answer({ errors: [error] })],
[ENV_2, answer()],
]);
expect(merged?.errors).toEqual([{ ...error, environmentId: ENV_1 }]);
});
it("folds a host reached from two environments into one switcher row", () => {
const merged = mergePullRequestLists([
[ENV_1, answer()],
@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";
import {
EnvironmentId,
PullRequestListEntry,
PullRequestListProjectError,
PullRequestListResult,
resolvePullRequestAuthorFilter,
} from "@t3tools/contracts";
@@ -27,6 +28,10 @@ export interface EnvironmentPullRequestStat extends PullRequestDiffStat {
readonly environmentId: EnvironmentId;
}
export interface EnvironmentPullRequestError extends PullRequestListProjectError {
readonly environmentId: EnvironmentId;
}
export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
export interface PullRequestGroup<Entry extends PullRequestListEntry = PullRequestListEntry> {
@@ -452,7 +457,7 @@ export interface MergedPullRequestList {
readonly viewers: PullRequestViewers;
readonly providers: PullRequestListResult["providers"];
readonly entries: ReadonlyArray<EnvironmentPullRequestEntry>;
readonly errors: PullRequestListResult["errors"];
readonly errors: ReadonlyArray<EnvironmentPullRequestError>;
readonly truncated: boolean;
readonly nextCursors: Readonly<Record<string, PullRequestListCursors>>;
/**
@@ -476,7 +481,7 @@ export function mergePullRequestLists(
const truncatedEnvironments: string[] = [];
const providers = new Map<string, PullRequestListResult["providers"][number]>();
const entries: EnvironmentPullRequestEntry[] = [];
const errors: Array<PullRequestListResult["errors"][number]> = [];
const errors: EnvironmentPullRequestError[] = [];
const nextCursors: Record<string, PullRequestListCursors> = {};
let truncated = false;
for (const [environmentId, answer] of answers) {
@@ -498,7 +503,7 @@ export function mergePullRequestLists(
);
}
entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
errors.push(...answer.errors);
errors.push(...answer.errors.map((error) => ({ ...error, environmentId })));
truncated ||= answer.truncated;
if (answer.truncated) truncatedEnvironments.push(environmentId);
if (Object.keys(answer.nextCursors).length > 0) {
@@ -559,12 +564,18 @@ const EnvironmentPullRequestEntrySchema = Schema.Struct({
environmentId: EnvironmentId,
});
const EnvironmentPullRequestErrorSchema = Schema.Struct({
...PullRequestListProjectError.fields,
environmentId: EnvironmentId,
});
const decodeSnapshot = Schema.decodeUnknownOption(
Schema.Struct({
scope: Schema.String,
data: Schema.Struct({
...PullRequestListResult.fields,
entries: Schema.Array(EnvironmentPullRequestEntrySchema),
errors: Schema.Array(EnvironmentPullRequestErrorSchema),
// Per environment here, unlike the wire shape, which is per repository within one.
nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
truncatedEnvironments: Schema.Array(Schema.String),
@@ -493,6 +493,9 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays
? ["Auto-settle inactive threads"]
: []),
...(settings.sidebarAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge
? ["Auto-settle merged threads"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
...getChangedTypographySettingLabels(settings),
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
@@ -547,6 +550,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.enableLegacyTokenStreaming,
settings.enableProviderUpdateChecks,
settings.sidebarAutoSettleAfterDays,
settings.sidebarAutoSettleOnMerge,
settings.sidebarProjectGroupingMode,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
@@ -628,6 +632,7 @@ export function useSettingsRestore(onRestored?: () => void) {
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays,
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming,
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
@@ -1828,9 +1833,36 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
{...searchableSetting("auto-settle-merged-threads")}
description="Settle a thread when its pull request merges. Closed pull requests still settle automatically."
resetAction={
settings.sidebarAutoSettleOnMerge !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ? (
<SettingResetButton
label="auto-settle on merge"
onClick={() =>
updateSettings({
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
})
}
/>
) : null
}
control={
<Switch
checked={settings.sidebarAutoSettleOnMerge}
onCheckedChange={(checked) =>
updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) })
}
aria-label="Auto-settle merged threads"
/>
}
/>
<SettingsRow
{...searchableSetting("auto-settle-inactive-threads")}
description="Sidebar threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
description="Sidebar threads with no activity for this long settle automatically."
resetAction={
settings.sidebarAutoSettleAfterDays !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ? (
@@ -19,7 +19,7 @@ import {
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
import { usePrimaryEnvironment } from "../../state/environments";
import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
import { useEnvironmentQuery } from "../../state/query";
import { sourceControlEnvironment } from "../../state/sourceControl";
import { Badge } from "../ui/badge";
@@ -508,7 +508,15 @@ function EmptySourceControlDiscovery({
}
export function SourceControlSettingsPanel() {
const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const fallbackEnvironment =
environments.find((environment) => environment.connection.phase === "connected") ??
environments[0] ??
null;
const environmentId =
primaryEnvironment?.environmentId ?? fallbackEnvironment?.environmentId ?? null;
const isPrimaryEnvironment = environmentId === primaryEnvironment?.environmentId;
const discovery = useEnvironmentQuery(
environmentId === null
? null
@@ -561,7 +569,9 @@ export function SourceControlSettingsPanel() {
>
{result.versionControlSystems.map((item) => (
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
{item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
{item.kind === "git" && isPrimaryEnvironment ? (
<GitFetchIntervalSettings />
) : undefined}
</DiscoveryItemRow>
))}
</SettingsSection>
@@ -587,7 +597,7 @@ export function SourceControlSettingsPanel() {
/>
)}
{environmentId !== null ? <SourceControlWritingSettingsSection /> : null}
{isPrimaryEnvironment ? <SourceControlWritingSettingsSection /> : null}
</SettingsPageContainer>
);
}
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more