Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
593aa69833 | ||
|
|
4f648f1e11 | ||
|
|
53ab016efd | ||
|
|
d8e0ba3ea0 | ||
|
|
32e7844837 | ||
|
|
482d56233d | ||
|
|
6009720844 | ||
|
|
e26e55f389 | ||
|
|
4ac094fef6 | ||
|
|
a7e43b2281 |
No files matched your search
@@ -0,0 +1,110 @@
|
||||
name: Mobile EAS Production
|
||||
|
||||
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
|
||||
# Under the fingerprint runtime-version policy the fingerprint must be computed
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "build (+ auto-submit to TestFlight) or update (OTA)"
|
||||
required: true
|
||||
type: choice
|
||||
default: build
|
||||
options:
|
||||
- build
|
||||
- update
|
||||
platform:
|
||||
description: "Target platform"
|
||||
required: true
|
||||
type: choice
|
||||
default: ios
|
||||
options:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
packager: pnpm
|
||||
|
||||
- name: Pull production environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
vp staged
|
||||
@@ -66,7 +66,11 @@ const config: ExpoConfig = {
|
||||
scheme: variant.scheme,
|
||||
version: "0.1.0",
|
||||
runtimeVersion: {
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
|
||||
// could land on a binary missing the native changes it needs and crash.
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
|
||||
},
|
||||
orientation: "portrait",
|
||||
icon: "./assets/icon.png",
|
||||
@@ -157,6 +161,9 @@ const config: ExpoConfig = {
|
||||
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
|
||||
enablePushNotifications: true,
|
||||
// Agent activity can update many times an hour; without the
|
||||
// frequent-updates entitlement iOS throttles the update budget sooner.
|
||||
frequentUpdates: true,
|
||||
widgets: [
|
||||
{
|
||||
name: "AgentActivity",
|
||||
@@ -167,6 +174,9 @@ const config: ExpoConfig = {
|
||||
],
|
||||
},
|
||||
],
|
||||
// Must run after expo-widgets so the widget target exists when it wires in
|
||||
// the branded logo asset catalog.
|
||||
"./plugins/withWidgetLogoAsset.cjs",
|
||||
"./plugins/withIosSceneLifecycle.cjs",
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
],
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg width="111" height="74" viewBox="7 29 111 74" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="black"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 887 B |
@@ -6,6 +6,7 @@
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "development"
|
||||
},
|
||||
@@ -14,6 +15,7 @@
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview"
|
||||
},
|
||||
@@ -22,6 +24,7 @@
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview:dev": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview",
|
||||
"MOBILE_VERSION_POLICY": "fingerprint"
|
||||
@@ -35,6 +38,7 @@
|
||||
}
|
||||
},
|
||||
"production": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "production"
|
||||
},
|
||||
@@ -46,7 +50,10 @@
|
||||
"submit": {
|
||||
"production": {
|
||||
"ios": {
|
||||
"ascAppId": "6761315631"
|
||||
"ascAppId": "6787819824"
|
||||
},
|
||||
"android": {
|
||||
"track": "internal"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-keyboard-controller": "1.21.13",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
|
||||
// Bundle the widget asset catalog into an app-extension (widget) target.
|
||||
//
|
||||
// expo-widgets generates the widget target without a Resources build phase, and
|
||||
// hand-adding a PBXResourcesBuildPhase does NOT get picked up — xcodebuild's
|
||||
// planner never schedules `actool` for it (verified: even a full re-plan skips
|
||||
// it). So instead we add a shell-script phase that runs `actool` directly and
|
||||
// drops the compiled Assets.car into the extension bundle. Marked
|
||||
// alwaysOutOfDate so the build system always runs it.
|
||||
//
|
||||
// Idempotent across re-runs. Returns true when it added the phase, false when it
|
||||
// was already present or the target was not found.
|
||||
|
||||
const PHASE_NAME = "Compile Widget Assets";
|
||||
|
||||
// Compiles ExpoWidgetsTarget/Assets.xcassets into the extension's resources dir.
|
||||
// Uses only Xcode-provided build settings so it works for device + simulator.
|
||||
const ACTOOL_SCRIPT = [
|
||||
"set -e",
|
||||
'CATALOG="${SRCROOT}/ExpoWidgetsTarget/Assets.xcassets"',
|
||||
'if [ ! -d "$CATALOG" ]; then',
|
||||
' echo "warning: widget asset catalog not found at $CATALOG"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'DEST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"',
|
||||
'mkdir -p "$DEST"',
|
||||
'xcrun actool "$CATALOG" --compile "$DEST" --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET:-16.0}" --output-format human-readable-text',
|
||||
].join("\n");
|
||||
|
||||
function stripComments(map) {
|
||||
const out = {};
|
||||
for (const key of Object.keys(map || {})) {
|
||||
if (key.endsWith("_comment")) continue;
|
||||
out[key] = map[key];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function findByName(map, name) {
|
||||
for (const [uuid, value] of Object.entries(stripComments(map))) {
|
||||
if (value && value.name === name) return { uuid, value };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('xcode').XcodeProject} proj
|
||||
* @param {{ targetName: string }} opts
|
||||
*/
|
||||
function addWidgetAssetCatalog(proj, opts) {
|
||||
const objects = proj.hash.project.objects;
|
||||
const target = findByName(objects.PBXNativeTarget, opts.targetName);
|
||||
if (!target) return false;
|
||||
|
||||
const phases = target.value.buildPhases || [];
|
||||
const existing = objects.PBXShellScriptBuildPhase || {};
|
||||
const already = Object.entries(stripComments(existing)).some(
|
||||
([uuid, value]) =>
|
||||
value && value.name === `"${PHASE_NAME}"` && phases.some((p) => p.value === uuid),
|
||||
);
|
||||
if (already) return false;
|
||||
|
||||
const { uuid } = proj.addBuildPhase([], "PBXShellScriptBuildPhase", PHASE_NAME, target.uuid, {
|
||||
shellPath: "/bin/sh",
|
||||
shellScript: ACTOOL_SCRIPT,
|
||||
});
|
||||
// Always run: input-analysis is exactly what skipped the Resources phase.
|
||||
objects.PBXShellScriptBuildPhase[uuid].alwaysOutOfDate = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = { addWidgetAssetCatalog };
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
|
||||
// Ships the branded T3 mark to the Live Activity / widget extension.
|
||||
//
|
||||
// expo-widgets generates ExpoWidgetsTarget without a Resources build phase and
|
||||
// has no asset support, so this plugin (a) writes an SVG template image set into
|
||||
// the generated widget asset catalog and (b) wires that catalog into the widget
|
||||
// target with a dedicated Resources build phase. Both steps are idempotent and
|
||||
// survive `expo prebuild --clean`. Must be listed AFTER "expo-widgets" in the
|
||||
// plugins array so the widget target exists when this runs.
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
|
||||
const { addWidgetAssetCatalog } = require("./lib/addWidgetAssetCatalog.cjs");
|
||||
|
||||
const TARGET_NAME = "ExpoWidgetsTarget";
|
||||
const CATALOG_NAME = "Assets.xcassets";
|
||||
const IMAGE_SET = "T3Mark.imageset";
|
||||
const SVG_NAME = "T3Mark.svg";
|
||||
|
||||
const CATALOG_CONTENTS = JSON.stringify({ info: { author: "expo", version: 1 } }, null, 2) + "\n";
|
||||
const IMAGE_SET_CONTENTS =
|
||||
JSON.stringify(
|
||||
{
|
||||
images: [{ idiom: "universal", filename: SVG_NAME }],
|
||||
info: { author: "expo", version: 1 },
|
||||
properties: {
|
||||
"preserves-vector-representation": true,
|
||||
"template-rendering-intent": "template",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n";
|
||||
|
||||
function withAssetFiles(config) {
|
||||
return withDangerousMod(config, [
|
||||
"ios",
|
||||
(cfg) => {
|
||||
const source = path.join(cfg.modRequest.projectRoot, "assets", "widget", SVG_NAME);
|
||||
const catalogDir = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, CATALOG_NAME);
|
||||
const imageSetDir = path.join(catalogDir, IMAGE_SET);
|
||||
fs.mkdirSync(imageSetDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(catalogDir, "Contents.json"), CATALOG_CONTENTS);
|
||||
fs.writeFileSync(path.join(imageSetDir, "Contents.json"), IMAGE_SET_CONTENTS);
|
||||
fs.copyFileSync(source, path.join(imageSetDir, SVG_NAME));
|
||||
return cfg;
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function withAssetWiring(config) {
|
||||
return withXcodeProject(config, (cfg) => {
|
||||
addWidgetAssetCatalog(cfg.modResults, { targetName: TARGET_NAME });
|
||||
return cfg;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = function withWidgetLogoAsset(config) {
|
||||
return withAssetWiring(withAssetFiles(config));
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
|
||||
// One-off: apply the widget asset-catalog wiring to the already-generated
|
||||
// ios/ project so the current build compiles ExpoWidgetsTarget/Assets.xcassets
|
||||
// without a full `expo prebuild`. The durable equivalent lives in
|
||||
// plugins/withWidgetLogoAsset.cjs and runs on prebuild.
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
const xcodePath = require.resolve("xcode", {
|
||||
paths: [
|
||||
require.resolve("@expo/config-plugins", { paths: [require.resolve("expo/package.json")] }),
|
||||
],
|
||||
});
|
||||
const xcode = require(xcodePath);
|
||||
const { addWidgetAssetCatalog } = require("../plugins/lib/addWidgetAssetCatalog.cjs");
|
||||
|
||||
const pbxprojPath = path.join(__dirname, "..", "ios", "T3CodeDev.xcodeproj", "project.pbxproj");
|
||||
const proj = xcode.project(pbxprojPath);
|
||||
proj.parseSync();
|
||||
|
||||
const added = addWidgetAssetCatalog(proj, { targetName: "ExpoWidgetsTarget" });
|
||||
|
||||
if (added) {
|
||||
fs.writeFileSync(pbxprojPath, proj.writeSync());
|
||||
console.log("Added widget asset-compile phase to ExpoWidgetsTarget.");
|
||||
} else {
|
||||
console.log("No change: phase already present or target not found.");
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import { AppText as Text } from "./components/AppText";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
|
||||
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
|
||||
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
|
||||
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
|
||||
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
|
||||
@@ -220,6 +222,7 @@ const NewTaskSheetStack = createNativeStackNavigator({
|
||||
// influence the adaptive workspace layout: opening Settings over Home should
|
||||
// not flip the sidebar in or change the active thread.
|
||||
const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"ConnectOnboarding",
|
||||
"Connections",
|
||||
"ConnectionsNew",
|
||||
"GitBranches",
|
||||
@@ -251,6 +254,8 @@ function RootStackLayout(props: {
|
||||
}) {
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
|
||||
useConnectOnboardingNavigation();
|
||||
// Full pathname (sheets included) for keyboard-command scoping; the
|
||||
// workspace layout only reacts to the underlying non-overlay route.
|
||||
const path = getPathFromState(props.state, navigationPathConfig);
|
||||
@@ -412,6 +417,20 @@ export const RootStack = createNativeStackNavigator({
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
ConnectOnboarding: createNativeStackScreen({
|
||||
screen: ConnectOnboardingRouteScreen,
|
||||
linking: "connect-onboarding",
|
||||
options: {
|
||||
// Root screenOptions hide headers; formSheets that want the native
|
||||
// title bar opt back in with the sheet header preset.
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.6, 0.95],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
Connections: createNativeStackScreen({
|
||||
screen: ConnectionsRouteScreen,
|
||||
linking: "connections",
|
||||
|
||||
@@ -92,7 +92,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
if (session === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "Sign in to T3 Cloud to connect this environment.",
|
||||
detail: "Sign in to T3 Connect to connect this environment.",
|
||||
});
|
||||
}
|
||||
const token = yield* session.readClerkToken().pipe(
|
||||
@@ -107,7 +107,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
detail: "The T3 Connect session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
|
||||
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof snapshotLoaderLayer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof connectionPlatformLayer;
|
||||
|
||||
const connectionLayer = Connection.layer.pipe(
|
||||
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -32,7 +32,10 @@ import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
// v2 stores the snapshot sequence alongside the thread so a warm cache can
|
||||
// resume via `afterSequence` instead of re-downloading the full thread body.
|
||||
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
@@ -45,7 +48,7 @@ const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
thread: OrchestrationThread,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
});
|
||||
|
||||
const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
@@ -355,18 +358,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}),
|
||||
saveThread: (environmentId, thread) =>
|
||||
saveThread: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const file = yield* threadSnapshotFile(environmentId, snapshot.thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
threadId: snapshot.thread.id,
|
||||
snapshot,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
|
||||
@@ -2,11 +2,20 @@ import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
|
||||
|
||||
import type { Preferences } from "../../lib/storage";
|
||||
|
||||
// Development builds are Xcode-signed and receive sandbox APNs tokens;
|
||||
// preview and production builds are distribution-signed and use production
|
||||
// APNs. The relay routes each device's pushes accordingly.
|
||||
export function resolveApsEnvironment(appVariant: unknown): "sandbox" | "production" {
|
||||
return appVariant === "development" ? "sandbox" : "production";
|
||||
}
|
||||
|
||||
export function makeRelayDeviceRegistrationRequest(input: {
|
||||
readonly deviceId: string;
|
||||
readonly label: string;
|
||||
readonly iosMajorVersion: number;
|
||||
readonly appVersion?: string;
|
||||
readonly bundleId?: string;
|
||||
readonly apsEnvironment?: "sandbox" | "production";
|
||||
readonly pushToken?: string;
|
||||
readonly pushToStartToken?: string;
|
||||
readonly notificationsEnabled: boolean;
|
||||
@@ -19,6 +28,8 @@ export function makeRelayDeviceRegistrationRequest(input: {
|
||||
platform: "ios",
|
||||
iosMajorVersion: input.iosMajorVersion,
|
||||
appVersion: input.appVersion,
|
||||
...(input.bundleId ? { bundleId: input.bundleId } : {}),
|
||||
...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),
|
||||
...(input.pushToken ? { pushToken: input.pushToken } : {}),
|
||||
...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
|
||||
preferences: {
|
||||
|
||||
@@ -16,15 +16,23 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { cryptoLayer } from "../cloud/dpop";
|
||||
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
loadAgentAwarenessRegistrationRecord,
|
||||
loadOrCreateAgentAwarenessDeviceId,
|
||||
saveAgentAwarenessRegistrationRecord,
|
||||
} from "../../lib/storage";
|
||||
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
|
||||
import {
|
||||
AgentAwarenessOperationError,
|
||||
__resetAgentAwarenessRemoteRegistrationForTest,
|
||||
getAgentAwarenessRegistrationStatus,
|
||||
refreshActiveLiveActivityRemoteRegistration,
|
||||
refreshAgentAwarenessRegistration,
|
||||
normalizeAgentAwarenessRelayBaseUrl,
|
||||
registerAgentAwarenessConnection,
|
||||
registerLiveActivityPushToken,
|
||||
releaseAgentAwarenessRelayTokenProvider,
|
||||
setAgentAwarenessRelayTokenProvider,
|
||||
shouldRegisterAgentAwarenessDeviceForProvider,
|
||||
unregisterAgentAwarenessConnection,
|
||||
@@ -41,6 +49,16 @@ const backgroundRuntime = vi.hoisted(() => ({
|
||||
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
|
||||
}>,
|
||||
}));
|
||||
const appStateMock = vi.hoisted(() => ({
|
||||
listeners: [] as Array<(state: string) => void>,
|
||||
}));
|
||||
const registrationRecordStore = vi.hoisted(() => ({
|
||||
current: null as {
|
||||
readonly identity: string;
|
||||
readonly signature: string;
|
||||
readonly pushToStartToken?: string;
|
||||
} | null,
|
||||
}));
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -100,6 +118,19 @@ vi.mock("react-native", () => ({
|
||||
OS: "ios",
|
||||
Version: "18.0",
|
||||
},
|
||||
AppState: {
|
||||
addEventListener: (_event: string, listener: (state: string) => void) => {
|
||||
appStateMock.listeners.push(listener);
|
||||
return {
|
||||
remove: () => {
|
||||
const index = appStateMock.listeners.indexOf(listener);
|
||||
if (index >= 0) {
|
||||
appStateMock.listeners.splice(index, 1);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/runtime", () => ({
|
||||
@@ -114,7 +145,18 @@ vi.mock("../../lib/runtime", () => ({
|
||||
vi.mock("../../lib/storage", () => ({
|
||||
loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
|
||||
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
|
||||
loadPreferences: vi.fn(() => Promise.resolve({})),
|
||||
loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
|
||||
loadAgentAwarenessRegistrationRecord: vi.fn(() =>
|
||||
Promise.resolve(registrationRecordStore.current),
|
||||
),
|
||||
saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => {
|
||||
registrationRecordStore.current = record;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
clearAgentAwarenessRegistrationRecord: vi.fn(() => {
|
||||
registrationRecordStore.current = null;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
}));
|
||||
|
||||
function proofIat(proof: string): number {
|
||||
@@ -176,6 +218,12 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
backgroundRuntime.pending.length = 0;
|
||||
Constants.expoConfig!.extra = {};
|
||||
__resetAgentAwarenessRemoteRegistrationForTest();
|
||||
appStateMock.listeners.length = 0;
|
||||
registrationRecordStore.current = null;
|
||||
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
|
||||
vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
|
||||
vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
|
||||
widgetMocks.getInstances.mockReset();
|
||||
widgetMocks.getInstances.mockReturnValue([]);
|
||||
});
|
||||
@@ -213,6 +261,31 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("registers the app's APNs routing so the relay targets the right bundle", () => {
|
||||
expect(
|
||||
makeRelayDeviceRegistrationRequest({
|
||||
deviceId: "device-1",
|
||||
label: "Julius's iPhone",
|
||||
iosMajorVersion: 18,
|
||||
appVersion: "1.0.0",
|
||||
bundleId: "com.t3tools.t3code.preview",
|
||||
apsEnvironment: resolveApsEnvironment("preview"),
|
||||
notificationsEnabled: true,
|
||||
preferences: {},
|
||||
}),
|
||||
).toMatchObject({
|
||||
bundleId: "com.t3tools.t3code.preview",
|
||||
apsEnvironment: "production",
|
||||
});
|
||||
});
|
||||
|
||||
it("routes development builds to the APNs sandbox", () => {
|
||||
expect(resolveApsEnvironment("development")).toBe("sandbox");
|
||||
expect(resolveApsEnvironment("preview")).toBe("production");
|
||||
expect(resolveApsEnvironment("production")).toBe("production");
|
||||
expect(resolveApsEnvironment(undefined)).toBe("production");
|
||||
});
|
||||
|
||||
it("marks notification delivery disabled when APNs permission is unavailable", () => {
|
||||
expect(
|
||||
makeRelayDeviceRegistrationRequest({
|
||||
@@ -329,6 +402,53 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"re-registers active Live Activity tokens when the app returns to the foreground",
|
||||
() => {
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
activity.getPushToken.mockClear();
|
||||
|
||||
expect(appStateMock.listeners).toHaveLength(1);
|
||||
for (const listener of appStateMock.listeners) {
|
||||
listener("background");
|
||||
}
|
||||
yield* runBackgroundOperations();
|
||||
expect(activity.getPushToken).not.toHaveBeenCalled();
|
||||
|
||||
for (const listener of appStateMock.listeners) {
|
||||
listener("active");
|
||||
}
|
||||
yield* runBackgroundOperations();
|
||||
expect(activity.getPushToken).toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
},
|
||||
);
|
||||
|
||||
it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
|
||||
const end = vi.fn(() => Promise.resolve());
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
end,
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
expect(appStateMock.listeners).toHaveLength(1);
|
||||
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
|
||||
expect(end).toHaveBeenCalledWith("immediate");
|
||||
expect(appStateMock.listeners).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.effect("refreshes APNs registration for connected environments after settings changes", () => {
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
return Effect.gen(function* () {
|
||||
@@ -395,6 +515,174 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
nowEpochSeconds: proofIat(dpop),
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("marks registration failed when device registration cannot complete", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
|
||||
new Error("registration failed"),
|
||||
);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
// Drive the registration directly so the assertion does not depend on the
|
||||
// background queue draining; refreshAgentAwarenessRegistration swallows the
|
||||
// error but must record the failed status so the settings toggles cannot
|
||||
// read as enabled.
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("failed");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it("clears registration status on cloud sign-out", () => {
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
|
||||
expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("releases the provider without ending activities or clearing the registration", () => {
|
||||
const end = vi.fn(() => Promise.resolve());
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
end,
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
registrationRecordStore.current = { identity: "", signature: "sig" };
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
expect(appStateMock.listeners).toHaveLength(1);
|
||||
|
||||
releaseAgentAwarenessRelayTokenProvider();
|
||||
|
||||
expect(appStateMock.listeners).toHaveLength(0);
|
||||
expect(end).not.toHaveBeenCalled();
|
||||
expect(clearAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
|
||||
expect(registrationRecordStore.current).not.toBeNull();
|
||||
});
|
||||
|
||||
it.effect("resets a pending status to unknown when relay config is missing", () => {
|
||||
// No relay url configured: registration can neither run nor ever succeed,
|
||||
// so the status must not stick at "pending".
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("keeps a registered status when a later refresh fails", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
|
||||
// The relay still holds the accepted registration; a transient refresh
|
||||
// failure must not flip the settings toggles off.
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
|
||||
new Error("transient failure"),
|
||||
);
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("does not re-register the same account when nothing has changed", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
|
||||
expect(registrationRecordStore.current).not.toBeNull();
|
||||
|
||||
// Second attempt with an identical payload must skip the relay entirely,
|
||||
// so no new registration record is written.
|
||||
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
|
||||
expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("dedupes rapid activity-token re-registrations within the replay window", () => {
|
||||
// Fetch counts are unreliable here (the module-level relay layer captures
|
||||
// the first test's fetch), so assert on the flow's own seams: a real
|
||||
// registration attempt loads the device id, a deduped one short-circuits
|
||||
// before it.
|
||||
const fetchMock = vi.fn((request: RequestInfo | URL) => {
|
||||
const url = request instanceof Request ? request.url : String(request);
|
||||
return Promise.resolve(
|
||||
Response.json(
|
||||
url.endsWith("/v1/client/dpop-token")
|
||||
? {
|
||||
access_token: "relay-dpop-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "DPoP",
|
||||
expires_in: 300,
|
||||
scope: "mobile:registration",
|
||||
}
|
||||
: { ok: true },
|
||||
),
|
||||
);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
// Drains the sign-in refresh, which registers the activity token.
|
||||
yield* runBackgroundOperations();
|
||||
expect(activity.getPushToken).toHaveBeenCalled();
|
||||
|
||||
// A burst refresh (foreground / connection update seconds later) must
|
||||
// dedupe: it reads the token but never proceeds to a registration
|
||||
// attempt (which would load the device id first).
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockClear();
|
||||
yield* refreshActiveLiveActivityRemoteRegistration();
|
||||
expect(loadOrCreateAgentAwarenessDeviceId).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("re-registers when the stored account identity differs", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
registrationRecordStore.current = { identity: "someone-else", signature: "stale" };
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
|
||||
import { type LiveActivity } from "expo-widgets";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Platform } from "react-native";
|
||||
import { AppState, Platform } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
type RelayDeviceRegistrationRequest,
|
||||
type RelayAgentActivitySnapshotResponse,
|
||||
type RelayLiveActivityRegistrationRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
@@ -20,13 +21,16 @@ import {
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
loadAgentAwarenessDeviceId,
|
||||
loadAgentAwarenessRegistrationRecord,
|
||||
loadOrCreateAgentAwarenessDeviceId,
|
||||
loadPreferences,
|
||||
saveAgentAwarenessRegistrationRecord,
|
||||
} from "../../lib/storage";
|
||||
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
|
||||
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
|
||||
|
||||
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
|
||||
|
||||
@@ -42,6 +46,8 @@ const AgentAwarenessOperation = Schema.Literals([
|
||||
"read-live-activity-push-token",
|
||||
"load-live-activity-registration-identifier",
|
||||
"list-active-live-activities",
|
||||
"load-live-activity-prime-preferences",
|
||||
"prime-live-activity",
|
||||
]);
|
||||
|
||||
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
|
||||
@@ -58,8 +64,49 @@ export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentA
|
||||
|
||||
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
|
||||
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
|
||||
let pushToStartSubscription: { remove: () => void } | null = null;
|
||||
// Activity tokens the relay recently accepted, by acceptance time. The refresh
|
||||
// runs on sign-in, every app foreground, and every environment-connection
|
||||
// update, which arrive in bursts and spammed identical registrations. But the
|
||||
// registration is not a pure no-op: the relay replays the current aggregate to
|
||||
// this device on every accepted registration, and that replay is the
|
||||
// foreground reconciliation that repairs drifted or orphaned activities. So
|
||||
// dedupe only within a short window — bursts collapse to one request, while a
|
||||
// foreground after real time away still triggers a replay. Cleared on
|
||||
// sign-out/identity change alongside the device registration state.
|
||||
const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
|
||||
const registeredActivityPushTokens = new Map<string, number>();
|
||||
let pushTokenSubscription: { remove: () => void } | null = null;
|
||||
let appStateSubscription: { remove: () => void } | null = null;
|
||||
|
||||
// Whether the relay has actually accepted this device's registration. The
|
||||
// notification/Live Activity settings toggles must reflect this rather than
|
||||
// only local iOS permission or saved preferences: if the registration request
|
||||
// never succeeded, the device cannot receive anything, so the switches must
|
||||
// not read as enabled.
|
||||
export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "registered" | "failed";
|
||||
let registrationStatus: AgentAwarenessRegistrationStatus = "unknown";
|
||||
const registrationStatusListeners = new Set<() => void>();
|
||||
|
||||
function setRegistrationStatus(next: AgentAwarenessRegistrationStatus): void {
|
||||
if (registrationStatus === next) {
|
||||
return;
|
||||
}
|
||||
registrationStatus = next;
|
||||
for (const listener of registrationStatusListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus {
|
||||
return registrationStatus;
|
||||
}
|
||||
|
||||
export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {
|
||||
registrationStatusListeners.add(listener);
|
||||
return () => {
|
||||
registrationStatusListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
|
||||
let relayTokenProvider: (() => Promise<string | null>) | null = null;
|
||||
let relayTokenProviderIdentity: string | null = null;
|
||||
@@ -74,7 +121,6 @@ let pendingDeviceRegistration: {
|
||||
} | null = null;
|
||||
|
||||
interface DeviceRegistrationInput {
|
||||
readonly pushToStartToken?: string;
|
||||
readonly observedPushToken?: string;
|
||||
}
|
||||
|
||||
@@ -120,32 +166,66 @@ export function setAgentAwarenessRelayTokenProvider(
|
||||
deviceRegistrationGeneration++;
|
||||
activeDeviceRegistration = null;
|
||||
pendingDeviceRegistration = null;
|
||||
registeredActivityPushTokens.clear();
|
||||
}
|
||||
relayTokenProvider = provider;
|
||||
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
|
||||
if (!provider) {
|
||||
pushToStartSubscription?.remove();
|
||||
pushToStartSubscription = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
}
|
||||
// Without a signed-in user the relay can no longer update or end these
|
||||
// activities, so they would sit orphaned on the lock screen.
|
||||
endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
|
||||
setRegistrationStatus("unknown");
|
||||
// Sign-out is the only thing that invalidates a stored registration, so the
|
||||
// next sign-in re-registers.
|
||||
void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
|
||||
logRegistrationError("clear registration record on sign-out failed", error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
ensurePushToStartListener();
|
||||
ensurePushTokenListener();
|
||||
ensureAppStateListener();
|
||||
runRegistrationInBackground(
|
||||
refreshActiveLiveActivityRemoteRegistration(),
|
||||
"active live activity registration after cloud sign-in failed",
|
||||
);
|
||||
if (isExistingIdentity) {
|
||||
// Same account re-activating (e.g. Clerk token refresh) normally needs no
|
||||
// re-registration — but if the previous attempt never succeeded, this is
|
||||
// the only trigger that will retry it before the next cold start.
|
||||
if (registrationStatus !== "registered") {
|
||||
enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
|
||||
}
|
||||
|
||||
// Detach the provider and native listeners without the destructive sign-out
|
||||
// cleanup. For provider teardown while the user is still signed in (e.g. the
|
||||
// auth bridge unmounting/remounting), ending lock-screen activities and wiping
|
||||
// the persisted registration would be wrong — the relay still holds a valid
|
||||
// registration and the next mount reuses it.
|
||||
export function releaseAgentAwarenessRelayTokenProvider(): void {
|
||||
relayTokenProvider = null;
|
||||
relayTokenProviderIdentity = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
}
|
||||
}
|
||||
|
||||
function iosMajorVersion(): number {
|
||||
const version = Platform.Version;
|
||||
if (typeof version === "number") {
|
||||
@@ -211,6 +291,27 @@ const relayToken = (
|
||||
});
|
||||
});
|
||||
|
||||
// Stable fingerprint of everything the relay stores for this device. When it
|
||||
// matches the last accepted registration for the same account, re-registering
|
||||
// is a no-op, so a launch that changed nothing skips the request entirely.
|
||||
function registrationSignature(body: RelayDeviceRegistrationRequest): string {
|
||||
return [
|
||||
body.deviceId,
|
||||
body.pushToken ?? "",
|
||||
body.bundleId ?? "",
|
||||
body.apsEnvironment ?? "",
|
||||
body.appVersion ?? "",
|
||||
body.label,
|
||||
body.iosMajorVersion,
|
||||
body.preferences.notificationsEnabled,
|
||||
body.preferences.liveActivitiesEnabled,
|
||||
body.preferences.notifyOnApproval,
|
||||
body.preferences.notifyOnInput,
|
||||
body.preferences.notifyOnCompletion,
|
||||
body.preferences.notifyOnFailure,
|
||||
].join("|");
|
||||
}
|
||||
|
||||
function registerDeviceWithRelay(
|
||||
body: RelayDeviceRegistrationRequest,
|
||||
expectedGeneration: number,
|
||||
@@ -223,7 +324,13 @@ function registerDeviceWithRelay(
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!readRelayConfig()) return;
|
||||
const relayConfig = readRelayConfig();
|
||||
if (!relayConfig) {
|
||||
// Nothing is in flight and nothing can succeed until configuration
|
||||
// appears; "pending" would otherwise stick forever.
|
||||
setRegistrationStatus("unknown");
|
||||
return;
|
||||
}
|
||||
const token = yield* relayToken("read-device-registration-relay-token");
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
logRegistrationDebug("device registration cancelled after auth lookup", {
|
||||
@@ -234,6 +341,37 @@ function registerDeviceWithRelay(
|
||||
}
|
||||
if (!token) {
|
||||
logRegistrationDebug("relay device registration skipped; user is not signed in");
|
||||
setRegistrationStatus("unknown");
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip the request when this account already registered an identical
|
||||
// payload; the relay upsert would be a no-op. The record is only cleared on
|
||||
// sign-out, so a device stays registered across launches without re-hitting
|
||||
// the relay every time the app opens.
|
||||
const identity = relayTokenProviderIdentity ?? "";
|
||||
const persisted = yield* Effect.tryPromise({
|
||||
try: () => loadAgentAwarenessRegistrationRecord(),
|
||||
catch: (cause) => cause,
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
// Signed out while the record loaded — do not resurrect the cleared
|
||||
// record or report the previous account's registration as current.
|
||||
logRegistrationDebug("device registration cancelled after record lookup", {
|
||||
expectedGeneration,
|
||||
currentGeneration: deviceRegistrationGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const payload = body;
|
||||
// The relay URL participates so pointing the app at a different relay
|
||||
// invalidates the record and re-registers there.
|
||||
const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
|
||||
if (persisted && persisted.identity === identity && persisted.signature === signature) {
|
||||
setRegistrationStatus("registered");
|
||||
logRegistrationDebug("relay device registration skipped; already registered for account", {
|
||||
expectedGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -243,8 +381,27 @@ function registerDeviceWithRelay(
|
||||
});
|
||||
yield* client.registerDevice({
|
||||
clerkToken: token,
|
||||
payload: body,
|
||||
payload,
|
||||
});
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
// Signed out while the request was in flight: the sign-out path already
|
||||
// reset the status and cleared the record for the next account, so a
|
||||
// stale success must not overwrite either.
|
||||
logRegistrationDebug("device registration completed after sign-out; result discarded", {
|
||||
expectedGeneration,
|
||||
currentGeneration: deviceRegistrationGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setRegistrationStatus("registered");
|
||||
yield* Effect.promise(() =>
|
||||
saveAgentAwarenessRegistrationRecord({
|
||||
identity,
|
||||
signature,
|
||||
}).catch((error: unknown) => {
|
||||
logRegistrationError("persist registration record failed", error);
|
||||
}),
|
||||
);
|
||||
logRegistrationDebug("relay device registration request completed", {
|
||||
expectedGeneration,
|
||||
});
|
||||
@@ -278,6 +435,91 @@ function unregisterDeviceWithRelay(input: {
|
||||
});
|
||||
}
|
||||
|
||||
// Arms the lock-screen card the moment the user starts agent work from this
|
||||
// phone, while the app is still foregrounded and the fresh activity's token
|
||||
// can be registered immediately. The seeded row is a best-effort placeholder;
|
||||
// the relay's registration replay repaints it with the authoritative
|
||||
// aggregate within seconds. No-ops when a card is already armed.
|
||||
export function armAgentAwarenessLiveActivityForLocalWork(input: {
|
||||
readonly threadTitle: string;
|
||||
readonly projectTitle: string;
|
||||
}): void {
|
||||
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
|
||||
return;
|
||||
}
|
||||
void loadPreferences()
|
||||
.catch(() => null)
|
||||
.then((preferences) => {
|
||||
if (preferences?.liveActivitiesEnabled === false) {
|
||||
return;
|
||||
}
|
||||
armAgentAwarenessLiveActivityForLocalWorkNow(input);
|
||||
});
|
||||
}
|
||||
|
||||
function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
|
||||
readonly threadTitle: string;
|
||||
readonly projectTitle: string;
|
||||
}): void {
|
||||
try {
|
||||
if (AgentActivity.getInstances().length > 0) {
|
||||
return;
|
||||
}
|
||||
const nowIso = new Date(Date.now()).toISOString();
|
||||
const activity = AgentActivity.start({
|
||||
title: "T3 Code",
|
||||
subtitle: "Agent work in progress",
|
||||
activeCount: 1,
|
||||
updatedAt: nowIso,
|
||||
activities: [
|
||||
{
|
||||
environmentId: "",
|
||||
threadId: "",
|
||||
projectTitle: input.projectTitle,
|
||||
threadTitle: input.threadTitle,
|
||||
modelTitle: "",
|
||||
phase: "starting",
|
||||
status: "Connecting",
|
||||
updatedAt: nowIso,
|
||||
deepLink: "/",
|
||||
},
|
||||
],
|
||||
});
|
||||
logRegistrationDebug("live activity card armed for local work", {
|
||||
threadTitle: input.threadTitle,
|
||||
});
|
||||
runRegistrationInBackground(
|
||||
registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),
|
||||
"live activity arming after local task start failed",
|
||||
);
|
||||
} catch (error) {
|
||||
logRegistrationError("live activity arming failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
function readAgentActivitySnapshot(): Effect.Effect<
|
||||
RelayAgentActivitySnapshotResponse | null,
|
||||
never,
|
||||
ManagedRelay.ManagedRelayClient
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
if (!readRelayConfig()) return null;
|
||||
const token = yield* relayToken("read-live-activity-registration-relay-token");
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
const client = yield* ManagedRelay.ManagedRelayClient;
|
||||
return yield* client.getAgentActivitySnapshot({ clerkToken: token });
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
logRegistrationError("agent activity snapshot read failed", error);
|
||||
return null;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function registerLiveActivityWithRelay(
|
||||
body: RelayLiveActivityRegistrationRequest,
|
||||
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
@@ -332,14 +574,8 @@ function mergeDeviceRegistrationInput(
|
||||
current: DeviceRegistrationInput,
|
||||
next: DeviceRegistrationInput,
|
||||
): DeviceRegistrationInput {
|
||||
return {
|
||||
...((next.pushToStartToken ?? current.pushToStartToken)
|
||||
? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken }
|
||||
: {}),
|
||||
...((next.observedPushToken ?? current.observedPushToken)
|
||||
? { observedPushToken: next.observedPushToken ?? current.observedPushToken }
|
||||
: {}),
|
||||
};
|
||||
const observedPushToken = next.observedPushToken ?? current.observedPushToken;
|
||||
return observedPushToken ? { observedPushToken } : {};
|
||||
}
|
||||
|
||||
function registrationAddsInformation(
|
||||
@@ -347,8 +583,7 @@ function registrationAddsInformation(
|
||||
next: DeviceRegistrationInput,
|
||||
): boolean {
|
||||
return (
|
||||
(next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) ||
|
||||
(next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken)
|
||||
next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken
|
||||
);
|
||||
}
|
||||
|
||||
@@ -363,8 +598,10 @@ function startPendingDeviceRegistration(): void {
|
||||
logRegistrationDebug("device registration started", {
|
||||
generation,
|
||||
hasObservedPushToken: next.input.observedPushToken !== undefined,
|
||||
hasPushToStartToken: next.input.pushToStartToken !== undefined,
|
||||
});
|
||||
if (registrationStatus !== "registered") {
|
||||
setRegistrationStatus("pending");
|
||||
}
|
||||
const registration = {
|
||||
input: next.input,
|
||||
operation: Promise.resolve(),
|
||||
@@ -375,6 +612,13 @@ function startPendingDeviceRegistration(): void {
|
||||
runtime.runPromiseExit(registerDevice(next.input, generation)),
|
||||
);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
// A transient failure on a later refresh (e.g. token rotation) leaves
|
||||
// the prior accepted registration intact on the relay, so an already
|
||||
// registered device stays "registered" rather than flipping the
|
||||
// settings toggles off.
|
||||
if (registrationStatus !== "registered") {
|
||||
setRegistrationStatus("failed");
|
||||
}
|
||||
logRegistrationError(next.context, squashAtomCommandFailure(result));
|
||||
}
|
||||
logRegistrationDebug("device registration finished", { generation });
|
||||
@@ -444,14 +688,16 @@ function registerDevice(
|
||||
expectedGeneration,
|
||||
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
|
||||
});
|
||||
const bundleId = Constants.expoConfig?.ios?.bundleIdentifier?.trim();
|
||||
yield* registerDeviceWithRelay(
|
||||
makeRelayDeviceRegistrationRequest({
|
||||
deviceId,
|
||||
label: Constants.deviceName?.trim() || "iOS device",
|
||||
iosMajorVersion: iosMajorVersion(),
|
||||
appVersion: Constants.expoConfig?.version,
|
||||
...(bundleId ? { bundleId } : {}),
|
||||
apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant),
|
||||
...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
|
||||
...(input?.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
|
||||
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
|
||||
preferences,
|
||||
}),
|
||||
@@ -460,27 +706,12 @@ function registerDevice(
|
||||
});
|
||||
}
|
||||
|
||||
function registerDeviceForCurrentUser(
|
||||
pushToStartToken?: string,
|
||||
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
return registerDevice(pushToStartToken ? { pushToStartToken } : undefined);
|
||||
}
|
||||
|
||||
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
|
||||
enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed");
|
||||
}
|
||||
|
||||
function ensurePushToStartListener(): void {
|
||||
if (pushToStartSubscription || !canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
|
||||
pushToStartSubscription = addPushToStartTokenListener((event) => {
|
||||
const token = event.activityPushToStartToken;
|
||||
if (token) {
|
||||
registerPushToStartTokenForCurrentUser(token);
|
||||
}
|
||||
});
|
||||
function registerDeviceForCurrentUser(): Effect.Effect<
|
||||
void,
|
||||
unknown,
|
||||
ManagedRelay.ManagedRelayClient
|
||||
> {
|
||||
return registerDevice(undefined);
|
||||
}
|
||||
|
||||
function ensurePushTokenListener(): void {
|
||||
@@ -498,14 +729,51 @@ function ensurePushTokenListener(): void {
|
||||
});
|
||||
}
|
||||
|
||||
// Re-registering activity tokens on foreground makes the relay replay the
|
||||
// current aggregate to this device, which updates content that drifted while
|
||||
// pushes could not be delivered and ends orphaned activities whose end push
|
||||
// never arrived. (Deduped by ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS: rapid
|
||||
// foreground/sign-in bursts collapse to one registration, but returning after
|
||||
// real time away still replays.)
|
||||
function ensureAppStateListener(): void {
|
||||
if (appStateSubscription || !canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
|
||||
appStateSubscription = AppState.addEventListener("change", (state) => {
|
||||
if (state !== "active") {
|
||||
return;
|
||||
}
|
||||
runRegistrationInBackground(
|
||||
refreshActiveLiveActivityRemoteRegistration(),
|
||||
"active live activity reconciliation after app foreground failed",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function endLocalLiveActivities(context: string): void {
|
||||
if (!canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (const activity of AgentActivity.getInstances()) {
|
||||
activity.end("immediate").catch((error: unknown) => {
|
||||
logRegistrationError(context, error);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logRegistrationError(context, error);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {
|
||||
if (!canRegisterRemoteLiveActivities()) {
|
||||
return;
|
||||
}
|
||||
|
||||
environmentConnections.set(connection.environmentId, connection);
|
||||
ensurePushToStartListener();
|
||||
ensurePushTokenListener();
|
||||
ensureAppStateListener();
|
||||
enqueueDeviceRegistration({}, "device registration failed");
|
||||
runRegistrationInBackground(
|
||||
refreshActiveLiveActivityRemoteRegistration(),
|
||||
@@ -523,10 +791,10 @@ export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId)
|
||||
|
||||
export function unregisterAllAgentAwarenessConnections(): void {
|
||||
environmentConnections.clear();
|
||||
pushToStartSubscription?.remove();
|
||||
pushToStartSubscription = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
@@ -541,6 +809,11 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
|
||||
return registerDeviceForCurrentUser().pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
// Same rationale as the queued path: a failed refresh does not undo an
|
||||
// already accepted registration.
|
||||
if (registrationStatus !== "registered") {
|
||||
setRegistrationStatus("failed");
|
||||
}
|
||||
logRegistrationError("device registration refresh failed", error);
|
||||
}),
|
||||
),
|
||||
@@ -549,10 +822,10 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
|
||||
|
||||
export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
|
||||
environmentConnections.clear();
|
||||
pushToStartSubscription?.remove();
|
||||
pushToStartSubscription = null;
|
||||
pushTokenSubscription?.remove();
|
||||
pushTokenSubscription = null;
|
||||
appStateSubscription?.remove();
|
||||
appStateSubscription = null;
|
||||
if (activeLiveActivityRegistrationRetry) {
|
||||
clearTimeout(activeLiveActivityRegistrationRetry);
|
||||
activeLiveActivityRegistrationRetry = null;
|
||||
@@ -562,6 +835,9 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
|
||||
deviceRegistrationGeneration++;
|
||||
activeDeviceRegistration = null;
|
||||
pendingDeviceRegistration = null;
|
||||
registrationStatus = "unknown";
|
||||
registrationStatusListeners.clear();
|
||||
registeredActivityPushTokens.clear();
|
||||
}
|
||||
|
||||
export function unregisterAgentAwarenessDeviceForCurrentUser(
|
||||
@@ -649,6 +925,13 @@ function registerLiveActivityPushTokenValue(input: {
|
||||
readonly activityPushToken: string;
|
||||
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
|
||||
if (
|
||||
acceptedAt !== undefined &&
|
||||
Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
@@ -662,6 +945,7 @@ function registerLiveActivityPushTokenValue(input: {
|
||||
activityPushToken: input.activityPushToken,
|
||||
});
|
||||
if (registered) {
|
||||
registeredActivityPushTokens.set(input.activityPushToken, Date.now());
|
||||
logRegistrationDebug("live activity push token registered", {
|
||||
tokenSuffix: input.activityPushToken.slice(-8),
|
||||
});
|
||||
@@ -694,7 +978,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
|
||||
return;
|
||||
}
|
||||
|
||||
const activities = yield* Effect.try({
|
||||
let activities = yield* Effect.try({
|
||||
try: () => AgentActivity.getInstances(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
@@ -710,6 +994,79 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
|
||||
),
|
||||
);
|
||||
|
||||
// The relay tracks exactly one card per device; if concurrent arming ever
|
||||
// produced extras, end them so only one keeps receiving updates.
|
||||
if (activities.length > 1) {
|
||||
for (const extra of activities.slice(1)) {
|
||||
extra.end("immediate").catch((error: unknown) => {
|
||||
logRegistrationError("duplicate live activity cleanup failed", error);
|
||||
});
|
||||
}
|
||||
activities = activities.slice(0, 1);
|
||||
}
|
||||
|
||||
// Activities are only ever created here, in the foreground, where the
|
||||
// update token can be observed and registered immediately — the relay
|
||||
// never remote-starts one (background push-to-start wakes proved too
|
||||
// unreliable to hand the token over). Arming is conditional: the relay is
|
||||
// asked what the card would show first, so an idle open never creates an
|
||||
// empty lock-screen card, and an armed card is born with the real
|
||||
// aggregate instead of a placeholder.
|
||||
if (activities.length === 0) {
|
||||
const preferences = yield* Effect.tryPromise({
|
||||
try: () => loadPreferences(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-live-activity-prime-preferences",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
// The toggle defaults to on: an unset preference (fresh install) must
|
||||
// prime, so only an explicit false blocks it.
|
||||
if (preferences?.liveActivitiesEnabled !== false) {
|
||||
const snapshot = yield* readAgentActivitySnapshot();
|
||||
// The snapshot request yields; an arm-on-send may have created the
|
||||
// card in the meantime. Re-check so two cards are never started.
|
||||
const armedMeanwhile = yield* Effect.try({
|
||||
try: () => AgentActivity.getInstances(),
|
||||
catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
|
||||
}).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
|
||||
if (armedMeanwhile.length > 0) {
|
||||
activities = [...armedMeanwhile];
|
||||
} else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
|
||||
const aggregate = snapshot.aggregate;
|
||||
const primed = yield* Effect.try({
|
||||
try: () =>
|
||||
AgentActivity.start({
|
||||
title: aggregate.title,
|
||||
subtitle: aggregate.subtitle,
|
||||
activeCount: aggregate.activeCount,
|
||||
updatedAt: aggregate.updatedAt,
|
||||
activities: aggregate.activities,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "prime-live-activity",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
logRegistrationError("live activity priming failed", error);
|
||||
return null;
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (primed) {
|
||||
logRegistrationDebug("live activity card primed", {
|
||||
activeCount: aggregate.activeCount,
|
||||
});
|
||||
activities = [primed];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const registrationResults = yield* Effect.forEach(activities, (activity) =>
|
||||
registerLiveActivityPushToken({ activity }).pipe(
|
||||
Effect.map((registered) => !registered),
|
||||
|
||||
@@ -333,7 +333,7 @@ function ArchivedThreadRow(props: {
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
style={{ fontVariant: ["tabular-nums"], minWidth: 30, textAlign: "right" }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
|
||||
@@ -14,9 +14,11 @@ import { runtime } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import {
|
||||
releaseAgentAwarenessRelayTokenProvider,
|
||||
setAgentAwarenessRelayTokenProvider,
|
||||
unregisterAgentAwarenessDeviceForCurrentUser,
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { requestConnectOnboarding } from "./connectOnboarding";
|
||||
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
|
||||
|
||||
function resetManagedRelayTokenCache() {
|
||||
@@ -66,6 +68,14 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
const nextAccount = isSignedIn && userId ? userId : null;
|
||||
observedAccountRef.current = nextAccount;
|
||||
|
||||
// Every sign-in that completes during this session (a cold start observes
|
||||
// undefined → account and must not re-prompt) requests the T3 Connect
|
||||
// onboarding sheet — sign-out clears the connected environments, so each
|
||||
// new session starts with no devices to reach.
|
||||
if (previousObservedAccount === null && nextAccount !== null) {
|
||||
requestConnectOnboarding(nextAccount);
|
||||
}
|
||||
|
||||
const queueAccountCleanup = (
|
||||
previous: {
|
||||
readonly userId: string;
|
||||
@@ -143,7 +153,11 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
useEffect(
|
||||
() => () => {
|
||||
previousTokenProviderRef.current = null;
|
||||
deactivateCloudRelayAccount();
|
||||
// Unmounting is not a sign-out: the user is usually still signed in, so
|
||||
// detach the provider without ending lock-screen activities or wiping the
|
||||
// persisted registration (a remount reuses both).
|
||||
releaseAgentAwarenessRelayTokenProvider();
|
||||
setManagedRelaySession(appAtomRegistry, null);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
@@ -39,7 +39,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
You are on the waitlist
|
||||
</Text>
|
||||
<Text className="text-center font-sans text-base text-foreground-secondary">
|
||||
We will email you when your T3 Cloud access is ready.
|
||||
We will email you when your T3 Connect access is ready.
|
||||
</Text>
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { NativeHeaderToolbar } from "../../native/StackHeader";
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
import { splitEnvironmentSections } from "../connection/environmentSections";
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
|
||||
import { hasCloudPublicConfig } from "./publicConfig";
|
||||
|
||||
/**
|
||||
* Post-sign-in onboarding sheet for T3 Connect. Mobile never publishes
|
||||
* environments itself — it consumes ones published elsewhere — so this simply
|
||||
* surfaces the account's T3 Connect environments right after sign-in so every
|
||||
* device can be connected in one go. It shows on every sign-in: sign-out
|
||||
* clears the connected environments, so each new session starts from zero.
|
||||
*/
|
||||
export function ConnectOnboardingRouteScreen() {
|
||||
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
|
||||
}
|
||||
|
||||
function ConfiguredConnectOnboardingRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();
|
||||
const { refreshRelayEnvironments } = useConnectionController();
|
||||
const { connectedCloudEnvironments } = splitEnvironmentSections({
|
||||
connectedEnvironments,
|
||||
cloudEnvironments: null,
|
||||
});
|
||||
|
||||
// Pull-to-refresh tracks its own spinner instead of discovery's refreshing
|
||||
// flag, so background refreshes (e.g. the sign-in one) don't yank the
|
||||
// content down.
|
||||
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
|
||||
const handlePullRefresh = useCallback(() => {
|
||||
void (async () => {
|
||||
setIsPullRefreshing(true);
|
||||
await refreshRelayEnvironments();
|
||||
setIsPullRefreshing(false);
|
||||
})();
|
||||
}, [refreshRelayEnvironments]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
navigation.goBack();
|
||||
}, [navigation]);
|
||||
|
||||
const handleDontShowAgain = useCallback(() => {
|
||||
if (userId) {
|
||||
void (async () => {
|
||||
const result = await settlePromise(() => optOutOfConnectOnboarding(userId));
|
||||
reportAtomCommandResult(result, { label: "connect onboarding opt-out" });
|
||||
})();
|
||||
}
|
||||
navigation.goBack();
|
||||
}, [navigation, userId]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
gap: 16,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={isPullRefreshing} onRefresh={handlePullRefresh} />
|
||||
}
|
||||
>
|
||||
{isSignedIn ? (
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
showHeader={false}
|
||||
/>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card p-5">
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
Sign in to your T3 account to set up T3 Connect.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{userId ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
hitSlop={8}
|
||||
onPress={handleDontShowAgain}
|
||||
className="items-center py-1 active:opacity-70"
|
||||
>
|
||||
<Text className="text-xs text-foreground-muted">{"Don't show this again"}</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
|
||||
// Signals RootStackLayout (inside the navigation tree) that an in-session
|
||||
// sign-in just completed. Holds the account id so a sign-out between the
|
||||
// request and the navigation cannot present the sheet for the wrong account.
|
||||
export const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:connect-onboarding-request"),
|
||||
);
|
||||
|
||||
/**
|
||||
* Requests the onboarding sheet for the given account. Sign-out clears the
|
||||
* connected environments, so onboarding runs on every in-session sign-in —
|
||||
* each new session starts with no connected devices.
|
||||
*/
|
||||
export function requestConnectOnboarding(accountId: string): void {
|
||||
appAtomRegistry.set(connectOnboardingRequestAtom, accountId);
|
||||
}
|
||||
|
||||
export function clearConnectOnboardingRequest(): void {
|
||||
appAtomRegistry.set(connectOnboardingRequestAtom, null);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
|
||||
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
|
||||
|
||||
// Sign-in happens inside the Settings sheet; give its detent/session-state
|
||||
// transitions a beat to settle before presenting another formSheet on top.
|
||||
const PRESENT_ONBOARDING_DELAY_MS = 600;
|
||||
|
||||
/**
|
||||
* Consumes the onboarding request inside the navigation tree (RootStackLayout)
|
||||
* and presents the onboarding formSheet. Lives apart from connectOnboarding.ts
|
||||
* so non-navigation consumers (CloudAuthProvider) do not pull
|
||||
* @react-navigation into their module graph.
|
||||
*/
|
||||
export function useConnectOnboardingNavigation(): void {
|
||||
const navigation = useNavigation();
|
||||
const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);
|
||||
|
||||
useEffect(() => {
|
||||
if (requestedAccountId === null) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
const timer = setTimeout(() => {
|
||||
void (async () => {
|
||||
// A failed preference read prefers showing the sheet.
|
||||
const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false);
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
clearConnectOnboardingRequest();
|
||||
if (!optedOut) {
|
||||
navigation.navigate("ConnectOnboarding");
|
||||
}
|
||||
})();
|
||||
}, PRESENT_ONBOARDING_DELAY_MS);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [navigation, requestedAccountId]);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
|
||||
|
||||
// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports
|
||||
// the request signal) never pulls lib/storage — expo-secure-store — into its
|
||||
// module graph; that breaks CloudAuthProvider.test.ts suite loading.
|
||||
|
||||
/** Whether the account chose "Don't show this again". */
|
||||
export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {
|
||||
const preferences = await loadPreferences();
|
||||
return preferences.connectOnboardingOptOutAccounts?.includes(accountId) ?? false;
|
||||
}
|
||||
|
||||
/** Persists "Don't show this again" for the account. */
|
||||
export async function optOutOfConnectOnboarding(accountId: string): Promise<void> {
|
||||
const preferences = await loadPreferences();
|
||||
const optedOut = preferences.connectOnboardingOptOutAccounts ?? [];
|
||||
if (optedOut.includes(accountId)) {
|
||||
return;
|
||||
}
|
||||
await savePreferencesPatch({ connectOnboardingOptOutAccounts: [...optedOut, accountId] });
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import {
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPhase,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
Switch,
|
||||
type NativeSyntheticEvent,
|
||||
type TextLayoutEventData,
|
||||
View,
|
||||
} from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
|
||||
|
||||
/**
|
||||
* "T3 Connect" section: every environment published to the signed-in account,
|
||||
* with connect switches, availability status, refresh, and loading/error
|
||||
* states. Shared between the Settings environments screen and the T3 Connect
|
||||
* onboarding sheet.
|
||||
*/
|
||||
export function CloudEnvironmentRows(props: {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
/**
|
||||
* Hide the "T3 Connect" section title + refresh button for hosts that
|
||||
* provide their own chrome (the onboarding sheet's native header and
|
||||
* pull-to-refresh).
|
||||
*/
|
||||
readonly showHeader?: boolean;
|
||||
}) {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments = controller.availableRelayEnvironments;
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
|
||||
const handleConnectCloudEnvironment = useCallback(
|
||||
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
|
||||
[controller],
|
||||
);
|
||||
|
||||
const handleDisconnectCloudEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
|
||||
[controller],
|
||||
);
|
||||
|
||||
const handleToggleCloudError = useCallback((environmentId: string) => {
|
||||
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
|
||||
}, []);
|
||||
|
||||
const showHeader = props.showHeader ?? true;
|
||||
|
||||
if (!isSignedIn) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
|
||||
{showHeader ? (
|
||||
<View className="flex-row items-center justify-between px-1">
|
||||
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
onPress={() => {
|
||||
void controller.refreshRelayEnvironments();
|
||||
}}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{controller.relayDiscovery.isRefreshing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{hasCloudRows ? (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{props.connectedCloudEnvironments.map((environment, index) => (
|
||||
<ConnectedCloudEnvironmentRow
|
||||
key={environment.environmentId}
|
||||
environment={environment}
|
||||
borderTop={index !== 0}
|
||||
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
|
||||
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
|
||||
errorExpanded={expandedErrorId === environment.environmentId}
|
||||
onToggleError={() => handleToggleCloudError(environment.environmentId)}
|
||||
/>
|
||||
))}
|
||||
{availableCloudEnvironments.map((environment, index) => (
|
||||
<CloudEnvironmentRow
|
||||
key={environment.environment.environmentId}
|
||||
environment={environment}
|
||||
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
|
||||
onConnect={() => handleConnectCloudEnvironment(environment)}
|
||||
errorExpanded={expandedErrorId === environment.environment.environmentId}
|
||||
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
) : controller.relayDiscovery.isRefreshing ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
|
||||
<ActivityIndicator color={iconColor} />
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
Loading linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
) : controller.relayDiscovery.error ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
|
||||
<Text className="text-base font-t3-bold text-foreground">
|
||||
Could not load T3 Connect environments
|
||||
</Text>
|
||||
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
|
||||
{controller.relayDiscovery.errorTraceId ? (
|
||||
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card p-5">
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
No additional linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectedCloudEnvironmentRow(props: {
|
||||
readonly environment: ConnectedEnvironmentSummary;
|
||||
readonly borderTop: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly onConnect: () => void;
|
||||
readonly onDisconnect: () => void;
|
||||
readonly onToggleError: () => void;
|
||||
}) {
|
||||
return (
|
||||
<CloudEnvironmentRowShell
|
||||
borderTop={props.borderTop}
|
||||
connectionError={props.environment.connectionError}
|
||||
connectionErrorTraceId={props.environment.connectionErrorTraceId}
|
||||
connectionState={props.environment.connectionState}
|
||||
errorExpanded={props.errorExpanded}
|
||||
label={props.environment.environmentLabel}
|
||||
onValueChange={(enabled) => {
|
||||
if (enabled) {
|
||||
props.onConnect();
|
||||
return;
|
||||
}
|
||||
props.onDisconnect();
|
||||
}}
|
||||
onToggleError={props.onToggleError}
|
||||
value={props.environment.connectionState !== "available"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CloudEnvironmentRow(props: {
|
||||
readonly environment: RelayEnvironmentView;
|
||||
readonly borderTop: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly onConnect: () => void;
|
||||
readonly onToggleError: () => void;
|
||||
}) {
|
||||
const presentation = availableCloudEnvironmentPresentation({
|
||||
isStatusPending: props.environment.availability === "checking",
|
||||
status: props.environment.status,
|
||||
statusError: props.environment.error,
|
||||
statusErrorTraceId: props.environment.traceId,
|
||||
});
|
||||
|
||||
return (
|
||||
<CloudEnvironmentRowShell
|
||||
borderTop={props.borderTop}
|
||||
connectionError={presentation.connectionError}
|
||||
connectionErrorTraceId={presentation.connectionErrorTraceId}
|
||||
connectionState={presentation.connectionState}
|
||||
errorExpanded={props.errorExpanded}
|
||||
label={props.environment.environment.label}
|
||||
onValueChange={(enabled) => {
|
||||
if (enabled) {
|
||||
props.onConnect();
|
||||
}
|
||||
}}
|
||||
onToggleError={props.onToggleError}
|
||||
statusText={presentation.statusText}
|
||||
value={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowShell(props: {
|
||||
readonly borderTop: boolean;
|
||||
readonly connectionError: string | null;
|
||||
readonly connectionErrorTraceId: string | null;
|
||||
readonly connectionState: EnvironmentConnectionPhase;
|
||||
readonly disabled?: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly label: string;
|
||||
readonly onToggleError: () => void;
|
||||
readonly onValueChange: (enabled: boolean) => void;
|
||||
readonly statusText?: string;
|
||||
readonly value: boolean;
|
||||
}) {
|
||||
const activeTrack = String(useThemeColor("--color-switch-active"));
|
||||
const track = String(useThemeColor("--color-secondary-border"));
|
||||
const chevron = useThemeColor("--color-chevron");
|
||||
const isRetrying =
|
||||
props.connectionState === "connecting" || props.connectionState === "reconnecting";
|
||||
const shouldPulse = isRetrying;
|
||||
const statusText =
|
||||
props.statusText ??
|
||||
connectionStatusText({
|
||||
phase: props.connectionState,
|
||||
error: props.connectionError,
|
||||
traceId: props.connectionErrorTraceId,
|
||||
});
|
||||
const statusClassName = props.connectionError
|
||||
? "text-rose-500 dark:text-rose-400"
|
||||
: "text-foreground-muted";
|
||||
const [errorMeasurement, setErrorMeasurement] = useState<{
|
||||
readonly text: string;
|
||||
readonly lineCount: number;
|
||||
} | null>(null);
|
||||
const errorTraceId = props.connectionErrorTraceId;
|
||||
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
|
||||
const errorLineCount =
|
||||
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
|
||||
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
|
||||
const isErrorExpanded = errorCanExpand && props.errorExpanded;
|
||||
const StatusContainer = errorCanExpand ? Pressable : View;
|
||||
const onMeasuredErrorTextLayout = useCallback(
|
||||
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
|
||||
if (!props.connectionError) {
|
||||
return;
|
||||
}
|
||||
const nextLineCount = event.nativeEvent.lines.length;
|
||||
setErrorMeasurement((currentMeasurement) =>
|
||||
currentMeasurement?.text === measuredErrorText &&
|
||||
currentMeasurement.lineCount === nextLineCount
|
||||
? currentMeasurement
|
||||
: { text: measuredErrorText, lineCount: nextLineCount },
|
||||
);
|
||||
},
|
||||
[measuredErrorText, props.connectionError],
|
||||
);
|
||||
return (
|
||||
<View
|
||||
collapsable={false}
|
||||
className={cn(
|
||||
"flex-row items-center gap-3 bg-card px-4 py-3.5",
|
||||
props.borderTop && "border-t border-border",
|
||||
)}
|
||||
>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<View className="min-w-0 flex-row items-center gap-2">
|
||||
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
|
||||
<Text
|
||||
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</View>
|
||||
{props.connectionError ? (
|
||||
<Text
|
||||
aria-hidden
|
||||
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
|
||||
onTextLayout={onMeasuredErrorTextLayout}
|
||||
style={{ opacity: 0, zIndex: -1 }}
|
||||
>
|
||||
{measuredErrorText}
|
||||
</Text>
|
||||
) : null}
|
||||
<StatusContainer
|
||||
{...(errorCanExpand
|
||||
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
|
||||
: {})}
|
||||
className="min-w-0 flex-row items-start gap-1"
|
||||
>
|
||||
<Text
|
||||
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
|
||||
numberOfLines={isErrorExpanded ? undefined : 1}
|
||||
>
|
||||
{statusText}
|
||||
{errorTraceId ? (
|
||||
<>
|
||||
{" Trace ID: "}
|
||||
<Text
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className={cn("text-xs underline", statusClassName)}
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
style={{ textDecorationStyle: "dotted" }}
|
||||
>
|
||||
{errorTraceId}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Text>
|
||||
{errorCanExpand ? (
|
||||
<SymbolView
|
||||
name="chevron.down"
|
||||
size={10}
|
||||
tintColor={chevron}
|
||||
type="monochrome"
|
||||
style={{
|
||||
marginTop: 3,
|
||||
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</StatusContainer>
|
||||
</View>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
onValueChange={props.onValueChange}
|
||||
trackColor={{ false: track, true: activeTrack }}
|
||||
value={props.value}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function CopyTraceIdButton(props: { readonly traceId: string }) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
|
||||
}}
|
||||
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
|
||||
>
|
||||
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
|
||||
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -135,7 +135,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
>
|
||||
{props.environment.isRelayManaged ? (
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
Managed by T3 Cloud. Tunnel details update automatically.
|
||||
Managed by T3 Connect. Tunnel details update automatically.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -35,7 +35,7 @@ function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord {
|
||||
}
|
||||
|
||||
describe("mobile environment settings sections", () => {
|
||||
it("keeps saved relay-managed connections under T3 Cloud", () => {
|
||||
it("keeps saved relay-managed connections under T3 Connect", () => {
|
||||
const local = connectedEnvironment({
|
||||
environmentId: "environment-local",
|
||||
isRelayManaged: false,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
@@ -13,6 +14,7 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
import { useHomeListOptions } from "./home-list-options";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
@@ -26,6 +28,8 @@ export function HomeRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
Arr.sort(
|
||||
@@ -116,8 +120,21 @@ export function HomeRouteScreen() {
|
||||
threadId: thread.id,
|
||||
});
|
||||
}}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
onNewThreadInProject={(project) => {
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: String(project.environmentId),
|
||||
projectId: String(project.id),
|
||||
title: project.title,
|
||||
},
|
||||
});
|
||||
}}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
pendingTasks={pendingTasks}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
|
||||
@@ -22,7 +22,9 @@ import { EmptyState } from "../../components/EmptyState";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
PendingTaskListRow,
|
||||
ThreadListGroupHeader,
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
@@ -47,6 +49,7 @@ import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-stat
|
||||
interface HomeScreenProps {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly catalogState: WorkspaceState;
|
||||
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
@@ -67,6 +70,9 @@ interface HomeScreenProps {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
}
|
||||
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
@@ -189,6 +195,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
buildHomeThreadGroups({
|
||||
projects: props.projects,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
@@ -196,6 +203,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
@@ -241,11 +249,31 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
isFirst={item.isFirst}
|
||||
groupKey={item.group.key}
|
||||
onGroupAction={updateGroupDisplay}
|
||||
// Aggregated groups (same repo across machines) have no single
|
||||
// target project, and `pending-project:` groups hold a placeholder
|
||||
// built from queued-task metadata rather than a real project shell,
|
||||
// so the quick new-thread button is single-real-project only.
|
||||
newThreadTarget={item.group.newThreadTarget}
|
||||
onNewThread={props.onNewThreadInProject}
|
||||
project={item.group.representative}
|
||||
threadCount={item.group.threads.length}
|
||||
threadCount={item.group.threads.length + item.group.pendingTasks.length}
|
||||
title={item.group.title}
|
||||
/>
|
||||
);
|
||||
case "pending-task":
|
||||
return (
|
||||
<PendingTaskListRow
|
||||
variant="compact"
|
||||
pendingTask={item.pendingTask}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[item.pendingTask.message.environmentId]
|
||||
?.environmentLabel ?? null
|
||||
}
|
||||
isLast={item.isLast}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
);
|
||||
case "thread": {
|
||||
const thread = item.thread;
|
||||
return (
|
||||
@@ -285,7 +313,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
handleSwipeableWillOpen,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
props.onDeleteThread,
|
||||
props.onNewThreadInProject,
|
||||
props.onSelectPendingTask,
|
||||
props.onSelectThread,
|
||||
props.savedConnectionsById,
|
||||
updateGroupDisplay,
|
||||
@@ -295,7 +326,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
|
||||
|
||||
/* Empty states */
|
||||
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
|
||||
const hasAnyThreads =
|
||||
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
|
||||
const hasResults = projectGroups.length > 0;
|
||||
const selectedEnvironmentLabel =
|
||||
props.selectedEnvironmentId === null
|
||||
|
||||
@@ -57,14 +57,20 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
|
||||
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
||||
const project = makeProject(key, key);
|
||||
const threads = Array.from({ length: threadCount }, (_, index) =>
|
||||
makeThread(`${key}-thread-${index}`, project.id),
|
||||
);
|
||||
return {
|
||||
key,
|
||||
title: key,
|
||||
representative: project,
|
||||
projects: [project],
|
||||
threads: Array.from({ length: threadCount }, (_, index) =>
|
||||
makeThread(`${key}-thread-${index}`, project.id),
|
||||
),
|
||||
pendingTasks: [],
|
||||
threads,
|
||||
// All threads inside the recency window, so the baseline stays at the
|
||||
// initial page size and the pagination expectations below hold.
|
||||
recentThreads: threads,
|
||||
newThreadTarget: project,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -152,6 +158,48 @@ describe("buildHomeListLayout", () => {
|
||||
expect(reset.visibleCount).toBe(HOME_INITIAL_VISIBLE_THREADS);
|
||||
});
|
||||
|
||||
it("offers show-less after expanding a stale group whose baseline is below the page size", () => {
|
||||
// Stale project: 10 threads total but only 3 within the recency window.
|
||||
const project = makeProject("stale", "stale");
|
||||
const threads = Array.from({ length: 10 }, (_, index) =>
|
||||
makeThread(`stale-thread-${index}`, project.id),
|
||||
);
|
||||
const group: HomeThreadGroup = {
|
||||
key: "stale",
|
||||
title: "stale",
|
||||
representative: project,
|
||||
projects: [project],
|
||||
pendingTasks: [],
|
||||
threads,
|
||||
recentThreads: threads.slice(0, 3),
|
||||
newThreadTarget: project,
|
||||
};
|
||||
|
||||
const collapsedToRecent = buildHomeListLayout({
|
||||
groups: [group],
|
||||
displayStates: displayStates({}),
|
||||
});
|
||||
expect(collapsedToRecent.items.filter((item) => item.type === "thread")).toHaveLength(3);
|
||||
expect(collapsedToRecent.items.at(-1)).toMatchObject({
|
||||
type: "show-more",
|
||||
hiddenCount: 7,
|
||||
canShowLess: false,
|
||||
});
|
||||
|
||||
const expanded = buildHomeListLayout({
|
||||
groups: [group],
|
||||
displayStates: displayStates({
|
||||
stale: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
|
||||
}),
|
||||
});
|
||||
expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10);
|
||||
expect(expanded.items.at(-1)).toMatchObject({
|
||||
type: "show-more",
|
||||
hiddenCount: 0,
|
||||
canShowLess: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("hides threads and the show-more row for collapsed groups", () => {
|
||||
const layout = buildHomeListLayout({
|
||||
groups: [makeGroup("alpha", 12), makeGroup("beta", 2)],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import type { HomeThreadGroup } from "./homeThreadList";
|
||||
|
||||
/** Threads shown per project before the "Show more" affordance appears. */
|
||||
@@ -33,6 +34,13 @@ export interface HomeThreadListItem {
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
export interface HomePendingTaskListItem {
|
||||
readonly type: "pending-task";
|
||||
readonly key: string;
|
||||
readonly pendingTask: PendingNewTask;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
export interface HomeShowMoreListItem {
|
||||
readonly type: "show-more";
|
||||
readonly key: string;
|
||||
@@ -43,7 +51,11 @@ export interface HomeShowMoreListItem {
|
||||
readonly canShowLess: boolean;
|
||||
}
|
||||
|
||||
export type HomeListItem = HomeHeaderListItem | HomeThreadListItem | HomeShowMoreListItem;
|
||||
export type HomeListItem =
|
||||
| HomeHeaderListItem
|
||||
| HomePendingTaskListItem
|
||||
| HomeThreadListItem
|
||||
| HomeShowMoreListItem;
|
||||
|
||||
export interface HomeListLayout {
|
||||
readonly items: ReadonlyArray<HomeListItem>;
|
||||
@@ -82,6 +94,12 @@ export function homeListItemsAreEqual(previous: HomeListItem, item: HomeListItem
|
||||
previous.collapsed === item.collapsed &&
|
||||
previous.isFirst === item.isFirst
|
||||
);
|
||||
case "pending-task":
|
||||
return (
|
||||
previous.type === "pending-task" &&
|
||||
previous.pendingTask === item.pendingTask &&
|
||||
previous.isLast === item.isLast
|
||||
);
|
||||
case "thread":
|
||||
return (
|
||||
previous.type === "thread" &&
|
||||
@@ -127,12 +145,40 @@ export function buildHomeListLayout(input: {
|
||||
}
|
||||
|
||||
const totalCount = group.threads.length;
|
||||
// Default to the group's recent-activity window (last few days, or a small
|
||||
// fallback for stale projects), capped at the initial page size. Until the
|
||||
// user taps "Show more", older threads stay hidden to save vertical space;
|
||||
// "Show less" resets visibleCount to the initial constant, which lands back
|
||||
// here at the recency baseline.
|
||||
const baselineCount = Math.min(
|
||||
group.recentThreads.length,
|
||||
HOME_INITIAL_VISIBLE_THREADS,
|
||||
totalCount,
|
||||
);
|
||||
const visibleCount = input.showAllThreads
|
||||
? totalCount
|
||||
: Math.min(Math.max(display.visibleCount, HOME_INITIAL_VISIBLE_THREADS), totalCount);
|
||||
: Math.min(
|
||||
display.visibleCount > HOME_INITIAL_VISIBLE_THREADS
|
||||
? display.visibleCount
|
||||
: baselineCount,
|
||||
totalCount,
|
||||
);
|
||||
const visibleThreads = group.threads.slice(0, visibleCount);
|
||||
const hiddenCount = totalCount - visibleCount;
|
||||
const hasShowMoreRow = !input.showAllThreads && totalCount > HOME_INITIAL_VISIBLE_THREADS;
|
||||
const hasShowMoreRow = !input.showAllThreads && totalCount > baselineCount;
|
||||
|
||||
// Pending (unsent) tasks lead the group and are never paginated away.
|
||||
for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) {
|
||||
items.push({
|
||||
type: "pending-task",
|
||||
key: `pending-task:${pendingTask.message.messageId}`,
|
||||
pendingTask,
|
||||
isLast:
|
||||
pendingIndex === group.pendingTasks.length - 1 &&
|
||||
visibleThreads.length === 0 &&
|
||||
!hasShowMoreRow,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [threadIndex, thread] of visibleThreads.entries()) {
|
||||
items.push({
|
||||
@@ -149,7 +195,10 @@ export function buildHomeListLayout(input: {
|
||||
key: `show-more:${group.key}`,
|
||||
groupKey: group.key,
|
||||
hiddenCount,
|
||||
canShowLess: visibleCount > HOME_INITIAL_VISIBLE_THREADS,
|
||||
// Compare against the group's own baseline, not the global page size:
|
||||
// stale projects start below HOME_INITIAL_VISIBLE_THREADS, and "Show
|
||||
// less" must be offered as soon as anything beyond the baseline shows.
|
||||
canShowLess: visibleCount > baselineCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,8 @@ function makeThread(
|
||||
};
|
||||
}
|
||||
|
||||
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
|
||||
|
||||
function buildGroups(
|
||||
projects: ReadonlyArray<EnvironmentProject>,
|
||||
threads: ReadonlyArray<EnvironmentThreadShell>,
|
||||
@@ -57,6 +59,7 @@ function buildGroups(
|
||||
projectSortOrder: "updated_at",
|
||||
threadSortOrder: "updated_at",
|
||||
projectGroupingMode: "repository",
|
||||
now: NOW,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
@@ -220,4 +223,144 @@ describe("buildHomeThreadGroups", () => {
|
||||
);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("default view shows only threads from the last 5 days", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "T3 Code",
|
||||
});
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("recent-1"),
|
||||
projectId: project.id,
|
||||
title: "Today",
|
||||
updatedAt: "2026-06-28T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("recent-2"),
|
||||
projectId: project.id,
|
||||
title: "Within window",
|
||||
updatedAt: "2026-06-25T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("old"),
|
||||
projectId: project.id,
|
||||
title: "Two weeks ago",
|
||||
updatedAt: "2026-06-14T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const group = buildGroups([project], threads)[0];
|
||||
// Default view trims to recent threads...
|
||||
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2"]);
|
||||
// ...while full history stays available for the expanded view.
|
||||
expect(group?.threads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2", "old"]);
|
||||
});
|
||||
|
||||
it("falls back to the most recent 3 threads when none are within 5 days", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "T3 Code",
|
||||
});
|
||||
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
|
||||
(day, index) =>
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make(`thread-${index}`),
|
||||
projectId: project.id,
|
||||
title: `Thread ${index}`,
|
||||
updatedAt: `${day}T00:00:00.000Z`,
|
||||
}),
|
||||
);
|
||||
|
||||
const group = buildGroups([project], threads)[0];
|
||||
expect(group?.recentThreads.map((thread) => thread.id)).toEqual([
|
||||
"thread-4",
|
||||
"thread-3",
|
||||
"thread-2",
|
||||
]);
|
||||
expect(group?.threads).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("does not apply the recency window while searching", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "T3 Code",
|
||||
});
|
||||
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
|
||||
(day, index) =>
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make(`thread-${index}`),
|
||||
projectId: project.id,
|
||||
title: `Thread ${index}`,
|
||||
updatedAt: `${day}T00:00:00.000Z`,
|
||||
}),
|
||||
);
|
||||
|
||||
const group = buildGroups([project], threads, { searchQuery: "T3 Code" })[0];
|
||||
// Search reaches the full history rather than the 3-thread fallback.
|
||||
expect(group?.recentThreads).toHaveLength(5);
|
||||
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(
|
||||
group?.threads.map((thread) => thread.id),
|
||||
);
|
||||
});
|
||||
|
||||
it("targets quick new threads at the group member with the newest thread", () => {
|
||||
const laptopEnv = EnvironmentId.make("environment-laptop");
|
||||
const desktopEnv = EnvironmentId.make("environment-desktop");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const laptopProject = makeProject({
|
||||
environmentId: laptopEnv,
|
||||
id: ProjectId.make("project-laptop"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const desktopProject = makeProject({
|
||||
environmentId: desktopEnv,
|
||||
id: ProjectId.make("project-desktop"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId: laptopEnv,
|
||||
id: ThreadId.make("thread-laptop"),
|
||||
projectId: laptopProject.id,
|
||||
title: "Older laptop thread",
|
||||
updatedAt: "2026-06-27T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId: desktopEnv,
|
||||
id: ThreadId.make("thread-desktop"),
|
||||
projectId: desktopProject.id,
|
||||
title: "Newest desktop thread",
|
||||
updatedAt: "2026-06-28T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
// Aggregated into one group by repository; the quick new-thread target
|
||||
// must follow the newest thread (desktop), not the arbitrary first member.
|
||||
const groups = buildGroups([laptopProject, desktopProject], threads);
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.projects).toHaveLength(2);
|
||||
expect(groups[0]?.newThreadTarget?.environmentId).toBe(desktopEnv);
|
||||
expect(groups[0]?.newThreadTarget?.id).toBe(desktopProject.id);
|
||||
});
|
||||
});
|
||||
@@ -14,42 +14,92 @@ import type {
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
|
||||
|
||||
/**
|
||||
* Default home view only surfaces threads active within this window, to keep the
|
||||
* screen compact while keeping recent work visible.
|
||||
*/
|
||||
const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
|
||||
/** Fallback when a project has no threads inside the recency window. */
|
||||
const RECENT_THREAD_FALLBACK_COUNT = 3;
|
||||
|
||||
export interface HomeThreadGroup {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly representative: EnvironmentProject;
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
/** Full sorted thread history for the group (revealed when expanded / searching). */
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
/** Subset shown by default: threads from the last few days, or the most recent few. */
|
||||
readonly recentThreads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
/**
|
||||
* Where a quick "new thread in this project" should land. For aggregated
|
||||
* groups (same repo on several machines) this is the member that owns the
|
||||
* group's most recent thread — the machine the user last worked on — rather
|
||||
* than the arbitrary first member; the draft's computer picker covers
|
||||
* switching from there. Null only for synthetic pending-project groups,
|
||||
* whose single "project" is a placeholder built from queued-task metadata.
|
||||
*/
|
||||
readonly newThreadTarget: EnvironmentProject | null;
|
||||
}
|
||||
|
||||
interface MutableHomeThreadGroup {
|
||||
readonly key: string;
|
||||
readonly projects: EnvironmentProject[];
|
||||
readonly pendingTasks: PendingNewTask[];
|
||||
readonly threads: EnvironmentThreadShell[];
|
||||
}
|
||||
|
||||
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
|
||||
return group.threads.reduce(
|
||||
const latestThread = group.threads.reduce(
|
||||
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
return group.pendingTasks.reduce((latest, pendingTask) => {
|
||||
const timestamp = Date.parse(pendingTask.message.createdAt);
|
||||
return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp);
|
||||
}, latestThread);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trims a group's threads to recent activity for the default home view.
|
||||
* `sortedThreads` must already be ordered newest-first for `threadSortOrder`.
|
||||
* Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps
|
||||
* the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes.
|
||||
*/
|
||||
function selectRecentThreads(
|
||||
sortedThreads: ReadonlyArray<EnvironmentThreadShell>,
|
||||
threadSortOrder: SidebarThreadSortOrder,
|
||||
now: number,
|
||||
): ReadonlyArray<EnvironmentThreadShell> {
|
||||
const cutoff = now - RECENT_THREAD_WINDOW_MS;
|
||||
const recent = sortedThreads.filter(
|
||||
(thread) => getThreadSortTimestamp(thread, threadSortOrder) >= cutoff,
|
||||
);
|
||||
return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT);
|
||||
}
|
||||
|
||||
export function buildHomeThreadGroups(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly searchQuery: string;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
/** Current time used for the recency window; defaults to now. Injectable for tests. */
|
||||
readonly now?: number;
|
||||
}): ReadonlyArray<HomeThreadGroup> {
|
||||
const now = input.now ?? Date.now();
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
@@ -68,10 +118,49 @@ export function buildHomeThreadGroups(input: {
|
||||
if (existing) {
|
||||
existing.projects.push(project);
|
||||
} else {
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
|
||||
}
|
||||
}
|
||||
|
||||
for (const pendingTask of input.pendingTasks ?? []) {
|
||||
if (input.environmentId !== null && pendingTask.message.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const physicalKey = scopedProjectKey(
|
||||
pendingTask.message.environmentId,
|
||||
pendingTask.creation.projectId,
|
||||
);
|
||||
let groupKey = groupKeyByProjectKey.get(physicalKey);
|
||||
if (!groupKey) {
|
||||
// The project shell is not loaded (environment offline / project gone).
|
||||
// A queued task must stay visible and deletable regardless, so build a
|
||||
// standalone group from the metadata snapshotted at enqueue time.
|
||||
groupKey = `pending-project:${physicalKey}`;
|
||||
groupKeyByProjectKey.set(physicalKey, groupKey);
|
||||
groups.set(groupKey, {
|
||||
key: groupKey,
|
||||
projects: [
|
||||
{
|
||||
environmentId: pendingTask.message.environmentId,
|
||||
id: pendingTask.creation.projectId,
|
||||
title: pendingTask.creation.projectTitle ?? "Unknown project",
|
||||
workspaceRoot:
|
||||
pendingTask.creation.projectCwd ?? String(pendingTask.creation.projectId),
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: pendingTask.message.createdAt,
|
||||
updatedAt: pendingTask.message.createdAt,
|
||||
},
|
||||
],
|
||||
pendingTasks: [],
|
||||
threads: [],
|
||||
});
|
||||
}
|
||||
groups.get(groupKey)?.pendingTasks.push(pendingTask);
|
||||
}
|
||||
|
||||
for (const thread of input.threads) {
|
||||
if (thread.archivedAt !== null) {
|
||||
continue;
|
||||
@@ -93,7 +182,7 @@ export function buildHomeThreadGroups(input: {
|
||||
|
||||
for (const group of groups.values()) {
|
||||
const representative = group.projects[0];
|
||||
if (!representative || group.threads.length === 0) {
|
||||
if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -108,17 +197,53 @@ export function buildHomeThreadGroups(input: {
|
||||
const matchingThreads = groupMatches
|
||||
? group.threads
|
||||
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
|
||||
const matchingPendingTasks = groupMatches
|
||||
? group.pendingTasks
|
||||
: group.pendingTasks.filter((pendingTask) =>
|
||||
pendingTask.title.toLocaleLowerCase().includes(query),
|
||||
);
|
||||
|
||||
if (matchingThreads.length === 0) {
|
||||
if (matchingThreads.length === 0 && matchingPendingTasks.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder);
|
||||
// An active search should reach the full history, so the recency window
|
||||
// only trims the default (no-query) view.
|
||||
const recentThreads =
|
||||
query.length === 0
|
||||
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
|
||||
: sortedThreads;
|
||||
|
||||
// Sorted newest-first, so the first thread whose project is a group member
|
||||
// marks the machine the user last worked on.
|
||||
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
|
||||
group.projects.some(
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
group.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
),
|
||||
Option.getOrNull,
|
||||
);
|
||||
|
||||
result.push({
|
||||
key: group.key,
|
||||
title,
|
||||
representative,
|
||||
projects: group.projects,
|
||||
threads: sortThreads(matchingThreads, input.threadSortOrder),
|
||||
pendingTasks: matchingPendingTasks,
|
||||
threads: sortedThreads,
|
||||
recentThreads,
|
||||
newThreadTarget: group.key.startsWith("pending-project:")
|
||||
? null
|
||||
: (lastActiveProject ?? representative),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useCallback } from "react";
|
||||
import { Alert } from "react-native";
|
||||
|
||||
import { removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { releaseEditingQueuedMessage } from "../../state/use-thread-outbox";
|
||||
|
||||
export function usePendingTaskListActions(): {
|
||||
readonly openPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
} {
|
||||
const navigation = useNavigation();
|
||||
|
||||
const openPendingTask = useCallback(
|
||||
(pendingTask: PendingNewTask) => {
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: String(pendingTask.message.environmentId),
|
||||
projectId: String(pendingTask.creation.projectId),
|
||||
pendingTaskId: String(pendingTask.message.messageId),
|
||||
},
|
||||
});
|
||||
},
|
||||
[navigation],
|
||||
);
|
||||
|
||||
const confirmDeletePendingTask = useCallback((pendingTask: PendingNewTask) => {
|
||||
Alert.alert(
|
||||
"Delete pending task?",
|
||||
`“${pendingTask.title}” has not been sent yet and will be removed from the outbox.`,
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Delete",
|
||||
style: "destructive",
|
||||
onPress: () => {
|
||||
// Release the edit lock only after removal succeeds, and only if
|
||||
// it is held for THIS task — clearing it up front (or for another
|
||||
// task) would let the drain deliver a mid-edit payload.
|
||||
void removeThreadOutboxMessage(pendingTask.message)
|
||||
.then(() => releaseEditingQueuedMessage(pendingTask.message.messageId))
|
||||
.catch((error) => {
|
||||
Alert.alert(
|
||||
"Could not delete pending task",
|
||||
error instanceof Error ? error.message : "The pending task could not be removed.",
|
||||
);
|
||||
});
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
}, []);
|
||||
|
||||
return { openPendingTask, confirmDeletePendingTask };
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useFocusEffect } from "@react-navigation/native";
|
||||
import {
|
||||
@@ -401,6 +404,20 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
|
||||
}, [navigation]);
|
||||
|
||||
const handleNewThreadInProject = useCallback(
|
||||
(project: EnvironmentProject) => {
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: String(project.environmentId),
|
||||
projectId: String(project.id),
|
||||
title: project.title,
|
||||
},
|
||||
});
|
||||
},
|
||||
[navigation],
|
||||
);
|
||||
|
||||
const renderedSidebarWidth = useSharedValue(
|
||||
panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
|
||||
);
|
||||
@@ -477,6 +494,7 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
selectedThreadKey={selectedThreadKey}
|
||||
onOpenSettings={handleOpenSettings}
|
||||
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
|
||||
onNewThreadInProject={handleNewThreadInProject}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSearchQueryChange={setPrimarySidebarSearchQuery}
|
||||
searchQuery={primarySidebarSearchQuery}
|
||||
|
||||
@@ -1,38 +1,18 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { NativeHeaderToolbar } from "../../native/StackHeader";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import {
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPhase,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Switch,
|
||||
type NativeSyntheticEvent,
|
||||
type TextLayoutEventData,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import {
|
||||
type RelayEnvironmentView,
|
||||
useConnectionController,
|
||||
} from "../connection/useConnectionController";
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
|
||||
import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
|
||||
import { splitEnvironmentSections } from "../connection/environmentSections";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
|
||||
export function SettingsEnvironmentsRouteScreen() {
|
||||
@@ -117,7 +97,7 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
)}
|
||||
|
||||
{hasCloudPublicConfig() ? (
|
||||
<ConfiguredCloudEnvironmentRows
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
/>
|
||||
@@ -126,323 +106,3 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfiguredCloudEnvironmentRows(props: {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
}) {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments = controller.availableRelayEnvironments;
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
|
||||
const handleConnectCloudEnvironment = useCallback(
|
||||
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
|
||||
[controller],
|
||||
);
|
||||
|
||||
const handleDisconnectCloudEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
|
||||
[controller],
|
||||
);
|
||||
|
||||
const handleToggleCloudError = useCallback((environmentId: string) => {
|
||||
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
|
||||
}, []);
|
||||
|
||||
if (!isSignedIn) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="mt-5 gap-3">
|
||||
<View className="flex-row items-center justify-between px-1">
|
||||
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
onPress={() => {
|
||||
void controller.refreshRelayEnvironments();
|
||||
}}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{controller.relayDiscovery.isRefreshing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{hasCloudRows ? (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{props.connectedCloudEnvironments.map((environment, index) => (
|
||||
<ConnectedCloudEnvironmentRow
|
||||
key={environment.environmentId}
|
||||
environment={environment}
|
||||
borderTop={index !== 0}
|
||||
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
|
||||
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
|
||||
errorExpanded={expandedErrorId === environment.environmentId}
|
||||
onToggleError={() => handleToggleCloudError(environment.environmentId)}
|
||||
/>
|
||||
))}
|
||||
{availableCloudEnvironments.map((environment, index) => (
|
||||
<CloudEnvironmentRow
|
||||
key={environment.environment.environmentId}
|
||||
environment={environment}
|
||||
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
|
||||
onConnect={() => handleConnectCloudEnvironment(environment)}
|
||||
errorExpanded={expandedErrorId === environment.environment.environmentId}
|
||||
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
) : controller.relayDiscovery.isRefreshing ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
|
||||
<ActivityIndicator color={iconColor} />
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
Loading linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
) : controller.relayDiscovery.error ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
|
||||
<Text className="text-base font-t3-bold text-foreground">
|
||||
Could not load T3 Cloud environments
|
||||
</Text>
|
||||
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
|
||||
{controller.relayDiscovery.errorTraceId ? (
|
||||
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card p-5">
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
No additional linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectedCloudEnvironmentRow(props: {
|
||||
readonly environment: ConnectedEnvironmentSummary;
|
||||
readonly borderTop: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly onConnect: () => void;
|
||||
readonly onDisconnect: () => void;
|
||||
readonly onToggleError: () => void;
|
||||
}) {
|
||||
return (
|
||||
<CloudEnvironmentRowShell
|
||||
borderTop={props.borderTop}
|
||||
connectionError={props.environment.connectionError}
|
||||
connectionErrorTraceId={props.environment.connectionErrorTraceId}
|
||||
connectionState={props.environment.connectionState}
|
||||
errorExpanded={props.errorExpanded}
|
||||
label={props.environment.environmentLabel}
|
||||
onValueChange={(enabled) => {
|
||||
if (enabled) {
|
||||
props.onConnect();
|
||||
return;
|
||||
}
|
||||
props.onDisconnect();
|
||||
}}
|
||||
onToggleError={props.onToggleError}
|
||||
value={props.environment.connectionState !== "available"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CloudEnvironmentRow(props: {
|
||||
readonly environment: RelayEnvironmentView;
|
||||
readonly borderTop: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly onConnect: () => void;
|
||||
readonly onToggleError: () => void;
|
||||
}) {
|
||||
const presentation = availableCloudEnvironmentPresentation({
|
||||
isStatusPending: props.environment.availability === "checking",
|
||||
status: props.environment.status,
|
||||
statusError: props.environment.error,
|
||||
statusErrorTraceId: props.environment.traceId,
|
||||
});
|
||||
|
||||
return (
|
||||
<CloudEnvironmentRowShell
|
||||
borderTop={props.borderTop}
|
||||
connectionError={presentation.connectionError}
|
||||
connectionErrorTraceId={presentation.connectionErrorTraceId}
|
||||
connectionState={presentation.connectionState}
|
||||
errorExpanded={props.errorExpanded}
|
||||
label={props.environment.environment.label}
|
||||
onValueChange={(enabled) => {
|
||||
if (enabled) {
|
||||
props.onConnect();
|
||||
}
|
||||
}}
|
||||
onToggleError={props.onToggleError}
|
||||
statusText={presentation.statusText}
|
||||
value={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowShell(props: {
|
||||
readonly borderTop: boolean;
|
||||
readonly connectionError: string | null;
|
||||
readonly connectionErrorTraceId: string | null;
|
||||
readonly connectionState: EnvironmentConnectionPhase;
|
||||
readonly disabled?: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly label: string;
|
||||
readonly onToggleError: () => void;
|
||||
readonly onValueChange: (enabled: boolean) => void;
|
||||
readonly statusText?: string;
|
||||
readonly value: boolean;
|
||||
}) {
|
||||
const activeTrack = String(useThemeColor("--color-switch-active"));
|
||||
const track = String(useThemeColor("--color-secondary-border"));
|
||||
const chevron = useThemeColor("--color-chevron");
|
||||
const isRetrying =
|
||||
props.connectionState === "connecting" || props.connectionState === "reconnecting";
|
||||
const shouldPulse = isRetrying;
|
||||
const statusText =
|
||||
props.statusText ??
|
||||
connectionStatusText({
|
||||
phase: props.connectionState,
|
||||
error: props.connectionError,
|
||||
traceId: props.connectionErrorTraceId,
|
||||
});
|
||||
const statusClassName = props.connectionError
|
||||
? "text-rose-500 dark:text-rose-400"
|
||||
: "text-foreground-muted";
|
||||
const [errorMeasurement, setErrorMeasurement] = useState<{
|
||||
readonly text: string;
|
||||
readonly lineCount: number;
|
||||
} | null>(null);
|
||||
const errorTraceId = props.connectionErrorTraceId;
|
||||
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
|
||||
const errorLineCount =
|
||||
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
|
||||
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
|
||||
const isErrorExpanded = errorCanExpand && props.errorExpanded;
|
||||
const StatusContainer = errorCanExpand ? Pressable : View;
|
||||
const onMeasuredErrorTextLayout = useCallback(
|
||||
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
|
||||
if (!props.connectionError) {
|
||||
return;
|
||||
}
|
||||
const nextLineCount = event.nativeEvent.lines.length;
|
||||
setErrorMeasurement((currentMeasurement) =>
|
||||
currentMeasurement?.text === measuredErrorText &&
|
||||
currentMeasurement.lineCount === nextLineCount
|
||||
? currentMeasurement
|
||||
: { text: measuredErrorText, lineCount: nextLineCount },
|
||||
);
|
||||
},
|
||||
[measuredErrorText, props.connectionError],
|
||||
);
|
||||
return (
|
||||
<View
|
||||
collapsable={false}
|
||||
className={cn(
|
||||
"flex-row items-center gap-3 bg-card px-4 py-3.5",
|
||||
props.borderTop && "border-t border-border",
|
||||
)}
|
||||
>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<View className="min-w-0 flex-row items-center gap-2">
|
||||
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
|
||||
<Text
|
||||
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</View>
|
||||
{props.connectionError ? (
|
||||
<Text
|
||||
aria-hidden
|
||||
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
|
||||
onTextLayout={onMeasuredErrorTextLayout}
|
||||
style={{ opacity: 0, zIndex: -1 }}
|
||||
>
|
||||
{measuredErrorText}
|
||||
</Text>
|
||||
) : null}
|
||||
<StatusContainer
|
||||
{...(errorCanExpand
|
||||
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
|
||||
: {})}
|
||||
className="min-w-0 flex-row items-start gap-1"
|
||||
>
|
||||
<Text
|
||||
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
|
||||
numberOfLines={isErrorExpanded ? undefined : 1}
|
||||
>
|
||||
{statusText}
|
||||
{errorTraceId ? (
|
||||
<>
|
||||
{" Trace ID: "}
|
||||
<Text
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className={cn("text-xs underline", statusClassName)}
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
style={{ textDecorationStyle: "dotted" }}
|
||||
>
|
||||
{errorTraceId}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Text>
|
||||
{errorCanExpand ? (
|
||||
<SymbolView
|
||||
name="chevron.down"
|
||||
size={10}
|
||||
tintColor={chevron}
|
||||
type="monochrome"
|
||||
style={{
|
||||
marginTop: 3,
|
||||
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</StatusContainer>
|
||||
</View>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
onValueChange={props.onValueChange}
|
||||
trackColor={{ false: track, true: activeTrack }}
|
||||
value={props.value}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function CopyTraceIdButton(props: { readonly traceId: string }) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
|
||||
}}
|
||||
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
|
||||
>
|
||||
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
|
||||
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useAuth, useUser } from "@clerk/expo";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Updates from "expo-updates";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
@@ -18,7 +20,11 @@ import {
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
|
||||
import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
|
||||
import { refreshAgentAwarenessRegistration } from "../agent-awareness/remoteRegistration";
|
||||
import {
|
||||
getAgentAwarenessRegistrationStatus,
|
||||
refreshAgentAwarenessRegistration,
|
||||
subscribeAgentAwarenessRegistrationStatus,
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
|
||||
@@ -35,6 +41,19 @@ import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
|
||||
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
|
||||
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
|
||||
|
||||
// Reflects whether the relay actually accepted this device's registration.
|
||||
// The notification and Live Activity switches are gated on this so they can
|
||||
// never read as enabled when the device cannot receive anything (e.g. the
|
||||
// registration request timed out).
|
||||
function useDeviceRegistered(): boolean {
|
||||
const status = useSyncExternalStore(
|
||||
subscribeAgentAwarenessRegistrationStatus,
|
||||
getAgentAwarenessRegistrationStatus,
|
||||
() => "unknown" as const,
|
||||
);
|
||||
return status === "registered";
|
||||
}
|
||||
|
||||
export function SettingsRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
@@ -111,6 +130,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
|
||||
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
|
||||
const deviceRegistered = useDeviceRegistered();
|
||||
|
||||
const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
|
||||
const environmentCount = connections.length;
|
||||
@@ -180,10 +200,19 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
if (result.value.type === "granted") {
|
||||
setNotificationStatus("enabled");
|
||||
Alert.alert(
|
||||
"Notifications enabled",
|
||||
"Live Activity notifications are enabled for this device.",
|
||||
);
|
||||
// Permission alone is not enough: the switch stays off until the relay
|
||||
// registration succeeds, so tell the user the truth about which happened.
|
||||
if (getAgentAwarenessRegistrationStatus() === "registered") {
|
||||
Alert.alert(
|
||||
"Notifications enabled",
|
||||
"Live Activity notifications are enabled for this device.",
|
||||
);
|
||||
} else {
|
||||
Alert.alert(
|
||||
"Couldn't finish enabling notifications",
|
||||
"Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (result.value.type === "unsupported") {
|
||||
@@ -211,8 +240,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
const promptSignIn = useCallback(() => {
|
||||
Alert.alert(
|
||||
"Request T3 Cloud access",
|
||||
"Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.",
|
||||
"Request T3 Connect access",
|
||||
"Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
@@ -269,12 +298,22 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
refreshManagedRelayEnvironments();
|
||||
setLiveActivityStatus("enabled");
|
||||
Alert.alert(
|
||||
"Live Activities enabled",
|
||||
environmentCount > 0
|
||||
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
|
||||
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
|
||||
);
|
||||
// The environment link can succeed while this device's own registration
|
||||
// (the push-to-start token the relay needs) has not — don't claim Live
|
||||
// Activities are live until the device is actually registered.
|
||||
if (getAgentAwarenessRegistrationStatus() === "registered") {
|
||||
Alert.alert(
|
||||
"Live Activities enabled",
|
||||
environmentCount > 0
|
||||
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
|
||||
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
|
||||
);
|
||||
} else {
|
||||
Alert.alert(
|
||||
"Couldn't finish enabling Live Activities",
|
||||
"This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",
|
||||
);
|
||||
}
|
||||
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
|
||||
|
||||
const handleDeviceNotificationsChange = useCallback(
|
||||
@@ -393,7 +432,10 @@ function ConfiguredSettingsRouteScreen() {
|
||||
icon="bell.badge"
|
||||
label="Device Notifications"
|
||||
disabled={notificationStatus === "checking" || notificationStatus === "unsupported"}
|
||||
value={notificationStatus === "enabled"}
|
||||
// Only reads as on when this device is actually registered with the
|
||||
// relay; otherwise notifications cannot be delivered regardless of
|
||||
// the local iOS permission.
|
||||
value={notificationStatus === "enabled" && deviceRegistered}
|
||||
onValueChange={handleDeviceNotificationsChange}
|
||||
/>
|
||||
<SettingsSwitchRow
|
||||
@@ -402,7 +444,12 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
icon="bolt.circle"
|
||||
label="Live Activity Updates"
|
||||
value={liveActivityStatus === "enabled" || liveActivityStatus === "linking"}
|
||||
// Same gate: a saved preference is meaningless until the device
|
||||
// registration the relay needs to push updates has succeeded.
|
||||
value={
|
||||
(liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
|
||||
deviceRegistered
|
||||
}
|
||||
onValueChange={handleLiveActivitiesChange}
|
||||
/>
|
||||
</SettingsSection>
|
||||
@@ -422,6 +469,23 @@ function ConfiguredSettingsRouteScreen() {
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
|
||||
const version = Constants.expoConfig?.version ?? "0.0.0";
|
||||
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
|
||||
// missing variant never mislabels a production build as development.
|
||||
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
|
||||
const variantLabel = variant === "production" ? "" : capitalize(variant);
|
||||
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
|
||||
// Which JS is actually running: the bundle shipped in the binary, or an OTA
|
||||
// update downloaded on top of it. Surfacing this makes "am I even on the
|
||||
// right build?" answerable at a glance.
|
||||
const bundleLabel = Updates.isEnabled
|
||||
? Updates.isEmbeddedLaunch
|
||||
? "Embedded"
|
||||
: Updates.updateId
|
||||
? `OTA ${Updates.updateId.slice(0, 7)}`
|
||||
: null
|
||||
: null;
|
||||
|
||||
return (
|
||||
<SettingsSection title="App">
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
@@ -433,12 +497,21 @@ function AppSettingsSection() {
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<Text className="text-lg text-foreground-muted">Alpha</Text>
|
||||
<View className="items-end">
|
||||
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
|
||||
{bundleLabel ? (
|
||||
<Text className="text-xs text-foreground-muted/70">{bundleLabel}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function capitalize(value: string): string {
|
||||
return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
|
||||
}
|
||||
|
||||
function ArchivedThreadsSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="Threads">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { StaticScreenProps } from "@react-navigation/native";
|
||||
import { useMemo } from "react";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
|
||||
import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
|
||||
@@ -7,11 +8,25 @@ type NewTaskDraftRouteParams = {
|
||||
readonly environmentId?: string | string[];
|
||||
readonly projectId?: string | string[];
|
||||
readonly title?: string | string[];
|
||||
readonly pendingTaskId?: string | string[];
|
||||
};
|
||||
|
||||
export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
|
||||
const params = route.params ?? {};
|
||||
|
||||
// Keyed on the params object so a fresh navigation to this (already
|
||||
// mounted) screen produces a new reference, letting the draft screen
|
||||
// re-apply the requested project.
|
||||
const initialProjectRef = useMemo(
|
||||
() => ({
|
||||
environmentId: Array.isArray(params.environmentId)
|
||||
? params.environmentId[0]
|
||||
: params.environmentId,
|
||||
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
|
||||
}),
|
||||
[route.params],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
@@ -20,12 +35,10 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
|
||||
}}
|
||||
/>
|
||||
<NewTaskDraftScreen
|
||||
initialProjectRef={{
|
||||
environmentId: Array.isArray(params.environmentId)
|
||||
? params.environmentId[0]
|
||||
: params.environmentId,
|
||||
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
|
||||
}}
|
||||
initialProjectRef={initialProjectRef}
|
||||
pendingTaskId={
|
||||
Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -23,6 +23,7 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
|
||||
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
|
||||
import {
|
||||
applyProviderOptionMenuEvent,
|
||||
@@ -30,10 +31,13 @@ import {
|
||||
providerOptionsConfigurationLabel,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
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 { useCreateProjectThread } from "./use-project-actions";
|
||||
|
||||
@@ -54,6 +58,8 @@ export function NewTaskDraftScreen(props: {
|
||||
readonly environmentId?: string;
|
||||
readonly projectId?: string;
|
||||
};
|
||||
/** Queued outbox message id when editing an existing pending task. */
|
||||
readonly pendingTaskId?: string;
|
||||
}) {
|
||||
const projects = useProjects();
|
||||
const createProjectThread = useCreateProjectThread();
|
||||
@@ -64,24 +70,84 @@ export function NewTaskDraftScreen(props: {
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const environmentConnected =
|
||||
selectedProject !== null &&
|
||||
connectedEnvironments.find(
|
||||
(environment) => environment.environmentId === selectedProject.environmentId,
|
||||
)?.connectionState === "connected";
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
const appliedInitialProjectKeyRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
appliedInitialProjectKeyRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow;
|
||||
const attemptedPendingTaskIdRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
|
||||
return;
|
||||
}
|
||||
// Attempt each pending task once: after it is delivered or deleted the
|
||||
// editing session legitimately ends, and re-running must not navigate.
|
||||
if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
|
||||
return;
|
||||
}
|
||||
attemptedPendingTaskIdRef.current = props.pendingTaskId;
|
||||
if (!beginEditingPendingTask(props.pendingTaskId)) {
|
||||
// The queued task no longer exists (sent or deleted before opening).
|
||||
navigation.dispatch(StackActions.replace("NewTask"));
|
||||
}
|
||||
}, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.pendingTaskId) return;
|
||||
return () => {
|
||||
// Allow a later navigation for the same pending task to re-hydrate it.
|
||||
attemptedPendingTaskIdRef.current = null;
|
||||
cancelEditingPendingTask();
|
||||
};
|
||||
}, [props.pendingTaskId, cancelEditingPendingTask]);
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
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)";
|
||||
|
||||
// A new navigation to this mounted screen delivers a fresh initialProjectRef
|
||||
// reference — treat it as a new request and let it apply again.
|
||||
const lastInitialProjectRefRef = useRef(props.initialProjectRef);
|
||||
|
||||
useEffect(() => {
|
||||
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
|
||||
// Pending-task editing owns project selection (and must not fall through
|
||||
// to the replace("NewTask") fallback while its hydration is in flight).
|
||||
if (props.pendingTaskId) {
|
||||
return;
|
||||
}
|
||||
if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
|
||||
lastInitialProjectRefRef.current = props.initialProjectRef;
|
||||
appliedInitialProjectKeyRef.current = null;
|
||||
}
|
||||
const initialEnvironmentId = props.initialProjectRef?.environmentId;
|
||||
const initialProjectId = props.initialProjectRef?.projectId;
|
||||
if (initialEnvironmentId && initialProjectId) {
|
||||
const directProject =
|
||||
projects.find(
|
||||
(project) =>
|
||||
project.environmentId === props.initialProjectRef?.environmentId &&
|
||||
project.id === props.initialProjectRef?.projectId,
|
||||
project.environmentId === initialEnvironmentId && project.id === initialProjectId,
|
||||
) ?? null;
|
||||
|
||||
if (directProject) {
|
||||
// Apply the route's project once. Re-applying on every change would
|
||||
// instantly revert environment/project switches made in the picker.
|
||||
const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
|
||||
if (appliedInitialProjectKeyRef.current === directProjectKey) {
|
||||
return;
|
||||
}
|
||||
appliedInitialProjectKeyRef.current = directProjectKey;
|
||||
if (
|
||||
selectedProject?.environmentId === directProject.environmentId &&
|
||||
selectedProject.id === directProject.id
|
||||
@@ -106,8 +172,8 @@ export function NewTaskDraftScreen(props: {
|
||||
}, [
|
||||
logicalProjects,
|
||||
projects,
|
||||
props.initialProjectRef?.environmentId,
|
||||
props.initialProjectRef?.projectId,
|
||||
props.initialProjectRef,
|
||||
props.pendingTaskId,
|
||||
navigation,
|
||||
selectedProject,
|
||||
setProject,
|
||||
@@ -274,12 +340,24 @@ export function NewTaskDraftScreen(props: {
|
||||
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,
|
||||
]);
|
||||
|
||||
@@ -344,6 +422,10 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
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);
|
||||
@@ -379,17 +461,17 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
async function handleStart(): Promise<void> {
|
||||
const selectedProject = flow.selectedProject;
|
||||
if (!selectedProject) {
|
||||
const draftKey = flow.draftKey;
|
||||
if (!selectedProject || !draftKey) {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(
|
||||
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
|
||||
);
|
||||
const draft = getComposerDraftSnapshot(draftKey);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
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 initialMessageText = draft.text.trim();
|
||||
@@ -403,17 +485,76 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
const editingPendingTask = flow.editingPendingTask;
|
||||
|
||||
if (!environmentConnected) {
|
||||
// Offline: park the task in the outbox; the drain sends it when the
|
||||
// environment reconnects. Editing an existing pending task re-queues it
|
||||
// under its original identifiers.
|
||||
const metadata = editingPendingTask
|
||||
? {
|
||||
threadId: editingPendingTask.threadId,
|
||||
commandId: editingPendingTask.commandId,
|
||||
messageId: editingPendingTask.messageId,
|
||||
createdAt: editingPendingTask.createdAt,
|
||||
}
|
||||
: makeTurnCommandMetadata();
|
||||
const message = flow.buildPendingTaskMessage(metadata);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
flow.setSubmitting(true);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage(message);
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Could not queue task",
|
||||
error instanceof Error ? error.message : "The task could not be saved to the outbox.",
|
||||
);
|
||||
return;
|
||||
} finally {
|
||||
flow.setSubmitting(false);
|
||||
}
|
||||
if (editingPendingTask) {
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
}
|
||||
navigation.getParent()?.goBack();
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setSubmitting(true);
|
||||
// Arm the lock-screen card before the async thread creation: backgrounding
|
||||
// the app right after tapping submit would otherwise reject the foreground
|
||||
// -only Activity start. If creation fails, the token registration's replay
|
||||
// finds no work and ends the card within seconds.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
|
||||
projectTitle: selectedProject.title,
|
||||
});
|
||||
const result = await createProjectThread({
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
startFromOrigin,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
...(editingPendingTask
|
||||
? {
|
||||
turnMetadata: {
|
||||
threadId: editingPendingTask.threadId,
|
||||
commandId: editingPendingTask.commandId,
|
||||
messageId: editingPendingTask.messageId,
|
||||
createdAt: editingPendingTask.createdAt,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
flow.setSubmitting(false);
|
||||
|
||||
@@ -428,8 +569,17 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
if (editingPendingTask) {
|
||||
try {
|
||||
await removeThreadOutboxMessage(editingPendingTask);
|
||||
} catch (error) {
|
||||
console.warn("[new-task] failed to remove delivered pending task", error);
|
||||
}
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
environmentId: String(result.value.environmentId),
|
||||
@@ -463,7 +613,7 @@ export function NewTaskDraftScreen(props: {
|
||||
onPasteImages={(uris) => void handleNativePasteImages(uris)}
|
||||
placeholder={`Describe a coding task in ${selectedProject.title}`}
|
||||
style={{ flex: 1, minHeight: 0 }}
|
||||
textStyle={bodyText}
|
||||
textStyle={headlineText}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -538,8 +688,14 @@ export function NewTaskDraftScreen(props: {
|
||||
</ControlPillMenu>
|
||||
</ComposerToolbarScroller>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={flow.submitting ? "Starting task" : "Start task"}
|
||||
icon="arrow.up"
|
||||
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}
|
||||
|
||||
@@ -25,7 +25,9 @@ import {
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -112,6 +114,10 @@ export interface ThreadComposerProps {
|
||||
* The pill / card container — renders as LiquidGlassView on supported
|
||||
* iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
|
||||
*/
|
||||
// One timing for every piece of the expanded↔compact morph so the surface,
|
||||
// toolbar, and siblings move together instead of popping between layouts.
|
||||
const COMPOSER_LAYOUT_TRANSITION = LinearTransition.duration(220);
|
||||
|
||||
function ComposerSurface(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly style: ViewStyle;
|
||||
@@ -130,7 +136,7 @@ function ComposerSurface(props: {
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<View style={shadowStyle}>
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<LiquidGlassView
|
||||
effect="regular"
|
||||
interactive
|
||||
@@ -139,12 +145,12 @@ function ComposerSurface(props: {
|
||||
>
|
||||
{props.children}
|
||||
</LiquidGlassView>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={shadowStyle}>
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<View
|
||||
style={[
|
||||
props.style,
|
||||
@@ -157,7 +163,7 @@ function ComposerSurface(props: {
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -494,12 +500,24 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
if (inFlightThreadIdsRef.current.has(threadKey)) return;
|
||||
inFlightThreadIdsRef.current.add(threadKey);
|
||||
// Sending a prompt starts agent work: arm the lock-screen card now, while
|
||||
// the app is foregrounded and the activity token can be registered.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
threadTitle: props.selectedThread.title,
|
||||
projectTitle: props.environmentLabel ?? "T3 Code",
|
||||
});
|
||||
try {
|
||||
await onSendMessage();
|
||||
} finally {
|
||||
inFlightThreadIdsRef.current.delete(threadKey);
|
||||
}
|
||||
}, [onSendMessage, props.environmentId, props.selectedThread.id]);
|
||||
}, [
|
||||
onSendMessage,
|
||||
props.environmentId,
|
||||
props.environmentLabel,
|
||||
props.selectedThread.id,
|
||||
props.selectedThread.title,
|
||||
]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
if (!composerTrigger) return;
|
||||
@@ -669,7 +687,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
<Animated.View
|
||||
layout={COMPOSER_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: isExpanded ? 8 : 6,
|
||||
@@ -679,8 +698,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
|
||||
}}
|
||||
>
|
||||
<View
|
||||
<Animated.View
|
||||
className="w-full"
|
||||
layout={COMPOSER_LAYOUT_TRANSITION}
|
||||
style={{ alignSelf: "center", maxWidth: props.contentMaxWidth, position: "relative" }}
|
||||
>
|
||||
{composerTrigger && composerMenuItems.length > 0 ? (
|
||||
@@ -733,13 +753,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
>
|
||||
{/* Attachment strip — inside the card, above the text input */}
|
||||
{isExpanded ? (
|
||||
<View style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}>
|
||||
<Animated.View
|
||||
entering={FadeIn.duration(160)}
|
||||
exiting={FadeOut.duration(120)}
|
||||
style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}
|
||||
>
|
||||
<ComposerAttachmentStrip
|
||||
attachments={props.draftAttachments}
|
||||
onRemove={props.onRemoveDraftImage}
|
||||
onPressImage={onPressImage}
|
||||
/>
|
||||
</View>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
|
||||
<View style={isExpanded ? undefined : { flex: 1, minWidth: 0 }}>
|
||||
@@ -812,81 +836,87 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
</View>
|
||||
) : null}
|
||||
{!isExpanded ? (
|
||||
showStopAction ? (
|
||||
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
|
||||
) : (
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
/>
|
||||
)
|
||||
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
|
||||
{showStopAction ? (
|
||||
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
|
||||
) : (
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
/>
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{/* Toolbar row — matches draft page layout (expanded only) */}
|
||||
{isExpanded ? (
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={toolbarFadeOpaque}
|
||||
fadeTransparent={toolbarFadeTransparent}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
icon="plus"
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={toolbarFadeOpaque}
|
||||
fadeTransparent={toolbarFadeTransparent}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
onPress={props.onStopThread}
|
||||
icon="plus"
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerToolbarScroller>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={sendLabel}
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
showChevron={false}
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
onPress={props.onStopThread}
|
||||
showChevron={false}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerToolbarScroller>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={sendLabel}
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
showChevron={false}
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
|
||||
{/* Queue count */}
|
||||
{props.queueCount > 0 ? (
|
||||
<Text className="text-xs text-foreground-muted" style={{ paddingTop: 8 }}>
|
||||
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
|
||||
automatically.
|
||||
</Text>
|
||||
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
|
||||
<Text className="text-xs text-foreground-muted" style={{ paddingTop: 8 }}>
|
||||
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
|
||||
automatically.
|
||||
</Text>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</View>
|
||||
</Animated.View>
|
||||
|
||||
<ImageViewing
|
||||
images={previewImageUri ? [{ uri: previewImageUri }] : []}
|
||||
@@ -896,6 +926,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
swipeToCloseEnabled
|
||||
doubleTapToZoomEnabled
|
||||
/>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
@@ -17,11 +17,10 @@ import type {
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { runOnJS } from "react-native-reanimated";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
@@ -73,7 +72,6 @@ export interface ThreadDetailScreenProps {
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly onOpenDrawer: () => void;
|
||||
readonly onOpenConnectionEditor: () => void;
|
||||
readonly onChangeDraftMessage: (value: string) => void;
|
||||
readonly onPickDraftImages: () => Promise<void>;
|
||||
@@ -173,7 +171,11 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
const WORKING_INDICATOR_HEIGHT = 44;
|
||||
// Pre-measurement estimate for the working pill's slot (the real height is
|
||||
// measured via onComposerLayout since the pill lives inside the composer
|
||||
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
|
||||
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
|
||||
const WORKING_INDICATOR_HEIGHT = 52;
|
||||
|
||||
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
|
||||
readonly startedAt: string;
|
||||
@@ -190,7 +192,12 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
|
||||
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
|
||||
|
||||
return (
|
||||
<View className="px-4 pb-2" style={{ flexShrink: 0 }}>
|
||||
<Animated.View
|
||||
className="px-4 pb-2 pt-2"
|
||||
entering={FadeInDown.duration(200)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
style={{ flexShrink: 0 }}
|
||||
>
|
||||
<View className="self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="flex-row items-center gap-1">
|
||||
@@ -203,13 +210,11 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const { onOpenDrawer } = props;
|
||||
|
||||
const insets = useSafeAreaInsets();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
@@ -243,11 +248,21 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
// UIKit add the safe-area bottom to the content inset AGAIN — leaving a
|
||||
// dead strip between the resting content and the composer. Report the
|
||||
// overlay height minus the safe area; UIKit adds it back, and ThreadFeed
|
||||
// hands LegendList the same delta via contentInsetEndStaticAdjustment so
|
||||
// its end-scroll math matches the real resting position.
|
||||
const nativeInsetOvercount =
|
||||
props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
|
||||
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
|
||||
listRef,
|
||||
composerOverlayRef,
|
||||
estimatedOverlayHeight,
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
-nativeInsetOvercount,
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const showContent = props.showContent ?? true;
|
||||
@@ -263,28 +278,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
[props.serverConfig, selectedInstanceId],
|
||||
);
|
||||
|
||||
const completeDrawerGesture = useCallback(() => {
|
||||
void Haptics.selectionAsync();
|
||||
onOpenDrawer();
|
||||
}, [onOpenDrawer]);
|
||||
|
||||
const drawerGestureThreshold = 80;
|
||||
const headerDrawerGesture = useMemo(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.enabled(!isSplitLayout)
|
||||
.hitSlop({ left: 0, width: 40 })
|
||||
.activeOffsetX([10, 999])
|
||||
.failOffsetY([-24, 24])
|
||||
.onEnd((event) => {
|
||||
const translationX = Math.max(event.translationX, 0);
|
||||
if (event.y < drawerGestureThreshold && translationX > 56) {
|
||||
runOnJS(completeDrawerGesture)();
|
||||
}
|
||||
}),
|
||||
[completeDrawerGesture, isSplitLayout],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
@@ -311,16 +304,31 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
});
|
||||
// Wait for the keyboard dismissal (started by blur() on send) to finish
|
||||
// before scrolling: scrollMessageToEnd freezes keyboard-driven inset
|
||||
// updates while it runs, and a close event swallowed by that freeze
|
||||
// leaves the keyboard padding permanently applied — overshooting the
|
||||
// anchor and leaving a phantom bottom inset once the reply streams in.
|
||||
void KeyboardController.dismiss()
|
||||
.then(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
return scrollMessageToEnd({ animated: true, closeKeyboard: false });
|
||||
})
|
||||
.catch(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
@@ -379,115 +387,120 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<GestureDetector gesture={headerDrawerGesture}>
|
||||
<View className="flex-1">
|
||||
{showContent ? (
|
||||
<View
|
||||
style={{ flex: 1 }}
|
||||
onTouchStart={handleFeedTouchStart}
|
||||
onTouchMove={handleFeedTouchMove}
|
||||
onTouchEnd={handleFeedTouchEnd}
|
||||
onTouchCancel={handleFeedTouchCancel}
|
||||
>
|
||||
<ThreadFeed
|
||||
key={props.selectedThread.id}
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
workspaceRoot={props.threadCwd}
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
<View className="flex-1">
|
||||
{showContent ? (
|
||||
<View
|
||||
style={{ flex: 1 }}
|
||||
onTouchStart={handleFeedTouchStart}
|
||||
onTouchMove={handleFeedTouchMove}
|
||||
onTouchEnd={handleFeedTouchEnd}
|
||||
onTouchCancel={handleFeedTouchCancel}
|
||||
>
|
||||
<ThreadFeed
|
||||
key={props.selectedThread.id}
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
workspaceRoot={props.threadCwd}
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View style={{ flex: 1 }} />
|
||||
)}
|
||||
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
<KeyboardStickyView
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
{/* No paddingTop here: the overlay's measured height becomes the
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ width: "100%" }}>
|
||||
<Animated.View
|
||||
layout={LinearTransition.duration(220)}
|
||||
style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}
|
||||
>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="gap-3 px-4 pb-3"
|
||||
entering={FadeInDown.duration(220)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
style={{ flexShrink: 0 }}
|
||||
>
|
||||
{props.activePendingApproval ? (
|
||||
<PendingApprovalCard
|
||||
approval={props.activePendingApproval}
|
||||
respondingApprovalId={props.respondingApprovalId}
|
||||
onRespond={props.onRespondToApproval}
|
||||
/>
|
||||
) : null}
|
||||
{props.activePendingUserInput ? (
|
||||
<PendingUserInputCard
|
||||
pendingUserInput={props.activePendingUserInput}
|
||||
drafts={props.activePendingUserInputDrafts}
|
||||
answers={props.activePendingUserInputAnswers}
|
||||
respondingUserInputId={props.respondingUserInputId}
|
||||
onSelectOption={props.onSelectUserInputOption}
|
||||
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
|
||||
onSubmit={props.onSubmitUserInput}
|
||||
/>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View style={{ flex: 1 }} />
|
||||
)}
|
||||
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
<KeyboardStickyView
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View
|
||||
ref={composerOverlayRef}
|
||||
onLayout={onComposerLayout}
|
||||
style={{ width: "100%", paddingTop: 8 }}
|
||||
>
|
||||
<View style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
|
||||
{props.activePendingApproval ? (
|
||||
<PendingApprovalCard
|
||||
approval={props.activePendingApproval}
|
||||
respondingApprovalId={props.respondingApprovalId}
|
||||
onRespond={props.onRespondToApproval}
|
||||
/>
|
||||
) : null}
|
||||
{props.activePendingUserInput ? (
|
||||
<PendingUserInputCard
|
||||
pendingUserInput={props.activePendingUserInput}
|
||||
drafts={props.activePendingUserInputDrafts}
|
||||
answers={props.activePendingUserInputAnswers}
|
||||
respondingUserInputId={props.respondingUserInputId}
|
||||
onSelectOption={props.onSelectUserInputOption}
|
||||
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
|
||||
onSubmit={props.onSubmitUserInput}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
</View>
|
||||
</GestureDetector>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -4,11 +4,14 @@ import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
@@ -41,7 +44,13 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { type SharedValue } from "react-native-reanimated";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInUp,
|
||||
FadeOut,
|
||||
LinearTransition,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
@@ -96,6 +105,19 @@ function formatMessageTime(input: string): string {
|
||||
return MESSAGE_TIME_FORMATTER.format(timestamp);
|
||||
}
|
||||
|
||||
// Rows shift when content above them grows (streaming text, work-log folds);
|
||||
// animating the container position turns those jumps into slides.
|
||||
const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180);
|
||||
|
||||
// Entering animations must only play for rows born just now — LegendList
|
||||
// remounts rows when they scroll back into view, and replaying an entrance for
|
||||
// old content would be its own kind of jank.
|
||||
const FRESH_ENTRY_WINDOW_MS = 3_000;
|
||||
function isFreshTimestamp(input: string): boolean {
|
||||
const timestamp = Date.parse(input);
|
||||
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
|
||||
}
|
||||
|
||||
export interface ThreadFeedProps {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
@@ -749,8 +771,12 @@ function renderFeedEntry(
|
||||
!message.streaming;
|
||||
|
||||
if (isUser) {
|
||||
const enterAnimated = isFreshTimestamp(message.createdAt);
|
||||
return (
|
||||
<View className="mb-5 items-end">
|
||||
<Animated.View
|
||||
className="mb-5 items-end"
|
||||
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
|
||||
>
|
||||
<View
|
||||
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
|
||||
style={{
|
||||
@@ -794,7 +820,7 @@ function renderFeedEntry(
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -804,8 +830,12 @@ function renderFeedEntry(
|
||||
return null;
|
||||
}
|
||||
|
||||
const enterAnimated = isFreshTimestamp(message.createdAt);
|
||||
return (
|
||||
<View className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}>
|
||||
<Animated.View
|
||||
className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}
|
||||
{...(enterAnimated ? { entering: FadeIn.duration(220) } : {})}
|
||||
>
|
||||
{message.text.trim().length > 0 ? (
|
||||
hasNativeSelectableMarkdownText() ? (
|
||||
<SelectableMarkdownText
|
||||
@@ -850,7 +880,7 @@ function renderFeedEntry(
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1146,6 +1176,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
props.layoutVariant === "split" ? 0 : windowWidth,
|
||||
);
|
||||
const [viewportHeight, setViewportHeight] = useState(0);
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
@@ -1177,6 +1208,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const bottomContentInset = props.contentBottomInset ?? 18;
|
||||
const usesNativeAutomaticInsets =
|
||||
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
|
||||
// With automatic insets the header inset lives in UIKit's adjustedContentInset,
|
||||
// which LegendList's JS anchoring math cannot see — it measures the anchored
|
||||
// end space from the scroll view's frame top. Fold the header height back into
|
||||
// the anchor offset or a just-sent message anchors underneath the header and
|
||||
// the oversized end space keeps maintainScrollAtEnd snapping away from earlier
|
||||
// messages. Read the context directly (useHeaderHeight throws outside a
|
||||
// header-providing screen) and fall back to the standard iOS bar height.
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext);
|
||||
const anchorTopInset = usesNativeAutomaticInsets
|
||||
? navigationHeaderHeight || insets.top + 44
|
||||
: topContentInset;
|
||||
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const userBubbleColor = useThemeColor("--color-user-bubble");
|
||||
@@ -1242,13 +1284,19 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
const handleScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + topContentInset > 6);
|
||||
// anchorTopInset, not topContentInset: under automatic insets the list
|
||||
// rests at contentOffset.y = -headerHeight (the inset lives only in
|
||||
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
|
||||
// header height back or the material toggles a full header too late.
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
|
||||
},
|
||||
[reportHeaderMaterialVisibility, topContentInset],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset],
|
||||
);
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1275,15 +1323,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
// content-inset override — and useKeyboardChatComposerInset (mounted above
|
||||
// the remount boundary) deduplicates by height, so it never re-reports the
|
||||
// composer inset to the fresh instance. Without this, the remounted list's
|
||||
// initial scroll-to-end computes with a zero end inset and rests one
|
||||
// composer-height short of the end. Layout effect: it must land before the
|
||||
// list's first positioning tick or the one-shot initial scroll misses it.
|
||||
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
useLayoutEffect(() => {
|
||||
const bottom = props.contentInsetEndAdjustment.value;
|
||||
if (bottom > 0) {
|
||||
props.listRef.current?.reportContentInset({ bottom });
|
||||
}
|
||||
}, [listMountKey, props.contentInsetEndAdjustment, props.listRef]);
|
||||
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
resolveChatListAnchoredEndSpace(
|
||||
presentedFeed,
|
||||
props.anchorMessageId,
|
||||
(entry) => (entry.type === "message" ? entry.id : null),
|
||||
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
|
||||
{ anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
|
||||
),
|
||||
[presentedFeed, props.anchorMessageId, topContentInset],
|
||||
[presentedFeed, props.anchorMessageId, anchorTopInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
@@ -1506,8 +1569,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// an already-attached list under a transparent header can pin
|
||||
// short content at offset 0 (one header-height too high). A fresh
|
||||
// mount positions during attach, where UIKit applies the inset.
|
||||
key={`${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`}
|
||||
key={listMountKey}
|
||||
style={{ flex: 1 }}
|
||||
// RN 0.81+ drops touches inside the contentInset area
|
||||
// (facebook/react-native#54123); the anchored end space after a send
|
||||
// is pure inset, so without this the blank region can't be scrolled.
|
||||
applyWorkaroundForContentInsetHitTestBug
|
||||
contentInsetAdjustmentBehavior={usesNativeAutomaticInsets ? "automatic" : "never"}
|
||||
automaticallyAdjustsScrollIndicatorInsets={usesNativeAutomaticInsets}
|
||||
{...(usesNativeAutomaticInsets
|
||||
@@ -1523,13 +1590,35 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION}
|
||||
// Patched LegendList prop (patches/@[email protected]):
|
||||
// lets its scroll math clamp programmatic scrolls to -headerInset
|
||||
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
|
||||
// content rest below the transparent header rather than at frame top.
|
||||
contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
// UIKit's automatic behavior adds the safe-area bottom on top of the
|
||||
// raw contentInset the keyboard integration writes. The detail screen
|
||||
// under-reports the composer inset by this amount (see
|
||||
// ThreadDetailScreen); this tells LegendList's scroll math about the
|
||||
// extra so programmatic end scrolls land at the true resting offset.
|
||||
contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0}
|
||||
// The keyboard integration's offset math (end pinning, max scroll)
|
||||
// must add the same UIKit-added extra, or its keyboard-open end
|
||||
// targets land one safe-area short of the true resting offset.
|
||||
adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0}
|
||||
freeze={props.freeze}
|
||||
// Animated: on send, the optimistic message's dataChange fires
|
||||
// maintainScrollAtEnd before any render-cycle suppression could
|
||||
// engage — an instant snap there teleports the feed to the anchor
|
||||
// instead of scrolling to it. Keeping it enabled (animated) during
|
||||
// anchor scrolls also lets it correct a scroll that landed on a
|
||||
// stale end target once the anchor row finishes measuring.
|
||||
maintainScrollAtEnd={
|
||||
disclosureToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
animated: true,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
@@ -1548,6 +1637,21 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
// Seed the list's scroll math with the real viewport before its own
|
||||
// onLayout: the empty→filled remount can then tell at mount that
|
||||
// short content underflows the viewport and skip programmatic
|
||||
// positioning entirely (any offset write during screen attach races
|
||||
// UIKit's adjustedContentInset application and lands high or low).
|
||||
{...(viewportHeight > 0 && viewportWidth > 0
|
||||
? { estimatedListSize: { height: viewportHeight, width: viewportWidth } }
|
||||
: {})}
|
||||
// RN's native scrollTo command clamps targets to a floor of
|
||||
// -contentInset.top using the RAW inset — under automatic insets the
|
||||
// header inset only exists in adjustedContentInset, so scrolls to
|
||||
// negative offsets (content top below the transparent header) get
|
||||
// clamped to 0. This prop disables that clamp; UIKit still bounces
|
||||
// user overscroll back to the adjusted rest position.
|
||||
scrollToOverflowEnabled
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onScroll={handleScroll}
|
||||
|
||||
@@ -1,255 +0,0 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
type ColorValue,
|
||||
Modal,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, {
|
||||
runOnJS,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { StatusPill } from "../../components/StatusPill";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { resolveThreadStatus } from "./threadPresentation";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { buildThreadNavigationGroups } from "./thread-navigation-groups";
|
||||
|
||||
export function ThreadNavigationDrawer(props: {
|
||||
readonly visible: boolean;
|
||||
readonly selectedThreadKey: string | null;
|
||||
readonly onClose: () => void;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const { width } = useWindowDimensions();
|
||||
const drawerWidth = Math.min(width * 0.84, 360);
|
||||
const [mounted, setMounted] = useState(props.visible);
|
||||
const translateX = useSharedValue(-drawerWidth);
|
||||
const overlayOpacity = useSharedValue(0);
|
||||
|
||||
const backdropColor = useThemeColor("--color-backdrop");
|
||||
const drawerBg = useThemeColor("--color-drawer");
|
||||
const drawerShadow = useThemeColor("--color-drawer-shadow");
|
||||
const primaryForeground = useThemeColor("--color-primary-foreground");
|
||||
const borderSubtleColor = useThemeColor("--color-border-subtle");
|
||||
|
||||
useEffect(() => {
|
||||
if (props.visible) {
|
||||
setMounted(true);
|
||||
translateX.value = withTiming(0, { duration: 240 });
|
||||
overlayOpacity.value = withTiming(1, { duration: 220 });
|
||||
return;
|
||||
}
|
||||
|
||||
overlayOpacity.value = withTiming(0, { duration: 180 });
|
||||
translateX.value = withTiming(-drawerWidth, { duration: 220 }, (finished) => {
|
||||
if (finished) {
|
||||
runOnJS(setMounted)(false);
|
||||
}
|
||||
});
|
||||
}, [drawerWidth, overlayOpacity, props.visible, translateX]);
|
||||
|
||||
const closeDrawer = useCallback(() => {
|
||||
props.onClose();
|
||||
}, [props]);
|
||||
|
||||
const panGesture = useMemo(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.activeOffsetX([-12, 12])
|
||||
.failOffsetY([-24, 24])
|
||||
.onUpdate((event) => {
|
||||
translateX.value = Math.min(0, event.translationX);
|
||||
})
|
||||
.onEnd((event) => {
|
||||
const shouldClose = event.translationX < -drawerWidth * 0.2 || event.velocityX < -500;
|
||||
if (shouldClose) {
|
||||
runOnJS(closeDrawer)();
|
||||
return;
|
||||
}
|
||||
|
||||
translateX.value = withTiming(0, { duration: 180 });
|
||||
}),
|
||||
[closeDrawer, drawerWidth, translateX],
|
||||
);
|
||||
|
||||
const drawerStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ translateX: translateX.value }],
|
||||
}));
|
||||
|
||||
const backdropStyle = useAnimatedStyle(() => ({
|
||||
opacity: overlayOpacity.value,
|
||||
}));
|
||||
|
||||
if (!mounted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal transparent visible={mounted} onRequestClose={props.onClose} statusBarTranslucent>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Animated.View
|
||||
pointerEvents="none"
|
||||
style={[
|
||||
{
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: backdropColor,
|
||||
},
|
||||
backdropStyle,
|
||||
]}
|
||||
/>
|
||||
<Pressable
|
||||
style={{ position: "absolute", left: 0, right: 0, top: 0, bottom: 0 }}
|
||||
onPress={props.onClose}
|
||||
/>
|
||||
|
||||
<GestureDetector gesture={panGesture}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: drawerWidth,
|
||||
backgroundColor: drawerBg,
|
||||
paddingTop: insets.top + 10,
|
||||
paddingBottom: Math.max(insets.bottom, 18),
|
||||
boxShadow: `20px 0 36px ${String(drawerShadow)}`,
|
||||
},
|
||||
drawerStyle,
|
||||
]}
|
||||
>
|
||||
<View className="flex-row items-center justify-between px-4 pb-5">
|
||||
<Text className="text-2xl font-t3-bold">Threads</Text>
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
props.onClose();
|
||||
props.onStartNewTask();
|
||||
}}
|
||||
className="h-11 w-11 items-center justify-center rounded-full bg-primary"
|
||||
>
|
||||
<SymbolView
|
||||
name="square.and.pencil"
|
||||
size={17}
|
||||
tintColor={primaryForeground}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<ThreadNavigationDrawerContent
|
||||
bottomInset={Math.max(insets.bottom, 18)}
|
||||
borderSubtleColor={borderSubtleColor}
|
||||
selectedThreadKey={props.selectedThreadKey}
|
||||
onClose={props.onClose}
|
||||
onSelectThread={props.onSelectThread}
|
||||
/>
|
||||
</Animated.View>
|
||||
</GestureDetector>
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadNavigationDrawerContent(props: {
|
||||
readonly bottomInset: number;
|
||||
readonly borderSubtleColor: ColorValue;
|
||||
readonly selectedThreadKey: string | null;
|
||||
readonly onClose: () => void;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
}) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const groupedThreads = useMemo(
|
||||
() => buildThreadNavigationGroups({ projects, threads }),
|
||||
[projects, threads],
|
||||
);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: props.bottomInset + 12 }}
|
||||
contentContainerStyle={{
|
||||
gap: 20,
|
||||
paddingHorizontal: 14,
|
||||
}}
|
||||
>
|
||||
{groupedThreads.map((group) => (
|
||||
<View key={group.key} className="gap-3">
|
||||
<Text
|
||||
className="px-1 text-base font-t3-bold text-foreground-muted"
|
||||
style={{ letterSpacing: -0.2 }}
|
||||
>
|
||||
{group.title}
|
||||
</Text>
|
||||
|
||||
<View className="overflow-hidden rounded-[22px] bg-card">
|
||||
{group.threads.length === 0 ? (
|
||||
<View className="px-4 py-4">
|
||||
<Text className="text-sm font-medium text-foreground-tertiary">No threads yet</Text>
|
||||
</View>
|
||||
) : (
|
||||
group.threads.map((thread, index) => {
|
||||
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
|
||||
const selected = props.selectedThreadKey === threadKey;
|
||||
const status = resolveThreadStatus(thread);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={threadKey}
|
||||
onPress={() => {
|
||||
props.onSelectThread(thread);
|
||||
props.onClose();
|
||||
}}
|
||||
style={{
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 15,
|
||||
borderTopWidth: index === 0 ? 0 : 1,
|
||||
borderTopColor: props.borderSubtleColor,
|
||||
backgroundColor: selected ? undefined : "transparent",
|
||||
}}
|
||||
className={selected ? "bg-subtle" : undefined}
|
||||
>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text className="text-base font-t3-bold" numberOfLines={1}>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-sm font-medium text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{relativeTime(thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
{status ? <StatusPill {...status} /> : null}
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
@@ -18,6 +21,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
@@ -40,6 +44,7 @@ import {
|
||||
} from "../home/homeListItems";
|
||||
import { buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
|
||||
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
|
||||
@@ -47,7 +52,12 @@ import { SidebarHeaderActions } from "./sidebar-header-actions";
|
||||
import { SidebarFilterButton } from "./sidebar-filter-button";
|
||||
import { createSidebarHeaderItems } from "./sidebar-native-header-items";
|
||||
import { SidebarNavigationShell } from "./sidebar-navigation-shell";
|
||||
import { ThreadListGroupHeader, ThreadListRow, ThreadListShowMoreRow } from "./thread-list-items";
|
||||
import {
|
||||
PendingTaskListRow,
|
||||
ThreadListGroupHeader,
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "./thread-list-items";
|
||||
|
||||
/**
|
||||
* Shared capsule behind the sidebar header buttons — a native liquid-glass
|
||||
@@ -100,6 +110,7 @@ interface ThreadNavigationSidebarProps {
|
||||
readonly selectedThreadKey: string | null;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onOpenEnvironmentSettings: () => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRequestVisibility: () => void;
|
||||
@@ -162,6 +173,8 @@ function ThreadNavigationSidebarPane(
|
||||
const headerIsOverContentRef = useRef(false);
|
||||
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
Object.values(savedConnectionsById)
|
||||
@@ -188,13 +201,14 @@ function ThreadNavigationSidebarPane(
|
||||
buildHomeThreadGroups({
|
||||
projects,
|
||||
threads,
|
||||
pendingTasks,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[options, projects, props.searchQuery, threads],
|
||||
[options, pendingTasks, projects, props.searchQuery, threads],
|
||||
);
|
||||
const [groupDisplayStates, setGroupDisplayStates] = useState<
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
@@ -403,11 +417,30 @@ function ThreadNavigationSidebarPane(
|
||||
isFirst={item.isFirst}
|
||||
groupKey={item.group.key}
|
||||
onGroupAction={updateGroupDisplay}
|
||||
// Same gating as the compact Home list: aggregated groups have no
|
||||
// single target project, and pending-project groups hold a
|
||||
// placeholder shell rather than a real project.
|
||||
newThreadTarget={item.group.newThreadTarget}
|
||||
onNewThread={props.onNewThreadInProject}
|
||||
project={item.group.representative}
|
||||
threadCount={item.group.threads.length}
|
||||
threadCount={item.group.threads.length + item.group.pendingTasks.length}
|
||||
title={item.group.title}
|
||||
/>
|
||||
);
|
||||
case "pending-task":
|
||||
return (
|
||||
<PendingTaskListRow
|
||||
variant="sidebar"
|
||||
pendingTask={item.pendingTask}
|
||||
environmentLabel={
|
||||
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
|
||||
null
|
||||
}
|
||||
isLast={item.isLast}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
/>
|
||||
);
|
||||
case "thread": {
|
||||
const thread = item.thread;
|
||||
return (
|
||||
@@ -449,11 +482,14 @@ function ThreadNavigationSidebarPane(
|
||||
},
|
||||
[
|
||||
archiveThread,
|
||||
confirmDeletePendingTask,
|
||||
confirmDeleteThread,
|
||||
handleSelectThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
openPendingTask,
|
||||
projectCwdByKey,
|
||||
props.onNewThreadInProject,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
savedConnectionsById,
|
||||
|
||||
@@ -49,7 +49,6 @@ import {
|
||||
useThreadGitRightHeaderItems,
|
||||
} from "./ThreadGitControls";
|
||||
import { GitOverviewSheet } from "./git/GitOverviewSheet";
|
||||
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
|
||||
@@ -197,7 +196,6 @@ function ThreadRouteContent(
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const navigation = useNavigation();
|
||||
const params = props.route.params;
|
||||
const [drawerVisible, setDrawerVisible] = useState(false);
|
||||
const environmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
|
||||
const threadId = firstRouteParam(params.threadId);
|
||||
@@ -326,18 +324,6 @@ function ThreadRouteContent(
|
||||
);
|
||||
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
|
||||
|
||||
const handleOpenDrawer = useCallback(() => {
|
||||
if (!layout.usesSplitView) {
|
||||
setDrawerVisible(true);
|
||||
}
|
||||
}, [layout.usesSplitView]);
|
||||
|
||||
useEffect(() => {
|
||||
if (layout.usesSplitView) {
|
||||
setDrawerVisible(false);
|
||||
}
|
||||
}, [layout.usesSplitView]);
|
||||
|
||||
const handleOpenGitInspector = useCallback(() => {
|
||||
setInspectorSelection({ routeThreadIdentity, mode: "git" });
|
||||
showAuxiliaryPane("inspector");
|
||||
@@ -655,6 +641,22 @@ function ThreadRouteContent(
|
||||
],
|
||||
[panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
|
||||
);
|
||||
// Deep links / cold starts land with Thread as the ONLY route, where the
|
||||
// native back button does not render. Provide an explicit Home escape for
|
||||
// that case; when history exists the native back button is used instead.
|
||||
const canGoBack = navigation.canGoBack();
|
||||
const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
|
||||
() => [
|
||||
withNativeGlassHeaderItem({
|
||||
accessibilityLabel: "Go to threads list",
|
||||
icon: { name: "list.bullet", type: "sfSymbol" as const },
|
||||
identifier: "thread-left-home",
|
||||
onPress: () => navigation.dispatch(StackActions.replace("Home")),
|
||||
type: "button" as const,
|
||||
}),
|
||||
],
|
||||
[navigation],
|
||||
);
|
||||
|
||||
if (!environmentId || !threadId) {
|
||||
return <OpeningThreadLoadingScreen />;
|
||||
@@ -704,7 +706,6 @@ function ThreadRouteContent(
|
||||
selectedThreadQueueCount={composer.selectedThreadQueueCount}
|
||||
layoutVariant={layout.variant}
|
||||
usesAutomaticContentInsets={usesNativeHeaderGlass}
|
||||
onOpenDrawer={handleOpenDrawer}
|
||||
onOpenConnectionEditor={handleOpenConnectionEditor}
|
||||
onChangeDraftMessage={composer.onChangeDraftMessage}
|
||||
onPickDraftImages={composer.onPickDraftImages}
|
||||
@@ -722,23 +723,6 @@ function ThreadRouteContent(
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
onSubmitUserInput={requests.onSubmitUserInput}
|
||||
/>
|
||||
|
||||
{layout.usesSplitView ? null : (
|
||||
<ThreadNavigationDrawer
|
||||
visible={drawerVisible}
|
||||
selectedThreadKey={selectedThreadKey}
|
||||
onClose={() => setDrawerVisible(false)}
|
||||
onSelectThread={(thread) => {
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
environmentId: String(thread.environmentId),
|
||||
threadId: String(thread.id),
|
||||
}),
|
||||
);
|
||||
}}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
@@ -757,11 +741,17 @@ function ThreadRouteContent(
|
||||
: undefined,
|
||||
title: selectedThread.title,
|
||||
headerBackVisible: !layout.usesSplitView,
|
||||
// Compact uses the NATIVE back button (Thread lives flat in the root
|
||||
// stack now, so a real previous route exists); only split view needs
|
||||
// custom left items.
|
||||
// Compact uses the NATIVE back button when a previous route exists;
|
||||
// deep links / cold starts get an explicit Home button instead.
|
||||
// Split view always uses its custom left items.
|
||||
unstable_headerLeftItems:
|
||||
Platform.OS === "ios" && layout.usesSplitView ? () => splitLeftHeaderItems : undefined,
|
||||
Platform.OS === "ios"
|
||||
? layout.usesSplitView
|
||||
? () => splitLeftHeaderItems
|
||||
: canGoBack
|
||||
? undefined
|
||||
: () => compactHomeHeaderItems
|
||||
: undefined,
|
||||
// Search lives in the persistent sidebar, so the split header keeps
|
||||
// the git controls on the RIGHT (no center items — center space is
|
||||
// reserved for future breadcrumbs/status).
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
@@ -8,18 +8,29 @@ import type {
|
||||
RuntimeMode,
|
||||
ServerProviderSkill,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
|
||||
import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";
|
||||
import type { TurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
clearComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
isComposerDraftEmpty,
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
setComposerDraftText,
|
||||
@@ -27,6 +38,17 @@ import {
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
import {
|
||||
flattenQueuedThreadMessages,
|
||||
threadOutboxManager,
|
||||
updateThreadOutboxMessage,
|
||||
type QueuedThreadMessage,
|
||||
} from "../../state/thread-outbox";
|
||||
import {
|
||||
holdEditingQueuedMessage,
|
||||
releaseEditingQueuedMessage,
|
||||
useThreadOutboxMessages,
|
||||
} from "../../state/use-thread-outbox";
|
||||
import {
|
||||
setPendingConnectionError,
|
||||
useSavedRemoteConnections,
|
||||
@@ -36,6 +58,23 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
|
||||
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
function pendingTaskDraftKey(messageId: string): string {
|
||||
return `pending-task:${messageId}`;
|
||||
}
|
||||
|
||||
// The message id owned by the currently active editing session, tracked
|
||||
// across provider instances. An in-flight flush from a dismissed session
|
||||
// consults it so it never drops the draft or releases the drain lock out from
|
||||
// under a newer session editing the same task.
|
||||
let activeEditingMessageId: string | null = null;
|
||||
|
||||
function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {
|
||||
const message = flattenQueuedThreadMessages(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
).find((candidate) => candidate.messageId === messageId);
|
||||
return message?.creation !== undefined ? message : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null {
|
||||
if (!branch.worktreePath) {
|
||||
return null;
|
||||
@@ -74,6 +113,9 @@ type NewTaskFlowContextValue = {
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
readonly selectedBranchName: string | null;
|
||||
readonly selectedWorktreePath: string | null;
|
||||
readonly startFromOrigin: boolean;
|
||||
readonly draftKey: string | null;
|
||||
readonly editingPendingTask: QueuedThreadMessage | null;
|
||||
readonly prompt: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly submitting: boolean;
|
||||
@@ -100,6 +142,11 @@ type NewTaskFlowContextValue = {
|
||||
readonly setSelectedModelKey: (key: string | null) => void;
|
||||
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
|
||||
readonly selectBranch: (branch: VcsRef) => void;
|
||||
readonly setStartFromOrigin: (value: boolean) => void;
|
||||
readonly beginEditingPendingTask: (messageId: string) => boolean;
|
||||
readonly finishEditingPendingTask: () => void;
|
||||
readonly cancelEditingPendingTask: () => void;
|
||||
readonly buildPendingTaskMessage: (metadata: TurnCommandMetadata) => QueuedThreadMessage | null;
|
||||
readonly setPrompt: (value: string) => void;
|
||||
readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
|
||||
readonly appendAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
|
||||
@@ -162,6 +209,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
|
||||
// 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);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
@@ -169,42 +220,17 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setExpandedProvider(null);
|
||||
const editing = editingPendingTaskRef.current;
|
||||
editingPendingTaskRef.current = null;
|
||||
setEditingPendingTask(null);
|
||||
if (editing) {
|
||||
if (activeEditingMessageId === editing.messageId) {
|
||||
activeEditingMessageId = null;
|
||||
}
|
||||
releaseEditingQueuedMessage(editing.messageId);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
[
|
||||
...new Set(
|
||||
pipe(
|
||||
projects,
|
||||
Arr.map((project) => project.environmentId),
|
||||
),
|
||||
),
|
||||
],
|
||||
Arr.map((environmentId) => {
|
||||
const environment = savedConnectionsById[environmentId];
|
||||
if (!environment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
environmentId,
|
||||
environmentLabel: environment.environmentLabel,
|
||||
};
|
||||
}),
|
||||
Arr.filter(
|
||||
(
|
||||
entry,
|
||||
): entry is {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly environmentLabel: string;
|
||||
} => entry !== null,
|
||||
),
|
||||
),
|
||||
[projects, savedConnectionsById],
|
||||
);
|
||||
|
||||
const projectsForEnvironment = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
@@ -214,24 +240,115 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
[projects, selectedEnvironmentId],
|
||||
);
|
||||
|
||||
// Stand-in for the edited task's project while its shell is not loaded
|
||||
// (environment offline / still synchronizing), built from the metadata
|
||||
// snapshotted at enqueue time.
|
||||
const editingPendingProject = useMemo<EnvironmentProject | null>(() => {
|
||||
const creation = editingPendingTask?.creation;
|
||||
if (!editingPendingTask || !creation) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
environmentId: editingPendingTask.environmentId,
|
||||
id: creation.projectId,
|
||||
title: creation.projectTitle ?? "Unknown project",
|
||||
// Deliberately empty when the snapshot has no cwd — downstream consumers
|
||||
// (branch queries, worktree bootstrap) must skip it, not receive a
|
||||
// fabricated path.
|
||||
workspaceRoot: creation.projectCwd ?? "",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: editingPendingTask.modelSelection ?? null,
|
||||
scripts: [],
|
||||
createdAt: editingPendingTask.createdAt,
|
||||
updatedAt: editingPendingTask.createdAt,
|
||||
};
|
||||
}, [editingPendingTask]);
|
||||
|
||||
const selectedProject =
|
||||
projectsForEnvironment.find(
|
||||
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
|
||||
) ??
|
||||
projectsForEnvironment[0] ??
|
||||
null;
|
||||
// While editing a queued task whose project shell is absent, keep the task
|
||||
// pinned to its own project — falling through to an arbitrary first
|
||||
// project would silently retarget it (and its reused turn identifiers).
|
||||
(editingPendingProject !== null &&
|
||||
selectedProjectKey ===
|
||||
scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
|
||||
? editingPendingProject
|
||||
: (projectsForEnvironment[0] ?? null));
|
||||
|
||||
// Only offer machines that actually host the currently selected repository, so
|
||||
// switching computers moves the same repo across machines instead of jumping to
|
||||
// whatever unrelated project happens to be first on the other machine. Repository
|
||||
// identity is the primary signal; projects that haven't reported one yet (still
|
||||
// indexing) fall back to workspace basename / title so a valid host isn't hidden.
|
||||
const selectedRepositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
|
||||
// `|| null` (not `??`): a pending-task placeholder project can have an empty
|
||||
// workspaceRoot, and an "" basename would reject every real host below.
|
||||
const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
|
||||
const selectedProjectTitle = selectedProject?.title ?? null;
|
||||
const environments = useMemo(() => {
|
||||
const seen = new Set<EnvironmentId>();
|
||||
const result: Array<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly environmentLabel: string;
|
||||
}> = [];
|
||||
const hostsSelectedRepository = (project: EnvironmentProject) => {
|
||||
if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) {
|
||||
return true;
|
||||
}
|
||||
const projectKey = project.repositoryIdentity?.canonicalKey ?? null;
|
||||
if (selectedRepositoryKey !== null && projectKey !== null) {
|
||||
return projectKey === selectedRepositoryKey;
|
||||
}
|
||||
return (
|
||||
project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename ||
|
||||
(selectedProjectTitle !== null && project.title === selectedProjectTitle)
|
||||
);
|
||||
};
|
||||
for (const project of projects) {
|
||||
if (!hostsSelectedRepository(project)) {
|
||||
continue;
|
||||
}
|
||||
if (seen.has(project.environmentId)) {
|
||||
continue;
|
||||
}
|
||||
const environment = savedConnectionsById[project.environmentId];
|
||||
if (!environment) {
|
||||
continue;
|
||||
}
|
||||
seen.add(project.environmentId);
|
||||
result.push({
|
||||
environmentId: project.environmentId,
|
||||
environmentLabel: environment.environmentLabel,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}, [
|
||||
projects,
|
||||
savedConnectionsById,
|
||||
selectedRepositoryKey,
|
||||
selectedWorkspaceBasename,
|
||||
selectedProjectTitle,
|
||||
]);
|
||||
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
selectedProject?.environmentId ?? null,
|
||||
);
|
||||
const selectedProjectDraftKey = selectedProject
|
||||
? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
|
||||
: null;
|
||||
// While a queued pending task is being edited its draft lives under a key
|
||||
// scoped to the queued message, so per-project new-task drafts stay intact.
|
||||
const selectedProjectDraftKey = editingPendingTask
|
||||
? pendingTaskDraftKey(editingPendingTask.messageId)
|
||||
: selectedProject
|
||||
? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
|
||||
: null;
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
@@ -350,7 +467,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const branchTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: selectedProject?.environmentId ?? null,
|
||||
cwd: selectedProject?.workspaceRoot ?? null,
|
||||
// `|| null` also skips the stand-in project's empty workspaceRoot.
|
||||
cwd: selectedProject?.workspaceRoot || null,
|
||||
query: null,
|
||||
}),
|
||||
[selectedProject?.environmentId, selectedProject?.workspaceRoot],
|
||||
@@ -384,10 +502,36 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
}, []);
|
||||
|
||||
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(null);
|
||||
}, []);
|
||||
const selectEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => {
|
||||
const projectsOnTarget = projects.filter(
|
||||
(project) => project.environmentId === environmentId,
|
||||
);
|
||||
const repositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
|
||||
// Prefer the repository identity; projects without one (e.g. not yet
|
||||
// indexed) fall back to workspace basename, then title, so switching
|
||||
// computers still follows the same repo instead of resetting to
|
||||
// whatever project is first on the target machine.
|
||||
const workspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
|
||||
const match =
|
||||
(repositoryKey !== null
|
||||
? projectsOnTarget.find(
|
||||
(project) => (project.repositoryIdentity?.canonicalKey ?? null) === repositoryKey,
|
||||
)
|
||||
: undefined) ??
|
||||
(workspaceBasename !== null
|
||||
? projectsOnTarget.find(
|
||||
(project) => project.workspaceRoot.split("/").at(-1) === workspaceBasename,
|
||||
)
|
||||
: undefined) ??
|
||||
(selectedProject !== null
|
||||
? projectsOnTarget.find((project) => project.title === selectedProject.title)
|
||||
: undefined);
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
|
||||
},
|
||||
[projects, selectedProject],
|
||||
);
|
||||
|
||||
const setWorkspaceMode = useCallback(
|
||||
(mode: WorkspaceMode) => {
|
||||
@@ -399,10 +543,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
@@ -415,10 +560,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
|
||||
);
|
||||
|
||||
const setStartFromOrigin = useCallback(
|
||||
(value: boolean) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
startFromOrigin: value,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, workspaceMode],
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
@@ -460,6 +623,183 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const beginEditingPendingTask = useCallback((messageId: string): boolean => {
|
||||
const message = findQueuedPendingTask(messageId);
|
||||
if (!message?.creation) {
|
||||
return false;
|
||||
}
|
||||
const draftKey = pendingTaskDraftKey(message.messageId);
|
||||
// Only hydrate a fresh editing draft; reopening mid-edit keeps newer edits.
|
||||
if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) {
|
||||
setComposerDraftText(draftKey, message.text);
|
||||
replaceComposerDraftAttachments(draftKey, message.attachments);
|
||||
updateComposerDraftSettings(draftKey, {
|
||||
modelSelection: message.modelSelection,
|
||||
runtimeMode: message.runtimeMode,
|
||||
interactionMode: message.interactionMode,
|
||||
workspaceSelection: {
|
||||
mode: message.creation.workspaceMode,
|
||||
branch: message.creation.branch,
|
||||
worktreePath: message.creation.worktreePath,
|
||||
startFromOrigin: message.creation.startFromOrigin ?? false,
|
||||
},
|
||||
});
|
||||
}
|
||||
setSelectedEnvironmentId(message.environmentId);
|
||||
setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
|
||||
activeEditingMessageId = message.messageId;
|
||||
editingPendingTaskRef.current = message;
|
||||
setEditingPendingTask(message);
|
||||
// Hold the outbox drain off this task while it is open in the editor.
|
||||
holdEditingQueuedMessage(message.messageId);
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
const buildPendingTaskMessage = useCallback(
|
||||
(metadata: TurnCommandMetadata): QueuedThreadMessage | null => {
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return null;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
|
||||
const text = draft.text.trim();
|
||||
const draftModelSelection = draft.modelSelection ?? selectedModel;
|
||||
if (text.length === 0 || !draftModelSelection) {
|
||||
return null;
|
||||
}
|
||||
const workspaceSelection = draft.workspaceSelection;
|
||||
const mode = workspaceSelection?.mode ?? "local";
|
||||
// When the selection is the stand-in built from the queued snapshot,
|
||||
// persist the original (possibly absent) snapshot values — the
|
||||
// stand-in's placeholder title/workspaceRoot must never be written back
|
||||
// as if they were real project metadata.
|
||||
const usingPendingSnapshot = selectedProject === editingPendingProject;
|
||||
const projectTitle = usingPendingSnapshot
|
||||
? editingPendingTask?.creation?.projectTitle
|
||||
: selectedProject.title;
|
||||
const projectCwd = usingPendingSnapshot
|
||||
? editingPendingTask?.creation?.projectCwd
|
||||
: selectedProject.workspaceRoot;
|
||||
return {
|
||||
environmentId: selectedProject.environmentId,
|
||||
threadId: ThreadId.make(metadata.threadId),
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments: draft.attachments,
|
||||
modelSelection: draftModelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: draft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
creation: {
|
||||
projectId: selectedProject.id,
|
||||
...(projectTitle !== undefined ? { projectTitle } : {}),
|
||||
...(projectCwd !== undefined ? { projectCwd } : {}),
|
||||
workspaceMode: mode,
|
||||
branch: workspaceSelection?.branch ?? null,
|
||||
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
|
||||
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
createdAt: metadata.createdAt,
|
||||
};
|
||||
},
|
||||
[
|
||||
editingPendingProject,
|
||||
editingPendingTask,
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
],
|
||||
);
|
||||
|
||||
const finishEditingPendingTask = useCallback(() => {
|
||||
const editing = editingPendingTaskRef.current;
|
||||
editingPendingTaskRef.current = null;
|
||||
if (editing) {
|
||||
if (activeEditingMessageId === editing.messageId) {
|
||||
activeEditingMessageId = null;
|
||||
}
|
||||
clearComposerDraft(pendingTaskDraftKey(editing.messageId));
|
||||
releaseEditingQueuedMessage(editing.messageId);
|
||||
}
|
||||
setEditingPendingTask(null);
|
||||
}, []);
|
||||
|
||||
// If the queued task disappears mid-edit (deleted from the list, or
|
||||
// delivered), end the editing session immediately without saving — a later
|
||||
// flush must not resurrect it, and the composer should fall back to the
|
||||
// regular per-project draft.
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
useEffect(() => {
|
||||
const editing = editingPendingTaskRef.current;
|
||||
if (!editing) {
|
||||
return;
|
||||
}
|
||||
const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some(
|
||||
(candidate) => candidate.messageId === editing.messageId,
|
||||
);
|
||||
if (!stillQueued) {
|
||||
finishEditingPendingTask();
|
||||
}
|
||||
}, [finishEditingPendingTask, queuedMessagesByThreadKey]);
|
||||
|
||||
// Leaving the flow mid-edit (sheet dismissed or draft screen popped) saves
|
||||
// the current edits back into the queued task so nothing typed here is lost.
|
||||
const editingFlushRef = useRef<(() => void) | null>(null);
|
||||
useEffect(() => {
|
||||
editingFlushRef.current = () => {
|
||||
const editing = editingPendingTaskRef.current;
|
||||
if (!editing) {
|
||||
return;
|
||||
}
|
||||
editingPendingTaskRef.current = null;
|
||||
setEditingPendingTask(null);
|
||||
if (activeEditingMessageId === editing.messageId) {
|
||||
activeEditingMessageId = null;
|
||||
}
|
||||
|
||||
const message = buildPendingTaskMessage({
|
||||
threadId: editing.threadId,
|
||||
commandId: editing.commandId,
|
||||
messageId: editing.messageId,
|
||||
createdAt: editing.createdAt,
|
||||
});
|
||||
|
||||
if (!message) {
|
||||
// The edits are currently unsendable (e.g. the prompt was cleared).
|
||||
// Keep both the draft and the drain lock: the stale queued payload
|
||||
// must not auto-send content the user just removed, and reopening the
|
||||
// task resumes from the saved draft.
|
||||
return;
|
||||
}
|
||||
|
||||
// update() rewrites the task only if it is still queued — a concurrent
|
||||
// delete or delivery wins, so the flush cannot resurrect it.
|
||||
void updateThreadOutboxMessage(message)
|
||||
.then(() => {
|
||||
// If this task was reopened (possibly in a fresh provider) while
|
||||
// the save was in flight, that session owns the draft and the lock.
|
||||
if (activeEditingMessageId === editing.messageId) {
|
||||
return;
|
||||
}
|
||||
clearComposerDraft(pendingTaskDraftKey(editing.messageId));
|
||||
releaseEditingQueuedMessage(editing.messageId);
|
||||
})
|
||||
.catch((error) => {
|
||||
// Keep the drain lock and the draft: delivering the stale payload
|
||||
// would silently drop the newer edits. Reopening the task retries.
|
||||
console.warn("[new-task] failed to save edited pending task", error);
|
||||
});
|
||||
};
|
||||
}, [buildPendingTaskMessage]);
|
||||
const cancelEditingPendingTask = useCallback(() => {
|
||||
editingFlushRef.current?.();
|
||||
}, []);
|
||||
useEffect(
|
||||
() => () => {
|
||||
editingFlushRef.current?.();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
logicalProjects,
|
||||
@@ -469,6 +809,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
workspaceMode,
|
||||
selectedBranchName,
|
||||
selectedWorktreePath,
|
||||
startFromOrigin,
|
||||
draftKey: selectedProjectDraftKey,
|
||||
editingPendingTask,
|
||||
prompt,
|
||||
attachments,
|
||||
submitting,
|
||||
@@ -492,6 +835,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSelectedModelKey,
|
||||
setWorkspaceMode,
|
||||
selectBranch,
|
||||
setStartFromOrigin,
|
||||
beginEditingPendingTask,
|
||||
finishEditingPendingTask,
|
||||
cancelEditingPendingTask,
|
||||
buildPendingTaskMessage,
|
||||
setPrompt,
|
||||
replaceAttachments,
|
||||
appendAttachments,
|
||||
@@ -508,11 +856,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
[
|
||||
attachments,
|
||||
availableBranches,
|
||||
beginEditingPendingTask,
|
||||
branchQuery,
|
||||
branchesLoading,
|
||||
buildPendingTaskMessage,
|
||||
cancelEditingPendingTask,
|
||||
editingPendingTask,
|
||||
environments,
|
||||
expandedProvider,
|
||||
filteredBranches,
|
||||
finishEditingPendingTask,
|
||||
interactionMode,
|
||||
loadBranches,
|
||||
logicalProjects,
|
||||
@@ -527,6 +880,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedModel,
|
||||
selectedModelKey,
|
||||
selectedModelOption,
|
||||
selectedProjectDraftKey,
|
||||
selectedProviderSkills,
|
||||
setSelectedModelOptions,
|
||||
selectedProject,
|
||||
@@ -539,7 +893,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setPrompt,
|
||||
setRuntimeMode,
|
||||
setSelectedModelKey,
|
||||
setStartFromOrigin,
|
||||
setWorkspaceMode,
|
||||
startFromOrigin,
|
||||
submitting,
|
||||
workspaceMode,
|
||||
appendAttachments,
|
||||
|
||||
@@ -14,6 +14,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import type { HomeGroupDisplayAction } from "../home/homeListItems";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
@@ -42,31 +43,54 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
|
||||
readonly isFirst: boolean;
|
||||
readonly groupKey: string;
|
||||
readonly onGroupAction: (key: string, action: HomeGroupDisplayAction) => void;
|
||||
/** Project a quick new thread should target; null hides the button. */
|
||||
readonly newThreadTarget?: EnvironmentProject | null;
|
||||
readonly onNewThread?: (project: EnvironmentProject) => void;
|
||||
}) {
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const { groupKey, onGroupAction } = props;
|
||||
const iconMutedColor = useThemeColor("--color-icon-muted");
|
||||
const { groupKey, onGroupAction, onNewThread } = props;
|
||||
const newThreadTarget = props.newThreadTarget ?? null;
|
||||
const compact = props.variant === "compact";
|
||||
const handleToggle = useCallback(
|
||||
() => onGroupAction(groupKey, "toggle-collapsed"),
|
||||
[groupKey, onGroupAction],
|
||||
);
|
||||
const handleNewThread = useCallback(() => {
|
||||
if (newThreadTarget) {
|
||||
onNewThread?.(newThreadTarget);
|
||||
}
|
||||
}, [newThreadTarget, onNewThread]);
|
||||
const showNewThreadButton = onNewThread !== undefined && newThreadTarget !== null;
|
||||
|
||||
// The new-thread button is a SIBLING of the collapse toggle, not a child:
|
||||
// nested touchables are unreachable to VoiceOver/TalkBack (the parent
|
||||
// swallows focus). Row padding lives on the container (explicit styles —
|
||||
// dynamic padding classes on Pressable did not apply reliably) so both
|
||||
// children share one centerline; hitSlop restores the padded tap area.
|
||||
const verticalHitSlop = { top: props.isFirst ? 8 : 24, bottom: 12 };
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: !props.collapsed }}
|
||||
accessibilityLabel={`${props.title}, ${props.threadCount} threads`}
|
||||
accessibilityHint={props.collapsed ? "Expands the project" : "Collapses the project"}
|
||||
className={compact ? "bg-screen" : undefined}
|
||||
onPress={handleToggle}
|
||||
<View
|
||||
className={compact ? "flex-row items-center bg-screen" : "flex-row items-center"}
|
||||
style={{
|
||||
minHeight: compact ? 44 : 36,
|
||||
paddingLeft: compact ? 20 : 12,
|
||||
// Compact right padding centers the 20pt plus glyph on the thread
|
||||
// rows' trailing chevron column (18 + 13/2 ≈ 24.5 from the edge).
|
||||
paddingRight: compact ? 14 : 12,
|
||||
paddingBottom: compact ? 12 : 8,
|
||||
paddingTop: props.isFirst ? (compact ? 8 : 4) : compact ? 24 : 20,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: !props.collapsed }}
|
||||
accessibilityLabel={`${props.title}, ${props.threadCount} threads`}
|
||||
accessibilityHint={props.collapsed ? "Expands the project" : "Collapses the project"}
|
||||
className={
|
||||
compact
|
||||
? `flex-row items-center gap-2.5 px-5 pb-3 ${props.isFirst ? "pt-2" : "pt-6"}`
|
||||
: `flex-row items-center gap-2 px-3 pb-2 ${props.isFirst ? "pt-1" : "pt-5"}`
|
||||
compact ? "flex-1 flex-row items-center gap-2.5" : "flex-1 flex-row items-center gap-2"
|
||||
}
|
||||
style={{ minHeight: compact ? 44 : 36 }}
|
||||
hitSlop={{ ...verticalHitSlop, left: compact ? 20 : 12 }}
|
||||
onPress={handleToggle}
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
@@ -94,15 +118,25 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
|
||||
>
|
||||
{props.threadCount}
|
||||
</Text>
|
||||
<SymbolView
|
||||
name={props.collapsed ? "chevron.right" : "chevron.down"}
|
||||
size={compact ? 13 : 11}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</View>
|
||||
</Pressable>
|
||||
</Pressable>
|
||||
{showNewThreadButton ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Create new thread in ${props.title}`}
|
||||
accessibilityRole="button"
|
||||
hitSlop={{ ...verticalHitSlop, left: 10, right: 14 }}
|
||||
onPress={handleNewThread}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1, paddingLeft: 12 })}
|
||||
>
|
||||
<SymbolView
|
||||
name="plus"
|
||||
size={compact ? 20 : 16}
|
||||
tintColor={iconMutedColor}
|
||||
type="monochrome"
|
||||
weight="medium"
|
||||
/>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -180,6 +214,173 @@ export const ThreadListShowMoreRow = memo(function ThreadListShowMoreRow(props:
|
||||
);
|
||||
});
|
||||
|
||||
/* ─── Pending task row ───────────────────────────────────────────────── */
|
||||
|
||||
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
/**
|
||||
* A queued new task waiting in the outbox for its environment to reconnect.
|
||||
* Tapping reopens the new-task composer with everything prefilled; the row
|
||||
* disappears once the task is delivered and the real thread arrives.
|
||||
*/
|
||||
export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
|
||||
readonly variant: ThreadListVariant;
|
||||
readonly pendingTask: PendingNewTask;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly isLast: boolean;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
}) {
|
||||
const compact = props.variant === "compact";
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
|
||||
const { pendingTask, onSelectPendingTask, onDeletePendingTask } = props;
|
||||
const timestamp = relativeTime(pendingTask.message.createdAt);
|
||||
const subtitleParts = [props.environmentLabel, pendingTask.creation.branch].filter(
|
||||
(part): part is string => Boolean(part),
|
||||
);
|
||||
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "delete") onDeletePendingTask(pendingTask);
|
||||
},
|
||||
[onDeletePendingTask, pendingTask],
|
||||
);
|
||||
|
||||
const statusPill = (
|
||||
<View
|
||||
className="bg-zinc-500/12 dark:bg-zinc-500/16"
|
||||
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
|
||||
>
|
||||
<Text className="text-3xs font-t3-bold text-zinc-600 dark:text-zinc-300">Pending</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
const subtitleRow =
|
||||
subtitleParts.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
|
||||
<SymbolView
|
||||
name="tray.and.arrow.up"
|
||||
size={10}
|
||||
tintColor={compact ? iconSubtleColor : mutedColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className={compact ? "text-sm text-foreground-muted" : "text-xs"}
|
||||
numberOfLines={1}
|
||||
style={compact ? { flexShrink: 1 } : { flexShrink: 1, color: mutedColor }}
|
||||
>
|
||||
{subtitleParts.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null;
|
||||
|
||||
const rowContent = compact ? (
|
||||
<Pressable
|
||||
accessibilityHint="Opens the queued task for editing"
|
||||
accessibilityLabel={pendingTask.title}
|
||||
accessibilityRole="button"
|
||||
className="bg-screen"
|
||||
onPress={() => onSelectPendingTask(pendingTask)}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
paddingLeft: THREAD_LIST_COMPACT_INSET,
|
||||
paddingRight: 18,
|
||||
paddingTop: 10,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
gap: 3,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
borderBottomColor: separatorColor,
|
||||
paddingBottom: 10,
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-2">
|
||||
<Text className="flex-1 text-lg font-t3-bold text-foreground" numberOfLines={1}>
|
||||
{pendingTask.title}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{statusPill}
|
||||
<Text
|
||||
className="text-base text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={13}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{subtitleRow}
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint="Opens the queued task for editing"
|
||||
accessibilityLabel={pendingTask.title}
|
||||
accessibilityRole="button"
|
||||
onPress={() => onSelectPendingTask(pendingTask)}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackgroundColor : "transparent",
|
||||
borderRadius: SIDEBAR_ROW_RADIUS,
|
||||
cursor: "pointer",
|
||||
minHeight: 64,
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 10,
|
||||
})}
|
||||
>
|
||||
<View style={{ gap: 3 }}>
|
||||
<View className="flex-row items-center justify-between gap-2">
|
||||
<Text
|
||||
className="flex-1 text-base font-t3-medium"
|
||||
numberOfLines={1}
|
||||
style={{ color: foregroundColor }}
|
||||
>
|
||||
{pendingTask.title}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{statusPill}
|
||||
<Text
|
||||
className="text-xs"
|
||||
numberOfLines={1}
|
||||
style={{ color: mutedColor, fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
{subtitleRow}
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
return (
|
||||
<ControlPillMenu
|
||||
actions={PENDING_TASK_MENU_ACTIONS}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
{rowContent}
|
||||
</ControlPillMenu>
|
||||
);
|
||||
});
|
||||
|
||||
/* ─── Thread row ─────────────────────────────────────────────────────── */
|
||||
|
||||
const THREAD_ROW_MENU_ACTIONS: MenuAction[] = [
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadNavigationGroups } from "./thread-navigation-groups";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeProject(input: Pick<EnvironmentProject, "id" | "title">): EnvironmentProject {
|
||||
return {
|
||||
environmentId,
|
||||
workspaceRoot: `/workspaces/${input.id}`,
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Pick<EnvironmentThreadShell, "id" | "projectId" | "title"> &
|
||||
Partial<EnvironmentThreadShell>,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadNavigationGroups", () => {
|
||||
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
|
||||
const threads = [
|
||||
makeThread({
|
||||
id: ThreadId.make("older"),
|
||||
projectId: project.id,
|
||||
title: "Fix reconnect flow",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("newer"),
|
||||
projectId: project.id,
|
||||
title: "Build adaptive sidebar",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
it("sorts each group by recent activity", () => {
|
||||
expect(
|
||||
buildThreadNavigationGroups({ projects: [project], threads })[0]?.threads.map(
|
||||
(thread) => thread.id,
|
||||
),
|
||||
).toEqual(["newer", "older"]);
|
||||
});
|
||||
|
||||
it("matches thread titles without dropping their group", () => {
|
||||
const groups = buildThreadNavigationGroups({
|
||||
projects: [project],
|
||||
threads,
|
||||
searchQuery: "reconnect",
|
||||
});
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual(["older"]);
|
||||
});
|
||||
|
||||
it("keeps every thread when the project title matches", () => {
|
||||
expect(
|
||||
buildThreadNavigationGroups({
|
||||
projects: [project],
|
||||
threads,
|
||||
searchQuery: "t3 code",
|
||||
})[0]?.threads.map((thread) => thread.id),
|
||||
).toEqual(["newer", "older"]);
|
||||
});
|
||||
|
||||
it("excludes archived threads from the navigation sidebar", () => {
|
||||
const archived = makeThread({
|
||||
id: ThreadId.make("archived"),
|
||||
projectId: project.id,
|
||||
title: "Archived work",
|
||||
archivedAt: "2026-06-04T00:00:00.000Z",
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
buildThreadNavigationGroups({
|
||||
projects: [project],
|
||||
threads: [...threads, archived],
|
||||
})[0]?.threads.map((thread) => thread.id),
|
||||
).toEqual(["newer", "older"]);
|
||||
});
|
||||
});
|
||||
@@ -1,64 +0,0 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
|
||||
export interface ThreadNavigationGroup {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
}
|
||||
|
||||
const threadActivityOrder = Order.mapInput(
|
||||
Order.Struct({
|
||||
activityAt: Order.flip(Order.Number),
|
||||
title: Order.String,
|
||||
}),
|
||||
(thread: EnvironmentThreadShell) => ({
|
||||
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
|
||||
title: thread.title,
|
||||
}),
|
||||
);
|
||||
|
||||
export function buildThreadNavigationGroups(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly searchQuery?: string;
|
||||
}): ReadonlyArray<ThreadNavigationGroup> {
|
||||
const query = input.searchQuery?.trim().toLocaleLowerCase() ?? "";
|
||||
const activeThreads = input.threads.filter((thread) => thread.archivedAt === null);
|
||||
|
||||
return groupProjectsByRepository({ ...input, threads: activeThreads }).flatMap((group) => {
|
||||
const threads = Arr.sort(
|
||||
group.projects.flatMap((projectGroup) => projectGroup.threads),
|
||||
threadActivityOrder,
|
||||
);
|
||||
const title = group.projects[0]?.project.title ?? group.title;
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
group.title.toLocaleLowerCase().includes(query) ||
|
||||
group.projects.some((projectGroup) =>
|
||||
projectGroup.project.title.toLocaleLowerCase().includes(query),
|
||||
);
|
||||
const matchingThreads = groupMatches
|
||||
? threads
|
||||
: threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
|
||||
|
||||
if (query.length > 0 && matchingThreads.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
key: group.key,
|
||||
title,
|
||||
threads: matchingThreads,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "re
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import Animated, { FadeIn } from "react-native-reanimated";
|
||||
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
@@ -68,6 +69,14 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
|
||||
}
|
||||
}
|
||||
|
||||
// Entering fades only for rows created moments ago: rows remount whenever the
|
||||
// list scrolls them back into view, and old rows must not replay an entrance.
|
||||
const FRESH_ROW_WINDOW_MS = 3_000;
|
||||
function isFreshRow(createdAt: string): boolean {
|
||||
const timestamp = Date.parse(createdAt);
|
||||
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
|
||||
}
|
||||
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
@@ -104,7 +113,10 @@ export function ThreadWorkLog(props: {
|
||||
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
|
||||
return (
|
||||
<View key={row.id}>
|
||||
<Animated.View
|
||||
key={row.id}
|
||||
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole={canExpand ? "button" : undefined}
|
||||
accessibilityLabel={displayText}
|
||||
@@ -207,7 +219,7 @@ export function ThreadWorkLog(props: {
|
||||
</ScrollView>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
@@ -4,8 +4,6 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { mapAtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
@@ -17,22 +15,13 @@ import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
|
||||
import { randomHex } from "../../lib/uuid";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
|
||||
import { validateProjectThreadCreation } from "./projectThreadCreationValidation";
|
||||
|
||||
function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return "New thread";
|
||||
}
|
||||
|
||||
const compact = trimmed.replace(/\s+/g, " ");
|
||||
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
|
||||
}
|
||||
|
||||
export function useCreateProjectThread() {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
|
||||
@@ -43,15 +32,17 @@ export function useCreateProjectThread() {
|
||||
readonly envMode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly startFromOrigin?: boolean;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly initialMessageText: string;
|
||||
readonly initialAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
/** Reuse identifiers from a queued pending task instead of minting new ones. */
|
||||
readonly turnMetadata?: TurnCommandMetadata;
|
||||
}) => {
|
||||
const metadata = makeTurnCommandMetadata();
|
||||
const metadata = input.turnMetadata ?? makeTurnCommandMetadata();
|
||||
const threadId = ThreadId.make(metadata.threadId);
|
||||
const initialMessageText = input.initialMessageText.trim();
|
||||
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
|
||||
|
||||
const validationError = validateProjectThreadCreation({
|
||||
environmentId: input.project.environmentId,
|
||||
@@ -65,46 +56,26 @@ export function useCreateProjectThread() {
|
||||
return AsyncResult.failure(Cause.fail(validationError));
|
||||
}
|
||||
|
||||
const isWorktree = input.envMode === "worktree";
|
||||
const result = await startTurn({
|
||||
environmentId: input.project.environmentId,
|
||||
input: {
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
role: "user",
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
},
|
||||
input: buildProjectThreadStartTurnInput({
|
||||
projectId: input.project.id,
|
||||
projectCwd: input.project.workspaceRoot,
|
||||
threadId: metadata.threadId,
|
||||
commandId: metadata.commandId,
|
||||
messageId: metadata.messageId,
|
||||
createdAt: metadata.createdAt,
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
modelSelection: input.modelSelection,
|
||||
titleSeed: nextTitle,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: input.project.id,
|
||||
title: nextTitle,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch: input.branch,
|
||||
worktreePath: isWorktree ? null : input.worktreePath,
|
||||
createdAt: metadata.createdAt,
|
||||
},
|
||||
...(isWorktree
|
||||
? {
|
||||
prepareWorktree: {
|
||||
projectCwd: input.project.workspaceRoot,
|
||||
baseBranch: input.branch!,
|
||||
branch: buildTemporaryWorktreeBranchName(uuidv4),
|
||||
},
|
||||
runSetupScript: true,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
createdAt: metadata.createdAt,
|
||||
},
|
||||
workspaceMode: input.envMode,
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
startFromOrigin: input.startFromOrigin ?? false,
|
||||
worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
|
||||
}),
|
||||
});
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
type ModelSelection,
|
||||
type ProjectId,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { DraftComposerImageAttachment } from "./composerImages";
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return "New thread";
|
||||
}
|
||||
|
||||
const compact = trimmed.replace(/\s+/g, " ");
|
||||
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
|
||||
}
|
||||
|
||||
export interface ProjectThreadStartTurnSpec {
|
||||
readonly projectId: ProjectId;
|
||||
readonly projectCwd: string;
|
||||
readonly threadId: string;
|
||||
readonly commandId: string;
|
||||
readonly messageId: string;
|
||||
readonly createdAt: string;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly workspaceMode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly startFromOrigin: boolean;
|
||||
/** Generated temp branch for worktree mode; unused for local mode. */
|
||||
readonly worktreeBranchName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of the `thread.turn.start` bootstrap payload used to create a
|
||||
* thread from a project draft — shared by the immediate send path and the
|
||||
* offline outbox drain so both deliver identical commands.
|
||||
*/
|
||||
export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpec) {
|
||||
const title = deriveThreadTitleFromPrompt(spec.text);
|
||||
const isWorktree = spec.workspaceMode === "worktree";
|
||||
return {
|
||||
commandId: CommandId.make(spec.commandId),
|
||||
threadId: ThreadId.make(spec.threadId),
|
||||
message: {
|
||||
messageId: MessageId.make(spec.messageId),
|
||||
role: "user" as const,
|
||||
text: spec.text,
|
||||
attachments: spec.attachments,
|
||||
},
|
||||
modelSelection: spec.modelSelection,
|
||||
titleSeed: title,
|
||||
runtimeMode: spec.runtimeMode,
|
||||
interactionMode: spec.interactionMode,
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: spec.projectId,
|
||||
title,
|
||||
modelSelection: spec.modelSelection,
|
||||
runtimeMode: spec.runtimeMode,
|
||||
interactionMode: spec.interactionMode,
|
||||
branch: spec.branch,
|
||||
worktreePath: isWorktree ? null : spec.worktreePath,
|
||||
createdAt: spec.createdAt,
|
||||
},
|
||||
...(isWorktree
|
||||
? {
|
||||
prepareWorktree: {
|
||||
projectCwd: spec.projectCwd,
|
||||
baseBranch: spec.branch!,
|
||||
branch: spec.worktreeBranchName,
|
||||
...(spec.startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
runSetupScript: true,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
createdAt: spec.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -13,10 +13,12 @@ import {
|
||||
const CONNECTIONS_KEY = "t3code.connections";
|
||||
const PREFERENCES_KEY = "t3code.preferences";
|
||||
const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
|
||||
const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration";
|
||||
const MobileStorageKey = Schema.Literals([
|
||||
CONNECTIONS_KEY,
|
||||
PREFERENCES_KEY,
|
||||
AGENT_AWARENESS_DEVICE_ID_KEY,
|
||||
AGENT_AWARENESS_REGISTRATION_KEY,
|
||||
]);
|
||||
type MobileStorageKeyValue = typeof MobileStorageKey.Type;
|
||||
|
||||
@@ -67,6 +69,8 @@ export interface Preferences {
|
||||
/** Code/diff font size override; null/absent means derived from baseFontSize. */
|
||||
readonly codeFontSize?: number | null;
|
||||
readonly codeWordBreak?: boolean;
|
||||
/** Cloud account ids that opted out of the T3 Connect onboarding sheet. */
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
async function readStorageItem(key: MobileStorageKeyValue): Promise<string | null> {
|
||||
@@ -165,6 +169,7 @@ export async function loadPreferences(): Promise<Preferences> {
|
||||
markdownFontSize?: number;
|
||||
codeFontSize?: number | null;
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
} = {};
|
||||
|
||||
if (typeof parsed.liveActivitiesEnabled === "boolean") {
|
||||
@@ -185,6 +190,11 @@ export async function loadPreferences(): Promise<Preferences> {
|
||||
if (typeof parsed.codeWordBreak === "boolean") {
|
||||
preferences.codeWordBreak = parsed.codeWordBreak;
|
||||
}
|
||||
if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
|
||||
preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
|
||||
(account): account is string => typeof account === "string",
|
||||
);
|
||||
}
|
||||
|
||||
return preferences;
|
||||
}
|
||||
@@ -222,3 +232,46 @@ export async function loadAgentAwarenessDeviceId(): Promise<string | null> {
|
||||
const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
|
||||
return existing?.trim() ? existing : null;
|
||||
}
|
||||
|
||||
export interface AgentAwarenessRegistrationRecord {
|
||||
readonly identity: string;
|
||||
readonly signature: string;
|
||||
// Last push-to-start token the relay accepted. Registrations triggered
|
||||
// without a token event merge it back in so token absence never reads as a
|
||||
// change (which would defeat the register-once skip every launch).
|
||||
readonly pushToStartToken?: string;
|
||||
}
|
||||
|
||||
// Remembers the account identity and payload signature the relay last accepted
|
||||
// so the app does not re-register on every launch while nothing has changed.
|
||||
// Cleared only on sign-out.
|
||||
export async function loadAgentAwarenessRegistrationRecord(): Promise<AgentAwarenessRegistrationRecord | null> {
|
||||
const parsed = await readJsonStorageItem<AgentAwarenessRegistrationRecord>(
|
||||
AGENT_AWARENESS_REGISTRATION_KEY,
|
||||
);
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed !== "object" ||
|
||||
typeof parsed.identity !== "string" ||
|
||||
typeof parsed.signature !== "string"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
identity: parsed.identity,
|
||||
signature: parsed.signature,
|
||||
...(typeof parsed.pushToStartToken === "string" && parsed.pushToStartToken
|
||||
? { pushToStartToken: parsed.pushToStartToken }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveAgentAwarenessRegistrationRecord(
|
||||
record: AgentAwarenessRegistrationRecord,
|
||||
): Promise<void> {
|
||||
await writeJsonStorageItem(AGENT_AWARENESS_REGISTRATION_KEY, record);
|
||||
}
|
||||
|
||||
export async function clearAgentAwarenessRegistrationRecord(): Promise<void> {
|
||||
await writeStorageItem(AGENT_AWARENESS_REGISTRATION_KEY, "");
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
export function relativeTime(input: string): string {
|
||||
const timestamp = Date.parse(input);
|
||||
if (Number.isNaN(timestamp)) {
|
||||
return "now";
|
||||
return "<1m";
|
||||
}
|
||||
|
||||
// Anything under a minute renders as "<1m" rather than a live seconds count.
|
||||
// The seconds ticker changed width every second and reflowed the surrounding row.
|
||||
const deltaSeconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000));
|
||||
if (deltaSeconds < 10) return "now";
|
||||
if (deltaSeconds < 60) return `${deltaSeconds}s`;
|
||||
if (deltaSeconds < 60) return "<1m";
|
||||
|
||||
const deltaMinutes = Math.floor(deltaSeconds / 60);
|
||||
if (deltaMinutes < 60) return `${deltaMinutes}m`;
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import * as Crypto from "expo-crypto";
|
||||
|
||||
export const uuidv4 = () => Crypto.randomUUID();
|
||||
|
||||
/** Random lowercase hex string of `byteLength` bytes (2 chars per byte). */
|
||||
export const randomHex = (byteLength: number): string =>
|
||||
Array.from(Crypto.getRandomBytes(byteLength), (byte) => byte.toString(16).padStart(2, "0")).join(
|
||||
"",
|
||||
);
|
||||
@@ -15,6 +15,7 @@ export class ThreadOutboxManagerError extends Schema.TaggedErrorClass<ThreadOutb
|
||||
operation: Schema.Literals([
|
||||
"load",
|
||||
"enqueue",
|
||||
"update",
|
||||
"remove",
|
||||
"clear-environment-load",
|
||||
"clear-environment-remove",
|
||||
@@ -103,6 +104,35 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
setMessages([...currentMessages(), message]);
|
||||
});
|
||||
|
||||
// Rewrites an already-queued message. A no-op when the message has been
|
||||
// removed in the meantime (e.g. deleted or delivered), so a trailing editor
|
||||
// flush can never resurrect it. Returns whether the message was updated.
|
||||
const update = (message: QueuedThreadMessage): Promise<boolean> =>
|
||||
serialize(async () => {
|
||||
const exists = currentMessages().some(
|
||||
(candidate) => candidate.messageId === message.messageId,
|
||||
);
|
||||
if (!exists) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await options.storage.write(message);
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "update",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
]);
|
||||
return true;
|
||||
});
|
||||
|
||||
const remove = (message: QueuedThreadMessage): Promise<void> =>
|
||||
serialize(async () => {
|
||||
try {
|
||||
@@ -171,6 +201,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
serialize,
|
||||
load,
|
||||
enqueue,
|
||||
update,
|
||||
remove,
|
||||
clearEnvironment,
|
||||
};
|
||||
|
||||
@@ -6,10 +6,12 @@ import {
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
type ModelSelection as ModelSelectionType,
|
||||
type ProjectId as ProjectIdType,
|
||||
type ProviderInteractionMode as ProviderInteractionModeType,
|
||||
type RuntimeMode as RuntimeModeType,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -19,11 +21,23 @@ import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 3;
|
||||
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
|
||||
|
||||
const QueuedThreadCreationSchema = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
// Snapshot of the project's display metadata so a pending task stays
|
||||
// presentable in the thread list even when the project shell is not loaded.
|
||||
projectTitle: Schema.optional(Schema.String),
|
||||
projectCwd: Schema.optional(Schema.String),
|
||||
workspaceMode: Schema.Literals(["local", "worktree"]),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
startFromOrigin: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
@@ -33,12 +47,25 @@ export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
// Present when the queued item creates a brand-new thread (pending task)
|
||||
// instead of appending a turn to an existing one.
|
||||
creation: Schema.optional(QueuedThreadCreationSchema),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema);
|
||||
const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema);
|
||||
|
||||
export interface QueuedThreadCreation {
|
||||
readonly projectId: ProjectIdType;
|
||||
readonly projectTitle?: string;
|
||||
readonly projectCwd?: string;
|
||||
readonly workspaceMode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly startFromOrigin?: boolean;
|
||||
}
|
||||
|
||||
export interface QueuedThreadMessage {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
@@ -49,6 +76,7 @@ export interface QueuedThreadMessage {
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
readonly creation?: QueuedThreadCreation;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
@@ -121,17 +149,43 @@ export function threadOutboxRetryDelayMs(attempt: number): number {
|
||||
export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send";
|
||||
|
||||
export function resolveThreadOutboxDeliveryAction(input: {
|
||||
readonly isCreation: boolean;
|
||||
readonly threadExists: boolean;
|
||||
readonly shellStatus: EnvironmentShellStatus;
|
||||
readonly environmentConnected: boolean;
|
||||
readonly threadBusy: boolean;
|
||||
}): ThreadOutboxDeliveryAction {
|
||||
if (input.isCreation) {
|
||||
// A pending task creates its thread on delivery. If the thread already
|
||||
// exists the creation command went through and only cleanup remains.
|
||||
if (input.threadExists) {
|
||||
return "remove";
|
||||
}
|
||||
// Wait for the shell to be live before sending: until the thread list has
|
||||
// synchronized, a previously delivered creation whose cleanup failed would
|
||||
// look missing and get re-issued, duplicating the thread.
|
||||
return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
|
||||
}
|
||||
if (!input.threadExists) {
|
||||
return input.shellStatus === "live" ? "remove" : "wait";
|
||||
}
|
||||
return input.environmentConnected && !input.threadBusy ? "send" : "wait";
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued creation can only be dispatched once its payload would pass server
|
||||
* validation; incomplete payloads stay pending until the user edits them.
|
||||
*/
|
||||
export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
|
||||
if (!message.creation) {
|
||||
return false;
|
||||
}
|
||||
if (message.text.trim().length === 0 || message.modelSelection === undefined) {
|
||||
return false;
|
||||
}
|
||||
return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string | null {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
groupQueuedThreadMessages,
|
||||
isQueuedThreadCreationSendable,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
@@ -292,9 +294,43 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("updates a queued message in place but never resurrects a removed one", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const storage: ThreadOutboxStorage = {
|
||||
load: async () => [...stored.values()],
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
remove: async (message) => {
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
};
|
||||
const manager = createThreadOutboxManager({ registry, storage });
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
|
||||
await manager.enqueue(message);
|
||||
const edited = { ...message, text: "edited" };
|
||||
await expect(manager.update(edited)).resolves.toBe(true);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [edited],
|
||||
});
|
||||
expect(stored.get(message.messageId)).toEqual(edited);
|
||||
|
||||
await manager.remove(edited);
|
||||
await expect(manager.update({ ...message, text: "stale flush" })).resolves.toBe(false);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
expect(stored.size).toBe(0);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("only removes a missing-thread message after shell synchronization is live", () => {
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
isCreation: false,
|
||||
threadExists: false,
|
||||
shellStatus: "synchronizing",
|
||||
environmentConnected: true,
|
||||
@@ -303,6 +339,7 @@ describe("thread outbox", () => {
|
||||
).toBe("wait");
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
isCreation: false,
|
||||
threadExists: false,
|
||||
shellStatus: "live",
|
||||
environmentConnected: true,
|
||||
@@ -311,6 +348,7 @@ describe("thread outbox", () => {
|
||||
).toBe("remove");
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
isCreation: false,
|
||||
threadExists: true,
|
||||
shellStatus: "live",
|
||||
environmentConnected: true,
|
||||
@@ -319,6 +357,89 @@ describe("thread outbox", () => {
|
||||
).toBe("send");
|
||||
});
|
||||
|
||||
it("sends queued creations once connected and live, removing already-created ones", () => {
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
isCreation: true,
|
||||
threadExists: false,
|
||||
shellStatus: "cached",
|
||||
environmentConnected: false,
|
||||
threadBusy: false,
|
||||
}),
|
||||
).toBe("wait");
|
||||
// Connected but not yet synchronized: a previously delivered creation may
|
||||
// simply not be visible yet — sending now could duplicate the thread.
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
isCreation: true,
|
||||
threadExists: false,
|
||||
shellStatus: "synchronizing",
|
||||
environmentConnected: true,
|
||||
threadBusy: false,
|
||||
}),
|
||||
).toBe("wait");
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
isCreation: true,
|
||||
threadExists: false,
|
||||
shellStatus: "live",
|
||||
environmentConnected: true,
|
||||
threadBusy: false,
|
||||
}),
|
||||
).toBe("send");
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
isCreation: true,
|
||||
threadExists: true,
|
||||
shellStatus: "live",
|
||||
environmentConnected: true,
|
||||
threadBusy: true,
|
||||
}),
|
||||
).toBe("remove");
|
||||
});
|
||||
|
||||
it("round-trips queued creations and gates incomplete ones from sending", () => {
|
||||
const base = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const creationMessage = {
|
||||
...base,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
creation: {
|
||||
projectId: ProjectId.make("project-1"),
|
||||
workspaceMode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
startFromOrigin: true,
|
||||
},
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(creationMessage))).toEqual(
|
||||
creationMessage,
|
||||
);
|
||||
expect(isQueuedThreadCreationSendable(creationMessage)).toBe(true);
|
||||
expect(
|
||||
isQueuedThreadCreationSendable({
|
||||
...creationMessage,
|
||||
creation: { ...creationMessage.creation, branch: null },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isQueuedThreadCreationSendable({
|
||||
...creationMessage,
|
||||
creation: { ...creationMessage.creation, branch: "" },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(isQueuedThreadCreationSendable({ ...creationMessage, modelSelection: undefined })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isQueuedThreadCreationSendable(base)).toBe(false);
|
||||
});
|
||||
|
||||
it("retries transport failures but drops deterministic command failures", () => {
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true);
|
||||
expect(
|
||||
|
||||
@@ -20,6 +20,11 @@ export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promis
|
||||
return threadOutboxManager.enqueue(message);
|
||||
}
|
||||
|
||||
/** Rewrite a queued message; no-op (false) if it was removed in the meantime. */
|
||||
export function updateThreadOutboxMessage(message: QueuedThreadMessage): Promise<boolean> {
|
||||
return threadOutboxManager.update(message);
|
||||
}
|
||||
|
||||
export function removeThreadOutboxMessage(message: QueuedThreadMessage): Promise<void> {
|
||||
return threadOutboxManager.remove(message);
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ export interface ComposerDraftWorkspaceSelection {
|
||||
readonly mode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly startFromOrigin?: boolean;
|
||||
}
|
||||
|
||||
export type ComposerDraftSettingsUpdate = Pick<
|
||||
@@ -59,6 +60,7 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
mode: Schema.Literals(["local", "worktree"]),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
startFromOrigin: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
@@ -107,6 +109,10 @@ export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
|
||||
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
|
||||
}
|
||||
|
||||
export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
|
||||
return isEmptyDraft(draft);
|
||||
}
|
||||
|
||||
function isEmptyDraft(draft: ComposerDraft): boolean {
|
||||
return (
|
||||
draft.text.length === 0 &&
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
|
||||
import {
|
||||
flattenQueuedThreadMessages,
|
||||
type QueuedThreadCreation,
|
||||
type QueuedThreadMessage,
|
||||
} from "./thread-outbox-model";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
|
||||
/** A queued new-task creation, shaped for thread-list presentation. */
|
||||
export interface PendingNewTask {
|
||||
readonly message: QueuedThreadMessage;
|
||||
readonly creation: QueuedThreadCreation;
|
||||
readonly title: string;
|
||||
}
|
||||
|
||||
export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
return useMemo(() => {
|
||||
const tasks: PendingNewTask[] = [];
|
||||
for (const message of flattenQueuedThreadMessages(queuedMessagesByThreadKey)) {
|
||||
if (!message.creation) {
|
||||
continue;
|
||||
}
|
||||
tasks.push({
|
||||
message,
|
||||
creation: message.creation,
|
||||
title: deriveThreadTitleFromPrompt(message.text),
|
||||
});
|
||||
}
|
||||
tasks.sort((left, right) => right.message.createdAt.localeCompare(left.message.createdAt));
|
||||
return tasks;
|
||||
}, [queuedMessagesByThreadKey]);
|
||||
}
|
||||
@@ -1,27 +1,44 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { CommandId, type MessageId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type MessageId,
|
||||
} from "@t3tools/contracts";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
|
||||
import { randomHex } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useThreadShells } from "./entities";
|
||||
import { useProjects, useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
isQueuedThreadCreationSendable,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadCreation,
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
import { useThreadOutboxMessages, useThreadOutboxShellStatuses } from "./use-thread-outbox";
|
||||
import {
|
||||
editingQueuedMessageIdsAtom,
|
||||
useThreadOutboxMessages,
|
||||
useThreadOutboxShellStatuses,
|
||||
} from "./use-thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
|
||||
|
||||
export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
|
||||
@@ -48,6 +65,17 @@ function findThread(
|
||||
);
|
||||
}
|
||||
|
||||
function findCreationProject(
|
||||
projects: ReadonlyArray<EnvironmentProject>,
|
||||
message: QueuedThreadMessage,
|
||||
): EnvironmentProject | undefined {
|
||||
return projects.find(
|
||||
(candidate) =>
|
||||
candidate.environmentId === message.environmentId &&
|
||||
candidate.id === message.creation?.projectId,
|
||||
);
|
||||
}
|
||||
|
||||
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
|
||||
return CommandId.make(`${message.commandId}:${setting}`);
|
||||
}
|
||||
@@ -64,9 +92,11 @@ export function useThreadOutboxDrain(): void {
|
||||
reportFailure: false,
|
||||
});
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const editingQueuedMessageIds = useAtomValue(editingQueuedMessageIdsAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
const shellStatuses = useThreadOutboxShellStatuses();
|
||||
const threads = useThreadShells();
|
||||
const projects = useProjects();
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const [retryTick, setRetryTick] = useState(0);
|
||||
const retryAttemptRef = useRef(new Map<MessageId, number>());
|
||||
@@ -83,52 +113,57 @@ export function useThreadOutboxDrain(): void {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
}
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
const makeDeliveryHelpers = useCallback((queuedMessage: QueuedThreadMessage) => {
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
}
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
});
|
||||
return retry;
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
error,
|
||||
});
|
||||
return retry;
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
return { reportFailure, completeDelivery };
|
||||
}, []);
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const { reportFailure, completeDelivery } = makeDeliveryHelpers(queuedMessage);
|
||||
|
||||
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
@@ -196,7 +231,50 @@ export function useThreadOutboxDrain(): void {
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
},
|
||||
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
|
||||
[
|
||||
makeDeliveryHelpers,
|
||||
setThreadInteractionMode,
|
||||
setThreadRuntimeMode,
|
||||
startTurn,
|
||||
updateThreadMetadata,
|
||||
],
|
||||
);
|
||||
|
||||
const sendQueuedCreation = useCallback(
|
||||
async (
|
||||
queuedMessage: QueuedThreadMessage,
|
||||
creation: QueuedThreadCreation,
|
||||
projectCwd: string,
|
||||
) => {
|
||||
const modelSelection = queuedMessage.modelSelection;
|
||||
if (modelSelection === undefined) {
|
||||
return false;
|
||||
}
|
||||
const { completeDelivery } = makeDeliveryHelpers(queuedMessage);
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: buildProjectThreadStartTurnInput({
|
||||
projectId: creation.projectId,
|
||||
projectCwd,
|
||||
threadId: queuedMessage.threadId,
|
||||
commandId: queuedMessage.commandId,
|
||||
messageId: queuedMessage.messageId,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
text: queuedMessage.text.trim(),
|
||||
attachments: queuedMessage.attachments,
|
||||
modelSelection,
|
||||
runtimeMode: queuedMessage.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: queuedMessage.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
workspaceMode: creation.workspaceMode,
|
||||
branch: creation.branch,
|
||||
worktreePath: creation.worktreePath,
|
||||
startFromOrigin: creation.startFromOrigin ?? false,
|
||||
worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
|
||||
}),
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
},
|
||||
[makeDeliveryHelpers, startTurn],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -209,6 +287,9 @@ export function useThreadOutboxDrain(): void {
|
||||
if (!nextQueuedMessage) {
|
||||
continue;
|
||||
}
|
||||
if (editingQueuedMessageIds[nextQueuedMessage.messageId]) {
|
||||
continue;
|
||||
}
|
||||
if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
|
||||
continue;
|
||||
}
|
||||
@@ -218,37 +299,65 @@ export function useThreadOutboxDrain(): void {
|
||||
continue;
|
||||
}
|
||||
|
||||
const creation = nextQueuedMessage.creation;
|
||||
const environment = connectedEnvironments.find(
|
||||
(candidate) => candidate.environmentId === nextQueuedMessage.environmentId,
|
||||
);
|
||||
const shellStatus = shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty";
|
||||
const deliveryAction = resolveThreadOutboxDeliveryAction({
|
||||
isCreation: creation !== undefined,
|
||||
threadExists: thread !== undefined,
|
||||
shellStatus: shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty",
|
||||
shellStatus,
|
||||
environmentConnected: environment?.connectionState === "connected",
|
||||
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
|
||||
});
|
||||
if (deliveryAction === "wait") {
|
||||
continue;
|
||||
}
|
||||
// The live project shell is preferred for the workspace path, with the
|
||||
// snapshot taken at enqueue time as the fallback so a task never dies
|
||||
// just because its project shell is not loaded.
|
||||
const creationProjectCwd =
|
||||
creation !== undefined
|
||||
? (findCreationProject(projects, nextQueuedMessage)?.workspaceRoot ??
|
||||
creation.projectCwd ??
|
||||
null)
|
||||
: null;
|
||||
// An incomplete pending task (e.g. worktree mode without a branch) stays
|
||||
// queued until the user finishes it in the editor.
|
||||
if (deliveryAction === "send" && creation !== undefined) {
|
||||
if (!isQueuedThreadCreationSendable(nextQueuedMessage)) {
|
||||
continue;
|
||||
}
|
||||
if (creationProjectCwd === null && shellStatus !== "live") {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
|
||||
const removeQueuedMessage = (warning: string) =>
|
||||
removeThreadOutboxMessage(nextQueuedMessage).then(
|
||||
() => true,
|
||||
(error) => {
|
||||
console.warn(warning, {
|
||||
environmentId: nextQueuedMessage.environmentId,
|
||||
threadId: nextQueuedMessage.threadId,
|
||||
messageId: nextQueuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
},
|
||||
);
|
||||
const delivery =
|
||||
deliveryAction === "remove"
|
||||
? removeThreadOutboxMessage(nextQueuedMessage).then(
|
||||
() => true,
|
||||
(error) => {
|
||||
console.warn("[thread-outbox] failed to remove message for a missing thread", {
|
||||
environmentId: nextQueuedMessage.environmentId,
|
||||
threadId: nextQueuedMessage.threadId,
|
||||
messageId: nextQueuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
},
|
||||
)
|
||||
: thread !== undefined
|
||||
? sendQueuedMessage(nextQueuedMessage, thread)
|
||||
: Promise.resolve(false);
|
||||
? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
|
||||
: creation !== undefined
|
||||
? creationProjectCwd !== null
|
||||
? sendQueuedCreation(nextQueuedMessage, creation, creationProjectCwd)
|
||||
: removeQueuedMessage("[thread-outbox] dropped pending task for a missing project")
|
||||
: thread !== undefined
|
||||
? sendQueuedMessage(nextQueuedMessage, thread)
|
||||
: Promise.resolve(false);
|
||||
void delivery
|
||||
.then((sent) => {
|
||||
if (sent) {
|
||||
@@ -284,8 +393,11 @@ export function useThreadOutboxDrain(): void {
|
||||
}, [
|
||||
connectedEnvironments,
|
||||
dispatchingQueuedMessageId,
|
||||
editingQueuedMessageIds,
|
||||
projects,
|
||||
queuedMessagesByThreadKey,
|
||||
retryTick,
|
||||
sendQueuedCreation,
|
||||
sendQueuedMessage,
|
||||
shellStatuses,
|
||||
threads,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, MessageId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { environmentShell } from "./shell";
|
||||
import { threadOutboxManager } from "./thread-outbox";
|
||||
|
||||
@@ -19,6 +20,35 @@ const threadOutboxShellStatusesAtom = Atom.make(
|
||||
},
|
||||
).pipe(Atom.withLabel("mobile:thread-outbox:shell-statuses"));
|
||||
|
||||
/**
|
||||
* Queued pending tasks the outbox drain must not deliver right now: the one
|
||||
* open in the new-task editor, plus any whose latest edits could not be saved
|
||||
* back yet (delivering those would send stale content). Editing sessions hold
|
||||
* their message id here and release it once the queued payload is current.
|
||||
*/
|
||||
export const editingQueuedMessageIdsAtom = Atom.make<Readonly<Record<MessageId, true>>>({}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:thread-outbox:editing-message-ids"),
|
||||
);
|
||||
|
||||
export function holdEditingQueuedMessage(messageId: MessageId): void {
|
||||
const current = appAtomRegistry.get(editingQueuedMessageIdsAtom);
|
||||
if (current[messageId]) {
|
||||
return;
|
||||
}
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, { ...current, [messageId]: true });
|
||||
}
|
||||
|
||||
export function releaseEditingQueuedMessage(messageId: MessageId): void {
|
||||
const current = appAtomRegistry.get(editingQueuedMessageIdsAtom);
|
||||
if (!current[messageId]) {
|
||||
return;
|
||||
}
|
||||
const next = { ...current };
|
||||
delete next[messageId];
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, next);
|
||||
}
|
||||
|
||||
export function useThreadOutboxMessages() {
|
||||
return useAtomValue(threadOutboxManager.queuedMessagesByThreadKeyAtom);
|
||||
}
|
||||
|
||||
@@ -2,23 +2,48 @@ import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("@expo/ui/swift-ui", () => ({
|
||||
HStack: "HStack",
|
||||
Image: "Image",
|
||||
Spacer: "Spacer",
|
||||
Text: "Text",
|
||||
VStack: "VStack",
|
||||
ZStack: "ZStack",
|
||||
}));
|
||||
|
||||
vi.mock("@expo/ui/swift-ui/modifiers", () => ({
|
||||
font: (value: unknown) => value,
|
||||
foregroundStyle: (value: unknown) => value,
|
||||
frame: (value: unknown) => value,
|
||||
layoutPriority: (value: unknown) => value,
|
||||
lineLimit: (value: unknown) => value,
|
||||
padding: (value: unknown) => value,
|
||||
resizable: (value: unknown) => value,
|
||||
widgetURL: (value: unknown) => ({ widgetURL: value }),
|
||||
}));
|
||||
|
||||
vi.mock("expo-widgets", () => ({
|
||||
createLiveActivity: vi.fn((name: string, layout: unknown) => ({ layout, name })),
|
||||
}));
|
||||
|
||||
import { AgentActivity, type AgentActivityProps } from "./AgentActivity";
|
||||
import {
|
||||
AgentActivity,
|
||||
type AgentActivityProps,
|
||||
type AgentActivityRowProps,
|
||||
} from "./AgentActivity";
|
||||
|
||||
function makeRow(overrides: Partial<AgentActivityRowProps>): AgentActivityRowProps {
|
||||
return {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
projectTitle: "Project",
|
||||
threadTitle: "Thread",
|
||||
modelTitle: "gpt-5.4",
|
||||
phase: "running",
|
||||
status: "Working",
|
||||
updatedAt: "2026-05-25T13:07:00.000Z",
|
||||
deepLink: "/threads/env-1/thread-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const props = {
|
||||
title: "T3 Code",
|
||||
@@ -33,17 +58,162 @@ const environment = {
|
||||
isLuminanceReduced: false,
|
||||
} as const;
|
||||
|
||||
const lightEnvironment = {
|
||||
colorScheme: "light",
|
||||
isLuminanceReduced: false,
|
||||
} as const;
|
||||
|
||||
describe("AgentActivity widget layout", () => {
|
||||
it("formats its updated-at label without app-runtime helper references", () => {
|
||||
expect(JSON.stringify(AgentActivity(props, environment as never))).toContain(
|
||||
'"children":["Updated ","1:07"]',
|
||||
it("tints each row by its own phase using the web sidebar's dark palette", () => {
|
||||
const layout = AgentActivity(
|
||||
{
|
||||
...props,
|
||||
activeCount: 2,
|
||||
activities: [
|
||||
makeRow({}),
|
||||
makeRow({ threadId: "thread-2", phase: "waiting_for_approval", status: "Approval" }),
|
||||
],
|
||||
},
|
||||
environment as never,
|
||||
);
|
||||
expect(AgentActivity.toString()).not.toContain("formatAgentActivityUpdatedAtLabel");
|
||||
const banner = JSON.stringify(layout.banner);
|
||||
expect(banner).toContain("#7dd3fc"); // sky-300: running
|
||||
expect(banner).toContain("#fcd34d"); // amber-300: waiting_for_approval
|
||||
});
|
||||
|
||||
it("uses now when the updated-at timestamp is malformed", () => {
|
||||
it("switches to the web sidebar's light palette when the scheme is light", () => {
|
||||
// macOS (iPhone Mirroring / Mac notification center) renders the activity
|
||||
// on a light background; the dark-material palette is illegible there.
|
||||
const layout = AgentActivity(
|
||||
{
|
||||
...props,
|
||||
activeCount: 2,
|
||||
activities: [
|
||||
makeRow({}),
|
||||
makeRow({ threadId: "thread-2", phase: "waiting_for_approval", status: "Approval" }),
|
||||
],
|
||||
},
|
||||
lightEnvironment as never,
|
||||
);
|
||||
const banner = JSON.stringify(layout.banner);
|
||||
expect(banner).toContain("#0284c7"); // sky-600: running
|
||||
expect(banner).toContain("#d97706"); // amber-600: waiting_for_approval
|
||||
expect(banner).not.toContain("#7dd3fc");
|
||||
expect(banner).not.toContain("#fcd34d");
|
||||
});
|
||||
|
||||
it("orders rows attention-first in the banner", () => {
|
||||
const layout = AgentActivity(
|
||||
{
|
||||
...props,
|
||||
activeCount: 2,
|
||||
activities: [
|
||||
makeRow({ threadTitle: "Working thread" }),
|
||||
makeRow({
|
||||
threadId: "thread-2",
|
||||
threadTitle: "Blocked thread",
|
||||
phase: "waiting_for_approval",
|
||||
status: "Approval",
|
||||
}),
|
||||
],
|
||||
},
|
||||
environment as never,
|
||||
);
|
||||
const banner = JSON.stringify(layout.banner);
|
||||
expect(banner.indexOf("Blocked thread")).toBeGreaterThan(-1);
|
||||
expect(banner.indexOf("Blocked thread")).toBeLessThan(banner.indexOf("Working thread"));
|
||||
});
|
||||
|
||||
it("summarizes the attention count in the banner header", () => {
|
||||
const layout = AgentActivity(
|
||||
{
|
||||
...props,
|
||||
activeCount: 3,
|
||||
activities: [
|
||||
makeRow({}),
|
||||
makeRow({ threadId: "thread-2", phase: "waiting_for_input", status: "Input" }),
|
||||
],
|
||||
},
|
||||
environment as never,
|
||||
);
|
||||
const banner = JSON.stringify(layout.banner);
|
||||
expect(banner).toContain("3 active agents");
|
||||
expect(banner).toContain("1 needs attention");
|
||||
});
|
||||
|
||||
it("uses the attention tint for the compact presentations when a row needs input", () => {
|
||||
const layout = AgentActivity(
|
||||
{
|
||||
...props,
|
||||
activeCount: 2,
|
||||
activities: [
|
||||
makeRow({}),
|
||||
makeRow({ threadId: "thread-2", phase: "waiting_for_input", status: "Input" }),
|
||||
],
|
||||
},
|
||||
environment as never,
|
||||
);
|
||||
expect(JSON.stringify(layout.compactLeading)).toContain("#a5b4fc"); // indigo-300
|
||||
expect(JSON.stringify(layout.compactTrailing)).toContain("Input");
|
||||
expect(JSON.stringify(layout.minimal)).toContain("#a5b4fc");
|
||||
});
|
||||
|
||||
it("deep links the banner to the row that needs attention", () => {
|
||||
const layout = AgentActivity(
|
||||
{
|
||||
...props,
|
||||
activeCount: 2,
|
||||
activities: [
|
||||
makeRow({}),
|
||||
makeRow({
|
||||
threadId: "thread-2",
|
||||
phase: "waiting_for_approval",
|
||||
status: "Approval",
|
||||
deepLink: "/threads/env-1/thread-2",
|
||||
}),
|
||||
],
|
||||
},
|
||||
environment as never,
|
||||
);
|
||||
expect(JSON.stringify(layout.banner)).toContain(
|
||||
'"widgetURL":"t3code://threads/env-1/thread-2"',
|
||||
);
|
||||
});
|
||||
|
||||
it("deep links the banner to the first row when nothing needs attention", () => {
|
||||
const layout = AgentActivity({ ...props, activities: [makeRow({})] }, environment as never);
|
||||
expect(JSON.stringify(layout.banner)).toContain(
|
||||
'"widgetURL":"t3code://threads/env-1/thread-1"',
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the deep link for unsafe paths and empty aggregates", () => {
|
||||
expect(JSON.stringify(AgentActivity(props, environment as never))).not.toContain("widgetURL");
|
||||
expect(
|
||||
JSON.stringify(AgentActivity({ ...props, updatedAt: "not-a-date" }, environment as never)),
|
||||
).toContain('"children":["Updated ","now"]');
|
||||
JSON.stringify(
|
||||
AgentActivity(
|
||||
{ ...props, activities: [makeRow({ deepLink: "//evil.example" })] },
|
||||
environment as never,
|
||||
),
|
||||
),
|
||||
).not.toContain("widgetURL");
|
||||
});
|
||||
|
||||
it("renders up to five rows in the banner", () => {
|
||||
const layout = AgentActivity(
|
||||
{
|
||||
...props,
|
||||
activeCount: 6,
|
||||
activities: [1, 2, 3, 4, 5, 6].map((n) =>
|
||||
makeRow({ threadId: `t${n}`, threadTitle: `Thread ${n}` }),
|
||||
),
|
||||
},
|
||||
environment as never,
|
||||
);
|
||||
const banner = JSON.stringify(layout.banner);
|
||||
for (const visible of [1, 2, 3, 4, 5]) {
|
||||
expect(banner).toContain(`Thread ${visible}`);
|
||||
}
|
||||
expect(banner).not.toContain("Thread 6");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,15 @@
|
||||
import { HStack, Spacer, Text, VStack } from "@expo/ui/swift-ui";
|
||||
import { font, foregroundStyle, lineLimit, padding } from "@expo/ui/swift-ui/modifiers";
|
||||
import { HStack, Image, Spacer, Text, VStack, ZStack } from "@expo/ui/swift-ui";
|
||||
import type { ComponentProps } from "react";
|
||||
import {
|
||||
font,
|
||||
foregroundStyle,
|
||||
frame,
|
||||
layoutPriority,
|
||||
lineLimit,
|
||||
padding,
|
||||
resizable,
|
||||
widgetURL,
|
||||
} from "@expo/ui/swift-ui/modifiers";
|
||||
import {
|
||||
createLiveActivity,
|
||||
type LiveActivityComponent,
|
||||
@@ -37,282 +47,319 @@ export interface AgentActivityProps {
|
||||
readonly activities: ReadonlyArray<AgentActivityRowProps>;
|
||||
}
|
||||
|
||||
// This function is serialized into the widget extension's JS bundle, so it
|
||||
// must stay self-contained: no references to module-scope helpers, only the
|
||||
// imported view/modifier factories.
|
||||
export function AgentActivity(
|
||||
props: AgentActivityProps,
|
||||
environment: LiveActivityEnvironment,
|
||||
): LiveActivityLayout {
|
||||
"widget";
|
||||
|
||||
const row0 = props.activities[0];
|
||||
const row1 = props.activities[1];
|
||||
const row2 = props.activities[2];
|
||||
const updatedAtMatch = /^\d{4}-\d{2}-\d{2}T(\d{2}):(\d{2}):/.exec(props.updatedAt);
|
||||
const updatedAtHours24 = Number(updatedAtMatch?.[1]);
|
||||
const updatedAtMinutes = updatedAtMatch?.[2];
|
||||
const updatedAt =
|
||||
Number.isInteger(updatedAtHours24) &&
|
||||
updatedAtHours24 >= 0 &&
|
||||
updatedAtHours24 <= 23 &&
|
||||
updatedAtMinutes
|
||||
? `${updatedAtHours24 % 12 || 12}:${updatedAtMinutes}`
|
||||
: "now";
|
||||
// Use SwiftUI's semantic label colors rather than fixed hex keyed off the
|
||||
// device color scheme. A Live Activity banner always renders over a dark
|
||||
// system material regardless of the device's light/dark setting, so
|
||||
// scheme-derived dark text read as unreadable dark-on-dark on the lock
|
||||
// screen. Semantic colors adapt to whatever material the OS places them on:
|
||||
// the dark LA banner and the (light or dark) home-screen widget alike.
|
||||
const primaryForeground = "primary";
|
||||
const secondaryForeground = "secondary";
|
||||
|
||||
// Status tints mirror the web sidebar's pills
|
||||
// (apps/web/src/components/Sidebar.logic.ts resolveThreadStatusPill): amber
|
||||
// for approval, indigo for input, sky for working, emerald for completed.
|
||||
// On iPhone the LA sits on a dark material, but macOS (iPhone Mirroring /
|
||||
// Mac notification center) renders it on a light one — so pick the web
|
||||
// palette's light (-600) or dark (-300) variant off the color scheme.
|
||||
const isLightScheme = environment.colorScheme === "light";
|
||||
const phaseTint = (phase: AgentActivityPhase | undefined): string => {
|
||||
if (environment.isLuminanceReduced) {
|
||||
return secondaryForeground;
|
||||
}
|
||||
switch (phase) {
|
||||
case "waiting_for_approval":
|
||||
return isLightScheme ? "#d97706" : "#fcd34d"; // amber-600 / amber-300
|
||||
case "waiting_for_input":
|
||||
return isLightScheme ? "#4f46e5" : "#a5b4fc"; // indigo-600 / indigo-300
|
||||
case "failed":
|
||||
return isLightScheme ? "#dc2626" : "#fca5a5"; // red-600 / red-300
|
||||
case "completed":
|
||||
return isLightScheme ? "#059669" : "#6ee7b7"; // emerald-600 / emerald-300
|
||||
case "starting":
|
||||
case "running":
|
||||
default:
|
||||
return isLightScheme ? "#0284c7" : "#7dd3fc"; // sky-600 / sky-300
|
||||
}
|
||||
};
|
||||
|
||||
// Order attention-first so whatever needs the user floats to the top of every
|
||||
// presentation, then failures, then in-flight work, then finished/stale.
|
||||
const phasePriority = (phase: AgentActivityPhase): number => {
|
||||
if (phase === "waiting_for_approval" || phase === "waiting_for_input") return 0;
|
||||
if (phase === "failed") return 1;
|
||||
if (phase === "running" || phase === "starting") return 2;
|
||||
return 3;
|
||||
};
|
||||
const ordered = [...props.activities].sort(
|
||||
(a, b) => phasePriority(a.phase) - phasePriority(b.phase),
|
||||
);
|
||||
const row0 = ordered[0];
|
||||
const row1 = ordered[1];
|
||||
const row2 = ordered[2];
|
||||
const row3 = ordered[3];
|
||||
const row4 = ordered[4];
|
||||
|
||||
const attentionRows = props.activities.filter(
|
||||
(row) => row.phase === "waiting_for_approval" || row.phase === "waiting_for_input",
|
||||
);
|
||||
const attentionRow = attentionRows[0];
|
||||
const failedRow = props.activities.find((row) => row.phase === "failed");
|
||||
const heroRow = attentionRow ?? failedRow ?? row0;
|
||||
const tint = phaseTint(heroRow?.phase);
|
||||
// Headline count leans on the accent when a human is actually blocked.
|
||||
const headerTint = attentionRow
|
||||
? phaseTint(attentionRow.phase)
|
||||
: failedRow
|
||||
? phaseTint(failedRow.phase)
|
||||
: tint;
|
||||
|
||||
// Header copy: "5 active agents" + (", 1 needs attention"). The banner renders
|
||||
// the two parts in-line so the attention half can carry the accent color;
|
||||
// `summary` is the short form for tight spots (expanded center, watch card).
|
||||
const agentWord = props.activeCount === 1 ? "agent" : "agents";
|
||||
const agentsLabel = `${props.activeCount} active ${agentWord}`;
|
||||
const attentionSuffix =
|
||||
attentionRows.length > 0
|
||||
? `${attentionRows.length} need${attentionRows.length === 1 ? "s" : ""} attention`
|
||||
: "";
|
||||
const summary = attentionSuffix || `${props.activeCount} active`;
|
||||
|
||||
// Any registered scheme variant routes back to this app; taps are delivered
|
||||
// to the widget's containing app, so the prod scheme is safe for all builds.
|
||||
const deepLinkRow = attentionRow ?? row0;
|
||||
const deepLink =
|
||||
deepLinkRow && deepLinkRow.deepLink.startsWith("/") && !deepLinkRow.deepLink.startsWith("//")
|
||||
? `t3code://${deepLinkRow.deepLink.slice(1)}`
|
||||
: null;
|
||||
|
||||
const activeLabel = `${props.activeCount} active`;
|
||||
const isLight = environment.colorScheme === "light";
|
||||
const primaryForeground = isLight ? "#262626" : "#f5f5f5";
|
||||
const secondaryForeground = isLight ? "#525252" : "#a3a3a3";
|
||||
const mutedForeground = isLight ? "#737373" : "#8e8e93";
|
||||
const tint = environment.isLuminanceReduced
|
||||
? secondaryForeground
|
||||
: row0?.phase === "waiting_for_approval" || row0?.phase === "waiting_for_input"
|
||||
? "#f97316"
|
||||
: row0?.phase === "failed"
|
||||
? "#ef4444"
|
||||
: "#14b8a6";
|
||||
|
||||
// A scannable status glyph per phase — reads faster than colored words and
|
||||
// ties the compact / expanded / banner / watch presentations together.
|
||||
type SFName = NonNullable<ComponentProps<typeof Image>["systemName"]>;
|
||||
const phaseSymbol = (phase: AgentActivityPhase): SFName => {
|
||||
switch (phase) {
|
||||
case "waiting_for_approval":
|
||||
return "exclamationmark.circle.fill";
|
||||
case "waiting_for_input":
|
||||
return "questionmark.circle.fill";
|
||||
case "failed":
|
||||
return "xmark.octagon.fill";
|
||||
case "completed":
|
||||
return "checkmark.circle.fill";
|
||||
case "starting":
|
||||
return "circle.dotted";
|
||||
case "stale":
|
||||
return "clock.arrow.circlepath";
|
||||
case "running":
|
||||
default:
|
||||
return "arrow.triangle.2.circlepath";
|
||||
}
|
||||
};
|
||||
|
||||
// SF Symbols, like the logo, ignore frame/foregroundStyle applied directly to
|
||||
// the image; size + tint them through a container the resizable symbol fills.
|
||||
const renderGlyph = (systemName: SFName, size: number, color: string) => (
|
||||
<HStack modifiers={[frame({ width: size, height: size }), foregroundStyle(color)]}>
|
||||
<Image systemName={systemName} modifiers={[resizable()]} />
|
||||
</HStack>
|
||||
);
|
||||
|
||||
// Single-line row used by every presentation: glyph, title, inline project,
|
||||
// status. The project and status carry layoutPriority(1) so when space runs
|
||||
// out it's the title that truncates, never the (short) project name or the
|
||||
// status label. Single-line keeps rows inside the expanded island's hard
|
||||
// height budget (~160pt) and lets the banner fit more agents.
|
||||
const renderCompactRow = (row: AgentActivityRowProps) => (
|
||||
<HStack spacing={7} alignment="center">
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "semibold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row.threadTitle}
|
||||
</Text>
|
||||
{/* No layoutPriority and no frame on the project: two bare texts take
|
||||
their ideal width when it fits and shrink proportionally only when it
|
||||
doesn't — so short rows never truncate, and long title + long project
|
||||
truncate together. (A maxWidth frame is greedy and reserved its full
|
||||
width even for short names; layoutPriority let the project starve the
|
||||
title.) */}
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}>
|
||||
{row.projectTitle}
|
||||
</Text>
|
||||
<Spacer minLength={8} />
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "semibold", size: 11 }),
|
||||
foregroundStyle(phaseTint(row.phase)),
|
||||
layoutPriority(1),
|
||||
]}
|
||||
>
|
||||
{row.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
);
|
||||
|
||||
// The branded T3 mark. `assetName` resolves the template image set bundled in
|
||||
// the widget extension's asset catalog. Image views only honor `resizable`
|
||||
// directly (frame/foregroundStyle are dropped), so we size it via a container
|
||||
// frame the resizable image fills and tint it through the container's
|
||||
// foreground style, which the template image inherits. The 3:2 frame matches
|
||||
// the glyph's aspect ratio so it never distorts.
|
||||
const renderLogo = (height: number, color: string) => (
|
||||
<HStack modifiers={[frame({ width: height * 1.5, height }), foregroundStyle(color)]}>
|
||||
<Image assetName="T3Mark" modifiers={[resizable()]} />
|
||||
</HStack>
|
||||
);
|
||||
|
||||
return {
|
||||
banner: (
|
||||
<VStack modifiers={[padding({ all: 14 })]}>
|
||||
<HStack>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[font({ weight: "bold", size: 15 }), foregroundStyle(primaryForeground)]}
|
||||
>
|
||||
{props.title}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 12 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{props.subtitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 12 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
</HStack>
|
||||
{row0 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row0.projectTitle} - {row0.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row0.status}
|
||||
</Text>
|
||||
<VStack
|
||||
alignment="leading"
|
||||
spacing={6}
|
||||
modifiers={deepLink ? [padding({ all: 14 }), widgetURL(deepLink)] : [padding({ all: 14 })]}
|
||||
>
|
||||
{/* Logo pinned to the leading edge; the status texts centered across the
|
||||
full width (ZStack so the logo doesn't skew the centering). No footer —
|
||||
overflow beyond the visible rows is inferable from the count. */}
|
||||
<ZStack>
|
||||
<HStack spacing={0} alignment="center">
|
||||
{renderLogo(13, primaryForeground)}
|
||||
<Spacer minLength={0} />
|
||||
</HStack>
|
||||
) : null}
|
||||
{row1 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row1.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row1.projectTitle} - {row1.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row1.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
{row2 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row2.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row2.projectTitle} - {row2.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row2.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(mutedForeground)]}>
|
||||
Updated {updatedAt}
|
||||
</Text>
|
||||
</VStack>
|
||||
),
|
||||
bannerSmall: (
|
||||
<VStack modifiers={[padding({ all: 12 })]}>
|
||||
<HStack>
|
||||
<Text
|
||||
modifiers={[font({ weight: "bold", size: 13 }), foregroundStyle(primaryForeground)]}
|
||||
>
|
||||
{props.title}
|
||||
</Text>
|
||||
<Spacer minLength={6} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 12 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
</HStack>
|
||||
{row0 ? (
|
||||
<VStack>
|
||||
<HStack spacing={6} alignment="center">
|
||||
<Spacer minLength={0} />
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 12 }),
|
||||
font({ weight: "semibold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{agentsLabel}
|
||||
</Text>
|
||||
{attentionSuffix ? (
|
||||
<Text modifiers={[font({ size: 13 }), foregroundStyle(secondaryForeground)]}>·</Text>
|
||||
) : null}
|
||||
{attentionSuffix ? (
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "semibold", size: 13 }),
|
||||
foregroundStyle(headerTint),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{attentionSuffix}
|
||||
</Text>
|
||||
) : null}
|
||||
<Spacer minLength={0} />
|
||||
</HStack>
|
||||
</ZStack>
|
||||
{row0 ? renderCompactRow(row0) : null}
|
||||
{row1 ? renderCompactRow(row1) : null}
|
||||
{row2 ? renderCompactRow(row2) : null}
|
||||
{row3 ? renderCompactRow(row3) : null}
|
||||
{row4 ? renderCompactRow(row4) : null}
|
||||
</VStack>
|
||||
),
|
||||
// Compact card for the watchOS Smart Stack + CarPlay (the `.small` family):
|
||||
// brand + count, then the single most important agent with its status glyph.
|
||||
bannerSmall: (
|
||||
<VStack alignment="leading" spacing={5} modifiers={[padding({ all: 10 })]}>
|
||||
<HStack spacing={7} alignment="center">
|
||||
{renderLogo(14, primaryForeground)}
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(headerTint),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{attentionRows.length > 0 ? summary : activeLabel}
|
||||
</Text>
|
||||
<Spacer minLength={6} />
|
||||
</HStack>
|
||||
{row0 ? (
|
||||
<HStack spacing={7} alignment="center">
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "semibold", size: 12 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row0.projectTitle} - {row0.status}
|
||||
</Text>
|
||||
</VStack>
|
||||
) : null}
|
||||
</VStack>
|
||||
),
|
||||
compactLeading: (
|
||||
<Text modifiers={[font({ weight: "bold", size: 11 }), foregroundStyle(tint)]}>T3</Text>
|
||||
),
|
||||
compactTrailing: (
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
),
|
||||
minimal: (
|
||||
<Text modifiers={[font({ weight: "bold", size: 11 }), foregroundStyle(tint)]}>T3</Text>
|
||||
),
|
||||
expandedLeading: (
|
||||
<VStack modifiers={[padding({ all: 8 })]}>
|
||||
<Text modifiers={[font({ weight: "bold", size: 12 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
</VStack>
|
||||
),
|
||||
expandedCenter: row0 ? (
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 12 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}>
|
||||
{row0.projectTitle} - {row0.status}
|
||||
</Text>
|
||||
</VStack>
|
||||
) : null,
|
||||
expandedTrailing: (
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground)]}>
|
||||
Updated {updatedAt}
|
||||
</Text>
|
||||
),
|
||||
expandedBottom: (
|
||||
<VStack modifiers={[padding({ all: 8 })]}>
|
||||
{row0 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row0.projectTitle} - {row0.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
<Spacer minLength={6} />
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(phaseTint(row0.phase))]}>
|
||||
{row0.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
{row1 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row1.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row1.projectTitle} - {row1.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row1.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
{row2 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row2.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row2.projectTitle} - {row2.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row2.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
</VStack>
|
||||
),
|
||||
compactLeading: renderLogo(14, tint),
|
||||
compactTrailing: (
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{attentionRow
|
||||
? attentionRow.phase === "waiting_for_approval"
|
||||
? "Approval"
|
||||
: "Input"
|
||||
: activeLabel}
|
||||
</Text>
|
||||
),
|
||||
// The shared/minimal form is a ~22pt circle — a single signal reads there,
|
||||
// the wordmark does not. Show the blocking phase glyph, else the mark.
|
||||
minimal:
|
||||
attentionRow || failedRow
|
||||
? renderGlyph(phaseSymbol(heroRow.phase), 13, phaseTint(heroRow.phase))
|
||||
: renderLogo(11, tint),
|
||||
expandedLeading: (
|
||||
<HStack spacing={5} alignment="center" modifiers={[padding({ leading: 4, vertical: 4 })]}>
|
||||
{renderLogo(15, tint)}
|
||||
<Text modifiers={[font({ weight: "bold", size: 13 }), foregroundStyle(tint)]}>
|
||||
{`${props.activeCount}`}
|
||||
</Text>
|
||||
</HStack>
|
||||
),
|
||||
// No center content: the phase glyphs + statuses in expandedBottom already
|
||||
// carry the attention signal, and the expanded island's height budget is
|
||||
// tight enough that a summary line there pushed the third row off.
|
||||
expandedCenter: null,
|
||||
// No trailing content: a timestamp is glanceable-lock-screen info, not
|
||||
// useful in a view the user is actively holding open — and the trailing
|
||||
// region hugs the island's corner radius, which clipped it anyway.
|
||||
expandedTrailing: null,
|
||||
expandedBottom: (
|
||||
// Vertical padding only: the expanded region provides its own horizontal
|
||||
// content margins, so `all` padding double-indented the rows.
|
||||
// Horizontal padding keeps both edges clear of the island's corner
|
||||
// curvature (right edge clipped status labels; titles hugged the left).
|
||||
<VStack
|
||||
alignment="leading"
|
||||
spacing={5}
|
||||
modifiers={
|
||||
deepLink
|
||||
? [padding({ vertical: 2, horizontal: 8 }), widgetURL(deepLink)]
|
||||
: [padding({ vertical: 2, horizontal: 8 })]
|
||||
}
|
||||
>
|
||||
{row0 ? renderCompactRow(row0) : null}
|
||||
{row1 ? renderCompactRow(row1) : null}
|
||||
{row2 ? renderCompactRow(row2) : null}
|
||||
</VStack>
|
||||
),
|
||||
};
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
EnvironmentOperationForbiddenError,
|
||||
EnvironmentRequestInvalidError,
|
||||
type EnvironmentRequestInvalidReason,
|
||||
EnvironmentResourceNotFoundError,
|
||||
type EnvironmentResourceNotFoundReason,
|
||||
EnvironmentScopeRequiredError,
|
||||
EnvironmentAuthenticatedAuth,
|
||||
EnvironmentAuthenticatedPrincipal,
|
||||
@@ -137,6 +139,14 @@ function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_a
|
||||
);
|
||||
}
|
||||
|
||||
export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) {
|
||||
return currentEnvironmentTraceId.pipe(
|
||||
Effect.flatMap((traceId) =>
|
||||
Effect.fail(new EnvironmentResourceNotFoundError({ code: "not_found", reason, traceId })),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
|
||||
return Effect.gen(function* () {
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
|
||||
@@ -107,6 +107,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
}),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -199,6 +200,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -281,6 +283,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -348,6 +351,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -400,6 +404,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -8,7 +8,11 @@ import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
|
||||
import { acquireRelayClientForLink, reportCloudDisconnectResults } from "./connect.ts";
|
||||
import {
|
||||
acquireRelayClientForLink,
|
||||
isPublishAgentActivityEnabledValue,
|
||||
reportCloudDisconnectResults,
|
||||
} from "./connect.ts";
|
||||
|
||||
const managedExecutable = {
|
||||
status: "available",
|
||||
@@ -153,3 +157,10 @@ it.effect("keeps disconnect causes in structured logs and out of console warning
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("treats only the literal 'true' as publish-enabled", () => {
|
||||
assert.equal(isPublishAgentActivityEnabledValue("true"), true);
|
||||
assert.equal(isPublishAgentActivityEnabledValue("false"), false);
|
||||
assert.equal(isPublishAgentActivityEnabledValue(null), false);
|
||||
assert.equal(isPublishAgentActivityEnabledValue("TRUE"), false);
|
||||
});
|
||||
+136
-25
@@ -29,7 +29,11 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as CliState from "../cloud/CliState.ts";
|
||||
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
|
||||
import { CLOUD_LINKED_USER_ID, RELAY_URL_SECRET } from "../cloud/config.ts";
|
||||
import {
|
||||
CLOUD_LINKED_USER_ID,
|
||||
PUBLISH_AGENT_ACTIVITY_SECRET,
|
||||
RELAY_URL_SECRET,
|
||||
} from "../cloud/config.ts";
|
||||
import { relayUrlConfig } from "../cloud/publicConfig.ts";
|
||||
import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
@@ -46,12 +50,21 @@ function bytesToString(value: Uint8Array): string {
|
||||
return new TextDecoder().decode(value);
|
||||
}
|
||||
|
||||
function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
|
||||
export function isPublishAgentActivityEnabledValue(value: string | null): boolean {
|
||||
return value === "true";
|
||||
}
|
||||
|
||||
interface CloudCliStatus {
|
||||
readonly desired: boolean;
|
||||
readonly authenticated: boolean;
|
||||
readonly linked: boolean;
|
||||
readonly cloudUserId: string | null;
|
||||
readonly relayUrl: string | null;
|
||||
readonly publishAgentActivity: boolean;
|
||||
readonly relayClient: RelayClient.RelayClientStatus;
|
||||
}
|
||||
|
||||
@@ -104,6 +117,7 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
|
||||
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
|
||||
` Environment link: ${provisioned}`,
|
||||
` Relay: ${status.relayUrl ?? "not provisioned"}`,
|
||||
` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
|
||||
...formatRelayClientStatus(status.relayClient),
|
||||
...(nextStep ? ["", `Next: ${nextStep}`] : []),
|
||||
].join("\n");
|
||||
@@ -368,31 +382,52 @@ const connectLoginCommand = Command.make("login", {
|
||||
|
||||
const connectLinkCommand = Command.make("link", {
|
||||
...projectLocationFlags,
|
||||
publishOnly: Flag.boolean("publish-only").pipe(
|
||||
Flag.withDescription(
|
||||
"Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
|
||||
),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Authorize this environment for T3 Connect on next start."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const installed = yield* acquireRelayClientForLink(
|
||||
relayClient,
|
||||
confirmRelayClientInstall,
|
||||
reportRelayClientInstallProgress,
|
||||
);
|
||||
if (Option.isNone(installed)) {
|
||||
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
|
||||
return;
|
||||
// A publish-only link needs no Cloudflare tunnel, so skip installing the
|
||||
// relay client entirely.
|
||||
if (!flags.publishOnly) {
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const installed = yield* acquireRelayClientForLink(
|
||||
relayClient,
|
||||
confirmRelayClientInstall,
|
||||
reportRelayClientInstallProgress,
|
||||
);
|
||||
if (Option.isNone(installed)) {
|
||||
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
|
||||
);
|
||||
}
|
||||
yield* Console.log(
|
||||
`Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
|
||||
);
|
||||
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
yield* tokens.get;
|
||||
yield* CliState.setCliDesiredCloudLink(true);
|
||||
yield* CliState.setCliDesiredCloudLink(
|
||||
true,
|
||||
flags.publishOnly ? "publish_only" : "managed",
|
||||
);
|
||||
if (flags.publishOnly) {
|
||||
// A publish-only link exists solely to publish; without the publish
|
||||
// flag the link would be inert and the success message a lie.
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
|
||||
}
|
||||
yield* Console.log(
|
||||
"This T3 environment will be available through T3 Connect the next time T3 starts.",
|
||||
flags.publishOnly
|
||||
? "This environment will publish agent activity to your mobile clients the next time T3 starts (no managed tunnel)."
|
||||
: "This T3 environment will be available through T3 Connect the next time T3 starts.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
@@ -411,22 +446,27 @@ const connectStatusCommand = Command.make("status", {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
|
||||
[
|
||||
CliState.readCliDesiredCloudLink,
|
||||
tokens.hasCredential,
|
||||
secrets.get(CLOUD_LINKED_USER_ID),
|
||||
secrets.get(RELAY_URL_SECRET),
|
||||
relayClient.resolve,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const [desired, authenticated, cloudUserId, relayUrl, publishAgentActivity, executable] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
CliState.readCliDesiredCloudLink,
|
||||
tokens.hasCredential,
|
||||
secrets.get(CLOUD_LINKED_USER_ID),
|
||||
secrets.get(RELAY_URL_SECRET),
|
||||
secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
|
||||
relayClient.resolve,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const status: CloudCliStatus = {
|
||||
desired,
|
||||
authenticated,
|
||||
linked: Option.isSome(cloudUserId),
|
||||
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
|
||||
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
|
||||
publishAgentActivity: isPublishAgentActivityEnabledValue(
|
||||
Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,
|
||||
),
|
||||
relayClient: executable,
|
||||
};
|
||||
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
|
||||
@@ -438,6 +478,76 @@ const connectStatusCommand = Command.make("status", {
|
||||
),
|
||||
);
|
||||
|
||||
const connectPublishCommand = Command.make("publish", {
|
||||
...projectLocationFlags,
|
||||
disable: Flag.boolean("disable").pipe(
|
||||
Flag.withDescription("Stop publishing agent activity to your mobile clients."),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription(
|
||||
"Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
const enabled = !flags.disable;
|
||||
yield* secrets.set(
|
||||
PUBLISH_AGENT_ACTIVITY_SECRET,
|
||||
stringToBytes(enabled ? "true" : "false"),
|
||||
);
|
||||
if (!enabled) {
|
||||
// If enabling scheduled a publish-only link that hasn't been
|
||||
// provisioned yet, disabling must cancel it too — otherwise the next
|
||||
// start still links an environment whose only purpose was publishing.
|
||||
// A pending managed link is left alone; it exists for the tunnel.
|
||||
const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
|
||||
if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") {
|
||||
yield* CliState.setCliDesiredCloudLink(false);
|
||||
yield* Console.log("Cancelled the pending publish-only T3 Connect link.");
|
||||
}
|
||||
yield* Console.log("Publishing agent activity disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Console.log("Publishing agent activity enabled.");
|
||||
const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
|
||||
if (linked) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Publishing needs the relay to know this environment belongs to you.
|
||||
// Establish a tunnel-free publish-only link automatically so signing in
|
||||
// is all it takes — the mobile client can still reach the environment
|
||||
// out of band without T3 Connect.
|
||||
if (!(yield* tokens.hasCredential)) {
|
||||
yield* Console.log(
|
||||
"Run `t3 connect login` first so this environment can be authorized to publish.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
// A link may already be desired (e.g. `t3 connect link` before the
|
||||
// server's first start). Never downgrade it: a desired managed link
|
||||
// also covers publishing, so only request a publish-only link when no
|
||||
// link is pending at all.
|
||||
if (yield* CliState.readCliDesiredCloudLink) {
|
||||
yield* Console.log(
|
||||
"A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
yield* CliState.setCliDesiredCloudLink(true, "publish_only");
|
||||
yield* Console.log(
|
||||
"Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectUnlinkCommand = Command.make("unlink", {
|
||||
...projectLocationFlags,
|
||||
}).pipe(
|
||||
@@ -461,6 +571,7 @@ export const connectCommand = Command.make("connect").pipe(
|
||||
Command.withSubcommands([
|
||||
connectLoginCommand,
|
||||
connectLinkCommand,
|
||||
connectPublishCommand,
|
||||
connectStatusCommand,
|
||||
connectUnlinkCommand,
|
||||
connectLogoutCommand,
|
||||
|
||||
@@ -56,4 +56,27 @@ it.layer(NodeServices.layer)("CliState", (it) => {
|
||||
}
|
||||
}).pipe(Effect.provide(makeTestLayer())),
|
||||
);
|
||||
|
||||
it.effect("round-trips the desired link mode and defaults legacy links to managed", () =>
|
||||
Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
|
||||
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
|
||||
|
||||
yield* CliState.setCliDesiredCloudLink(true, "publish_only");
|
||||
assert.isTrue(yield* CliState.readCliDesiredCloudLink);
|
||||
assert.equal(yield* CliState.readCliDesiredLinkMode, "publish_only");
|
||||
|
||||
yield* CliState.setCliDesiredCloudLink(true, "managed");
|
||||
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
|
||||
|
||||
// A pre-existing link persisted the literal "true"; treat it as managed.
|
||||
yield* secrets.set(CliState.CLOUD_CLI_DESIRED_LINK_SECRET, new TextEncoder().encode("true"));
|
||||
assert.isTrue(yield* CliState.readCliDesiredCloudLink);
|
||||
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
|
||||
|
||||
yield* CliState.setCliDesiredCloudLink(false);
|
||||
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
|
||||
}).pipe(Effect.provide(makeTestLayer())),
|
||||
);
|
||||
});
|
||||
@@ -14,19 +14,43 @@ import {
|
||||
|
||||
export const CLOUD_CLI_DESIRED_LINK_SECRET = "cloud-cli-desired-link";
|
||||
|
||||
const TRUE_BYTES = new TextEncoder().encode("true");
|
||||
// "managed" provisions a Cloudflare tunnel (default, legacy value "true").
|
||||
// "publish_only" links the environment to the relay purely to publish agent
|
||||
// activity — no tunnel, no relay-advertised endpoint — so activity can flow to
|
||||
// mobile clients even when they reach the environment out of band (Tailscale,
|
||||
// direct pairing) without T3 Connect.
|
||||
export type CliDesiredLinkMode = "managed" | "publish_only";
|
||||
|
||||
const MANAGED_BYTES = new TextEncoder().encode("managed");
|
||||
const PUBLISH_ONLY_BYTES = new TextEncoder().encode("publish_only");
|
||||
|
||||
export const readCliDesiredCloudLink = Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
return Option.isSome(yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET));
|
||||
});
|
||||
|
||||
export const readCliDesiredLinkMode = Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const value = yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET);
|
||||
if (Option.isNone(value)) {
|
||||
return "managed" as CliDesiredLinkMode;
|
||||
}
|
||||
// Legacy links stored the literal "true" and are always managed.
|
||||
return new TextDecoder().decode(value.value) === "publish_only"
|
||||
? ("publish_only" as CliDesiredLinkMode)
|
||||
: ("managed" as CliDesiredLinkMode);
|
||||
});
|
||||
|
||||
export const setCliDesiredCloudLink = Effect.fn("cloud.cli_state.set_desired")(function* (
|
||||
desired: boolean,
|
||||
mode: CliDesiredLinkMode = "managed",
|
||||
) {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
if (desired) {
|
||||
yield* secrets.set(CLOUD_CLI_DESIRED_LINK_SECRET, TRUE_BYTES);
|
||||
yield* secrets.set(
|
||||
CLOUD_CLI_DESIRED_LINK_SECRET,
|
||||
mode === "publish_only" ? PUBLISH_ONLY_BYTES : MANAGED_BYTES,
|
||||
);
|
||||
} else {
|
||||
yield* secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,13 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
|
||||
import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
|
||||
import {
|
||||
consumeCloudReplayGuards,
|
||||
isSupportedLinkProviderKind,
|
||||
linkProofScopes,
|
||||
reconcileDesiredCloudLink,
|
||||
} from "./http.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
|
||||
|
||||
@@ -205,3 +211,32 @@ describe("reconcileDesiredCloudLink", () => {
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("link proof provider kinds", () => {
|
||||
const proofRequest = (
|
||||
providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],
|
||||
): RelayLinkProofRequest => ({
|
||||
challenge: "challenge",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
endpoint: {
|
||||
httpBaseUrl: "http://127.0.0.1:7331",
|
||||
wsBaseUrl: "ws://127.0.0.1:7331",
|
||||
providerKind,
|
||||
},
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },
|
||||
});
|
||||
|
||||
it("accepts managed and manual endpoints but not t3_relay", () => {
|
||||
expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);
|
||||
expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);
|
||||
expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);
|
||||
});
|
||||
|
||||
it("only claims the managed-tunnel scope for tunnel links", () => {
|
||||
expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([
|
||||
"agent_activity_notifications",
|
||||
"managed_tunnels",
|
||||
]);
|
||||
expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);
|
||||
});
|
||||
});
|
||||
@@ -68,7 +68,7 @@ import {
|
||||
RELAY_URL_SECRET,
|
||||
} from "./config.ts";
|
||||
import { relayUrlConfig } from "./publicConfig.ts";
|
||||
import { setCliDesiredCloudLink } from "./CliState.ts";
|
||||
import { readCliDesiredLinkMode, setCliDesiredCloudLink } from "./CliState.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
|
||||
import { traceRelayRequest } from "./traceRelayRequest.ts";
|
||||
@@ -299,8 +299,23 @@ function isAllowedEndpointOrigin(input: {
|
||||
return input.origin.localHttpPort === endpointRequestPort(url);
|
||||
}
|
||||
|
||||
function providerKindMatchesRequestedLinkScopes(request: RelayLinkProofRequest): boolean {
|
||||
return request.endpoint.providerKind === "cloudflare_tunnel";
|
||||
// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must
|
||||
// point at a loopback origin. A manual endpoint is reached out of band (e.g.
|
||||
// Tailscale) or not advertised at all for publish-only links, so it is not
|
||||
// tied to the managed-tunnel scope.
|
||||
export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {
|
||||
return (
|
||||
request.endpoint.providerKind === "cloudflare_tunnel" ||
|
||||
request.endpoint.providerKind === "manual"
|
||||
);
|
||||
}
|
||||
|
||||
export function linkProofScopes(
|
||||
request: RelayLinkProofRequest,
|
||||
): RelayEnvironmentLinkProofPayload["scopes"] {
|
||||
return request.endpoint.providerKind === "cloudflare_tunnel"
|
||||
? ["agent_activity_notifications", "managed_tunnels"]
|
||||
: ["agent_activity_notifications"];
|
||||
}
|
||||
|
||||
function hasExactScope(input: {
|
||||
@@ -352,7 +367,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
|
||||
) {
|
||||
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
|
||||
if (
|
||||
!providerKindMatchesRequestedLinkScopes(request) ||
|
||||
!isSupportedLinkProviderKind(request) ||
|
||||
!isAllowedEndpointOrigin({
|
||||
origin: request.origin,
|
||||
requestUrl,
|
||||
@@ -379,7 +394,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
|
||||
environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
|
||||
endpoint: request.endpoint,
|
||||
origin: request.origin,
|
||||
scopes: ["agent_activity_notifications", "managed_tunnels"],
|
||||
scopes: linkProofScopes(request),
|
||||
} satisfies RelayEnvironmentLinkProofPayload;
|
||||
return yield* signRelayJwt({
|
||||
privateKey: keyPair.privateKey,
|
||||
@@ -537,6 +552,8 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
}),
|
||||
),
|
||||
);
|
||||
const mode = yield* readCliDesiredLinkMode;
|
||||
const managedTunnelsEnabled = mode !== "publish_only";
|
||||
const relayUrl = yield* requireRelayUrl;
|
||||
const challenge = yield* relayClientRequest(dependencies, {
|
||||
url: `${relayUrl}/v1/client/environment-link-challenges`,
|
||||
@@ -544,7 +561,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
payload: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
managedTunnelsEnabled,
|
||||
},
|
||||
schema: RelayEnvironmentLinkChallengeResponse,
|
||||
});
|
||||
@@ -556,7 +573,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
endpoint: {
|
||||
httpBaseUrl: localOrigin,
|
||||
wsBaseUrl: localWsOrigin,
|
||||
providerKind: "cloudflare_tunnel",
|
||||
providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
|
||||
},
|
||||
origin: {
|
||||
localHttpHost: localUrl.hostname,
|
||||
@@ -572,11 +589,11 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
proof,
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
managedTunnelsEnabled,
|
||||
},
|
||||
schema: RelayEnvironmentLinkResponse,
|
||||
});
|
||||
yield* setCliDesiredCloudLink(true);
|
||||
yield* setCliDesiredCloudLink(true, mode);
|
||||
return yield* applyCloudRelayConfig(dependencies, {
|
||||
relayUrl,
|
||||
relayIssuer: link.relayIssuer,
|
||||
@@ -608,20 +625,25 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
|
||||
const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
|
||||
dependencies: CloudHttpDependencies,
|
||||
) {
|
||||
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity] = yield* Effect.all(
|
||||
[
|
||||
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
|
||||
dependencies.secrets.get(RELAY_URL_SECRET),
|
||||
dependencies.secrets.get(RELAY_ISSUER_SECRET),
|
||||
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
|
||||
],
|
||||
{ concurrency: 4 },
|
||||
);
|
||||
const [cloudUserId, relayUrl, relayIssuer, endpointRuntimeConfig, publishAgentActivity] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
|
||||
dependencies.secrets.get(RELAY_URL_SECRET),
|
||||
dependencies.secrets.get(RELAY_ISSUER_SECRET),
|
||||
dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),
|
||||
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
|
||||
],
|
||||
{ concurrency: 5 },
|
||||
);
|
||||
return {
|
||||
linked: Option.isSome(cloudUserId),
|
||||
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
|
||||
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
|
||||
relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,
|
||||
// The managed tunnel runtime config is only stored for managed links; a
|
||||
// publish-only link leaves it absent.
|
||||
managedTunnelActive: Option.isSome(endpointRuntimeConfig),
|
||||
publishAgentActivity: Option.isSome(publishAgentActivity)
|
||||
? bytesToString(publishAgentActivity.value) === "true"
|
||||
: false,
|
||||
|
||||
@@ -200,6 +200,7 @@ describe("OrchestrationEngine", () => {
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
|
||||
@@ -306,8 +306,8 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
|
||||
);
|
||||
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive);
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive, limit);
|
||||
|
||||
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ProjectScript,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
@@ -2033,6 +2034,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const getThreadDetailSnapshot: ProjectionSnapshotQueryShape["getThreadDetailSnapshot"] = (
|
||||
threadId,
|
||||
) =>
|
||||
// Read the thread detail and the snapshot sequence within a single
|
||||
// transaction so the sequence is consistent with the returned state; a
|
||||
// projector update landing between two separate reads could otherwise return
|
||||
// a sequence ahead of the thread detail, causing the client to resume from
|
||||
// too far and drop events.
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const thread = yield* getThreadDetailById(threadId);
|
||||
if (Option.isNone(thread)) {
|
||||
return Option.none<OrchestrationThreadDetailSnapshot>();
|
||||
}
|
||||
const { snapshotSequence } = yield* getSnapshotSequence();
|
||||
return Option.some({ snapshotSequence, thread: thread.value });
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
isPersistenceError(error)
|
||||
? error
|
||||
: toPersistenceSqlError("ProjectionSnapshotQuery.getThreadDetailSnapshot:transaction")(
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
getCommandReadModel,
|
||||
getSnapshot,
|
||||
@@ -2047,6 +2077,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
getFullThreadDiffContext,
|
||||
getThreadShellById,
|
||||
getThreadDetailById,
|
||||
getThreadDetailSnapshot,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -26,10 +26,15 @@ export interface OrchestrationEngineShape {
|
||||
* Replay persisted orchestration events from an exclusive sequence cursor.
|
||||
*
|
||||
* @param fromSequenceExclusive - Sequence cursor (exclusive).
|
||||
* @param limit - Maximum number of events to read. Defaults to the event
|
||||
* store's page-bounded default; pass a higher value when the caller must
|
||||
* read every event after the cursor (e.g. per-thread catch-up that filters
|
||||
* a small subset out of a potentially larger global range).
|
||||
* @returns Stream containing ordered events.
|
||||
*/
|
||||
readonly readEvents: (
|
||||
fromSequenceExclusive: number,
|
||||
limit?: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
OrchestrationThreadShell,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -157,6 +158,16 @@ export interface ProjectionSnapshotQueryShape {
|
||||
readonly getThreadDetailById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread detail together with the projection snapshot
|
||||
* sequence in one consistent transaction, so the returned `snapshotSequence`
|
||||
* exactly matches the state reflected in `thread` (no interleaving projector
|
||||
* update between the two reads).
|
||||
*/
|
||||
readonly getThreadDetailSnapshot: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import { normalizeDispatchCommand } from "./Normalizer.ts";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
annotateEnvironmentRequest,
|
||||
failEnvironmentInternal,
|
||||
failEnvironmentInvalidRequest,
|
||||
failEnvironmentNotFound,
|
||||
requireEnvironmentScope,
|
||||
} from "../auth/http.ts";
|
||||
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
|
||||
@@ -38,6 +40,38 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"shellSnapshot",
|
||||
Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
|
||||
return yield* projectionSnapshotQuery
|
||||
.getShellSnapshot()
|
||||
.pipe(
|
||||
Effect.catch((cause) =>
|
||||
failEnvironmentInternal("orchestration_snapshot_failed", cause),
|
||||
),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"threadSnapshot",
|
||||
Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
|
||||
const snapshot = yield* projectionSnapshotQuery
|
||||
.getThreadDetailSnapshot(args.params.threadId)
|
||||
.pipe(
|
||||
Effect.catch((cause) =>
|
||||
failEnvironmentInternal("orchestration_thread_snapshot_failed", cause),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(snapshot)) {
|
||||
return yield* failEnvironmentNotFound("thread_not_found");
|
||||
}
|
||||
return snapshot.value;
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"dispatch",
|
||||
Effect.fn("environment.orchestration.dispatch")(function* (args) {
|
||||
|
||||
@@ -43,6 +43,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
});
|
||||
|
||||
const makeTerminalManagerLayer = (
|
||||
|
||||
@@ -209,6 +209,7 @@ describe("ProviderSessionReaper", () => {
|
||||
: Option.none(),
|
||||
),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -203,6 +203,26 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
|
||||
return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
|
||||
});
|
||||
|
||||
// Compact, log-safe view of the fields the awareness phase ladder reads.
|
||||
export function describeThreadShellForAwareness(
|
||||
thread: Option.Option<OrchestrationThreadShell>,
|
||||
): Record<string, unknown> {
|
||||
if (Option.isNone(thread)) {
|
||||
return { found: false };
|
||||
}
|
||||
const shell = thread.value;
|
||||
return {
|
||||
found: true,
|
||||
sessionStatus: shell.session?.status ?? null,
|
||||
sessionActiveTurnId: shell.session?.activeTurnId ?? null,
|
||||
latestTurnId: shell.latestTurn?.turnId ?? null,
|
||||
latestTurnState: shell.latestTurn?.state ?? null,
|
||||
latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null,
|
||||
hasPendingApprovals: shell.hasPendingApprovals,
|
||||
hasPendingUserInput: shell.hasPendingUserInput,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAgentAwarenessRelayPublishSnapshot(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
@@ -306,6 +326,14 @@ export const make = Effect.gen(function* () {
|
||||
transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
|
||||
}).pipe(Effect.provide(FetchHttpClient.layer));
|
||||
|
||||
// Deadlines for publishes that need confirmation (tombstones and
|
||||
// first-state completions). The confirming publish is re-enqueued through
|
||||
// the same drainable worker as every other publish, so a confirmed
|
||||
// tombstone can never race an in-flight live update; a recovered state
|
||||
// clears the deadline. Assigned after the worker exists.
|
||||
const publishConfirmDeadlines = new Map<ThreadId, number>();
|
||||
let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
|
||||
|
||||
const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
|
||||
const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
@@ -382,6 +410,11 @@ export const make = Effect.gen(function* () {
|
||||
const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
|
||||
const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
|
||||
if (publishedStateByThread.get(threadId) === publishIdentity) {
|
||||
// The projection is back at (or never left) the last published state, so
|
||||
// any pending deferred confirmation is moot. Leaving the deadline in
|
||||
// place would let a much later transient null find it already expired
|
||||
// and publish a tombstone immediately, skipping the deferral window.
|
||||
publishConfirmDeadlines.delete(threadId);
|
||||
yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -390,6 +423,50 @@ export const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
// Two projections need confirmation before publishing, because both can
|
||||
// appear transiently while the projector is mid-write and publishing them
|
||||
// immediately is destructive or noisy:
|
||||
// - null (tombstone) while the previous published state was live: deletes
|
||||
// the thread from every armed card mid-conversation.
|
||||
// - completed as the thread's FIRST published state: sessions boot at
|
||||
// "ready" before their first turn, which projects as completed for an
|
||||
// instant and sends a spurious Done notification at thread birth.
|
||||
// Defer, schedule a re-publish through the ordinary worker queue, and
|
||||
// only publish if the projection still holds when it drains.
|
||||
const requiresConfirmation =
|
||||
(snapshot.state === null &&
|
||||
publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
|
||||
(snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
|
||||
if (requiresConfirmation) {
|
||||
const nowMs = (yield* DateTime.now).epochMilliseconds;
|
||||
const deadline = publishConfirmDeadlines.get(threadId);
|
||||
if (deadline === undefined) {
|
||||
publishConfirmDeadlines.set(threadId, nowMs + 5_000);
|
||||
yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
|
||||
environmentId,
|
||||
threadId,
|
||||
reason: snapshot.reason,
|
||||
statePhase: snapshot.state?.phase ?? null,
|
||||
shell: describeThreadShellForAwareness(thread),
|
||||
});
|
||||
yield* schedulePublishConfirm(threadId);
|
||||
return;
|
||||
}
|
||||
if (nowMs < deadline) {
|
||||
return;
|
||||
}
|
||||
publishConfirmDeadlines.delete(threadId);
|
||||
yield* Effect.logInfo("agent activity deferred publish confirmed", {
|
||||
environmentId,
|
||||
threadId,
|
||||
reason: snapshot.reason,
|
||||
statePhase: snapshot.state?.phase ?? null,
|
||||
shell: describeThreadShellForAwareness(thread),
|
||||
});
|
||||
} else {
|
||||
publishConfirmDeadlines.delete(threadId);
|
||||
}
|
||||
|
||||
if (snapshot.reason === "thread-not-found") {
|
||||
yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
|
||||
environmentId,
|
||||
@@ -478,6 +555,19 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const worker = yield* makeDrainableWorker(publishThread);
|
||||
|
||||
schedulePublishConfirm = (threadId) =>
|
||||
Effect.forkDetach(
|
||||
Effect.sleep("5 seconds").pipe(
|
||||
Effect.andThen(worker.enqueue(threadId)),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("deferred agent activity confirmation failed", {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
|
||||
function* () {
|
||||
const [relayConfig, publishEnabled] = yield* Effect.all([
|
||||
|
||||
@@ -702,6 +702,7 @@ const buildAppUnderTest = (options?: {
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
@@ -1699,7 +1700,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects managed cloud link proofs for manual endpoint providers", () =>
|
||||
it.effect("rejects cloud link proofs for unsupported endpoint providers", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
@@ -1720,7 +1721,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
wsBaseUrl: linkProofUrl
|
||||
.replace("http://", "ws://")
|
||||
.replace("/api/connect/link-proof", "/ws"),
|
||||
providerKind: "manual",
|
||||
// "manual" and "cloudflare_tunnel" are supported; "t3_relay" is not.
|
||||
providerKind: "t3_relay",
|
||||
},
|
||||
origin: {
|
||||
localHttpHost: "127.0.0.1",
|
||||
|
||||
@@ -96,6 +96,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
Effect.provideService(AnalyticsService.AnalyticsService, {
|
||||
record: () => Effect.void,
|
||||
@@ -158,6 +159,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
@@ -200,6 +202,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
@@ -248,6 +251,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
|
||||
+109
-40
@@ -30,6 +30,8 @@ import {
|
||||
OrchestrationDispatchCommandError,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationShellStreamEvent,
|
||||
type OrchestrationShellStreamItem,
|
||||
type OrchestrationThreadStreamItem,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
@@ -1059,10 +1061,54 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: (_input) =>
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: (input) =>
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
Effect.gen(function* () {
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.mapEffect(toShellStreamEvent),
|
||||
Stream.flatMap((event) =>
|
||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
||||
),
|
||||
);
|
||||
|
||||
// When the client already holds a shell snapshot (cached, or loaded
|
||||
// over HTTP) it passes that snapshot's sequence, and we resume by
|
||||
// replaying shell events after it instead of re-sending the whole
|
||||
// projects/threads list over the socket. As in the thread path, the
|
||||
// live subscription is attached (into a scope-bound buffer) before
|
||||
// draining the catch-up replay so no event published during the
|
||||
// replay window is lost; overlapping events are deduped by sequence
|
||||
// on the client. The full range is read (not the store's default
|
||||
// page limit) since the shell filter runs after reading.
|
||||
if (input.afterSequence !== undefined) {
|
||||
const afterSequence = input.afterSequence;
|
||||
return Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const liveBuffer = yield* Queue.unbounded<OrchestrationShellStreamItem>();
|
||||
yield* Effect.forkScoped(
|
||||
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
||||
);
|
||||
const catchUpStream = orchestrationEngine
|
||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
||||
.pipe(
|
||||
Stream.mapEffect(toShellStreamEvent),
|
||||
Stream.flatMap((event) =>
|
||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
||||
),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to replay orchestration shell events",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("orchestration shell snapshot load failed", { cause }),
|
||||
@@ -1076,13 +1122,6 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
);
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.mapEffect(toShellStreamEvent),
|
||||
Stream.flatMap((event) =>
|
||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
||||
),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
@@ -1114,8 +1153,65 @@ const makeWsRpcLayer = (
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_WS_METHODS.subscribeThread,
|
||||
Effect.gen(function* () {
|
||||
const [threadDetail, snapshotSequence] = yield* Effect.all([
|
||||
projectionSnapshotQuery.getThreadDetailById(input.threadId).pipe(
|
||||
const isThisThreadDetailEvent = (event: OrchestrationEvent) =>
|
||||
event.aggregateKind === "thread" &&
|
||||
event.aggregateId === input.threadId &&
|
||||
isThreadDetailEvent(event);
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event,
|
||||
})),
|
||||
);
|
||||
|
||||
// When the client already loaded the snapshot over HTTP it passes
|
||||
// that snapshot's sequence, and we resume the live subscription by
|
||||
// replaying persisted events after it instead of re-sending the
|
||||
// (potentially multi-KB) snapshot frame over the socket.
|
||||
//
|
||||
// The live PubSub subscription must be attached *before* draining
|
||||
// the catch-up replay, otherwise events published during the replay
|
||||
// window are dropped (they are past the persisted tail the replay
|
||||
// read, but the live stream is not yet subscribed). So fork the
|
||||
// live stream into a buffer bound to this stream's scope, then emit
|
||||
// catch-up followed by the buffered/ongoing live events. Overlapping
|
||||
// events are deduped by sequence on the client.
|
||||
//
|
||||
// Read the full range after the cursor (not the store's default
|
||||
// page-bounded limit): the range is normally tiny (a fresh HTTP
|
||||
// snapshot sequence) and the per-thread filter runs after reading,
|
||||
// so a global cap could otherwise omit this thread's events.
|
||||
if (input.afterSequence !== undefined) {
|
||||
const afterSequence = input.afterSequence;
|
||||
return Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
|
||||
yield* Effect.forkScoped(
|
||||
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
||||
);
|
||||
const catchUpStream = orchestrationEngine
|
||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
||||
.pipe(
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({ kind: "event" as const, event })),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: `Failed to replay thread ${input.threadId} events`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const snapshot = yield* projectionSnapshotQuery
|
||||
.getThreadDetailSnapshot(input.threadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
@@ -1123,46 +1219,19 @@ const makeWsRpcLayer = (
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
projectionSnapshotQuery.getSnapshotSequence().pipe(
|
||||
Effect.map(({ snapshotSequence }) => snapshotSequence),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration snapshot sequence",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
]);
|
||||
);
|
||||
|
||||
if (Option.isNone(threadDetail)) {
|
||||
if (Option.isNone(snapshot)) {
|
||||
return yield* new OrchestrationGetSnapshotError({
|
||||
message: `Thread ${input.threadId} was not found`,
|
||||
cause: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.aggregateKind === "thread" &&
|
||||
event.aggregateId === input.threadId &&
|
||||
isThreadDetailEvent(event),
|
||||
),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event,
|
||||
})),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot: {
|
||||
snapshotSequence,
|
||||
thread: threadDetail.value,
|
||||
},
|
||||
snapshot: snapshot.value,
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
/**
|
||||
* Accounts that opted out of the post-sign-in T3 Connect onboarding wizard
|
||||
* ("Don't show this again"). The wizard otherwise shows on every sign-in,
|
||||
* since sign-out clears the connected environments.
|
||||
*/
|
||||
export const CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY = "t3code:connect-onboarding-opt-out:v1";
|
||||
|
||||
export const ConnectOnboardingOptOutSchema = Schema.Struct({
|
||||
optOutAccounts: Schema.Array(Schema.String),
|
||||
});
|
||||
|
||||
export type ConnectOnboardingOptOutState = typeof ConnectOnboardingOptOutSchema.Type;
|
||||
|
||||
export const EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE: ConnectOnboardingOptOutState = {
|
||||
optOutAccounts: [],
|
||||
};
|
||||
@@ -204,6 +204,7 @@ describe("web cloud link environment client", () => {
|
||||
cloudUserId: "user-1",
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
managedTunnelActive: true,
|
||||
publishAgentActivity: false,
|
||||
}),
|
||||
);
|
||||
@@ -217,6 +218,7 @@ describe("web cloud link environment client", () => {
|
||||
cloudUserId: "user-1",
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
managedTunnelActive: true,
|
||||
publishAgentActivity: false,
|
||||
}),
|
||||
);
|
||||
@@ -234,6 +236,7 @@ describe("web cloud link environment client", () => {
|
||||
cloudUserId: "user-1",
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
managedTunnelActive: true,
|
||||
publishAgentActivity: false,
|
||||
}),
|
||||
);
|
||||
@@ -261,6 +264,7 @@ describe("web cloud link environment client", () => {
|
||||
cloudUserId: "user-1",
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
managedTunnelActive: true,
|
||||
publishAgentActivity: true,
|
||||
}),
|
||||
);
|
||||
@@ -339,6 +343,57 @@ describe("web cloud link environment client", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("links publish-only without a managed tunnel", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({
|
||||
challenge: "challenge",
|
||||
expiresAt: "2026-06-06T00:05:00.000Z",
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(Response.json("signed-proof"))
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({
|
||||
ok: true,
|
||||
environmentId: TARGET.environmentId,
|
||||
endpoint: {
|
||||
httpBaseUrl: TARGET.httpBaseUrl,
|
||||
wsBaseUrl: TARGET.wsBaseUrl,
|
||||
providerKind: "manual",
|
||||
},
|
||||
endpointRuntime: null,
|
||||
relayIssuer: "https://relay.example.test",
|
||||
cloudUserId: "user-1",
|
||||
environmentCredential: "environment-credential",
|
||||
cloudMintPublicKey: "public-key",
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
yield* withServices(
|
||||
linkPrimaryEnvironmentToCloud({
|
||||
target: TARGET,
|
||||
clerkToken: "clerk-token",
|
||||
mode: "publish_only",
|
||||
}),
|
||||
);
|
||||
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
|
||||
managedTunnelsEnabled: false,
|
||||
});
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
|
||||
endpoint: { providerKind: "manual" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs a missing relay client before linking", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ malformed: true })));
|
||||
|
||||
@@ -383,9 +383,17 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
|
||||
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
|
||||
}
|
||||
|
||||
// "publish_only" links the environment to the relay for agent-activity
|
||||
// publishing alone: no managed tunnel is provisioned, so it can be toggled
|
||||
// independently of T3 Connect while clients reach the environment out of band.
|
||||
export type CloudLinkMode = "managed" | "publish_only";
|
||||
|
||||
const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
|
||||
|
||||
export function linkPrimaryEnvironmentToCloud(input: {
|
||||
readonly target: CloudLinkTarget;
|
||||
readonly clerkToken: string;
|
||||
readonly mode?: CloudLinkMode;
|
||||
}): Effect.Effect<
|
||||
void,
|
||||
CloudEnvironmentLinkError,
|
||||
@@ -398,9 +406,15 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
message: "T3CODE_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
|
||||
const providerKind = managedTunnelsEnabled
|
||||
? MANAGED_ENDPOINT_PROVIDER_KIND
|
||||
: PUBLISH_ONLY_PROVIDER_KIND;
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
|
||||
yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
|
||||
if (managedTunnelsEnabled) {
|
||||
yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
|
||||
}
|
||||
|
||||
const challenge = yield* relayClient
|
||||
.createEnvironmentLinkChallenge({
|
||||
@@ -408,7 +422,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
payload: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
managedTunnelsEnabled,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
@@ -427,7 +441,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
endpoint: {
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
wsBaseUrl: input.target.wsBaseUrl,
|
||||
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
|
||||
providerKind,
|
||||
},
|
||||
origin: endpointOrigin(input.target.httpBaseUrl),
|
||||
},
|
||||
@@ -440,7 +454,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
proof,
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
managedTunnelsEnabled,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
@@ -450,7 +464,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
);
|
||||
yield* ensureLinkedEnvironmentMatches({
|
||||
expectedEnvironmentId: input.target.environmentId,
|
||||
expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
|
||||
expectedProviderKind: providerKind,
|
||||
link,
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
import {
|
||||
linkPrimaryEnvironmentToCloud,
|
||||
type CloudLinkMode,
|
||||
type CloudLinkTarget,
|
||||
unlinkPrimaryEnvironmentFromCloud,
|
||||
updatePrimaryCloudPreferences,
|
||||
@@ -21,8 +22,11 @@ export const linkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime
|
||||
label: "web:cloud:link-primary-environment",
|
||||
scheduler: cloudLinkScheduler,
|
||||
concurrency: cloudLinkConcurrency,
|
||||
execute: (input: { readonly target: CloudLinkTarget; readonly clerkToken: string }) =>
|
||||
linkPrimaryEnvironmentToCloud(input),
|
||||
execute: (input: {
|
||||
readonly target: CloudLinkTarget;
|
||||
readonly clerkToken: string;
|
||||
readonly mode?: CloudLinkMode;
|
||||
}) => linkPrimaryEnvironmentToCloud(input),
|
||||
});
|
||||
|
||||
export const unlinkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, {
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useAuth } from "@clerk/react";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
settlePromise,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { useState } from "react";
|
||||
|
||||
import { toastManager } from "../components/ui/toast";
|
||||
import { relayEnvironmentDiscovery } from "../state/relay";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import {
|
||||
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
|
||||
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
|
||||
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
|
||||
} from "./linkEnvironmentAtoms";
|
||||
import { usePrimaryCloudLinkState } from "./primaryCloudLinkState";
|
||||
import { resolveRelayClerkTokenOptions } from "./publicConfig";
|
||||
|
||||
export interface CloudLinkDesiredState {
|
||||
readonly managedTunnel: boolean;
|
||||
readonly publish: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives the primary environment's T3 Connect link. T3 Connect (managed
|
||||
* tunnel) and agent-activity publishing are independent capabilities backed by
|
||||
* a single relay link, so consumers express the full desired state and
|
||||
* `reconcileCloudState` applies it: unlink when neither is wanted, otherwise
|
||||
* (re)link with the mode the managed-tunnel bit implies and set the publish
|
||||
* preference. Re-linking only happens when the managed-tunnel mode actually
|
||||
* changes, so flipping publish alone is cheap.
|
||||
*/
|
||||
export function useCloudLinkController() {
|
||||
const { getToken, isSignedIn } = useAuth();
|
||||
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const updatePrimaryEnvironmentPreferences = useAtomCommand(
|
||||
updatePrimaryEnvironmentPreferencesAtom,
|
||||
{ reportFailure: false },
|
||||
);
|
||||
const primaryCloudLinkState = usePrimaryCloudLinkState();
|
||||
const [operationError, setOperationError] = useState<string | null>(null);
|
||||
|
||||
const reportUpdateFailure = (cause: unknown) => {
|
||||
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
|
||||
const traceId = findErrorTraceId(cause);
|
||||
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
|
||||
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not update T3 Connect",
|
||||
description: message,
|
||||
data: traceId
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Copy trace ID",
|
||||
onClick: () => void navigator.clipboard?.writeText(traceId),
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
// Older environment servers predate the managedTunnelActive field; for them a
|
||||
// link always implies a managed tunnel, so fall back to `linked`.
|
||||
const managedTunnelActive =
|
||||
primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;
|
||||
const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
|
||||
const linked = primaryCloudLinkState.data?.linked ?? false;
|
||||
|
||||
const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
|
||||
setOperationError(null);
|
||||
const target = primaryCloudLinkState.target;
|
||||
if (!target) {
|
||||
reportUpdateFailure(new Error("Local environment is not ready yet."));
|
||||
return false;
|
||||
}
|
||||
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
|
||||
if (tokenResult._tag === "Failure") {
|
||||
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
|
||||
return false;
|
||||
}
|
||||
const clerkToken = tokenResult.value;
|
||||
const wantsLink = desired.managedTunnel || desired.publish;
|
||||
|
||||
// A failure after this point may follow a partially applied mutation (e.g.
|
||||
// the link succeeded but the preference update did not), so every exit —
|
||||
// success or failure — refreshes the rendered state to whatever the server
|
||||
// actually holds now.
|
||||
if (!wantsLink) {
|
||||
const unlinkResult = await unlinkPrimaryEnvironment({
|
||||
target,
|
||||
clerkToken: clerkToken ?? null,
|
||||
});
|
||||
if (unlinkResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(unlinkResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
|
||||
}
|
||||
primaryCloudLinkState.refresh();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!clerkToken) {
|
||||
reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
|
||||
return false;
|
||||
}
|
||||
if (!linked || managedTunnelActive !== desired.managedTunnel) {
|
||||
const linkResult = await linkPrimaryEnvironment({
|
||||
target,
|
||||
clerkToken,
|
||||
mode: desired.managedTunnel ? "managed" : "publish_only",
|
||||
});
|
||||
if (linkResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(linkResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(linkResult));
|
||||
}
|
||||
primaryCloudLinkState.refresh();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const prefResult = await updatePrimaryEnvironmentPreferences({
|
||||
target,
|
||||
publishAgentActivity: desired.publish,
|
||||
});
|
||||
if (prefResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(prefResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(prefResult));
|
||||
}
|
||||
primaryCloudLinkState.refresh();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
primaryCloudLinkState.refresh();
|
||||
const refreshResult = await refreshRelayEnvironments();
|
||||
if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(refreshResult));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
return {
|
||||
isSignedIn,
|
||||
linkState: primaryCloudLinkState,
|
||||
linked,
|
||||
managedTunnelActive,
|
||||
publishAgentActivity,
|
||||
operationError,
|
||||
reconcileCloudState,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
|
||||
type ConnectionStatusDotProps = {
|
||||
tooltipText?: string | null;
|
||||
dotClassName: string;
|
||||
pingClassName?: string | null;
|
||||
};
|
||||
|
||||
export function ConnectionStatusDot({
|
||||
tooltipText,
|
||||
dotClassName,
|
||||
pingClassName,
|
||||
}: ConnectionStatusDotProps) {
|
||||
const dotContent = (
|
||||
<>
|
||||
{pingClassName ? (
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inline-flex h-full w-full animate-ping rounded-full",
|
||||
pingClassName,
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
<span className={cn("relative inline-flex size-2 rounded-full", dotClassName)} />
|
||||
</>
|
||||
);
|
||||
|
||||
if (!tooltipText) {
|
||||
return (
|
||||
<span className="relative flex size-3 shrink-0 items-center justify-center">
|
||||
{dotContent}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const dot = (
|
||||
<button
|
||||
type="button"
|
||||
title={tooltipText}
|
||||
aria-label={tooltipText}
|
||||
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
|
||||
>
|
||||
{dotContent}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={dot} />
|
||||
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
|
||||
{tooltipText}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -5,27 +5,12 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import {
|
||||
memo,
|
||||
useMemo,
|
||||
useState,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
forwardRef,
|
||||
type ChangeEvent,
|
||||
type KeyboardEvent,
|
||||
} from "react";
|
||||
import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import { ModelListRow } from "./ModelListRow";
|
||||
import { ModelPickerSidebar } from "./ModelPickerSidebar";
|
||||
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
|
||||
import {
|
||||
buildModelPickerSearchText,
|
||||
normalizeModelPickerSearchQuery,
|
||||
scoreModelPickerSearch,
|
||||
} from "./modelPickerSearch";
|
||||
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
|
||||
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxListVirtualized } from "../ui/combobox";
|
||||
import { ModelEsque } from "./providerIconUtils";
|
||||
import {
|
||||
@@ -58,10 +43,6 @@ type ModelPickerItem = {
|
||||
|
||||
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
|
||||
|
||||
const SEARCH_ICON = (
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
);
|
||||
|
||||
// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs
|
||||
// can contain colons (e.g. some vendor model ids), so we only split on the
|
||||
// first colon — anything after that is the slug.
|
||||
@@ -76,111 +57,6 @@ function splitInstanceModelKey(key: string): { instanceId: ProviderInstanceId; s
|
||||
};
|
||||
}
|
||||
|
||||
const ModelPickerSearchInput = memo(
|
||||
forwardRef<
|
||||
HTMLInputElement,
|
||||
{
|
||||
onSearchQueryChange: (query: string) => void;
|
||||
onRequestClose: (() => void) | undefined;
|
||||
onSelectHighlightedModel: () => boolean;
|
||||
}
|
||||
>(function ModelPickerSearchInput(
|
||||
{ onSearchQueryChange, onRequestClose, onSelectHighlightedModel },
|
||||
ref,
|
||||
) {
|
||||
const [rawSearchQuery, setRawSearchQuery] = useState("");
|
||||
const handleChange = useCallback(
|
||||
(event: ChangeEvent<HTMLInputElement>) => {
|
||||
const nextRawSearchQuery = event.target.value;
|
||||
setRawSearchQuery(nextRawSearchQuery);
|
||||
onSearchQueryChange(normalizeModelPickerSearchQuery(nextRawSearchQuery));
|
||||
},
|
||||
[onSearchQueryChange],
|
||||
);
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onRequestClose?.();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter" && onSelectHighlightedModel()) {
|
||||
(event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
event.stopPropagation();
|
||||
},
|
||||
[onRequestClose, onSelectHighlightedModel],
|
||||
);
|
||||
|
||||
return (
|
||||
<ComboboxInput
|
||||
ref={ref}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={SEARCH_ICON}
|
||||
value={rawSearchQuery}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
onTouchStart={(event) => event.stopPropagation()}
|
||||
size="sm"
|
||||
unstyled
|
||||
/>
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
function useModelPickerJumpShortcuts(input: {
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
modelJumpShortcutContext: {
|
||||
readonly terminalFocus: false;
|
||||
readonly terminalOpen: boolean;
|
||||
readonly modelPickerOpen: true;
|
||||
};
|
||||
modelJumpModelKeys: ReadonlyArray<string>;
|
||||
handleModelSelect: (modelSlug: string, instanceId: ProviderInstanceId) => void;
|
||||
}) {
|
||||
const { keybindings, modelJumpShortcutContext, modelJumpModelKeys, handleModelSelect } = input;
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented || event.repeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
platform: navigator.platform,
|
||||
context: modelJumpShortcutContext,
|
||||
});
|
||||
const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
|
||||
if (jumpIndex === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetModelKey = modelJumpModelKeys[jumpIndex];
|
||||
if (!targetModelKey) {
|
||||
return;
|
||||
}
|
||||
const { instanceId, slug } = splitInstanceModelKey(targetModelKey);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleModelSelect(slug, instanceId);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown, true);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown, true);
|
||||
};
|
||||
}, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]);
|
||||
}
|
||||
|
||||
export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
/** The instance currently selected in the composer (combobox "value"). */
|
||||
activeInstanceId: ProviderInstanceId;
|
||||
@@ -242,9 +118,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
[providedKeybindings],
|
||||
);
|
||||
const updateSettings = useUpdateClientSettings();
|
||||
const handleSearchQueryChange = useCallback((nextQuery: string) => {
|
||||
setSearchQuery((currentQuery) => (currentQuery === nextQuery ? currentQuery : nextQuery));
|
||||
}, []);
|
||||
|
||||
const focusSearchInput = useCallback(() => {
|
||||
searchInputRef.current?.focus({ preventScroll: true });
|
||||
@@ -348,7 +221,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
}, [modelOptionsByInstance, entryByInstanceId, readyInstanceSet]);
|
||||
|
||||
const isLocked = props.lockedProvider !== null;
|
||||
const isSearching = searchQuery.length > 0;
|
||||
const isSearching = searchQuery.trim().length > 0;
|
||||
const lockedDisabledInstanceIds = useMemo(() => {
|
||||
if (!isLocked) {
|
||||
return undefined;
|
||||
@@ -388,7 +261,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
let result = flatModels;
|
||||
|
||||
// Apply tokenized fuzzy search across the combined provider/model search fields.
|
||||
if (searchQuery) {
|
||||
if (searchQuery.trim()) {
|
||||
const rankedMatches = result
|
||||
.map((model) => ({
|
||||
model,
|
||||
@@ -512,14 +385,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
},
|
||||
[entryByInstanceId, getModelDisabledReason, modelOptionsByInstance, onInstanceModelChange],
|
||||
);
|
||||
const selectHighlightedModel = useCallback(() => {
|
||||
if (!highlightedModelKeyRef.current) {
|
||||
return false;
|
||||
}
|
||||
const { instanceId, slug } = splitInstanceModelKey(highlightedModelKeyRef.current);
|
||||
handleModelSelect(slug, instanceId);
|
||||
return true;
|
||||
}, [handleModelSelect]);
|
||||
|
||||
const toggleFavorite = useCallback(
|
||||
(instanceId: ProviderInstanceId, model: string) => {
|
||||
@@ -607,12 +472,37 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
|
||||
}, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
|
||||
|
||||
useModelPickerJumpShortcuts({
|
||||
keybindings,
|
||||
modelJumpShortcutContext,
|
||||
modelJumpModelKeys,
|
||||
handleModelSelect,
|
||||
});
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented || event.repeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
platform: navigator.platform,
|
||||
context: modelJumpShortcutContext,
|
||||
});
|
||||
const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
|
||||
if (jumpIndex === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetModelKey = modelJumpModelKeys[jumpIndex];
|
||||
if (!targetModelKey) {
|
||||
return;
|
||||
}
|
||||
const { instanceId, slug } = splitInstanceModelKey(targetModelKey);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleModelSelect(slug, instanceId);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown, true);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown, true);
|
||||
};
|
||||
}, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setShowTopScrollFade(false);
|
||||
@@ -687,11 +577,42 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<ModelPickerSearchInput
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
onSearchQueryChange={handleSearchQueryChange}
|
||||
onRequestClose={props.onRequestClose}
|
||||
onSelectHighlightedModel={selectHighlightedModel}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
props.onRequestClose?.();
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" && highlightedModelKeyRef.current) {
|
||||
(
|
||||
e as typeof e & { preventBaseUIHandler?: () => void }
|
||||
).preventBaseUIHandler?.();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const { instanceId, slug } = splitInstanceModelKey(
|
||||
highlightedModelKeyRef.current,
|
||||
);
|
||||
handleModelSelect(slug, instanceId);
|
||||
return;
|
||||
}
|
||||
e.stopPropagation();
|
||||
}}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onTouchStart={(e) => e.stopPropagation()}
|
||||
size="sm"
|
||||
unstyled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildModelPickerSearchText,
|
||||
normalizeModelPickerSearchQuery,
|
||||
scoreModelPickerSearch,
|
||||
} from "./modelPickerSearch";
|
||||
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
|
||||
|
||||
describe("buildModelPickerSearchText", () => {
|
||||
it("builds provider-agnostic search text from generic fields", () => {
|
||||
@@ -19,12 +15,6 @@ describe("buildModelPickerSearchText", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeModelPickerSearchQuery", () => {
|
||||
it("normalizes casing and redundant whitespace before publishing picker searches", () => {
|
||||
expect(normalizeModelPickerSearchQuery(" GPT Codex ")).toBe("gpt codex");
|
||||
});
|
||||
});
|
||||
|
||||
describe("scoreModelPickerSearch", () => {
|
||||
it("matches typo-tolerant multi-token queries", () => {
|
||||
expect(
|
||||
|
||||
@@ -17,13 +17,6 @@ type ModelPickerSearchableModel = {
|
||||
|
||||
const MODEL_PICKER_FAVORITE_SCORE_BOOST = 24;
|
||||
|
||||
export function normalizeModelPickerSearchQuery(query: string): string {
|
||||
return normalizeSearchQuery(query)
|
||||
.split(/\s+/u)
|
||||
.filter((token) => token.length > 0)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function getModelPickerSearchFields(model: ModelPickerSearchableModel): string[] {
|
||||
return [
|
||||
normalizeSearchQuery(model.name),
|
||||
@@ -63,7 +56,9 @@ export function scoreModelPickerSearch(
|
||||
model: ModelPickerSearchableModel,
|
||||
query: string,
|
||||
): number | null {
|
||||
const tokens = normalizeModelPickerSearchQuery(query).split(/\s+/u).filter(Boolean);
|
||||
const tokens = normalizeSearchQuery(query)
|
||||
.split(/\s+/u)
|
||||
.filter((token) => token.length > 0);
|
||||
|
||||
if (tokens.length === 0) {
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import {
|
||||
RelayConnectionRegistration,
|
||||
RelayConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
|
||||
import * as Option from "effect/Option";
|
||||
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { environmentCatalog } from "~/connection/catalog";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { relayEnvironmentDiscovery } from "~/state/relay";
|
||||
import { useRelayEnvironmentDiscovery } from "~/state/environments";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { ConnectionStatusDot } from "../ConnectionStatusDot";
|
||||
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRows";
|
||||
import { Button } from "../ui/button";
|
||||
import { Skeleton } from "../ui/skeleton";
|
||||
import { toastManager } from "../ui/toast";
|
||||
|
||||
export function RemoteEnvironmentRowsSkeleton() {
|
||||
return (
|
||||
<div className={ITEM_ROW_CLASSNAME}>
|
||||
<div className={ITEM_ROW_INNER_CLASSNAME}>
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-32 rounded-full" />
|
||||
<Skeleton className="h-3 w-20 rounded-full" />
|
||||
</div>
|
||||
<Skeleton className="h-7 w-16 rounded-md" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's T3 Connect environments from relay discovery, each with a
|
||||
* Connect button. The primary environment is always excluded; already-saved
|
||||
* environments are hidden unless `showSavedAsConnected` renders them as
|
||||
* connected instead (used by onboarding, where the full device mesh should be
|
||||
* visible).
|
||||
*/
|
||||
export function CloudEnvironmentConnectRows({
|
||||
primaryEnvironmentId,
|
||||
savedEnvironmentIds,
|
||||
showSavedAsConnected = false,
|
||||
empty = null,
|
||||
}: {
|
||||
readonly primaryEnvironmentId: EnvironmentId | null;
|
||||
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
|
||||
readonly showSavedAsConnected?: boolean;
|
||||
readonly empty?: ReactNode;
|
||||
}) {
|
||||
const environmentsState = useRelayEnvironmentDiscovery();
|
||||
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const connectRelayEnvironment = useCallback(
|
||||
(environment: RelayClientEnvironmentRecord) =>
|
||||
registerEnvironment(
|
||||
new RelayConnectionRegistration({
|
||||
target: new RelayConnectionTarget({
|
||||
environmentId: environment.environmentId,
|
||||
label: environment.label,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
[registerEnvironment],
|
||||
);
|
||||
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
|
||||
null,
|
||||
);
|
||||
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshRelayEnvironments();
|
||||
}, [refreshRelayEnvironments]);
|
||||
|
||||
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
|
||||
setConnectingEnvironmentId(environment.environmentId);
|
||||
const result = await connectRelayEnvironment(environment);
|
||||
setConnectingEnvironmentId(null);
|
||||
if (result._tag === "Success") {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Environment connected",
|
||||
description: `${environment.label} is available through T3 Connect.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (isAtomCommandInterrupted(result)) {
|
||||
return;
|
||||
}
|
||||
const cause = squashAtomCommandFailure(result);
|
||||
const message =
|
||||
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
|
||||
const traceId = findErrorTraceId(cause);
|
||||
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not connect environment",
|
||||
description: message,
|
||||
data: traceId
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Copy trace ID",
|
||||
onClick: () => void navigator.clipboard?.writeText(traceId),
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
const visibleEnvironments = [...environmentsState.environments.values()].filter(
|
||||
({ environment }) =>
|
||||
environment.environmentId !== primaryEnvironmentId &&
|
||||
(showSavedAsConnected || !savedIds.has(environment.environmentId)),
|
||||
);
|
||||
|
||||
const standalone = showSavedAsConnected || savedEnvironmentIds.length === 0;
|
||||
|
||||
if (
|
||||
standalone &&
|
||||
visibleEnvironments.length === 0 &&
|
||||
environmentsState.refreshing &&
|
||||
environmentsState.environments.size === 0
|
||||
) {
|
||||
return <RemoteEnvironmentRowsSkeleton />;
|
||||
}
|
||||
|
||||
if (standalone && visibleEnvironments.length === 0) {
|
||||
return empty;
|
||||
}
|
||||
|
||||
return visibleEnvironments.map(({ environment, availability, error }) => {
|
||||
const alreadyConnected = savedIds.has(environment.environmentId);
|
||||
return (
|
||||
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
|
||||
<div className={ITEM_ROW_INNER_CLASSNAME}>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<ConnectionStatusDot
|
||||
dotClassName={
|
||||
availability === "online"
|
||||
? "bg-success"
|
||||
: availability === "error"
|
||||
? "bg-destructive"
|
||||
: availability === "checking"
|
||||
? "bg-warning"
|
||||
: "bg-muted-foreground/35"
|
||||
}
|
||||
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
|
||||
tooltipText={
|
||||
availability === "online"
|
||||
? "Relay online"
|
||||
: availability === "offline"
|
||||
? "Relay offline"
|
||||
: availability === "checking"
|
||||
? "Checking relay status"
|
||||
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
|
||||
}
|
||||
/>
|
||||
<p className="truncate text-sm font-medium">{environment.label}</p>
|
||||
</div>
|
||||
<p
|
||||
className={cn(
|
||||
"mt-1 truncate text-xs",
|
||||
availability === "error" ? "text-destructive" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{availability === "online"
|
||||
? "Available · Relay online"
|
||||
: availability === "offline"
|
||||
? "Available · Relay offline"
|
||||
: availability === "checking"
|
||||
? "Available · Checking relay status…"
|
||||
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
|
||||
</p>
|
||||
</div>
|
||||
{alreadyConnected ? (
|
||||
<Button size="sm" variant="outline" disabled>
|
||||
Connected
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={connectingEnvironmentId !== null}
|
||||
onClick={() => void connectEnvironment(environment)}
|
||||
>
|
||||
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
import { useAuth } from "@clerk/react";
|
||||
import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
|
||||
ConnectOnboardingOptOutSchema,
|
||||
EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
|
||||
} from "~/cloud/connectOnboarding";
|
||||
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
|
||||
import { usePrimarySessionState } from "~/environments/primary";
|
||||
import { useLocalStorage } from "~/hooks/useLocalStorage";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
|
||||
import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
|
||||
import { Button } from "../ui/button";
|
||||
import { Checkbox } from "../ui/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { toastManager } from "../ui/toast";
|
||||
|
||||
/**
|
||||
* Post-sign-in onboarding wizard for T3 Connect. Opens on every in-session
|
||||
* sign-in — sign-out removes the connected relay environments, so each new
|
||||
* session starts with no devices to reach. It first prompts to publish this
|
||||
* environment (managed tunnel + agent activity, both defaulting on) when the
|
||||
* current session is authorized to manage the relay link, then lists the
|
||||
* account's T3 Connect environments so every device can be connected right
|
||||
* away. A cold load with a restored session does not count as a sign-in.
|
||||
*/
|
||||
export function ConnectOnboardingDialog() {
|
||||
if (!hasCloudPublicConfig()) return null;
|
||||
|
||||
return <ConfiguredConnectOnboardingDialog />;
|
||||
}
|
||||
|
||||
type OnboardingStep = "publish" | "devices";
|
||||
|
||||
function ConfiguredConnectOnboardingDialog() {
|
||||
const { isLoaded, isSignedIn, userId } = useAuth();
|
||||
const [optOutState, setOptOutState] = useLocalStorage(
|
||||
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
|
||||
EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
|
||||
ConnectOnboardingOptOutSchema,
|
||||
);
|
||||
|
||||
const desktopBridge = window.desktopBridge;
|
||||
const primarySessionState = usePrimarySessionState();
|
||||
const currentSessionScopes = desktopBridge
|
||||
? AuthAdministrativeScopes
|
||||
: primarySessionState.data?.authenticated
|
||||
? (primarySessionState.data.scopes ?? null)
|
||||
: null;
|
||||
const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;
|
||||
// The publish step is only offered when we know the answer; opening the
|
||||
// wizard before the session state resolves would let the step set change
|
||||
// mid-flight. A failed session read still opens the wizard — it just means
|
||||
// no publish step.
|
||||
const sessionScopesKnown =
|
||||
Boolean(desktopBridge) ||
|
||||
primarySessionState.data !== null ||
|
||||
primarySessionState.error !== null;
|
||||
|
||||
const controller = useCloudLinkController();
|
||||
const showPublishStep = canManageRelay && controller.linkState.target !== null;
|
||||
const steps: ReadonlyArray<OnboardingStep> = showPublishStep
|
||||
? ["publish", "devices"]
|
||||
: ["devices"];
|
||||
|
||||
const [requestedAccount, setRequestedAccount] = useState<string | null>(null);
|
||||
const [openForAccount, setOpenForAccount] = useState<string | null>(null);
|
||||
const [step, setStep] = useState<OnboardingStep>("devices");
|
||||
const [exposeEnvironment, setExposeEnvironment] = useState(true);
|
||||
const [publishAgentActivity, setPublishAgentActivity] = useState(true);
|
||||
const [dontShowAgain, setDontShowAgain] = useState(false);
|
||||
const [isApplying, setIsApplying] = useState(false);
|
||||
const prefilledFromLinkStateRef = useRef(false);
|
||||
const observedAccountRef = useRef<string | null | undefined>(undefined);
|
||||
|
||||
const optOutAccounts = optOutState.optOutAccounts;
|
||||
|
||||
// Every sign-in that completes during this session requests the wizard. A
|
||||
// cold load observes undefined → account and must not re-prompt — only a
|
||||
// null → account transition is a sign-in.
|
||||
useEffect(() => {
|
||||
if (!isLoaded) return;
|
||||
const previousAccount = observedAccountRef.current;
|
||||
const nextAccount = isSignedIn && userId ? userId : null;
|
||||
observedAccountRef.current = nextAccount;
|
||||
if (previousAccount === null && nextAccount !== null) {
|
||||
setRequestedAccount(nextAccount);
|
||||
}
|
||||
}, [isLoaded, isSignedIn, userId]);
|
||||
|
||||
// Open once the session scopes resolve so the step set is stable. Accounts
|
||||
// that chose "Don't show this again" are skipped.
|
||||
useEffect(() => {
|
||||
if (requestedAccount === null || openForAccount !== null) return;
|
||||
if (optOutAccounts.includes(requestedAccount)) {
|
||||
setRequestedAccount(null);
|
||||
return;
|
||||
}
|
||||
if (!sessionScopesKnown) return;
|
||||
setRequestedAccount(null);
|
||||
prefilledFromLinkStateRef.current = false;
|
||||
setExposeEnvironment(true);
|
||||
setPublishAgentActivity(true);
|
||||
setDontShowAgain(false);
|
||||
setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
|
||||
setOpenForAccount(requestedAccount);
|
||||
}, [
|
||||
canManageRelay,
|
||||
controller.linkState.target,
|
||||
openForAccount,
|
||||
optOutAccounts,
|
||||
requestedAccount,
|
||||
sessionScopesKnown,
|
||||
]);
|
||||
|
||||
// Signing out (or switching accounts) mid-wizard invalidates everything the
|
||||
// wizard would do — close it and let the sign-in trigger re-evaluate.
|
||||
useEffect(() => {
|
||||
if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
|
||||
setOpenForAccount(null);
|
||||
}
|
||||
if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
|
||||
setRequestedAccount(null);
|
||||
}
|
||||
}, [isSignedIn, openForAccount, requestedAccount, userId]);
|
||||
|
||||
// Toggles default on, but an environment that is already linked should show
|
||||
// its actual configuration instead of silently proposing to rewrite it.
|
||||
const linkStateData = controller.linkState.data;
|
||||
useEffect(() => {
|
||||
if (openForAccount === null || prefilledFromLinkStateRef.current || linkStateData === null) {
|
||||
return;
|
||||
}
|
||||
prefilledFromLinkStateRef.current = true;
|
||||
if (linkStateData.linked) {
|
||||
setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
|
||||
setPublishAgentActivity(linkStateData.publishAgentActivity);
|
||||
}
|
||||
}, [linkStateData, openForAccount]);
|
||||
|
||||
const complete = () => {
|
||||
const account = openForAccount;
|
||||
setOpenForAccount(null);
|
||||
if (account !== null && dontShowAgain) {
|
||||
setOptOutState((state) =>
|
||||
state.optOutAccounts.includes(account)
|
||||
? state
|
||||
: { optOutAccounts: [...state.optOutAccounts, account] },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const applyPublishSelection = async () => {
|
||||
// The wizard only ever enables — with both toggles off there is nothing to
|
||||
// apply, and an existing link must not be torn down from onboarding.
|
||||
if (!exposeEnvironment && !publishAgentActivity) {
|
||||
setStep("devices");
|
||||
return;
|
||||
}
|
||||
setIsApplying(true);
|
||||
const ok = await controller.reconcileCloudState({
|
||||
managedTunnel: exposeEnvironment,
|
||||
publish: publishAgentActivity,
|
||||
});
|
||||
setIsApplying(false);
|
||||
if (!ok) return;
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "T3 Connect enabled",
|
||||
description: exposeEnvironment
|
||||
? "This environment is available to your other devices through T3 Connect."
|
||||
: "This environment publishes agent activity to your mobile clients.",
|
||||
});
|
||||
setStep("devices");
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={openForAccount !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) complete();
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Set up T3 Connect</DialogTitle>
|
||||
<DialogDescription>
|
||||
Mesh your devices together — publish this environment and connect the rest, all in one
|
||||
place.
|
||||
</DialogDescription>
|
||||
{steps.length > 1 ? (
|
||||
<OnboardingStepper steps={steps} currentStep={step} onStepSelect={setStep} />
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
<DialogPanel>
|
||||
{step === "publish" ? (
|
||||
<PublishStep
|
||||
exposeEnvironment={exposeEnvironment}
|
||||
publishAgentActivity={publishAgentActivity}
|
||||
disabled={isApplying}
|
||||
operationError={controller.operationError}
|
||||
onExposeEnvironmentChange={setExposeEnvironment}
|
||||
onPublishAgentActivityChange={setPublishAgentActivity}
|
||||
/>
|
||||
) : (
|
||||
<DevicesStep />
|
||||
)}
|
||||
</DialogPanel>
|
||||
<DialogFooter variant="bare" className="sm:justify-between">
|
||||
<label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
|
||||
<Checkbox
|
||||
checked={dontShowAgain}
|
||||
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
|
||||
/>
|
||||
Don't show this again
|
||||
</label>
|
||||
<div className="flex flex-col-reverse gap-2 sm:flex-row">
|
||||
{step === "publish" ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
|
||||
Not now
|
||||
</Button>
|
||||
<Button
|
||||
disabled={
|
||||
isApplying || (controller.linkState.isPending && linkStateData === null)
|
||||
}
|
||||
onClick={() => void applyPublishSelection()}
|
||||
>
|
||||
{isApplying ? "Enabling…" : "Continue"}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button onClick={complete}>Done</Button>
|
||||
)}
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
const STEP_LABELS: Record<OnboardingStep, string> = {
|
||||
publish: "Publish",
|
||||
devices: "Connect devices",
|
||||
};
|
||||
|
||||
function OnboardingStepper({
|
||||
steps,
|
||||
currentStep,
|
||||
onStepSelect,
|
||||
}: {
|
||||
readonly steps: ReadonlyArray<OnboardingStep>;
|
||||
readonly currentStep: OnboardingStep;
|
||||
readonly onStepSelect: (step: OnboardingStep) => void;
|
||||
}) {
|
||||
const currentIndex = steps.indexOf(currentStep);
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{steps.map((step, index) => (
|
||||
<button
|
||||
key={step}
|
||||
type="button"
|
||||
className={cn(
|
||||
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
|
||||
index === currentIndex
|
||||
? "border-primary bg-primary/10 ring-1 ring-primary/25"
|
||||
: index < currentIndex
|
||||
? "border-border bg-background"
|
||||
: "border-border bg-muted/40",
|
||||
)}
|
||||
onClick={() => onStepSelect(step)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
|
||||
index < currentIndex
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: index === currentIndex
|
||||
? "border-primary bg-background"
|
||||
: "border-muted-foreground/35 bg-background",
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
{index < currentIndex ? <CheckIcon className="size-3" /> : null}
|
||||
</span>
|
||||
<span className="text-[10px] font-medium uppercase text-muted-foreground">
|
||||
Step {index + 1}
|
||||
</span>
|
||||
<span className="truncate text-xs font-semibold text-foreground">
|
||||
{STEP_LABELS[step]}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PublishStep({
|
||||
exposeEnvironment,
|
||||
publishAgentActivity,
|
||||
disabled,
|
||||
operationError,
|
||||
onExposeEnvironmentChange,
|
||||
onPublishAgentActivityChange,
|
||||
}: {
|
||||
readonly exposeEnvironment: boolean;
|
||||
readonly publishAgentActivity: boolean;
|
||||
readonly disabled: boolean;
|
||||
readonly operationError: string | null;
|
||||
readonly onExposeEnvironmentChange: (enabled: boolean) => void;
|
||||
readonly onPublishAgentActivityChange: (enabled: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border">
|
||||
<OnboardingToggleRow
|
||||
title="Publish this environment"
|
||||
description="Make this environment available to your other devices through T3 Connect."
|
||||
checked={exposeEnvironment}
|
||||
disabled={disabled}
|
||||
onCheckedChange={onExposeEnvironmentChange}
|
||||
/>
|
||||
<OnboardingToggleRow
|
||||
title="Publish agent activity"
|
||||
description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
|
||||
checked={publishAgentActivity}
|
||||
disabled={disabled}
|
||||
onCheckedChange={onPublishAgentActivityChange}
|
||||
/>
|
||||
</div>
|
||||
{operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OnboardingToggleRow({
|
||||
title,
|
||||
description,
|
||||
checked,
|
||||
disabled,
|
||||
onCheckedChange,
|
||||
}: {
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly checked: boolean;
|
||||
readonly disabled: boolean;
|
||||
readonly onCheckedChange: (enabled: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium">{title}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
<Switch
|
||||
aria-label={title}
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onCheckedChange={onCheckedChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DevicesStep() {
|
||||
const { environments } = useEnvironments();
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const savedEnvironmentIds = useMemo(
|
||||
() =>
|
||||
environments
|
||||
.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget")
|
||||
.map((environment) => environment.environmentId),
|
||||
[environments],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<CloudEnvironmentConnectRows
|
||||
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
|
||||
savedEnvironmentIds={savedEnvironmentIds}
|
||||
showSavedAsConnected
|
||||
empty={
|
||||
<p className="px-4 py-6 text-center text-sm text-muted-foreground">
|
||||
No other environments are published to your account yet. Publish one from another device
|
||||
and it will show up here.
|
||||
</p>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,8 +7,7 @@ import {
|
||||
TerminalIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import { useAuth } from "@clerk/react";
|
||||
import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { type ReactNode, memo, useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
AuthAccessReadScope,
|
||||
AuthAccessWriteScope,
|
||||
@@ -30,18 +29,11 @@ import {
|
||||
type DesktopWslState,
|
||||
type EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
connectionStatusText,
|
||||
RelayConnectionRegistration,
|
||||
RelayConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import { connectionStatusText } from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
settlePromise,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
@@ -50,7 +42,6 @@ import { cn } from "../../lib/utils";
|
||||
import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
|
||||
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
|
||||
import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
|
||||
import { resolveRelayClerkTokenOptions } from "../../cloud/publicConfig";
|
||||
import {
|
||||
SettingsPageContainer,
|
||||
SettingsRow,
|
||||
@@ -82,7 +73,6 @@ import {
|
||||
} from "../ui/alert-dialog";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
import { QRCodeSvg } from "../ui/qr-code";
|
||||
import { Skeleton } from "../ui/skeleton";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
@@ -117,13 +107,8 @@ import {
|
||||
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
|
||||
import { useUiStateStore } from "~/uiStateStore";
|
||||
import { resolveServerConfigVersionMismatch } from "~/versionSkew";
|
||||
import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";
|
||||
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
import {
|
||||
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
|
||||
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
|
||||
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
|
||||
} from "~/cloud/linkEnvironmentAtoms";
|
||||
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
|
||||
import { authEnvironment } from "~/state/auth";
|
||||
import { environmentCatalog } from "~/connection/catalog";
|
||||
import {
|
||||
@@ -141,10 +126,11 @@ import {
|
||||
type EnvironmentPresentation,
|
||||
useEnvironments,
|
||||
usePrimaryEnvironment,
|
||||
useRelayEnvironmentDiscovery,
|
||||
} from "~/state/environments";
|
||||
import { relayEnvironmentDiscovery } from "~/state/relay";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { ConnectionStatusDot } from "../ConnectionStatusDot";
|
||||
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
|
||||
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
|
||||
|
||||
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
||||
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
|
||||
@@ -260,60 +246,6 @@ function AccessScopeSummary({
|
||||
);
|
||||
}
|
||||
|
||||
type ConnectionStatusDotProps = {
|
||||
tooltipText?: string | null;
|
||||
dotClassName: string;
|
||||
pingClassName?: string | null;
|
||||
};
|
||||
|
||||
function ConnectionStatusDot({
|
||||
tooltipText,
|
||||
dotClassName,
|
||||
pingClassName,
|
||||
}: ConnectionStatusDotProps) {
|
||||
const dotContent = (
|
||||
<>
|
||||
{pingClassName ? (
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inline-flex h-full w-full animate-ping rounded-full",
|
||||
pingClassName,
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
<span className={cn("relative inline-flex size-2 rounded-full", dotClassName)} />
|
||||
</>
|
||||
);
|
||||
|
||||
if (!tooltipText) {
|
||||
return (
|
||||
<span className="relative flex size-3 shrink-0 items-center justify-center">
|
||||
{dotContent}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const dot = (
|
||||
<button
|
||||
type="button"
|
||||
title={tooltipText}
|
||||
aria-label={tooltipText}
|
||||
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
|
||||
>
|
||||
{dotContent}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={dot} />
|
||||
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
|
||||
{tooltipText}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDesktopSshTarget(target: DesktopSshEnvironmentTarget): string {
|
||||
const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname;
|
||||
return target.port ? `${authority}:${target.port}` : authority;
|
||||
@@ -437,13 +369,8 @@ function formatDesktopSshConnectionError(error: unknown): string {
|
||||
return withoutTaggedErrorPrefix.trim() || fallback;
|
||||
}
|
||||
|
||||
/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
|
||||
const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
|
||||
const ENDPOINT_ROW_CLASSNAME = "border-t border-border/60 px-4 py-2.5 first:border-t-0 sm:px-5";
|
||||
|
||||
const ITEM_ROW_INNER_CLASSNAME =
|
||||
"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between";
|
||||
|
||||
type AccessSectionPresentation = "current" | "endpoint-rail";
|
||||
|
||||
function accessRowClassName(_presentation: AccessSectionPresentation) {
|
||||
@@ -1602,15 +1529,17 @@ function CloudLinkSwitch({
|
||||
disabled,
|
||||
disabledReason,
|
||||
onCheckedChange,
|
||||
ariaLabel = "Enable T3 Connect",
|
||||
}: {
|
||||
readonly checked: boolean;
|
||||
readonly disabled: boolean;
|
||||
readonly disabledReason: string | null;
|
||||
readonly onCheckedChange?: (enabled: boolean) => void;
|
||||
readonly ariaLabel?: string;
|
||||
}) {
|
||||
const control = (
|
||||
<Switch
|
||||
aria-label="Enable T3 Connect"
|
||||
aria-label={ariaLabel}
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
{...(onCheckedChange ? { onCheckedChange } : {})}
|
||||
@@ -1627,185 +1556,94 @@ function CloudLinkSwitch({
|
||||
}
|
||||
|
||||
function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
|
||||
const { getToken, isSignedIn } = useAuth();
|
||||
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const updatePrimaryEnvironmentPreferences = useAtomCommand(
|
||||
updatePrimaryEnvironmentPreferencesAtom,
|
||||
{ reportFailure: false },
|
||||
);
|
||||
const primaryCloudLinkState = usePrimaryCloudLinkState();
|
||||
const [operationError, setOperationError] = useState<string | null>(null);
|
||||
const {
|
||||
isSignedIn,
|
||||
linkState: primaryCloudLinkState,
|
||||
managedTunnelActive,
|
||||
publishAgentActivity,
|
||||
operationError,
|
||||
reconcileCloudState,
|
||||
} = useCloudLinkController();
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
|
||||
|
||||
const reportUpdateFailure = (cause: unknown) => {
|
||||
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
|
||||
const traceId = findErrorTraceId(cause);
|
||||
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
|
||||
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not update T3 Connect",
|
||||
description: message,
|
||||
data: traceId
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Copy trace ID",
|
||||
onClick: () => void navigator.clipboard?.writeText(traceId),
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
const updateLink = async (enabled: boolean) => {
|
||||
setIsUpdating(true);
|
||||
setOperationError(null);
|
||||
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
|
||||
if (tokenResult._tag === "Failure") {
|
||||
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
|
||||
setIsUpdating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const target = primaryCloudLinkState.target;
|
||||
if (!target) {
|
||||
reportUpdateFailure(new Error("Local environment is not ready yet."));
|
||||
setIsUpdating(false);
|
||||
return;
|
||||
}
|
||||
if (enabled && !tokenResult.value) {
|
||||
reportUpdateFailure(new Error("Sign in to T3 Connect before linking this environment."));
|
||||
setIsUpdating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const linkResult =
|
||||
enabled && tokenResult.value
|
||||
? await linkPrimaryEnvironment({
|
||||
target,
|
||||
clerkToken: tokenResult.value,
|
||||
})
|
||||
: await unlinkPrimaryEnvironment({
|
||||
target,
|
||||
clerkToken: tokenResult.value ?? null,
|
||||
});
|
||||
if (linkResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(linkResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(linkResult));
|
||||
}
|
||||
setIsUpdating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
primaryCloudLinkState.refresh();
|
||||
const refreshResult = await refreshRelayEnvironments();
|
||||
if (refreshResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(refreshResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(refreshResult));
|
||||
}
|
||||
setIsUpdating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: enabled ? "T3 Connect linked" : "T3 Connect unlinked",
|
||||
description: enabled
|
||||
? "This environment is available through T3 Connect."
|
||||
: "This environment is no longer available through T3 Connect.",
|
||||
});
|
||||
setIsUpdating(false);
|
||||
};
|
||||
|
||||
const updatePublishAgentActivity = async (enabled: boolean) => {
|
||||
const target = primaryCloudLinkState.target;
|
||||
if (!target) {
|
||||
reportUpdateFailure(new Error("Local environment is not ready yet."));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsUpdatingPreference(true);
|
||||
setOperationError(null);
|
||||
const updateResult = await updatePrimaryEnvironmentPreferences({
|
||||
target,
|
||||
publishAgentActivity: enabled,
|
||||
});
|
||||
if (updateResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(updateResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(updateResult));
|
||||
}
|
||||
setIsUpdatingPreference(false);
|
||||
return;
|
||||
}
|
||||
|
||||
primaryCloudLinkState.refresh();
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: enabled ? "Agent activity enabled" : "Agent activity disabled",
|
||||
description: enabled
|
||||
? "This environment can publish agent activity to your mobile clients."
|
||||
: "This environment will stop publishing agent activity.",
|
||||
});
|
||||
setIsUpdatingPreference(false);
|
||||
};
|
||||
const disabledReason = !isSignedIn
|
||||
? "Sign in to T3 Connect to manage this environment."
|
||||
: !canManageRelay
|
||||
? "Your session does not have permission to manage T3 Connect access."
|
||||
: null;
|
||||
const linked = primaryCloudLinkState.data?.linked ?? false;
|
||||
const isBusy = isUpdating || isUpdatingPreference;
|
||||
|
||||
const updateManagedTunnel = async (enabled: boolean) => {
|
||||
setIsUpdating(true);
|
||||
const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });
|
||||
if (ok) {
|
||||
// Turning the tunnel off while publishing stays on downgrades the link
|
||||
// rather than removing it — say so instead of claiming an unlink.
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: enabled
|
||||
? "T3 Connect linked"
|
||||
: publishAgentActivity
|
||||
? "T3 Connect tunnel disabled"
|
||||
: "T3 Connect unlinked",
|
||||
description: enabled
|
||||
? "This environment is available through T3 Connect."
|
||||
: publishAgentActivity
|
||||
? "The managed tunnel was removed. Agent activity publishing stays on."
|
||||
: "This environment is no longer available through T3 Connect.",
|
||||
});
|
||||
}
|
||||
setIsUpdating(false);
|
||||
};
|
||||
|
||||
const updatePublishAgentActivity = async (enabled: boolean) => {
|
||||
setIsUpdatingPreference(true);
|
||||
const ok = await reconcileCloudState({ managedTunnel: managedTunnelActive, publish: enabled });
|
||||
if (ok) {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: enabled ? "Agent activity enabled" : "Agent activity disabled",
|
||||
description: enabled
|
||||
? "This environment publishes agent activity to your mobile clients."
|
||||
: "This environment will stop publishing agent activity.",
|
||||
});
|
||||
}
|
||||
setIsUpdatingPreference(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsRow
|
||||
title="T3 Connect"
|
||||
description={
|
||||
linked
|
||||
managedTunnelActive
|
||||
? "This environment is available to your other devices through T3 Connect."
|
||||
: "Make this environment available to your other devices through T3 Connect."
|
||||
}
|
||||
status={operationError ?? primaryCloudLinkState.error}
|
||||
control={
|
||||
<CloudLinkSwitch
|
||||
checked={linked}
|
||||
disabled={
|
||||
!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isUpdating
|
||||
}
|
||||
checked={managedTunnelActive}
|
||||
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isBusy}
|
||||
disabledReason={disabledReason}
|
||||
onCheckedChange={(enabled) => void updateLink(enabled)}
|
||||
onCheckedChange={(enabled) => void updateManagedTunnel(enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
title="Publish agent activity"
|
||||
description="Send activity from this environment to your mobile clients for push notifications and Live Activities. Works without a T3 Connect tunnel."
|
||||
control={
|
||||
<CloudLinkSwitch
|
||||
ariaLabel="Publish agent activity to mobile clients"
|
||||
checked={publishAgentActivity}
|
||||
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isBusy}
|
||||
disabledReason={disabledReason}
|
||||
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{linked ? (
|
||||
<SettingsRow
|
||||
title="Publish agent activity"
|
||||
description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
|
||||
className="bg-muted/20 pl-7 sm:pl-8"
|
||||
control={
|
||||
<Switch
|
||||
aria-label="Publish agent activity to mobile clients"
|
||||
checked={primaryCloudLinkState.data?.publishAgentActivity ?? false}
|
||||
disabled={
|
||||
!canManageRelay ||
|
||||
!isSignedIn ||
|
||||
primaryCloudLinkState.isPending ||
|
||||
isUpdating ||
|
||||
isUpdatingPreference
|
||||
}
|
||||
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1832,163 +1670,6 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
|
||||
);
|
||||
}
|
||||
|
||||
function RemoteEnvironmentRowsSkeleton() {
|
||||
return (
|
||||
<div className={ITEM_ROW_CLASSNAME}>
|
||||
<div className={ITEM_ROW_INNER_CLASSNAME}>
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-32 rounded-full" />
|
||||
<Skeleton className="h-3 w-20 rounded-full" />
|
||||
</div>
|
||||
<Skeleton className="h-7 w-16 rounded-md" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfiguredCloudRemoteEnvironmentRows({
|
||||
primaryEnvironmentId,
|
||||
savedEnvironmentIds,
|
||||
}: {
|
||||
readonly primaryEnvironmentId: EnvironmentId | null;
|
||||
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
|
||||
}) {
|
||||
const environmentsState = useRelayEnvironmentDiscovery();
|
||||
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const connectRelayEnvironment = useCallback(
|
||||
(environment: RelayClientEnvironmentRecord) =>
|
||||
registerEnvironment(
|
||||
new RelayConnectionRegistration({
|
||||
target: new RelayConnectionTarget({
|
||||
environmentId: environment.environmentId,
|
||||
label: environment.label,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
[registerEnvironment],
|
||||
);
|
||||
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
|
||||
null,
|
||||
);
|
||||
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshRelayEnvironments();
|
||||
}, [refreshRelayEnvironments]);
|
||||
|
||||
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
|
||||
setConnectingEnvironmentId(environment.environmentId);
|
||||
const result = await connectRelayEnvironment(environment);
|
||||
setConnectingEnvironmentId(null);
|
||||
if (result._tag === "Success") {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Environment connected",
|
||||
description: `${environment.label} is available through T3 Connect.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (isAtomCommandInterrupted(result)) {
|
||||
return;
|
||||
}
|
||||
const cause = squashAtomCommandFailure(result);
|
||||
const message =
|
||||
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
|
||||
const traceId = findErrorTraceId(cause);
|
||||
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not connect environment",
|
||||
description: message,
|
||||
data: traceId
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Copy trace ID",
|
||||
onClick: () => void navigator.clipboard?.writeText(traceId),
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
const connectableEnvironments = [...environmentsState.environments.values()].filter(
|
||||
({ environment }) =>
|
||||
environment.environmentId !== primaryEnvironmentId &&
|
||||
!savedIds.has(environment.environmentId),
|
||||
);
|
||||
|
||||
if (
|
||||
savedEnvironmentIds.length === 0 &&
|
||||
environmentsState.refreshing &&
|
||||
environmentsState.environments.size === 0
|
||||
) {
|
||||
return <RemoteEnvironmentRowsSkeleton />;
|
||||
}
|
||||
|
||||
if (savedEnvironmentIds.length === 0 && connectableEnvironments.length === 0) {
|
||||
return <EmptyRemoteEnvironments />;
|
||||
}
|
||||
|
||||
return connectableEnvironments.map(({ environment, availability, error }) => (
|
||||
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
|
||||
<div className={ITEM_ROW_INNER_CLASSNAME}>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<ConnectionStatusDot
|
||||
dotClassName={
|
||||
availability === "online"
|
||||
? "bg-success"
|
||||
: availability === "error"
|
||||
? "bg-destructive"
|
||||
: availability === "checking"
|
||||
? "bg-warning"
|
||||
: "bg-muted-foreground/35"
|
||||
}
|
||||
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
|
||||
tooltipText={
|
||||
availability === "online"
|
||||
? "Relay online"
|
||||
: availability === "offline"
|
||||
? "Relay offline"
|
||||
: availability === "checking"
|
||||
? "Checking relay status"
|
||||
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
|
||||
}
|
||||
/>
|
||||
<p className="truncate text-sm font-medium">{environment.label}</p>
|
||||
</div>
|
||||
<p
|
||||
className={cn(
|
||||
"mt-1 truncate text-xs",
|
||||
availability === "error" ? "text-destructive" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{availability === "online"
|
||||
? "Available · Relay online"
|
||||
: availability === "offline"
|
||||
? "Available · Relay offline"
|
||||
: availability === "checking"
|
||||
? "Available · Checking relay status…"
|
||||
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={connectingEnvironmentId !== null}
|
||||
onClick={() => void connectEnvironment(environment)}
|
||||
>
|
||||
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
}
|
||||
|
||||
function CloudRemoteEnvironmentRows({
|
||||
primaryEnvironmentId,
|
||||
savedEnvironmentIds,
|
||||
@@ -1997,9 +1678,10 @@ function CloudRemoteEnvironmentRows({
|
||||
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
|
||||
}) {
|
||||
return hasCloudPublicConfig() ? (
|
||||
<ConfiguredCloudRemoteEnvironmentRows
|
||||
<CloudEnvironmentConnectRows
|
||||
primaryEnvironmentId={primaryEnvironmentId}
|
||||
savedEnvironmentIds={savedEnvironmentIds}
|
||||
empty={<EmptyRemoteEnvironments />}
|
||||
/>
|
||||
) : savedEnvironmentIds.length === 0 ? (
|
||||
<EmptyRemoteEnvironments cloudEnabled={false} />
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
|
||||
export const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
|
||||
|
||||
export const ITEM_ROW_INNER_CLASSNAME =
|
||||
"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between";
|
||||
@@ -182,7 +182,7 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
if (session === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "Sign in to T3 Cloud to connect this environment.",
|
||||
detail: "Sign in to T3 Connect to connect this environment.",
|
||||
});
|
||||
}
|
||||
const token = yield* session.readClerkToken().pipe(
|
||||
@@ -197,7 +197,7 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
detail: "The T3 Connect session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
|
||||
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof snapshotLoaderLayer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof connectionPlatformLayer;
|
||||
|
||||
const connectionLayer = Connection.layer.pipe(
|
||||
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -45,11 +45,14 @@ const StoredShellSnapshot = Schema.Struct({
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
|
||||
// v2 stores the snapshot sequence alongside the thread so a warm cache can
|
||||
// resume via `afterSequence` instead of re-downloading the full thread body.
|
||||
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
schemaVersion: Schema.Literal(2),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
thread: OrchestrationThread,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
});
|
||||
const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
|
||||
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
|
||||
@@ -473,7 +476,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
),
|
||||
);
|
||||
@@ -484,18 +487,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
: persistenceError("load-thread", cause),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
saveThread: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: 1,
|
||||
schemaVersion: 2,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
threadId: snapshot.thread.id,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* writeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, thread.id),
|
||||
threadCacheKey(environmentId, snapshot.thread.id),
|
||||
encoded,
|
||||
);
|
||||
}).pipe(
|
||||
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user