Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da8ebd3fcd | ||
|
|
cd25a3de9a | ||
|
|
c072888cff | ||
|
|
70c24206f1 | ||
|
|
90f0df5180 | ||
|
|
0ad91b6e7f | ||
|
|
ca72e381c6 | ||
|
|
491219bf1f | ||
|
|
e5c7547067 | ||
|
|
bfc31507f8 | ||
|
|
03adf215ce | ||
|
|
916cff733c | ||
|
|
a041981276 | ||
|
|
964cc27901 | ||
|
|
acf761b2f5 | ||
|
|
ab8182cb4e | ||
|
|
ef4ec2ad4b | ||
|
|
61514c1294 | ||
|
|
894d6d68f5 | ||
|
|
fccec9f097 | ||
|
|
50a3d6b872 | ||
|
|
e259dd23c7 | ||
|
|
df78cda8bf | ||
|
|
605c2bb734 | ||
|
|
cb11a71d63 | ||
|
|
41124c7260 | ||
|
|
b0b275227b | ||
|
|
cb293fe790 | ||
|
|
1d694dcbd8 | ||
|
|
32407df9c5 | ||
|
|
162e774294 | ||
|
|
063ed7120a | ||
|
|
34b15a9ace | ||
|
|
fbecb7365e | ||
|
|
4029b858ea | ||
|
|
5b2577f6a9 | ||
|
|
bc142f84a2 |
No files matched your search
@@ -66,7 +66,7 @@ Use these client origins:
|
||||
- Android Emulator: `http://10.0.2.2:<server-port>`
|
||||
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
|
||||
|
||||
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
|
||||
Enter the complete `http://` origin to make the test transport explicit. Bare IP addresses default to HTTP, while bare hostnames default to HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
|
||||
|
||||
## Start or reuse Metro safely
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ body:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- apps/mobile
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
|
||||
@@ -30,6 +30,7 @@ body:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- apps/mobile
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
|
||||
@@ -39,10 +39,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
# when the partial clone can't serve the unfetched blobs.
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -57,10 +57,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
# when the partial clone can't serve the unfetched blobs.
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -52,6 +52,7 @@ jobs:
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
@@ -100,6 +101,7 @@ jobs:
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 295 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 310 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 9.3 KiB |
@@ -54,7 +54,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
calls.setAboutPanelOptions.push(options);
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
|
||||
@@ -45,6 +45,27 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
: Option.none();
|
||||
};
|
||||
|
||||
export const resolveUserDataPath = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const legacyPath = environment.path.join(
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
@@ -90,24 +111,11 @@ export const make = Effect.gen(function* () {
|
||||
return commitHash;
|
||||
});
|
||||
|
||||
const resolveUserDataPath = Effect.gen(function* () {
|
||||
const legacyPath = environment.path.join(
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
|
||||
const userDataPath = resolveUserDataPath.pipe(
|
||||
Effect.provide(
|
||||
yield* Effect.context<DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem>(),
|
||||
),
|
||||
);
|
||||
|
||||
const configure = Effect.gen(function* () {
|
||||
const commitHash = yield* resolveAboutCommitHash;
|
||||
@@ -136,7 +144,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
|
||||
|
||||
return DesktopAppIdentity.of({
|
||||
resolveUserDataPath,
|
||||
resolveUserDataPath: userDataPath,
|
||||
configure,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,17 +22,38 @@ vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const makeDesktopClerkLayer = (isDevelopment = true) => {
|
||||
const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment,
|
||||
appDataDirectory: "/tmp/app-data",
|
||||
userDataDirName: isDevelopment ? "t3code-dev" : "t3code",
|
||||
legacyUserDataDirName: isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)",
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const electronApp = {
|
||||
setPath: (name: string, value: string) =>
|
||||
Effect.sync(() => {
|
||||
events.push(`setPath:${name}:${value}`);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
|
||||
return DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Layer.succeed(ElectronApp.ElectronApp, electronApp),
|
||||
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -55,11 +76,15 @@ describe("DesktopClerk", () => {
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
const events: string[] = [];
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
createClerkBridgeMock.mockImplementation(() => {
|
||||
events.push("createClerkBridge");
|
||||
return { cleanup, isPrimaryInstance: true };
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
@@ -71,6 +96,10 @@ describe("DesktopClerk", () => {
|
||||
],
|
||||
]);
|
||||
assert.equal(cleanup.mock.calls.length, 1);
|
||||
// The bridge acquires Electron's single-instance lock at creation, and
|
||||
// the lock both lives in and creates the userData directory — so the
|
||||
// real path must be set before the bridge exists.
|
||||
assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
@@ -124,11 +153,67 @@ describe("DesktopClerk", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("registers the second-instance handler in the primary instance", () => {
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
|
||||
const quit = vi.fn();
|
||||
const registeredEvents: string[] = [];
|
||||
const electronApp = {
|
||||
quit: Effect.sync(quit),
|
||||
on: (eventName: string) =>
|
||||
Effect.sync(() => {
|
||||
registeredEvents.push(eventName);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
|
||||
|
||||
assert.isTrue(Exit.isSuccess(exit));
|
||||
assert.equal(quit.mock.calls.length, 0);
|
||||
assert.deepEqual(registeredEvents, ["second-instance"]);
|
||||
}).pipe(
|
||||
Effect.provide(makeDesktopClerkLayer()),
|
||||
Effect.provideService(ElectronApp.ElectronApp, electronApp),
|
||||
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("quits and interrupts startup in a secondary instance", () => {
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
|
||||
const quit = vi.fn();
|
||||
const registeredEvents: string[] = [];
|
||||
const electronApp = {
|
||||
quit: Effect.sync(quit),
|
||||
on: (eventName: string) =>
|
||||
Effect.sync(() => {
|
||||
registeredEvents.push(eventName);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
|
||||
|
||||
assert.isTrue(Exit.hasInterrupts(exit));
|
||||
assert.equal(quit.mock.calls.length, 1);
|
||||
assert.deepEqual(registeredEvents, []);
|
||||
}).pipe(
|
||||
Effect.provide(makeDesktopClerkLayer()),
|
||||
Effect.provideService(ElectronApp.ElectronApp, electronApp),
|
||||
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isDevelopment: true, scheme: "t3code-dev" },
|
||||
{ isDevelopment: false, scheme: "t3code" },
|
||||
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
|
||||
const bridge = { cleanup: vi.fn() };
|
||||
const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
@@ -84,7 +85,18 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
|
||||
// Electron scopes the single-instance lock to the userData directory and
|
||||
// creates that directory when the lock is acquired. The SDK bridge takes
|
||||
// the lock at creation, so userData must already point at the real
|
||||
// directory here — under the default productName-derived path, acquiring
|
||||
// the lock would create "T3 Code (Alpha)" and make the legacy-install
|
||||
// detection in resolveUserDataPath match on fresh installs.
|
||||
const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
|
||||
yield* electronApp.setPath("userData", userDataPath);
|
||||
|
||||
const bridge = yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
|
||||
catch: (cause) =>
|
||||
@@ -113,7 +125,12 @@ export const make = Effect.gen(function* () {
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
// The SDK bridge holds Electron's single-instance lock (acquired at
|
||||
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
|
||||
// forwarded to the running app. In a secondary instance the bridge has
|
||||
// already begun quitting the app; app.quit() is asynchronous, so stop
|
||||
// bootstrap here before whenReady can fire.
|
||||
if (!bridge.isPrimaryInstance) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ describe("DesktopLifecycle", () => {
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
|
||||
@@ -14,7 +14,6 @@ const {
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
requestSingleInstanceLockMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
@@ -35,7 +34,6 @@ const {
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
requestSingleInstanceLockMock: vi.fn(() => true),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
@@ -67,7 +65,6 @@ vi.mock("electron", () => ({
|
||||
quit: quitMock,
|
||||
relaunch: relaunchMock,
|
||||
removeListener: removeListenerMock,
|
||||
requestSingleInstanceLock: requestSingleInstanceLockMock,
|
||||
runningUnderARM64Translation: false,
|
||||
setAboutPanelOptions: setAboutPanelOptionsMock,
|
||||
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
|
||||
|
||||
@@ -56,7 +56,6 @@ export class ElectronApp extends Context.Service<
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
@@ -153,7 +152,6 @@ export const make = ElectronApp.of({
|
||||
Effect.sync(() => {
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
@@ -212,6 +212,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
|
||||
@@ -71,6 +71,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
|
||||
@@ -34,7 +34,6 @@ function makeElectronAppLayer(
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
|
||||
@@ -39,7 +39,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "0.1.0",
|
||||
version: "1.0.1",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
@@ -181,6 +181,9 @@ const config: ExpoConfig = {
|
||||
ios: {
|
||||
icon: variant.assets.iosIcon,
|
||||
supportsTablet: true,
|
||||
// Multitasking-capable iPad apps cannot rotate programmatically, so the
|
||||
// showcase capture build requires full screen (see infoPlist below).
|
||||
requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1",
|
||||
bundleIdentifier: iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
@@ -197,6 +200,21 @@ const config: ExpoConfig = {
|
||||
NSLocalNetworkUsageDescription:
|
||||
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
|
||||
ITSAppUsesNonExemptEncryption: false,
|
||||
// The App Store screenshot harness rotates the iPad interface from
|
||||
// inside the app (CI denies osascript the Accessibility access that
|
||||
// Simulator menu scripting needs), and iPadOS ignores programmatic
|
||||
// orientation requests for multitasking-capable apps — so the capture
|
||||
// build opts out of multitasking and declares landscape support.
|
||||
...(process.env.T3_SHOWCASE_CAPTURE_BUILD === "1"
|
||||
? {
|
||||
"UISupportedInterfaceOrientations~ipad": [
|
||||
"UIInterfaceOrientationPortrait",
|
||||
"UIInterfaceOrientationPortraitUpsideDown",
|
||||
"UIInterfaceOrientationLandscapeLeft",
|
||||
"UIInterfaceOrientationLandscapeRight",
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
android: {
|
||||
@@ -275,10 +293,12 @@ const config: ExpoConfig = {
|
||||
"expo-camera",
|
||||
{
|
||||
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
|
||||
microphonePermission: false,
|
||||
barcodeScannerEnabled: true,
|
||||
recordAudioAndroid: false,
|
||||
},
|
||||
],
|
||||
["expo-image-picker", { photosPermission: false, microphonePermission: false }],
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import ExpoModulesCore
|
||||
import Security
|
||||
import UIKit
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
@@ -32,6 +33,50 @@ public final class T3NativeControlsModule: Module {
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("getShowcaseOrientation") { () -> String? in
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcaseOrientation"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
// Rotates the interface without Simulator menu UI scripting, which CI
|
||||
// runners cannot perform (osascript is denied Accessibility access there).
|
||||
AsyncFunction("applyShowcaseOrientation") { (orientation: String) in
|
||||
guard #available(iOS 16.0, *) else { return }
|
||||
let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
|
||||
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
|
||||
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
|
||||
NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
|
||||
}
|
||||
for window in windowScene.windows {
|
||||
window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
|
||||
}
|
||||
}
|
||||
}.runOnQueue(.main)
|
||||
|
||||
// The geometry request above can fail transiently (for example before the
|
||||
// scene is foreground-active), so callers poll this until it settles.
|
||||
// Screen bounds — not the scene's interface orientation — decide the
|
||||
// answer because they match the captured framebuffer: with iPadOS
|
||||
// windowing active, a floating landscape window still reports a portrait
|
||||
// screen, and screenshots would come out portrait.
|
||||
AsyncFunction("getInterfaceOrientation") { () -> String in
|
||||
guard
|
||||
let windowScene = UIApplication.shared.connectedScenes
|
||||
.compactMap({ $0 as? UIWindowScene })
|
||||
.first
|
||||
else {
|
||||
return "unknown"
|
||||
}
|
||||
let bounds = windowScene.screen.coordinateSpace.bounds
|
||||
return bounds.width > bounds.height ? "landscape" : "portrait"
|
||||
}.runOnQueue(.main)
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
|
||||
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
|
||||
|
||||
@@ -40,7 +40,7 @@ fails, run `xcodebuild -downloadComponent MetalToolchain`.
|
||||
## Rebuilding libghostty-vt for Android
|
||||
|
||||
The checked-in Android shared libraries and headers are pinned to the revision recorded in
|
||||
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
|
||||
`native/libghostty-vt/VERSION` at the repository root. Set `ANDROID_NDK_HOME` and run:
|
||||
|
||||
```bash
|
||||
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
|
||||
|
||||
@@ -18,13 +18,14 @@ Ghostty's MIT license applies to the vendored framework. Keep this notice in syn
|
||||
## Ghostty / libghostty-vt
|
||||
|
||||
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
|
||||
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
|
||||
|
||||
- Upstream project: https://github.com/ghostty-org/ghostty
|
||||
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
|
||||
- License: MIT
|
||||
|
||||
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
|
||||
updating `Vendor/libghostty-vt`.
|
||||
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
|
||||
artifacts in sync when updating the repository-root `native/libghostty-vt`.
|
||||
|
||||
## MesloLGS NF (Android terminal font)
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ add_library(t3terminal SHARED t3_terminal_jni.cpp)
|
||||
|
||||
target_include_directories(
|
||||
t3terminal
|
||||
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include"
|
||||
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../../../native/libghostty-vt/include"
|
||||
)
|
||||
|
||||
target_link_options(
|
||||
|
||||
@@ -4,7 +4,7 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
VENDOR_DIR="${MODULE_DIR}/Vendor/libghostty-vt"
|
||||
VENDOR_DIR="${MODULE_DIR}/../../../../native/libghostty-vt"
|
||||
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
|
||||
|
||||
GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
"start:preview": "APP_VARIANT=preview expo start",
|
||||
"start:prod": "APP_VARIANT=production expo start",
|
||||
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
|
||||
"showcase": "APP_VARIANT=production EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code --clear",
|
||||
"screenshots": "node ../../scripts/mobile-showcase.ts",
|
||||
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
|
||||
|
||||
@@ -15,6 +15,7 @@ import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "re
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
@@ -392,7 +393,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerBackVisible: false,
|
||||
title: "Threads",
|
||||
...getCompactBrandHeaderOptions(),
|
||||
},
|
||||
}),
|
||||
Thread: createNativeStackScreen({
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IconChevronUp,
|
||||
IconCircleCheck,
|
||||
IconCircleXFilled,
|
||||
IconClock,
|
||||
IconCopy,
|
||||
IconDeviceDesktop,
|
||||
IconDots,
|
||||
@@ -96,6 +97,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
camera: IconCamera,
|
||||
checkmark: IconCheck,
|
||||
"checkmark.circle": IconCircleCheck,
|
||||
clock: IconClock,
|
||||
"chevron.down": IconChevronDown,
|
||||
"chevron.left": IconChevronLeft,
|
||||
"chevron.left.forwardslash.chevron.right": IconCode,
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import Constants from "expo-constants";
|
||||
import type {
|
||||
NativeStackHeaderItem,
|
||||
NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { Platform, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3Wordmark } from "./T3Wordmark";
|
||||
import { IPAD_HOME_TITLE_OFFSET } from "../lib/layoutMetrics";
|
||||
import { resolveMobileStageLabel } from "../lib/mobileBranding";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
|
||||
|
||||
// Native leading items inherit different UIKit margins than title views.
|
||||
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
|
||||
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
export function CompactBrandTitle(
|
||||
props: {
|
||||
readonly nativeLeadingItem?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
const titleOffset =
|
||||
Platform.OS !== "ios"
|
||||
? 0
|
||||
: props.nativeLeadingItem
|
||||
? Platform.isPad
|
||||
? IPAD_NATIVE_LEADING_TITLE_OFFSET
|
||||
: IOS_NATIVE_LEADING_TITLE_OFFSET
|
||||
: Platform.isPad
|
||||
? IPAD_HOME_TITLE_OFFSET
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<View
|
||||
aria-level={1}
|
||||
accessibilityLabel="T3 Code, Threads"
|
||||
accessible
|
||||
role="heading"
|
||||
style={{
|
||||
alignItems: "center",
|
||||
flexDirection: "row",
|
||||
gap: 6,
|
||||
marginLeft: titleOffset,
|
||||
}}
|
||||
>
|
||||
<T3Wordmark color={iconColor} height={15} />
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Medium",
|
||||
fontSize: 21,
|
||||
letterSpacing: -0.5,
|
||||
}}
|
||||
>
|
||||
Code
|
||||
</Text>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Bold",
|
||||
fontSize: 9,
|
||||
letterSpacing: 0.9,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
{stageLabel}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function renderCompactBrandTitle() {
|
||||
return <CompactBrandTitle />;
|
||||
}
|
||||
|
||||
export function renderCompactBrandHeaderItems(): NativeStackHeaderItem[] {
|
||||
return [
|
||||
{
|
||||
element: <CompactBrandTitle nativeLeadingItem />,
|
||||
hidesSharedBackground: true,
|
||||
type: "custom",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function getCompactBrandHeaderOptions(
|
||||
fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"],
|
||||
): NativeStackNavigationOptions {
|
||||
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
|
||||
return {
|
||||
headerTitle: "Threads",
|
||||
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
|
||||
title: "Threads",
|
||||
unstable_headerLeftItems: renderCompactBrandHeaderItems,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
headerTitleStyle: fallbackTitleStyle,
|
||||
title: "Threads",
|
||||
};
|
||||
}
|
||||
@@ -1,11 +1,32 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildPairingUrl,
|
||||
extractPairingUrlFromQrPayload,
|
||||
PairingQrPayloadEmptyError,
|
||||
parsePairingUrl,
|
||||
} from "./pairing";
|
||||
|
||||
describe("buildPairingUrl", () => {
|
||||
it("uses HTTP for a schemeless IP address", () => {
|
||||
expect(buildPairingUrl("192.168.1.100:3773", "pairing-token")).toBe(
|
||||
"http://192.168.1.100:3773/#token=pairing-token",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps HTTPS as the default for a schemeless hostname", () => {
|
||||
expect(buildPairingUrl("remote.example.com", "pairing-token")).toBe(
|
||||
"https://remote.example.com/#token=pairing-token",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves an explicit scheme for an IP address", () => {
|
||||
expect(buildPairingUrl("https://192.168.1.100:3773", "pairing-token")).toBe(
|
||||
"https://192.168.1.100:3773/#token=pairing-token",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractPairingUrlFromQrPayload", () => {
|
||||
it("trims raw pairing urls from qr payloads", () => {
|
||||
expect(
|
||||
|
||||
@@ -3,6 +3,21 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
|
||||
|
||||
function isIpLiteral(host: string): boolean {
|
||||
try {
|
||||
const hostname = new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, "");
|
||||
if (hostname.includes(":")) return true;
|
||||
|
||||
const octets = hostname.split(".");
|
||||
return (
|
||||
octets.length === 4 &&
|
||||
octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export class PairingQrPayloadEmptyError extends Schema.TaggedErrorClass<PairingQrPayloadEmptyError>()(
|
||||
"PairingQrPayloadEmptyError",
|
||||
{},
|
||||
@@ -19,7 +34,7 @@ export function buildPairingUrl(host: string, code: string): string {
|
||||
if (!c) return h;
|
||||
|
||||
try {
|
||||
const url = new URL(h.includes("://") ? h : `https://${h}`);
|
||||
const url = new URL(h.includes("://") ? h : `${isIpLiteral(h) ? "http" : "https"}://${h}`);
|
||||
url.hash = new URLSearchParams([["token", c]]).toString();
|
||||
return url.toString();
|
||||
} catch {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import Constants from "expo-constants";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
@@ -9,6 +10,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
|
||||
import { resolveMobileStageLabel } from "../../lib/mobileBranding";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
@@ -64,6 +67,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
@@ -195,8 +199,9 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View
|
||||
className="border-b border-header-border bg-header px-4 pb-3"
|
||||
className="border-b border-header-border bg-header pb-3"
|
||||
style={{
|
||||
paddingHorizontal: HOME_HORIZONTAL_INSET,
|
||||
paddingTop: Math.max(insets.top, 12),
|
||||
}}
|
||||
>
|
||||
@@ -210,7 +215,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
</RNText>
|
||||
<View className="rounded-full bg-subtle px-2 py-0.75">
|
||||
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
|
||||
Alpha
|
||||
{stageLabel}
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
@@ -35,8 +36,14 @@ export function HomeRouteScreen() {
|
||||
void checkForAppUpdateOnLaunch();
|
||||
}, []);
|
||||
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(() => {
|
||||
@@ -93,7 +100,9 @@ export function HomeRouteScreen() {
|
||||
if (layout.usesSplitView) {
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ title: "", headerTitle: "" }} />
|
||||
<NativeStackScreenOptions
|
||||
options={{ title: "", headerTitle: "", unstable_headerLeftItems: () => [] }}
|
||||
/>
|
||||
<WorkspaceSidebarToolbar
|
||||
afterSidebarButton={
|
||||
<NativeHeaderToolbar.Button
|
||||
@@ -115,8 +124,8 @@ export function HomeRouteScreen() {
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title in case the split branch blanked it. */}
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
{/* Restore the compact title after the split branch blanks the detail header. */}
|
||||
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
@@ -143,6 +152,8 @@ export function HomeRouteScreen() {
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
|
||||
@@ -41,7 +41,12 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
ThreadListV2PendingRow,
|
||||
ThreadListV2Row,
|
||||
ThreadListV2SettledShelfHeader,
|
||||
ThreadListV2SnoozedShelfHeader,
|
||||
} from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
@@ -100,6 +105,11 @@ interface HomeScreenProps {
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** Resolves true iff the settle was dispatched and succeeded. */
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSnoozeThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
snoozedUntil: string,
|
||||
) => Promise<boolean>;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
@@ -494,6 +504,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
const handleSnoozeThread = useCallback(
|
||||
(thread: EnvironmentThreadShell, snoozedUntil: string) => {
|
||||
void props.onSnoozeThread(thread, snoozedUntil);
|
||||
},
|
||||
[props.onSnoozeThread],
|
||||
);
|
||||
const handleUnsnoozeThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onUnsnoozeThread(thread);
|
||||
},
|
||||
[props.onUnsnoozeThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -511,6 +533,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
// now is quantized to the minute and ticks so the inactivity auto-settle
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
@@ -551,7 +577,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return {
|
||||
items: [],
|
||||
hiddenSettledCount: 0,
|
||||
snoozedCount: 0,
|
||||
snoozedShelfHeaderIndex: null,
|
||||
settledCount: 0,
|
||||
settledShelfHeaderIndex: null,
|
||||
nextSnoozeWakeAt: null,
|
||||
};
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -566,11 +600,16 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
selectedThreadKey: null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
@@ -620,8 +659,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
buildThreadListV2ListItems({
|
||||
items: threadListV2Layout.items,
|
||||
pendingTasks: v2PendingTasks,
|
||||
snoozedCount: threadListV2Layout.snoozedCount,
|
||||
snoozedShelfExpanded,
|
||||
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
|
||||
settledCount: threadListV2Layout.settledCount,
|
||||
settledShelfExpanded,
|
||||
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
|
||||
snoozeLabelNow: `${nowMinute}:00.000Z`,
|
||||
}),
|
||||
[threadListV2Layout.items, v2PendingTasks],
|
||||
[settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks],
|
||||
);
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
@@ -648,12 +694,32 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.type === "v2-snoozed-shelf") {
|
||||
return (
|
||||
<ThreadListV2SnoozedShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSnoozedShelf}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.type === "v2-settled-shelf") {
|
||||
return (
|
||||
<ThreadListV2SettledShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSettledShelf}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const thread = item.item.thread;
|
||||
return (
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
snoozed={item.item.snoozed}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
}
|
||||
@@ -686,6 +752,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={handleSnoozeThread}
|
||||
onUnsnoozeThread={handleUnsnoozeThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
@@ -700,6 +769,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnsnoozeThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
@@ -712,9 +783,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadSearchMatchByKey,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
props.searchQuery,
|
||||
nowMinute,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
|
||||
@@ -730,6 +805,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
searchQuery: props.searchQuery,
|
||||
snoozePresetMinute: nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
}),
|
||||
[
|
||||
@@ -738,6 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
@@ -953,31 +1030,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
) : null;
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
// is empty. Snoozed threads need no special empty state: their shelf header
|
||||
// is a list row even while collapsed.
|
||||
const v2ListEmpty =
|
||||
hasSearchQuery && threadSearch.isPending && v2SnoozedCount === 0 ? null : hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
@@ -998,7 +1055,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
extraData={v2ExtraData}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import {
|
||||
createContext,
|
||||
@@ -47,13 +49,67 @@ export const THREAD_SWIPE_SPRING = {
|
||||
stiffness: 330,
|
||||
};
|
||||
|
||||
interface ThreadSwipePrimaryAction {
|
||||
interface ThreadSwipeAction {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly menu?: {
|
||||
readonly actions: MenuAction[];
|
||||
readonly onPressAction: NonNullable<ComponentProps<typeof ControlPillMenu>["onPressAction"]>;
|
||||
readonly title?: string;
|
||||
};
|
||||
readonly onPress: () => void;
|
||||
}
|
||||
|
||||
interface ThreadSwipeSecondaryAction extends ThreadSwipeAction {
|
||||
readonly backgroundColor: string;
|
||||
}
|
||||
|
||||
function swipeActionsWidth(hasSecondaryAction: boolean) {
|
||||
return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH;
|
||||
}
|
||||
|
||||
/** `undefined` keeps the v1 Delete default; `null` means one action only. */
|
||||
function resolveSecondaryAction(input: {
|
||||
readonly close: () => void;
|
||||
readonly onDelete: () => void;
|
||||
readonly secondaryAction: ThreadSwipeAction | null | undefined;
|
||||
readonly threadTitle: string;
|
||||
}): ThreadSwipeSecondaryAction | null {
|
||||
if (input.secondaryAction === null) return null;
|
||||
if (input.secondaryAction === undefined) {
|
||||
return {
|
||||
accessibilityLabel: `Delete ${input.threadTitle}`,
|
||||
backgroundColor: "#ff2d55",
|
||||
icon: "trash",
|
||||
label: "Delete",
|
||||
onPress: () => {
|
||||
input.close();
|
||||
input.onDelete();
|
||||
},
|
||||
};
|
||||
}
|
||||
const action = input.secondaryAction;
|
||||
return {
|
||||
...action,
|
||||
backgroundColor: "#5856d6",
|
||||
menu:
|
||||
action.menu === undefined
|
||||
? undefined
|
||||
: {
|
||||
...action.menu,
|
||||
onPressAction: (event) => {
|
||||
input.close();
|
||||
action.menu?.onPressAction(event);
|
||||
},
|
||||
},
|
||||
onPress: () => {
|
||||
input.close();
|
||||
action.onPress();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers the scroll gate to swipeables via context so that flipping it does
|
||||
* NOT re-render whole rows: putting the flag in list extraData/renderItem deps
|
||||
@@ -173,17 +229,22 @@ export function ThreadSwipeable(props: {
|
||||
readonly enabled?: boolean;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
/**
|
||||
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
|
||||
* button stretches) or "primary" — the advertised primary action fires and
|
||||
* its button stretches instead. A full swipe must always match the action
|
||||
* the stretching button advertises.
|
||||
* What a full swipe commits. Omitted keeps the v1 Delete behavior only when
|
||||
* the built-in Delete secondary action is in use; custom or absent
|
||||
* secondary actions default to the advertised primary action.
|
||||
*/
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly primaryAction: ThreadSwipeAction;
|
||||
/**
|
||||
* Omitted keeps the v1 destructive Delete action. Explicit null opts out of
|
||||
* a secondary action entirely so a gated Snooze can never fall back to an
|
||||
* unadvertised Delete.
|
||||
*/
|
||||
readonly secondaryAction?: ThreadSwipeAction | null;
|
||||
/**
|
||||
* Identity of the content being wrapped. When a recycled list reuses this
|
||||
* component for a different item, the swipeable snaps back to closed so an
|
||||
@@ -197,7 +258,11 @@ export function ThreadSwipeable(props: {
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
|
||||
const hasSecondaryAction = props.secondaryAction !== null;
|
||||
const actionsWidth = swipeActionsWidth(hasSecondaryAction);
|
||||
const fullSwipeThreshold = Math.max(actionsWidth + 44, props.fullSwipeWidth * 0.58);
|
||||
const fullSwipeAction =
|
||||
props.fullSwipeAction ?? (props.secondaryAction === undefined ? "delete" : "primary");
|
||||
const close = useCallback(() => swipeableRef.current?.close(), []);
|
||||
const gateEnabled = use(SwipeableScrollGateContext);
|
||||
const resetKey = props.resetKey;
|
||||
@@ -251,7 +316,7 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
if (fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
@@ -264,9 +329,8 @@ export function ThreadSwipeable(props: {
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
compact={props.compactActions === true}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeAction={fullSwipeAction}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
...props.primaryAction,
|
||||
@@ -275,12 +339,16 @@ export function ThreadSwipeable(props: {
|
||||
props.primaryAction.onPress();
|
||||
},
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.threadTitle}
|
||||
secondaryAction={resolveSecondaryAction({
|
||||
close: () => methods.close(),
|
||||
onDelete: props.onDelete,
|
||||
secondaryAction: props.secondaryAction,
|
||||
threadTitle: props.threadTitle,
|
||||
})}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
rightThreshold={actionsWidth * 0.42}
|
||||
simultaneousWithExternalGesture={props.simultaneousWithExternalGesture}
|
||||
>
|
||||
{props.children(close)}
|
||||
@@ -290,12 +358,14 @@ export function ThreadSwipeable(props: {
|
||||
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly actionsWidth: number;
|
||||
readonly backgroundColor: string;
|
||||
readonly compact: boolean;
|
||||
readonly entryRange: readonly [number, number];
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly menu?: ThreadSwipeAction["menu"];
|
||||
readonly onPress: () => void;
|
||||
readonly stretchesOnFullSwipe: boolean;
|
||||
readonly translation: SharedValue<number>;
|
||||
@@ -305,10 +375,10 @@ function SwipeActionButton(props: {
|
||||
const actionStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
const stretch = Math.max(reveal - props.actionsWidth, 0);
|
||||
const fullSwipeProgress = interpolate(
|
||||
reveal,
|
||||
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
|
||||
[props.actionsWidth, props.fullSwipeThreshold + 20],
|
||||
[0, 1],
|
||||
Extrapolation.CLAMP,
|
||||
);
|
||||
@@ -327,9 +397,7 @@ function SwipeActionButton(props: {
|
||||
});
|
||||
const circleStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch }],
|
||||
@@ -338,9 +406,7 @@ function SwipeActionButton(props: {
|
||||
});
|
||||
const iconStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
|
||||
const armedProgress = interpolate(
|
||||
reveal,
|
||||
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
|
||||
@@ -358,7 +424,7 @@ function SwipeActionButton(props: {
|
||||
}
|
||||
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
const stretch = Math.max(reveal - props.actionsWidth, 0);
|
||||
return {
|
||||
opacity: interpolate(
|
||||
reveal,
|
||||
@@ -370,6 +436,63 @@ function SwipeActionButton(props: {
|
||||
};
|
||||
});
|
||||
|
||||
const button = (
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
accessibilityRole="button"
|
||||
onPress={props.menu === undefined ? props.onPress : undefined}
|
||||
style={({ pressed }) => ({
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
justifyContent: "center",
|
||||
opacity: pressed ? 0.72 : 1,
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: circleSize, width: circleSize }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: circleSize,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
},
|
||||
circleStyle,
|
||||
]}
|
||||
/>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: circleSize,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: circleSize,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View
|
||||
style={[
|
||||
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
|
||||
labelStyle,
|
||||
]}
|
||||
>
|
||||
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
style={[
|
||||
@@ -383,60 +506,18 @@ function SwipeActionButton(props: {
|
||||
actionStyle,
|
||||
]}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
style={({ pressed }) => ({
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
justifyContent: "center",
|
||||
opacity: pressed ? 0.72 : 1,
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: circleSize, width: circleSize }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: circleSize,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
},
|
||||
circleStyle,
|
||||
]}
|
||||
/>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: circleSize,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: circleSize,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View
|
||||
style={[
|
||||
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
|
||||
labelStyle,
|
||||
]}
|
||||
{props.menu === undefined ? (
|
||||
button
|
||||
) : (
|
||||
<ControlPillMenu
|
||||
actions={props.menu.actions}
|
||||
onPressAction={props.menu.onPressAction}
|
||||
title={props.menu.title}
|
||||
style={{ height: "100%", width: "100%" }}
|
||||
>
|
||||
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
{button}
|
||||
</ControlPillMenu>
|
||||
)}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@@ -446,14 +527,14 @@ export function ThreadSwipeActions(props: {
|
||||
readonly compact: boolean;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly swipeableMethods: SwipeableMethods;
|
||||
readonly threadTitle: string;
|
||||
readonly primaryAction: ThreadSwipeAction;
|
||||
readonly secondaryAction: ThreadSwipeSecondaryAction | null;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
const secondaryAction = props.secondaryAction;
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary" || secondaryAction === null;
|
||||
const actionsWidth = swipeActionsWidth(secondaryAction !== null);
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -470,14 +551,19 @@ export function ThreadSwipeActions(props: {
|
||||
backgroundColor: props.backgroundColor,
|
||||
flexDirection: "row",
|
||||
height: "100%",
|
||||
width: THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
width: actionsWidth,
|
||||
}}
|
||||
>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={props.primaryAction.accessibilityLabel}
|
||||
actionsWidth={actionsWidth}
|
||||
backgroundColor="#007aff"
|
||||
compact={props.compact}
|
||||
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
|
||||
entryRange={
|
||||
secondaryAction === null
|
||||
? [8, ACTION_ITEM_WIDTH * 0.72]
|
||||
: [ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]
|
||||
}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
@@ -485,21 +571,22 @@ export function ThreadSwipeActions(props: {
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={`Delete ${props.threadTitle}`}
|
||||
backgroundColor="#ff2d55"
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon="trash"
|
||||
label="Delete"
|
||||
onPress={() => {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
{secondaryAction === null ? null : (
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={secondaryAction.accessibilityLabel}
|
||||
actionsWidth={actionsWidth}
|
||||
backgroundColor={secondaryAction.backgroundColor}
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={secondaryAction.icon}
|
||||
label={secondaryAction.label}
|
||||
menu={secondaryAction.menu}
|
||||
onPress={secondaryAction.onPress}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
@@ -22,6 +22,13 @@ function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["en
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -192,9 +199,14 @@ export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
|
||||
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -206,6 +218,94 @@ export function useThreadListActions(): {
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const snoozeThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (snoozeInFlightThreadKeys.current.has(key)) {
|
||||
return false;
|
||||
}
|
||||
snoozeInFlightThreadKeys.current.add(key);
|
||||
try {
|
||||
if (!environmentSupportsSnooze(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
"This environment's server does not support snoozing yet. Update the server to use Snooze.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (!canSnooze(thread, { now: new Date().toISOString() })) {
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
thread.hasPendingApprovals || thread.hasPendingUserInput
|
||||
? "This thread is waiting on you. Respond to the pending request before snoozing it."
|
||||
: "This thread is still starting a turn. Try again once it's running.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
selectionHaptic();
|
||||
const result = await snoozeMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: {
|
||||
threadId: thread.id,
|
||||
snoozedUntil,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be snoozed.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
snoozeInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[snoozeMutation],
|
||||
);
|
||||
const unsnoozeThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (snoozeInFlightThreadKeys.current.has(key)) {
|
||||
return false;
|
||||
}
|
||||
snoozeInFlightThreadKeys.current.add(key);
|
||||
try {
|
||||
if (!environmentSupportsSnooze(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not wake thread",
|
||||
"This environment's server does not support snoozing yet. Update the server to wake this thread.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
selectionHaptic();
|
||||
const result = await unsnoozeMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not wake thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be woken.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
snoozeInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[unsnoozeMutation],
|
||||
);
|
||||
const unsettleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
@@ -213,7 +313,14 @@ export function useThreadListActions(): {
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
|
||||
return {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
};
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -9,6 +9,8 @@ import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import {
|
||||
applyNativeShowcaseOrientation,
|
||||
getNativeShowcaseOrientation,
|
||||
getNativeShowcasePairingUrls,
|
||||
getNativeShowcaseScene,
|
||||
markNativeShowcaseReady,
|
||||
@@ -47,6 +49,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
const [pendingTasksReady, setPendingTasksReady] = useState(false);
|
||||
const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
|
||||
const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
|
||||
const [orientationSettled, setOrientationSettled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return;
|
||||
@@ -60,6 +63,25 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
return () => clearInterval(interval);
|
||||
}, [pairingUrls.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || orientationSettled) return;
|
||||
const orientation = getNativeShowcaseOrientation();
|
||||
if (orientation === null) {
|
||||
setOrientationSettled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
void retryShowcaseOperation(async () => applyNativeShowcaseOrientation(orientation), {
|
||||
isCancelled: () => cancelled,
|
||||
}).then((applied) => {
|
||||
if (!cancelled && applied) setOrientationSettled(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [orientationSettled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED) return;
|
||||
|
||||
@@ -182,7 +204,10 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
scene === null ||
|
||||
requestedScene === null ||
|
||||
scene !== requestedScene ||
|
||||
!hasFixture
|
||||
!hasFixture ||
|
||||
// Never report a scene ready while the capture orientation is still
|
||||
// being applied — a screenshot taken early has the wrong dimensions.
|
||||
!orientationSettled
|
||||
) {
|
||||
setReadyScene(null);
|
||||
return;
|
||||
@@ -210,7 +235,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
if (renderFrame !== null) cancelAnimationFrame(renderFrame);
|
||||
if (readyFrame !== null) cancelAnimationFrame(readyFrame);
|
||||
};
|
||||
}, [hasFixture, requestedScene, scene]);
|
||||
}, [hasFixture, orientationSettled, requestedScene, scene]);
|
||||
|
||||
if (!SHOWCASE_ENABLED || readyScene === null) return null;
|
||||
|
||||
|
||||
@@ -3,9 +3,14 @@ import { requireOptionalNativeModule } from "expo";
|
||||
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
|
||||
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
|
||||
|
||||
export type ShowcaseOrientation = "portrait" | "landscape";
|
||||
|
||||
interface NativeShowcaseControls {
|
||||
readonly getShowcasePairingUrl?: () => string | null;
|
||||
readonly getShowcaseScene?: () => string | null;
|
||||
readonly getShowcaseOrientation?: () => string | null;
|
||||
readonly applyShowcaseOrientation?: (orientation: ShowcaseOrientation) => Promise<void>;
|
||||
readonly getInterfaceOrientation?: () => Promise<string>;
|
||||
readonly prepareShowcaseCapture?: () => void;
|
||||
readonly markShowcaseReady?: (scene: ShowcaseScene) => void;
|
||||
}
|
||||
@@ -59,6 +64,35 @@ export function prepareNativeShowcaseCapture(): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function getNativeShowcaseOrientation(): ShowcaseOrientation | null {
|
||||
try {
|
||||
const orientation = nativeShowcaseControls()?.getShowcaseOrientation?.()?.trim();
|
||||
return orientation === "portrait" || orientation === "landscape" ? orientation : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyNativeShowcaseOrientation(
|
||||
orientation: ShowcaseOrientation,
|
||||
): Promise<boolean> {
|
||||
const controls = nativeShowcaseControls();
|
||||
if (!controls?.applyShowcaseOrientation || !controls.getInterfaceOrientation) {
|
||||
// A development build that predates this helper keeps its default
|
||||
// orientation; report success so callers do not retry forever.
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
await controls.applyShowcaseOrientation(orientation);
|
||||
// The geometry request settles asynchronously; confirm it took effect so
|
||||
// callers can retry attempts made before the scene was foreground-active.
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
return (await controls.getInterfaceOrientation()) === orientation;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function markNativeShowcaseReady(scene: ShowcaseScene): void {
|
||||
try {
|
||||
nativeShowcaseControls()?.markShowcaseReady?.(scene);
|
||||
|
||||
@@ -42,7 +42,8 @@ import {
|
||||
restoreComposerDraftSnapshot,
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
|
||||
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
@@ -90,6 +91,9 @@ export function NewTaskDraftScreen(props: {
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
selectedProject?.environmentId ?? null,
|
||||
);
|
||||
const environmentConnected =
|
||||
selectedProject !== null &&
|
||||
connectedEnvironments.find(
|
||||
@@ -795,7 +799,14 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(draftKey);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
// Snapshot read keeps just-typed selector state; the availability gate
|
||||
// still applies so a stored selection on a disabled provider falls back
|
||||
// to the flow's resolved model.
|
||||
const modelSelection =
|
||||
resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
draft.modelSelection ?? null,
|
||||
) ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
@@ -847,7 +858,10 @@ export function NewTaskDraftScreen(props: {
|
||||
if (editingPendingTask) {
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
clearComposerDraftContent(draftKey);
|
||||
// Drop the workspace selection with the content: the next task should
|
||||
// re-resolve mode/branch/origin from the server's configured defaults
|
||||
// instead of resurrecting this task's picks.
|
||||
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
|
||||
}
|
||||
navigation.getParent()?.goBack();
|
||||
return;
|
||||
@@ -905,7 +919,7 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
clearComposerDraftContent(draftKey);
|
||||
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
|
||||
@@ -67,7 +67,12 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "./thread-list-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
|
||||
import {
|
||||
ThreadListV2PendingRow,
|
||||
ThreadListV2Row,
|
||||
ThreadListV2SettledShelfHeader,
|
||||
ThreadListV2SnoozedShelfHeader,
|
||||
} from "./thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
@@ -193,8 +198,14 @@ function ThreadNavigationSidebarPane(
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const headerIsOverContentRef = useRef(false);
|
||||
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
@@ -428,6 +439,10 @@ function ThreadNavigationSidebarPane(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
// now ticks per minute so the inactivity auto-settle boundary is actually
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
@@ -468,7 +483,15 @@ function ThreadNavigationSidebarPane(
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return {
|
||||
items: [],
|
||||
hiddenSettledCount: 0,
|
||||
snoozedCount: 0,
|
||||
snoozedShelfHeaderIndex: null,
|
||||
settledCount: 0,
|
||||
settledShelfHeaderIndex: null,
|
||||
nextSnoozeWakeAt: null,
|
||||
};
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -481,11 +504,17 @@ function ThreadNavigationSidebarPane(
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
selectedThreadKey: props.selectedThreadKey ?? null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
settledShelfExpanded,
|
||||
props.selectedThreadKey,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
@@ -532,8 +561,15 @@ function ThreadNavigationSidebarPane(
|
||||
const items: SidebarListItem[] = buildThreadListV2ListItems({
|
||||
items: threadListV2Layout.items,
|
||||
pendingTasks: v2PendingTasks,
|
||||
snoozedCount: threadListV2Layout.snoozedCount,
|
||||
snoozedShelfExpanded,
|
||||
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
|
||||
settledCount: threadListV2Layout.settledCount,
|
||||
settledShelfExpanded,
|
||||
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
|
||||
snoozeLabelNow: `${nowMinute}:00.000Z`,
|
||||
});
|
||||
if (threadListV2Layout.hiddenSettledCount > 0) {
|
||||
if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
|
||||
items.push({
|
||||
type: "v2-show-more",
|
||||
key: "v2-show-more",
|
||||
@@ -543,10 +579,13 @@ function ThreadNavigationSidebarPane(
|
||||
return items;
|
||||
}, [
|
||||
listLayout.items,
|
||||
nowMinute,
|
||||
options.selectedEnvironmentId,
|
||||
pendingTasks,
|
||||
props.searchQuery,
|
||||
selectedProjectRefs,
|
||||
settledShelfExpanded,
|
||||
snoozedShelfExpanded,
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
@@ -731,6 +770,7 @@ function ThreadNavigationSidebarPane(
|
||||
projectTitleByProjectKey,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
snoozePresetMinute: nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
}),
|
||||
[
|
||||
@@ -740,6 +780,7 @@ function ThreadNavigationSidebarPane(
|
||||
projectTitleByProjectKey,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
nowMinute,
|
||||
threadSearchMatchByKey,
|
||||
],
|
||||
);
|
||||
@@ -750,7 +791,8 @@ function ThreadNavigationSidebarPane(
|
||||
previous.key === item.key &&
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.showSettledDivider === item.item.showSettledDivider
|
||||
previous.item.snoozed === item.item.snoozed &&
|
||||
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
|
||||
);
|
||||
}
|
||||
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
|
||||
@@ -762,13 +804,23 @@ function ThreadNavigationSidebarPane(
|
||||
previous.showPendingDivider === item.showPendingDivider
|
||||
);
|
||||
}
|
||||
if (previous.type === "v2-snoozed-shelf" && item.type === "v2-snoozed-shelf") {
|
||||
return previous.count === item.count && previous.expanded === item.expanded;
|
||||
}
|
||||
if (previous.type === "v2-settled-shelf" && item.type === "v2-settled-shelf") {
|
||||
return previous.count === item.count && previous.expanded === item.expanded;
|
||||
}
|
||||
if (
|
||||
previous.type === "v2-thread" ||
|
||||
previous.type === "v2-show-more" ||
|
||||
previous.type === "v2-pending" ||
|
||||
previous.type === "v2-snoozed-shelf" ||
|
||||
previous.type === "v2-settled-shelf" ||
|
||||
item.type === "v2-thread" ||
|
||||
item.type === "v2-show-more" ||
|
||||
item.type === "v2-pending"
|
||||
item.type === "v2-pending" ||
|
||||
item.type === "v2-snoozed-shelf" ||
|
||||
item.type === "v2-settled-shelf"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -826,7 +878,9 @@ function ThreadNavigationSidebarPane(
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
snoozed={item.item.snoozed}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
@@ -860,6 +914,9 @@ function ThreadNavigationSidebarPane(
|
||||
onArchiveThread={archiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
@@ -869,6 +926,24 @@ function ThreadNavigationSidebarPane(
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "v2-snoozed-shelf":
|
||||
return (
|
||||
<ThreadListV2SnoozedShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSnoozedShelf}
|
||||
pane="sidebar"
|
||||
/>
|
||||
);
|
||||
case "v2-settled-shelf":
|
||||
return (
|
||||
<ThreadListV2SettledShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSettledShelf}
|
||||
pane="sidebar"
|
||||
/>
|
||||
);
|
||||
case "v2-show-more":
|
||||
return (
|
||||
<Pressable
|
||||
@@ -984,7 +1059,13 @@ function ThreadNavigationSidebarPane(
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
sidebarScrollGesture,
|
||||
snoozeEnvironmentIds,
|
||||
snoozeThread,
|
||||
nowMinute,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
@@ -1031,30 +1112,19 @@ function ThreadNavigationSidebarPane(
|
||||
}),
|
||||
[filterIcon, filterMenu, props.onOpenSettings],
|
||||
);
|
||||
// "No threads yet" over an inbox that is merely all-snoozed reads as
|
||||
// data loss; name the snoozed threads instead.
|
||||
const snoozedCount = threadListV2Layout.snoozedCount;
|
||||
// Snoozed threads need no special case: the shelf header is a list row
|
||||
// even while collapsed.
|
||||
const listEmpty = (
|
||||
<Text className="px-2 py-4 text-sm text-foreground-muted">
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? threadSearch.isPending && snoozedCount === 0
|
||||
? threadSearch.isPending
|
||||
? "Searching thread messages…"
|
||||
: snoozedCount > 0
|
||||
? // Snoozed matches passed this same search filter — "No
|
||||
// matching threads" would misreport them as nonexistent.
|
||||
snoozedCount === 1
|
||||
? "1 matching thread snoozed"
|
||||
: "All matching threads snoozed"
|
||||
: "No matching threads"
|
||||
: snoozedCount > 0
|
||||
? snoozedCount === 1
|
||||
? "1 thread snoozed"
|
||||
: `${snoozedCount} threads snoozed`
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
: "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -22,7 +22,11 @@ import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../
|
||||
import type { TurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import {
|
||||
buildModelOptions,
|
||||
groupByProvider,
|
||||
resolveSelectableModelSelection,
|
||||
} from "../../lib/modelOptions";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
@@ -347,7 +351,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
// The server's configured default decides the mode until the user picks one
|
||||
// explicitly — same resolution web uses for new draft threads.
|
||||
const defaultWorkspaceMode: WorkspaceMode =
|
||||
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
// Keep the user's explicit choice separate from the resolved display value:
|
||||
@@ -361,22 +369,29 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
// Stored selections (draft and project default) only count while their
|
||||
// provider is usable on the server; otherwise the server's default model
|
||||
// wins instead of silently targeting a disabled provider.
|
||||
const draftModelSelection = resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? null,
|
||||
);
|
||||
const projectDefaultModelSelection = resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
);
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
draftModelSelection ?? projectDefaultModelSelection,
|
||||
),
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
[selectedEnvironmentServerConfig, draftModelSelection, projectDefaultModelSelection],
|
||||
);
|
||||
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
draftModelSelection ??
|
||||
projectDefaultModelSelection ??
|
||||
modelOptions.find((option) => option.isDefault)?.selection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
@@ -675,12 +690,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
|
||||
const text = draft.text.trim();
|
||||
const draftModelSelection = draft.modelSelection ?? selectedModel;
|
||||
// Same availability gate the composer display applies: a stored
|
||||
// selection targeting a disabled provider must not ride into the queue.
|
||||
const draftModelSelection =
|
||||
resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
draft.modelSelection ?? null,
|
||||
) ?? selectedModel;
|
||||
if (text.length === 0 || !draftModelSelection) {
|
||||
return null;
|
||||
}
|
||||
const workspaceSelection = draft.workspaceSelection;
|
||||
const mode = workspaceSelection?.mode ?? "local";
|
||||
// Fall back to the resolved mode (server default) so queued tasks drain
|
||||
// with the same mode the composer displayed.
|
||||
const mode = workspaceSelection?.mode ?? workspaceMode;
|
||||
// When the selection is the stand-in built from the queued snapshot,
|
||||
// persist the original (possibly absent) snapshot values — the
|
||||
// stand-in's placeholder title/workspaceRoot must never be written back
|
||||
@@ -722,10 +745,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
[
|
||||
editingPendingProject,
|
||||
editingPendingTask,
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
startFromOrigin,
|
||||
workspaceMode,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { ReactNode } from "react";
|
||||
import { Platform, useColorScheme } from "react-native";
|
||||
|
||||
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
|
||||
|
||||
@@ -35,10 +36,9 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? { backgroundColor: "transparent" } : undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
...getCompactBrandHeaderOptions({ fontSize: 18, fontWeight: "800" }),
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? SCROLL_EDGE_EFFECTS : undefined,
|
||||
title: "Threads",
|
||||
unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined,
|
||||
};
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
@@ -33,7 +34,7 @@ import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
export type ThreadListVariant = "compact" | "sidebar";
|
||||
|
||||
/** Left inset that aligns compact secondary rows with the title column. */
|
||||
export const THREAD_LIST_COMPACT_INSET = 20;
|
||||
export const THREAD_LIST_COMPACT_INSET = HOME_HORIZONTAL_INSET;
|
||||
const SIDEBAR_ROW_RADIUS = 12;
|
||||
|
||||
function pullRequestTintColor(
|
||||
|
||||
@@ -3,11 +3,20 @@ import type {
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
|
||||
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Platform,
|
||||
Pressable,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
@@ -18,7 +27,13 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
|
||||
import {
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
type ThreadListV2Status,
|
||||
} from "./threadListV2";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
|
||||
/**
|
||||
@@ -62,6 +77,11 @@ const SLIM_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
const SNOOZED_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "unsnooze", title: "Wake thread", image: "clock" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
// Pre-settlement servers: no lifecycle items, archive fills the gap.
|
||||
const LEGACY_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
@@ -90,6 +110,81 @@ export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivid
|
||||
);
|
||||
});
|
||||
|
||||
const SNOOZE_ACCENT_LIGHT = "#2563eb";
|
||||
const SNOOZE_ACCENT_DARK = "#60a5fa";
|
||||
|
||||
export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader(props: {
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint={
|
||||
props.expanded ? "Collapses the snoozed threads." : "Expands the snoozed threads."
|
||||
}
|
||||
accessibilityLabel={props.count === 1 ? "1 snoozed thread" : `${props.count} snoozed threads`}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
onPress={props.onToggle}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-blue-600 dark:text-blue-400">
|
||||
{props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
|
||||
</Text>
|
||||
<View className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={colorScheme === "dark" ? SNOOZE_ACCENT_DARK : SNOOZE_ACCENT_LIGHT}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadListV2SettledShelfHeader = memo(function ThreadListV2SettledShelfHeader(props: {
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
}) {
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint={
|
||||
props.expanded ? "Collapses the settled threads." : "Expands the settled threads."
|
||||
}
|
||||
accessibilityLabel={props.count === 1 ? "1 settled thread" : `${props.count} settled threads`}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
onPress={props.onToggle}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">
|
||||
{props.expanded ? "Settled" : `Settled (${props.count})`}
|
||||
</Text>
|
||||
<View className="h-px flex-1 bg-border" />
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={mutedColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
@@ -208,7 +303,14 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
/** Snoozed-shelf row: shows its wake time and offers Wake. */
|
||||
readonly snoozed?: boolean;
|
||||
/** Preformatted against the parent minute tick so this memoized row's
|
||||
countdown keeps moving. */
|
||||
readonly snoozeWakeLabelText?: string;
|
||||
/** Parent minute tick passed as a prop so this memoized row refreshes its
|
||||
native snooze menu while mounted. */
|
||||
readonly snoozePresetMinute: string;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly providerDriver: string | null;
|
||||
@@ -231,11 +333,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** False on environments whose server predates thread.settle/unsettle:
|
||||
swipe + menu fall back to Archive instead of failing on use. */
|
||||
readonly settlementSupported: boolean;
|
||||
/** False on servers that predate thread.snooze/unsnooze. */
|
||||
readonly snoozeSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
@@ -258,10 +364,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
@@ -283,27 +392,94 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleSnooze = useCallback(
|
||||
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
|
||||
[onSnoozeThread, thread],
|
||||
);
|
||||
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle],
|
||||
);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
// row can un-settle — explicit settles clear the override, auto-settled
|
||||
// rows get pinned active until real activity clears the pin.
|
||||
const canUnsettle = variant === "slim";
|
||||
const [snoozeGateTick, bumpSnoozeGateTick] = useState(0);
|
||||
const snoozeGateExpiryMs = props.snoozeSupported
|
||||
? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: new Date().toISOString() })
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (snoozeGateExpiryMs === null) return;
|
||||
const delayMs = Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeGateTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
}, [snoozeGateExpiryMs, snoozeGateTick]);
|
||||
const swipeActions = resolveThreadListV2SwipeActions({
|
||||
variant,
|
||||
settlementSupported: props.settlementSupported,
|
||||
snoozeSupported: props.snoozeSupported,
|
||||
snoozable: canSnooze(thread, { now: new Date().toISOString() }),
|
||||
snoozed: snoozedRow,
|
||||
});
|
||||
const snoozePresets = useMemo(
|
||||
() => (swipeActions.secondary === "snooze" ? resolveSnoozePresets(new Date()) : ([] as const)),
|
||||
[props.snoozePresetMinute, swipeActions.secondary],
|
||||
);
|
||||
const snoozePresetActions = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
snoozePresets.map((preset) => ({
|
||||
id: `snooze:${preset.id}`,
|
||||
title: preset.label,
|
||||
subtitle: preset.whenLabel,
|
||||
})),
|
||||
[snoozePresets],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{
|
||||
id: "snooze",
|
||||
title: "Snooze",
|
||||
image: "clock",
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[snoozePresetActions],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "unsnooze") handleUnsnooze();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: nativeEvent.event,
|
||||
displayedPresets: snoozePresets,
|
||||
now: new Date(),
|
||||
});
|
||||
if (snoozeSelection._tag === "selected") {
|
||||
handleSnooze(snoozeSelection.preset.snoozedUntil);
|
||||
} else if (snoozeSelection._tag === "expired") {
|
||||
Alert.alert("Could not snooze thread", "That snooze time has passed. Choose another time.");
|
||||
}
|
||||
},
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
handleUnsettle,
|
||||
handleUnsnooze,
|
||||
snoozePresets,
|
||||
],
|
||||
);
|
||||
const primaryAction = useMemo(() => {
|
||||
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
|
||||
// rows cannot occur here — unsupported environments never classify as
|
||||
// settled.)
|
||||
if (!props.settlementSupported) {
|
||||
if (swipeActions.primary === "archive") {
|
||||
return {
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
icon: "archivebox" as const,
|
||||
@@ -311,7 +487,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onPress: handleArchive,
|
||||
};
|
||||
}
|
||||
return canUnsettle
|
||||
if (swipeActions.primary === "unsnooze") {
|
||||
return {
|
||||
accessibilityLabel: `Wake ${thread.title} now`,
|
||||
icon: "clock" as const,
|
||||
label: "Wake",
|
||||
onPress: handleUnsnooze,
|
||||
};
|
||||
}
|
||||
return swipeActions.primary === "unsettle"
|
||||
? {
|
||||
accessibilityLabel: `Un-settle ${thread.title}`,
|
||||
icon: "arrow.uturn.backward" as const,
|
||||
@@ -325,13 +509,34 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onPress: handleSettle,
|
||||
};
|
||||
}, [
|
||||
canUnsettle,
|
||||
handleArchive,
|
||||
handleSettle,
|
||||
handleUnsettle,
|
||||
props.settlementSupported,
|
||||
handleUnsnooze,
|
||||
swipeActions.primary,
|
||||
thread.title,
|
||||
]);
|
||||
const secondaryAction = useMemo(
|
||||
() =>
|
||||
swipeActions.secondary === "snooze"
|
||||
? {
|
||||
accessibilityLabel: `Choose when to snooze ${thread.title}`,
|
||||
icon: "clock" as const,
|
||||
label: "Snooze",
|
||||
menu: {
|
||||
actions: snoozePresetActions,
|
||||
onPressAction: handleMenuAction,
|
||||
title: "Snooze until",
|
||||
},
|
||||
onPress: () => undefined,
|
||||
}
|
||||
: null,
|
||||
[handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title],
|
||||
);
|
||||
const swipeAccessibilityHint =
|
||||
secondaryAction === null
|
||||
? `Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`
|
||||
: `Opens the thread. Swipe left for ${primaryAction.label.toLowerCase()} and snooze actions.`;
|
||||
|
||||
// The sidebar pane fills selected rows with the accent color (matching the
|
||||
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
|
||||
@@ -453,7 +658,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const rowContent = (close: () => void) =>
|
||||
variant === "card" ? (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityHint={swipeAccessibilityHint}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
@@ -491,7 +696,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</Pressable>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityHint={swipeAccessibilityHint}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
@@ -551,11 +756,17 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<Text
|
||||
className={cn(
|
||||
"text-sm tabular-nums",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: snoozedRow
|
||||
? "text-blue-600 dark:text-blue-400"
|
||||
: "text-foreground-tertiary",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
{snoozedRow && props.snoozeWakeLabelText !== undefined
|
||||
? props.snoozeWakeLabelText
|
||||
: relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
@@ -563,9 +774,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showSettledDivider ? (
|
||||
<ThreadListV2SectionDivider label="Settled" pane={props.pane} />
|
||||
) : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={sidebarPane ? drawerColor : screenColor}
|
||||
compactActions={variant === "slim"}
|
||||
@@ -574,13 +782,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
}
|
||||
enableTrackpadSwipe
|
||||
// Full swipe commits the advertised lifecycle action (Settle /
|
||||
// Un-settle), never the destructive delete.
|
||||
// Un-settle), never the secondary snooze action.
|
||||
fullSwipeAction="primary"
|
||||
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
|
||||
onDelete={handleDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={primaryAction}
|
||||
secondaryAction={secondaryAction}
|
||||
resetKey={`${thread.environmentId}:${thread.id}`}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={thread.title}
|
||||
@@ -588,11 +797,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{(close) => (
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
!props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: CARD_MENU_ACTIONS
|
||||
snoozedRow
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
: !props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: CARD_MENU_ACTIONS
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import { resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
@@ -16,7 +17,10 @@ import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
resolveThreadListV2Enabled,
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
|
||||
@@ -50,6 +54,54 @@ function makeThread(
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2SnoozeMenuSelection", () => {
|
||||
it("accepts a displayed evening preset while its wake time is still future", () => {
|
||||
const menuOpenedAt = new Date(2026, 4, 8, 16, 59, 30);
|
||||
const selectedAt = new Date(2026, 4, 8, 17, 0, 30);
|
||||
const displayedPresets = resolveSnoozePresets(menuOpenedAt);
|
||||
|
||||
const selection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: "snooze:evening",
|
||||
displayedPresets,
|
||||
now: selectedAt,
|
||||
});
|
||||
|
||||
expect(selection).toEqual({
|
||||
_tag: "selected",
|
||||
preset: displayedPresets.find((preset) => preset.id === "evening"),
|
||||
});
|
||||
});
|
||||
|
||||
it("expires a displayed preset once its wake time has passed", () => {
|
||||
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 16, 59, 30));
|
||||
|
||||
expect(
|
||||
resolveThreadListV2SnoozeMenuSelection({
|
||||
event: "snooze:evening",
|
||||
displayedPresets,
|
||||
now: new Date(2026, 4, 8, 18, 0, 1),
|
||||
}),
|
||||
).toEqual({ _tag: "expired" });
|
||||
});
|
||||
|
||||
it("recomputes presets that remain available instead of using old timestamps", () => {
|
||||
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 10));
|
||||
const selectedAt = new Date(2026, 4, 8, 10, 30);
|
||||
const selection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: "snooze:hour",
|
||||
displayedPresets,
|
||||
now: selectedAt,
|
||||
});
|
||||
|
||||
expect(selection._tag).toBe("selected");
|
||||
if (selection._tag === "selected") {
|
||||
expect(selection.preset.snoozedUntil).toBe(
|
||||
new Date(selectedAt.getTime() + 60 * 60 * 1_000).toISOString(),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2Enabled", () => {
|
||||
it("defaults on when the device has never chosen", () => {
|
||||
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
|
||||
@@ -96,6 +148,105 @@ describe("resolveThreadListV2Status", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2SwipeActions", () => {
|
||||
it("offers settle and snooze for an active snoozable thread", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: "snooze" });
|
||||
});
|
||||
|
||||
it("offers un-settle and snooze for settled history", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "slim",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "unsettle", secondary: "snooze" });
|
||||
});
|
||||
|
||||
it("omits snooze when the server or thread does not allow it", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: false,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: null });
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: false,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: null });
|
||||
});
|
||||
|
||||
it("falls back to archive only for a pre-lifecycle server", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: false,
|
||||
snoozeSupported: false,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "archive", secondary: null });
|
||||
});
|
||||
|
||||
it("offers wake and no snooze on a snoozed row", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "slim",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
snoozed: true,
|
||||
}),
|
||||
).toEqual({ primary: "unsnooze", secondary: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2SnoozeGateExpiryMs", () => {
|
||||
it("reports when an unadopted turn's grace window lapses", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
latestUserMessageAt: "2026-06-02T00:00:30.000Z",
|
||||
});
|
||||
expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: "2026-06-02T00:01:00.000Z" })).toBe(
|
||||
Date.parse("2026-06-02T00:02:30.000Z"),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null once the thread is snoozable or when only data can unblock it", () => {
|
||||
expect(
|
||||
resolveThreadListV2SnoozeGateExpiryMs(
|
||||
makeThread({ id: ThreadId.make("ready"), title: "Ready" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(null);
|
||||
expect(
|
||||
resolveThreadListV2SnoozeGateExpiryMs(
|
||||
makeThread({
|
||||
id: ThreadId.make("blocked"),
|
||||
title: "Blocked",
|
||||
hasPendingApprovals: true,
|
||||
latestUserMessageAt: NOW,
|
||||
}),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForListV2([
|
||||
@@ -167,6 +318,93 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("builds snoozed rows between active and settled when the shelf is expanded", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("later"),
|
||||
title: "Wakes later",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("sooner"),
|
||||
title: "Wakes sooner",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
snoozedShelfExpanded: true,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([
|
||||
"active",
|
||||
"sooner",
|
||||
"later",
|
||||
"settled",
|
||||
]);
|
||||
expect(layout.items.map((item) => item.snoozed)).toEqual([false, true, true, false]);
|
||||
expect(layout.snoozedShelfHeaderIndex).toBe(1);
|
||||
expect(layout.snoozedCount).toBe(2);
|
||||
});
|
||||
|
||||
it("collapses to a header-only shelf", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items).toEqual([]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
expect(layout.snoozedShelfHeaderIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps the selected thread on a collapsed shelf", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("open"),
|
||||
title: "Open",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("other"),
|
||||
title: "Other",
|
||||
snoozedUntil: "2026-06-03T10:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
selectedThreadKey: `${environmentId}:open`,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["open"]);
|
||||
expect(layout.items[0]?.snoozed).toBe(true);
|
||||
expect(layout.snoozedCount).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
@@ -187,8 +425,8 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
it("partitions settled threads into a slim shelf", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
@@ -209,13 +447,64 @@ describe("buildThreadListV2Items", () => {
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["active", "card"],
|
||||
["settled", "slim"],
|
||||
["settled-2", "slim"],
|
||||
]);
|
||||
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
|
||||
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
expect(layout.items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
expect(layout.settledCount).toBe(2);
|
||||
expect(layout.settledShelfHeaderIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("collapses settled threads to a counted shelf header", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
settledShelfExpanded: false,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["active"]);
|
||||
expect(layout.settledCount).toBe(1);
|
||||
expect(layout.settledShelfHeaderIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps the selected settled thread visible when its shelf is collapsed", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("selected"),
|
||||
title: "Selected",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("other"),
|
||||
title: "Other",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
settledShelfExpanded: false,
|
||||
selectedThreadKey: `${environmentId}:selected`,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["selected"]);
|
||||
expect(layout.settledCount).toBe(2);
|
||||
expect(layout.settledShelfHeaderIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps cards in creation order while settled sorts by recency", () => {
|
||||
@@ -420,13 +709,21 @@ describe("buildThreadListV2ListItems", () => {
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: layout.items,
|
||||
pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
|
||||
settledCount: layout.settledCount,
|
||||
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
|
||||
});
|
||||
|
||||
expect(
|
||||
items.map((item) =>
|
||||
item.type === "v2-pending" ? item.pendingTask.title : item.item.thread.id,
|
||||
item.type === "v2-pending"
|
||||
? item.pendingTask.title
|
||||
: item.type === "v2-thread"
|
||||
? item.item.thread.id
|
||||
: item.type === "v2-snoozed-shelf"
|
||||
? "snoozed-shelf"
|
||||
: "settled-shelf",
|
||||
),
|
||||
).toEqual(["active", "queued-1", "queued-2", "settled"]);
|
||||
).toEqual(["active", "queued-1", "queued-2", "settled-shelf", "settled"]);
|
||||
// Only the leading queued row labels the section, exactly like Settled.
|
||||
expect(
|
||||
items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
|
||||
@@ -448,12 +745,58 @@ describe("buildThreadListV2ListItems", () => {
|
||||
expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
|
||||
});
|
||||
|
||||
it("leaves the thread order untouched when nothing is queued", () => {
|
||||
const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks: [] });
|
||||
it("keeps the settled shelf between active and settled rows when nothing is queued", () => {
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: layout.items,
|
||||
pendingTasks: [],
|
||||
settledCount: layout.settledCount,
|
||||
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual([
|
||||
`v2-thread:${environmentId}:active`,
|
||||
"v2-settled-shelf",
|
||||
`v2-thread:${environmentId}:settled`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("places queued tasks before a collapsed snoozed shelf", () => {
|
||||
const snoozedLayout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: snoozedLayout.items,
|
||||
pendingTasks: [makePendingTask("queued")],
|
||||
snoozedCount: snoozedLayout.snoozedCount,
|
||||
snoozedShelfExpanded: false,
|
||||
snoozedShelfHeaderIndex: snoozedLayout.snoozedShelfHeaderIndex,
|
||||
settledCount: snoozedLayout.settledCount,
|
||||
settledShelfHeaderIndex: snoozedLayout.settledShelfHeaderIndex,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.type)).toEqual([
|
||||
"v2-thread",
|
||||
"v2-pending",
|
||||
"v2-snoozed-shelf",
|
||||
"v2-settled-shelf",
|
||||
"v2-thread",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,20 @@
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
effectiveSettled,
|
||||
effectiveSnoozed,
|
||||
hasQueuedTurnStart,
|
||||
QUEUED_TURN_START_GRACE_MS,
|
||||
resolveSnoozePresets,
|
||||
snoozeWakeLabel,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export { snoozeWakeLabel };
|
||||
|
||||
/**
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
@@ -14,6 +24,76 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
* unlabeled resting state.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
|
||||
|
||||
export function resolveThreadListV2SnoozeMenuSelection(input: {
|
||||
readonly event: string;
|
||||
readonly displayedPresets: ReadonlyArray<SnoozePreset>;
|
||||
readonly now: Date;
|
||||
}):
|
||||
| { readonly _tag: "selected"; readonly preset: SnoozePreset }
|
||||
| { readonly _tag: "expired" }
|
||||
| { readonly _tag: "not-snooze" } {
|
||||
if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
|
||||
|
||||
const currentPreset = resolveSnoozePresets(input.now).find(
|
||||
(candidate) => input.event === `snooze:${candidate.id}`,
|
||||
);
|
||||
if (currentPreset) return { _tag: "selected", preset: currentPreset };
|
||||
|
||||
const displayedPreset = input.displayedPresets.find(
|
||||
(candidate) => input.event === `snooze:${candidate.id}`,
|
||||
);
|
||||
if (displayedPreset && Date.parse(displayedPreset.snoozedUntil) > input.now.getTime()) {
|
||||
return { _tag: "selected", preset: displayedPreset };
|
||||
}
|
||||
return { _tag: "expired" };
|
||||
}
|
||||
|
||||
export function resolveThreadListV2SwipeActions(input: {
|
||||
readonly variant: "card" | "slim";
|
||||
readonly settlementSupported: boolean;
|
||||
readonly snoozeSupported: boolean;
|
||||
readonly snoozable: boolean;
|
||||
/** Row is on the snoozed shelf. */
|
||||
readonly snoozed?: boolean;
|
||||
}): {
|
||||
readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
|
||||
readonly secondary: "snooze" | null;
|
||||
} {
|
||||
if (input.snoozed === true) {
|
||||
return { primary: "unsnooze", secondary: null };
|
||||
}
|
||||
const primary = input.settlementSupported
|
||||
? input.variant === "slim"
|
||||
? "unsettle"
|
||||
: "settle"
|
||||
: "archive";
|
||||
return {
|
||||
primary,
|
||||
secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The point at which a queued-turn snooze guard expires on its own. Rows arm
|
||||
* a one-shot timer for this boundary so Snooze appears without waiting for an
|
||||
* unrelated render. User-blocked threads return null because only fresh
|
||||
* server data can make them snoozable.
|
||||
*/
|
||||
export function resolveThreadListV2SnoozeGateExpiryMs(
|
||||
thread: Pick<
|
||||
EnvironmentThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): number | null {
|
||||
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
|
||||
if (!hasQueuedTurnStart(thread, options)) return null;
|
||||
const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
|
||||
if (Number.isNaN(messageAtMs)) return null;
|
||||
return messageAtMs + QUEUED_TURN_START_GRACE_MS;
|
||||
}
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more. Shared by the compact Home list and
|
||||
@@ -98,8 +178,8 @@ export function sortThreadsForListV2<T extends { readonly id: string; readonly c
|
||||
export interface ThreadListV2Item {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
/** First settled row after the card block draws the SETTLED divider. */
|
||||
readonly showSettledDivider: boolean;
|
||||
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
|
||||
readonly snoozed: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
@@ -107,10 +187,16 @@ export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
/** Snoozed threads hidden from the list (visibility parity with web's
|
||||
collapsed Snoozed shelf; mobile has no shelf UI yet). */
|
||||
/** Snoozed threads matching the current filters. */
|
||||
readonly snoozedCount: number;
|
||||
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
|
||||
/** Index in `items` where the Snoozed shelf header belongs. The header is
|
||||
still rendered when the shelf is collapsed and no snoozed rows exist. */
|
||||
readonly snoozedShelfHeaderIndex: number | null;
|
||||
/** Total settled threads in scope, including rows hidden by collapse/paging. */
|
||||
readonly settledCount: number;
|
||||
/** Index in `items` where the Settled shelf header belongs. */
|
||||
readonly settledShelfHeaderIndex: number | null;
|
||||
/** Soonest wake time among snoozed threads, or null. Callers arm
|
||||
a timeout at this boundary so the list re-partitions the moment a
|
||||
snooze expires instead of on the next minute tick. */
|
||||
readonly nextSnoozeWakeAt: string | null;
|
||||
@@ -120,6 +206,8 @@ export interface ThreadListV2ThreadListItem {
|
||||
readonly type: "v2-thread";
|
||||
readonly key: string;
|
||||
readonly item: ThreadListV2Item;
|
||||
/** Precomputed so recycled-list equality can see a minute-tick change. */
|
||||
readonly snoozeWakeLabelText: string | undefined;
|
||||
}
|
||||
|
||||
export interface ThreadListV2PendingListItem {
|
||||
@@ -130,28 +218,53 @@ export interface ThreadListV2PendingListItem {
|
||||
readonly showPendingDivider: boolean;
|
||||
}
|
||||
|
||||
export type ThreadListV2ListItem = ThreadListV2ThreadListItem | ThreadListV2PendingListItem;
|
||||
export interface ThreadListV2SnoozedShelfListItem {
|
||||
readonly type: "v2-snoozed-shelf";
|
||||
readonly key: "v2-snoozed-shelf";
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadListV2SettledShelfListItem {
|
||||
readonly type: "v2-settled-shelf";
|
||||
readonly key: "v2-settled-shelf";
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
}
|
||||
|
||||
export type ThreadListV2ListItem =
|
||||
| ThreadListV2ThreadListItem
|
||||
| ThreadListV2PendingListItem
|
||||
| ThreadListV2SnoozedShelfListItem
|
||||
| ThreadListV2SettledShelfListItem;
|
||||
|
||||
/**
|
||||
* Splices queued tasks between the active block and the settled tail, so the
|
||||
* list reads active → pending → settled. Queued work sits below the live
|
||||
* threads because nothing can happen to it until its environment returns:
|
||||
* it is waiting, not asking. Shared by the compact Home list and the iPad
|
||||
* sidebar so both order and label the sections identically.
|
||||
* Builds the shared mobile order: active → pending → snoozed shelf → settled.
|
||||
* Pending tasks are waiting rather than asking, and parked work remains
|
||||
* reachable without competing with either the inbox or settled history.
|
||||
*/
|
||||
export function buildThreadListV2ListItems(input: {
|
||||
readonly items: ReadonlyArray<ThreadListV2Item>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly snoozedCount?: number;
|
||||
readonly snoozedShelfExpanded?: boolean;
|
||||
readonly snoozedShelfHeaderIndex?: number | null;
|
||||
readonly settledCount?: number;
|
||||
readonly settledShelfExpanded?: boolean;
|
||||
readonly settledShelfHeaderIndex?: number | null;
|
||||
readonly snoozeLabelNow?: string;
|
||||
}): ThreadListV2ListItem[] {
|
||||
const threadItems = input.items.map(
|
||||
(item): ThreadListV2ListItem => ({
|
||||
type: "v2-thread",
|
||||
key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
|
||||
item,
|
||||
snoozeWakeLabelText:
|
||||
item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
|
||||
? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
if (input.pendingTasks.length === 0) return threadItems;
|
||||
|
||||
const pendingItems = input.pendingTasks.map(
|
||||
(pendingTask, index): ThreadListV2ListItem => ({
|
||||
type: "v2-pending",
|
||||
@@ -160,14 +273,32 @@ export function buildThreadListV2ListItems(input: {
|
||||
showPendingDivider: index === 0,
|
||||
}),
|
||||
);
|
||||
// The settled tail begins at the row that draws the SETTLED divider; with
|
||||
// no settled rows the queued block simply ends the list.
|
||||
const settledStart = threadItems.findIndex(
|
||||
(entry) => entry.type === "v2-thread" && entry.item.showSettledDivider,
|
||||
);
|
||||
return settledStart === -1
|
||||
? [...threadItems, ...pendingItems]
|
||||
: [...threadItems.slice(0, settledStart), ...pendingItems, ...threadItems.slice(settledStart)];
|
||||
const snoozedCount = input.snoozedCount ?? 0;
|
||||
const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
|
||||
const settledCount = input.settledCount ?? 0;
|
||||
const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
|
||||
const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length;
|
||||
const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
|
||||
const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems];
|
||||
if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
|
||||
result.push({
|
||||
type: "v2-snoozed-shelf",
|
||||
key: "v2-snoozed-shelf",
|
||||
count: snoozedCount,
|
||||
expanded: input.snoozedShelfExpanded === true,
|
||||
});
|
||||
result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
|
||||
}
|
||||
if (settledShelfHeaderIndex !== null && settledCount > 0) {
|
||||
result.push({
|
||||
type: "v2-settled-shelf",
|
||||
key: "v2-settled-shelf",
|
||||
count: settledCount,
|
||||
expanded: input.settledShelfExpanded !== false,
|
||||
});
|
||||
result.push(...threadItems.slice(settledShelfHeaderIndex));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -204,6 +335,13 @@ export function buildThreadListV2Items(input: {
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
/** Expands the snoozed shelf into rows. Collapsed is the default. */
|
||||
readonly snoozedShelfExpanded?: boolean;
|
||||
/** Expands the settled shelf into rows. Expanded is the default. */
|
||||
readonly settledShelfExpanded?: boolean;
|
||||
/** The selected thread remains visible on an otherwise collapsed shelf so
|
||||
a split-view detail can never lose its navigation row. */
|
||||
readonly selectedThreadKey?: string | null;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
@@ -215,7 +353,7 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
@@ -244,7 +382,7 @@ export function buildThreadListV2Items(input: {
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
snoozed.push(thread);
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
@@ -265,24 +403,60 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
|
||||
const orderedActive = sortThreadsForListV2(active);
|
||||
const orderedSnoozed = [...snoozed].sort(
|
||||
(left, right) =>
|
||||
parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
|
||||
);
|
||||
const selectedThreadKey = input.selectedThreadKey ?? null;
|
||||
const visibleSnoozed =
|
||||
input.snoozedShelfExpanded === true
|
||||
? orderedSnoozed
|
||||
: orderedSnoozed.filter(
|
||||
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
|
||||
);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
|
||||
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
|
||||
);
|
||||
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
|
||||
const visibleSettled =
|
||||
const pagedSettled =
|
||||
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
|
||||
const selectedSettled = orderedSettled
|
||||
.slice(pagedSettled.length)
|
||||
.find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
|
||||
if (selectedSettled !== undefined) pagedSettled.push(selectedSettled);
|
||||
const visibleSettled =
|
||||
input.settledShelfExpanded !== false
|
||||
? pagedSettled
|
||||
: pagedSettled.filter(
|
||||
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
|
||||
);
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of orderedActive) {
|
||||
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
snoozed: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
for (const [index, thread] of visibleSettled.entries()) {
|
||||
const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
|
||||
for (const thread of visibleSnoozed) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: index === 0,
|
||||
snoozed: true,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
|
||||
for (const thread of visibleSettled) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
snoozed: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
@@ -292,8 +466,11 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
hiddenSettledCount: orderedSettled.length - pagedSettled.length,
|
||||
snoozedCount: orderedSnoozed.length,
|
||||
snoozedShelfHeaderIndex,
|
||||
settledCount: orderedSettled.length,
|
||||
settledShelfHeaderIndex,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
}
|
||||
@@ -65,14 +65,6 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
};
|
||||
}
|
||||
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
|
||||
if (!permission.granted) {
|
||||
return {
|
||||
images: [],
|
||||
error: "Allow photo library access to attach images.",
|
||||
};
|
||||
}
|
||||
|
||||
const result = await imagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Horizontal inset shared by the home header and compact thread list. */
|
||||
export const HOME_HORIZONTAL_INSET = 20;
|
||||
|
||||
/** Compensates for the tighter native sidebar title margin on iPad. */
|
||||
export const IPAD_HOME_TITLE_OFFSET = 10;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveMobileStageLabel } from "./mobileBranding";
|
||||
|
||||
describe("resolveMobileStageLabel", () => {
|
||||
it.each([
|
||||
["development", "Dev"],
|
||||
["preview", "Nightly"],
|
||||
["production", "Alpha"],
|
||||
[undefined, "Alpha"],
|
||||
])("maps %s builds to %s", (appVariant, expected) => {
|
||||
expect(resolveMobileStageLabel(appVariant)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export type MobileStageLabel = "Alpha" | "Dev" | "Nightly";
|
||||
|
||||
export function resolveMobileStageLabel(appVariant: unknown): MobileStageLabel {
|
||||
if (appVariant === "development") return "Dev";
|
||||
if (appVariant === "preview") return "Nightly";
|
||||
return "Alpha";
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
|
||||
|
||||
import { buildModelOptions } from "./modelOptions";
|
||||
import { buildModelOptions, resolveSelectableModelSelection } from "./modelOptions";
|
||||
|
||||
describe("mobile model options", () => {
|
||||
it("normalizes a legacy fallback selection against current capabilities", () => {
|
||||
@@ -49,4 +49,46 @@ describe("mobile model options", () => {
|
||||
expect(option?.capabilities?.optionDescriptors?.[0]?.id).toBe("serviceTier");
|
||||
expect(option?.selection.options).toEqual([{ id: "serviceTier", value: "default" }]);
|
||||
});
|
||||
|
||||
it("rejects stored selections whose provider is not usable", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
{
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [],
|
||||
},
|
||||
{
|
||||
instanceId: "claudeAgent",
|
||||
driver: "claudeAgent",
|
||||
enabled: false,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [],
|
||||
},
|
||||
],
|
||||
} as unknown as ServerConfig;
|
||||
|
||||
const usable = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.6-sol",
|
||||
};
|
||||
const disabled = {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-5",
|
||||
};
|
||||
const removed = {
|
||||
instanceId: ProviderInstanceId.make("codex_personal"),
|
||||
model: "gpt-5.6-sol",
|
||||
};
|
||||
|
||||
expect(resolveSelectableModelSelection(config, usable)).toBe(usable);
|
||||
expect(resolveSelectableModelSelection(config, disabled)).toBeNull();
|
||||
expect(resolveSelectableModelSelection(config, removed)).toBeNull();
|
||||
// No config (environment offline) — nothing to validate against.
|
||||
expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);
|
||||
});
|
||||
});
|
||||
@@ -58,6 +58,31 @@ function normalizeSelectionOptions(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A stored model selection is only usable when its provider instance is
|
||||
* currently enabled, installed, and authenticated on the server. Returns the
|
||||
* selection unchanged when usable, otherwise `null` so callers fall through to
|
||||
* the server's default model. A missing config (environment offline) cannot be
|
||||
* validated, so stored selections pass through untouched.
|
||||
*/
|
||||
export function resolveSelectableModelSelection(
|
||||
config: T3ServerConfig | null | undefined,
|
||||
selection: ModelSelection | null,
|
||||
): ModelSelection | null {
|
||||
if (!selection || !config) {
|
||||
return selection;
|
||||
}
|
||||
const provider = config.providers.find(
|
||||
(candidate) => candidate.instanceId === selection.instanceId,
|
||||
);
|
||||
return provider &&
|
||||
provider.enabled &&
|
||||
provider.installed &&
|
||||
provider.auth.status !== "unauthenticated"
|
||||
? selection
|
||||
: null;
|
||||
}
|
||||
|
||||
export function buildModelOptions(
|
||||
config: T3ServerConfig | null | undefined,
|
||||
fallbackModelSelection: ModelSelection | null,
|
||||
|
||||
@@ -370,7 +370,8 @@ function NativeHeaderToolbarRoot(props: {
|
||||
const navigation = useNativeStackNavigation();
|
||||
const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
|
||||
|
||||
useEffect(() => {
|
||||
// Swap toolbar owners before paint so split and compact headers cannot clear each other.
|
||||
useLayoutEffect(() => {
|
||||
if (!navigation) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
|
||||
import { requireNativeView } from "expo";
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
@@ -9,12 +10,13 @@ import {
|
||||
useState,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
|
||||
import type { NativeSyntheticEvent, ViewProps } from "react-native";
|
||||
import { Image, StyleSheet } from "react-native";
|
||||
|
||||
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
|
||||
import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
|
||||
import { MOBILE_TYPOGRAPHY } from "../lib/typography";
|
||||
import { useNativePaste } from "../lib/useNativePaste";
|
||||
import { useFontFamily } from "../lib/useFontFamily";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import {
|
||||
@@ -117,6 +119,7 @@ export function ComposerEditor({
|
||||
const skillBorder = useThemeColor("--color-inline-skill-border");
|
||||
const skillText = useThemeColor("--color-inline-skill-foreground");
|
||||
const fileTint = useThemeColor("--color-icon-muted");
|
||||
const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
@@ -221,61 +224,63 @@ export function ComposerEditor({
|
||||
const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
|
||||
const regularFontFamily = useFontFamily("regular");
|
||||
return (
|
||||
<NativeView
|
||||
ref={nativeRef}
|
||||
controlledDocumentJson={controlledDocumentJson}
|
||||
themeJson={themeJson}
|
||||
placeholder={props.placeholder ?? ""}
|
||||
fontFamily={
|
||||
typeof resolvedTextStyle.fontFamily === "string"
|
||||
? resolvedTextStyle.fontFamily
|
||||
: regularFontFamily
|
||||
}
|
||||
fontSize={
|
||||
typeof resolvedTextStyle.fontSize === "number"
|
||||
? resolvedTextStyle.fontSize
|
||||
: MOBILE_TYPOGRAPHY.body.fontSize
|
||||
}
|
||||
lineHeight={
|
||||
typeof resolvedTextStyle.lineHeight === "number"
|
||||
? resolvedTextStyle.lineHeight
|
||||
: MOBILE_TYPOGRAPHY.body.lineHeight
|
||||
}
|
||||
contentInsetVertical={contentInsetVertical}
|
||||
singleLineCentered={props.singleLineCentered ?? false}
|
||||
editable={props.editable ?? true}
|
||||
scrollEnabled={props.scrollEnabled ?? true}
|
||||
autoFocus={props.autoFocus ?? false}
|
||||
autoCorrect={props.autoCorrect ?? true}
|
||||
spellCheck={props.spellCheck ?? true}
|
||||
style={style as StyleProp<ViewStyle>}
|
||||
onComposerChange={(event) => {
|
||||
const acknowledgedEventCount = acceptNativeEvent(
|
||||
event.nativeEvent.eventCount,
|
||||
event.nativeEvent.value,
|
||||
event.nativeEvent.selection,
|
||||
);
|
||||
if (acknowledgedEventCount === false) return;
|
||||
onChangeText(event.nativeEvent.value);
|
||||
onSelectionChange?.(event.nativeEvent.selection);
|
||||
setMostRecentEventCount(acknowledgedEventCount);
|
||||
setNativeEventSequence((sequence) => sequence + 1);
|
||||
}}
|
||||
onComposerSelectionChange={(event) => {
|
||||
const acknowledgedEventCount = acceptNativeEvent(
|
||||
event.nativeEvent.eventCount,
|
||||
event.nativeEvent.value,
|
||||
event.nativeEvent.selection,
|
||||
);
|
||||
if (acknowledgedEventCount === false) return;
|
||||
onSelectionChange?.(event.nativeEvent.selection);
|
||||
setMostRecentEventCount(acknowledgedEventCount);
|
||||
setNativeEventSequence((sequence) => sequence + 1);
|
||||
}}
|
||||
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
|
||||
onComposerFocus={onFocus}
|
||||
onComposerBlur={onBlur}
|
||||
/>
|
||||
<TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
|
||||
<NativeView
|
||||
ref={nativeRef}
|
||||
controlledDocumentJson={controlledDocumentJson}
|
||||
themeJson={themeJson}
|
||||
placeholder={props.placeholder ?? ""}
|
||||
fontFamily={
|
||||
typeof resolvedTextStyle.fontFamily === "string"
|
||||
? resolvedTextStyle.fontFamily
|
||||
: regularFontFamily
|
||||
}
|
||||
fontSize={
|
||||
typeof resolvedTextStyle.fontSize === "number"
|
||||
? resolvedTextStyle.fontSize
|
||||
: MOBILE_TYPOGRAPHY.body.fontSize
|
||||
}
|
||||
lineHeight={
|
||||
typeof resolvedTextStyle.lineHeight === "number"
|
||||
? resolvedTextStyle.lineHeight
|
||||
: MOBILE_TYPOGRAPHY.body.lineHeight
|
||||
}
|
||||
contentInsetVertical={contentInsetVertical}
|
||||
singleLineCentered={props.singleLineCentered ?? false}
|
||||
editable={props.editable ?? true}
|
||||
scrollEnabled={props.scrollEnabled ?? true}
|
||||
autoFocus={props.autoFocus ?? false}
|
||||
autoCorrect={props.autoCorrect ?? true}
|
||||
spellCheck={props.spellCheck ?? true}
|
||||
style={{ flex: 1, minHeight: 0 }}
|
||||
onComposerChange={(event) => {
|
||||
const acknowledgedEventCount = acceptNativeEvent(
|
||||
event.nativeEvent.eventCount,
|
||||
event.nativeEvent.value,
|
||||
event.nativeEvent.selection,
|
||||
);
|
||||
if (acknowledgedEventCount === false) return;
|
||||
onChangeText(event.nativeEvent.value);
|
||||
onSelectionChange?.(event.nativeEvent.selection);
|
||||
setMostRecentEventCount(acknowledgedEventCount);
|
||||
setNativeEventSequence((sequence) => sequence + 1);
|
||||
}}
|
||||
onComposerSelectionChange={(event) => {
|
||||
const acknowledgedEventCount = acceptNativeEvent(
|
||||
event.nativeEvent.eventCount,
|
||||
event.nativeEvent.value,
|
||||
event.nativeEvent.selection,
|
||||
);
|
||||
if (acknowledgedEventCount === false) return;
|
||||
onSelectionChange?.(event.nativeEvent.selection);
|
||||
setMostRecentEventCount(acknowledgedEventCount);
|
||||
setNativeEventSequence((sequence) => sequence + 1);
|
||||
}}
|
||||
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
|
||||
onComposerFocus={onFocus}
|
||||
onComposerBlur={onBlur}
|
||||
/>
|
||||
</TextInputWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -119,6 +119,36 @@ describe("mobile composer drafts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("drops the workspace selection when clearing a sent new-task draft", () => {
|
||||
const draftKey = "new-task:environment-1:project-1";
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
startFromOrigin: false,
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
clearComposerDraftContentState({ [draftKey]: draft }, draftKey, {
|
||||
clearWorkspaceSelection: true,
|
||||
}),
|
||||
).toEqual({
|
||||
[draftKey]: {
|
||||
modelSelection: draft.modelSelection,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the latest selector state synchronously for send", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const selectedDraft: ComposerDraft = {
|
||||
|
||||
@@ -372,14 +372,18 @@ export function updateComposerDraftSettings(
|
||||
export function clearComposerDraftContentState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
options?: { readonly clearWorkspaceSelection?: boolean },
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = current[draftKey];
|
||||
if (!existing) {
|
||||
return current;
|
||||
}
|
||||
const { importedShareIds: _importedShareIds, ...retained } = existing;
|
||||
const { importedShareIds: _importedShareIds, workspaceSelection, ...retained } = existing;
|
||||
const draft = {
|
||||
...retained,
|
||||
...(options?.clearWorkspaceSelection || workspaceSelection === undefined
|
||||
? {}
|
||||
: { workspaceSelection }),
|
||||
text: "",
|
||||
attachments: [],
|
||||
};
|
||||
@@ -526,8 +530,11 @@ export async function restoreComposerDraftSnapshot(
|
||||
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(draftKey: string): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
|
||||
export function clearComposerDraftContent(
|
||||
draftKey: string,
|
||||
options?: { readonly clearWorkspaceSelection?: boolean },
|
||||
): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
|
||||
}
|
||||
|
||||
export function clearComposerDraft(draftKey: string): void {
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as NetService from "@t3tools/shared/Net";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { authCommand } from "./cli/auth.ts";
|
||||
import { connectCommand } from "./cli/connect.ts";
|
||||
import { pairCommand } from "./cli/pair.ts";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
@@ -48,6 +49,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
Command.withSubcommands([
|
||||
startCommand,
|
||||
serveCommand,
|
||||
pairCommand,
|
||||
authCommand,
|
||||
projectCommand,
|
||||
serviceCommand,
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
|
||||
import * as NodeHttp from "node:http";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as TestConsole from "effect/testing/TestConsole";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "../bin.ts";
|
||||
import {
|
||||
makePersistedServerRuntimeState,
|
||||
persistServerRuntimeState,
|
||||
type PersistedServerRuntimeState,
|
||||
} from "../serverRuntimeState.ts";
|
||||
import {
|
||||
DevServerNotProxiableError,
|
||||
resolveDirectPairingBaseUrl,
|
||||
resolveTailscaleLocalTarget,
|
||||
} from "./pair.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
const baseState = {
|
||||
version: 1,
|
||||
pid: 123,
|
||||
port: 3_773,
|
||||
origin: "http://127.0.0.1:3773",
|
||||
startedAt: "2026-06-20T00:00:00.000Z",
|
||||
} as const satisfies PersistedServerRuntimeState;
|
||||
|
||||
describe("pair base URL selection", () => {
|
||||
it("pairs through the dev web origin when the server fronts a dev server", () => {
|
||||
expect(resolveDirectPairingBaseUrl({ ...baseState, devUrl: "http://localhost:5733/" })).toBe(
|
||||
"http://localhost:5733/",
|
||||
);
|
||||
});
|
||||
|
||||
it("pairs through the bound host when there is no dev server", () => {
|
||||
expect(resolveDirectPairingBaseUrl({ ...baseState, host: "100.64.0.7" })).toBe(
|
||||
"http://100.64.0.7:3773",
|
||||
);
|
||||
expect(resolveDirectPairingBaseUrl(baseState)).toBe("http://localhost:3773");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pair tailscale local target", () => {
|
||||
it("proxies the dev web port for dev servers", () => {
|
||||
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
|
||||
{ localPort: 5_733 },
|
||||
);
|
||||
// A dev server on a non-loopback interface must be proxied at that
|
||||
// interface; tailscale serve defaults to 127.0.0.1 otherwise.
|
||||
expect(
|
||||
resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
|
||||
).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
|
||||
// URL.hostname keeps IPv6 brackets, so the serve target stays valid.
|
||||
expect(
|
||||
resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
|
||||
).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
|
||||
});
|
||||
|
||||
it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
|
||||
expect(
|
||||
resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
|
||||
).toBeInstanceOf(DevServerNotProxiableError);
|
||||
});
|
||||
|
||||
it("proxies the backend port directly otherwise", () => {
|
||||
expect(resolveTailscaleLocalTarget(baseState)).toEqual({ localPort: 3_773 });
|
||||
expect(resolveTailscaleLocalTarget({ ...baseState, host: "0.0.0.0" })).toEqual({
|
||||
localPort: 3_773,
|
||||
});
|
||||
expect(resolveTailscaleLocalTarget({ ...baseState, host: "192.168.1.42" })).toEqual({
|
||||
localPort: 3_773,
|
||||
localHost: "192.168.1.42",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
|
||||
|
||||
const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.provide(effect, Layer.mergeAll(CliRuntimeLayer, TestConsole.layer));
|
||||
|
||||
// Console output accumulates across CLI runs within a test, and each
|
||||
// Console.log call is one entry — so the latest command's output is the last
|
||||
// entry, even when it spans many lines.
|
||||
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
provideCliTestLayers(
|
||||
Effect.gen(function* () {
|
||||
yield* effect;
|
||||
return (
|
||||
(yield* TestConsole.logLines).findLast(
|
||||
(line): line is string => typeof line === "string",
|
||||
) ?? ""
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const testDescriptor = {
|
||||
environmentId: "pair-test-environment",
|
||||
label: "pair-test",
|
||||
platform: { os: "linux", arch: "x64" },
|
||||
serverVersion: "0.0.1",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
};
|
||||
|
||||
const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A, E, R>) =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.callback<NodeHttp.Server>((resume) => {
|
||||
const server = NodeHttp.createServer((request, response) => {
|
||||
if (request.url === "/.well-known/t3/environment") {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify(testDescriptor));
|
||||
return;
|
||||
}
|
||||
response.writeHead(404);
|
||||
response.end();
|
||||
});
|
||||
server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
|
||||
}),
|
||||
(server) => {
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string") {
|
||||
return Effect.die(new Error("Expected a TCP address"));
|
||||
}
|
||||
return run(`http://127.0.0.1:${String(address.port)}`);
|
||||
},
|
||||
(server) => Effect.sync(() => server.close()),
|
||||
);
|
||||
|
||||
describe("t3 pair", () => {
|
||||
it.effect("mints a token and prints a QR pairing URL for a live server", () =>
|
||||
withDescriptorServer((origin) =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
|
||||
const port = Number(new URL(origin).port);
|
||||
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
|
||||
yield* persistServerRuntimeState({
|
||||
path: statePath,
|
||||
state: yield* makePersistedServerRuntimeState({
|
||||
config: { host: "127.0.0.1", devUrl: undefined },
|
||||
port,
|
||||
}),
|
||||
});
|
||||
|
||||
const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
|
||||
|
||||
assert.include(output, `Pairing with pair-test (${origin})`);
|
||||
assert.include(output, `Pairing URL: ${origin}/pair#token=`);
|
||||
assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
|
||||
// Loopback origins are not reachable from a phone; the output must say so.
|
||||
assert.include(output, "only reachable from this machine");
|
||||
|
||||
const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
|
||||
assert.isString(token);
|
||||
|
||||
// The token must be in the same store the running server reads.
|
||||
const listed = yield* captureStdout(
|
||||
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
|
||||
const credentials = JSON.parse(listed) as ReadonlyArray<{ readonly label?: string }>;
|
||||
assert.equal(credentials.length, 1);
|
||||
assert.equal(credentials[0]?.label, "t3 pair");
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("pairs through the recorded dev web URL for dev servers", () =>
|
||||
withDescriptorServer((origin) =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
|
||||
const port = Number(new URL(origin).port);
|
||||
const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
|
||||
yield* persistServerRuntimeState({
|
||||
path: statePath,
|
||||
state: yield* makePersistedServerRuntimeState({
|
||||
config: { host: undefined, devUrl: new URL("http://localhost:5733") },
|
||||
port,
|
||||
}),
|
||||
});
|
||||
|
||||
const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
|
||||
|
||||
assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("directs to t3 serve or t3 connect when no server is running", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-none-test-"));
|
||||
|
||||
const error = yield* provideCliTestLayers(
|
||||
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
|
||||
);
|
||||
|
||||
const rendered = String(
|
||||
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
|
||||
);
|
||||
assert.include(rendered, "No running T3 Code server found.");
|
||||
assert.include(rendered, "npx t3 serve");
|
||||
assert.include(rendered, "npx t3 connect");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
|
||||
withDescriptorServer((origin) =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
|
||||
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
|
||||
// The origin answers (another server reused the port), but the pid
|
||||
// that wrote this state file is dead — pairing must not mint a token
|
||||
// into the dead server's database.
|
||||
const state = yield* makePersistedServerRuntimeState({
|
||||
config: { host: "127.0.0.1", devUrl: undefined },
|
||||
port: Number(new URL(origin).port),
|
||||
});
|
||||
yield* persistServerRuntimeState({
|
||||
path: statePath,
|
||||
// pid 2**22 + 1 exceeds any default Linux/macOS pid range.
|
||||
state: { ...state, pid: 4_194_305 },
|
||||
});
|
||||
|
||||
const error = yield* provideCliTestLayers(
|
||||
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
|
||||
);
|
||||
|
||||
const rendered = String(
|
||||
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
|
||||
);
|
||||
assert.include(rendered, "No running T3 Code server found.");
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ignores stale runtime state pointing at a dead server", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-stale-test-"));
|
||||
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
|
||||
// A port from the dynamic range with nothing listening: the probe fails
|
||||
// fast with ECONNREFUSED and discovery moves on.
|
||||
yield* persistServerRuntimeState({
|
||||
path: statePath,
|
||||
state: yield* makePersistedServerRuntimeState({
|
||||
config: { host: "127.0.0.1", devUrl: undefined },
|
||||
port: 1,
|
||||
}),
|
||||
});
|
||||
|
||||
const error = yield* provideCliTestLayers(
|
||||
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
|
||||
);
|
||||
|
||||
const rendered = String(
|
||||
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
|
||||
);
|
||||
assert.include(rendered, "No running T3 Code server found.");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,542 @@
|
||||
/**
|
||||
* `t3 pair` - mint a pairing token for an already-running server and print it
|
||||
* as a QR code, without restarting anything.
|
||||
*
|
||||
* Discovery reads the `server-runtime.json` a live server persists next to its
|
||||
* database, then confirms the process is actually answering by fetching its
|
||||
* public environment descriptor. Inside a linked git worktree the worktree's
|
||||
* own `.t3` is checked first (matching dev-runner precedence); otherwise the
|
||||
* shared T3 home. `--tailscale` publishes the server over Tailscale Serve
|
||||
* HTTPS and pairs through the tailnet URL instead.
|
||||
*/
|
||||
import {
|
||||
AuthStandardClientScopes,
|
||||
ExecutionEnvironmentDescriptor,
|
||||
PortSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
import {
|
||||
buildTailscaleHttpsBaseUrl,
|
||||
DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
ensureTailscaleServe,
|
||||
readTailscaleStatus,
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Console from "effect/Console";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
HttpClientRequest,
|
||||
HttpClientResponse,
|
||||
} from "effect/unstable/http";
|
||||
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { resolveBaseDir } from "../os-jank.ts";
|
||||
import {
|
||||
type PersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "../serverRuntimeState.ts";
|
||||
import {
|
||||
buildPairingUrl,
|
||||
formatHostForUrl,
|
||||
isLoopbackHost,
|
||||
isWildcardHost,
|
||||
renderTerminalQrCode,
|
||||
resolveHeadlessConnectionString,
|
||||
} from "../startupAccess.ts";
|
||||
import { baseDirFlag, DurationFromString } from "./config.ts";
|
||||
|
||||
const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
|
||||
const PAIR_PROBE_TIMEOUT = Duration.millis(2_500);
|
||||
// Tailscale provisions an HTTPS certificate on the first request to a fresh
|
||||
// serve mapping, which can take a few seconds.
|
||||
const TAILSCALE_PROBE_ATTEMPTS = 5;
|
||||
const TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);
|
||||
|
||||
export type PairStateVariant = "userdata" | "dev";
|
||||
|
||||
// deriveServerPaths only checks devUrl for undefined-ness when picking the
|
||||
// dev-vs-userdata state directory; the value itself is not used.
|
||||
const DEV_VARIANT_PLACEHOLDER_URL = new URL("http://localhost");
|
||||
|
||||
export class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServerError>()(
|
||||
"NoRunningServerError",
|
||||
{
|
||||
checkedStatePaths: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return [
|
||||
"No running T3 Code server found.",
|
||||
...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
|
||||
"Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
|
||||
].join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Each tailscale failure gets its own class (same reasoning as
|
||||
// scripts/lib/dev-share.ts): distinct caller-visible message, distinct remedy.
|
||||
export class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(
|
||||
"TailscaleUnavailableError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";
|
||||
}
|
||||
}
|
||||
|
||||
export class MagicDnsNameMissingError extends Schema.TaggedErrorClass<MagicDnsNameMissingError>()(
|
||||
"MagicDnsNameMissingError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesOtherEnvironmentError>()(
|
||||
"ServesOtherEnvironmentError",
|
||||
{ servePort: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Tailscale Serve on HTTPS port ${String(this.servePort)} already fronts a different T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
|
||||
"TailscaleServeFailedError",
|
||||
{ servePort: Schema.Number, cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \`tailscale serve --https=${String(this.servePort)} --bg <local-url>\` by hand to see why.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(
|
||||
"ServePortOccupiedError",
|
||||
{ servePort: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `HTTPS port ${String(this.servePort)} on the tailnet already serves something that is not a T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** The URL a browser or phone should pair through, absent Tailscale. */
|
||||
export const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
|
||||
state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
|
||||
|
||||
export class DevServerNotProxiableError extends Schema.TaggedErrorClass<DevServerNotProxiableError>()(
|
||||
"DevServerNotProxiableError",
|
||||
{ devUrl: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
|
||||
}
|
||||
}
|
||||
|
||||
const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
|
||||
|
||||
/**
|
||||
* The local endpoint Tailscale Serve should proxy to. Dev servers are
|
||||
* single-origin, so the web dev server's port is the one to publish; the
|
||||
* backend rides along behind Vite's proxy. Serve targets are always plain
|
||||
* HTTP, so an HTTPS dev URL cannot be proxied and is rejected.
|
||||
*/
|
||||
export const resolveTailscaleLocalTarget = (
|
||||
state: PersistedServerRuntimeState,
|
||||
): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {
|
||||
if (state.devUrl !== undefined) {
|
||||
const devUrl = new URL(state.devUrl);
|
||||
if (devUrl.protocol !== "http:") {
|
||||
return new DevServerNotProxiableError({ devUrl: state.devUrl });
|
||||
}
|
||||
const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;
|
||||
return isLoopbackHost(devUrl.hostname)
|
||||
? { localPort }
|
||||
: { localPort, localHost: devUrl.hostname };
|
||||
}
|
||||
// A server bound to one specific interface does not answer on loopback, so
|
||||
// the proxy has to target that interface directly.
|
||||
if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {
|
||||
return { localPort: state.port, localHost: formatHostForUrl(state.host) };
|
||||
}
|
||||
return { localPort: state.port };
|
||||
};
|
||||
|
||||
export const formatPairOutput = (input: {
|
||||
readonly serverLabel: string;
|
||||
readonly origin: string;
|
||||
readonly pairingUrl: string;
|
||||
readonly token: string;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
readonly notes: ReadonlyArray<string>;
|
||||
}): string =>
|
||||
[
|
||||
`Pairing with ${input.serverLabel} (${input.origin}).`,
|
||||
"",
|
||||
renderTerminalQrCode(input.pairingUrl),
|
||||
"",
|
||||
`Pairing URL: ${input.pairingUrl}`,
|
||||
`Token: ${input.token}`,
|
||||
`Expires: ${DateTime.formatIso(input.expiresAt)}`,
|
||||
...input.notes.flatMap((note) => ["", `Note: ${note}`]),
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
/**
|
||||
* Three outcomes, because they drive different decisions: a T3 descriptor
|
||||
* (pair with it), nothing answering (safe to configure Tailscale Serve), or
|
||||
* something answering that is not a T3 server (do NOT overwrite its mapping).
|
||||
*/
|
||||
type EnvironmentProbeResult =
|
||||
| { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
|
||||
| { readonly _tag: "unreachable" }
|
||||
| { readonly _tag: "not-a-t3-server" };
|
||||
|
||||
const probeEnvironmentDescriptor = (
|
||||
baseUrl: string,
|
||||
): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
|
||||
Effect.gen(function* () {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
|
||||
const response = yield* client.execute(request).pipe(
|
||||
Effect.timeout(PAIR_PROBE_TIMEOUT),
|
||||
// Transport failure or timeout: nothing (reachable) is listening there.
|
||||
Effect.mapError(() => ({ _tag: "unreachable" }) as const),
|
||||
);
|
||||
// Bad-gateway family means a proxy (Tailscale Serve) answered for a
|
||||
// backend that is gone — a stale mapping, not a live occupant. Treating
|
||||
// it as unreachable lets `t3 pair --tailscale` repair its own mapping
|
||||
// after the server's port changed.
|
||||
if (response.status === 502 || response.status === 503 || response.status === 504) {
|
||||
return { _tag: "unreachable" } as const;
|
||||
}
|
||||
// Anything else that answered HTTP but not with a valid descriptor is
|
||||
// some other service.
|
||||
const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
|
||||
Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
|
||||
);
|
||||
return { _tag: "descriptor", descriptor } as const;
|
||||
}).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));
|
||||
|
||||
// signal 0 delivers nothing; it only reports whether the pid exists. EPERM
|
||||
// means it exists but belongs to another user, which still counts as alive.
|
||||
const isProcessAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return error instanceof Error && "code" in error && error.code === "EPERM";
|
||||
}
|
||||
};
|
||||
|
||||
interface DiscoveredPairTarget {
|
||||
readonly baseDir: string;
|
||||
readonly variant: PairStateVariant;
|
||||
readonly state: PersistedServerRuntimeState;
|
||||
readonly descriptor: ExecutionEnvironmentDescriptor;
|
||||
}
|
||||
|
||||
const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
|
||||
explicitBaseDir: string | undefined,
|
||||
) {
|
||||
const bases: Array<string> = [];
|
||||
if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
|
||||
bases.push(yield* resolveBaseDir(explicitBaseDir));
|
||||
} else {
|
||||
// Same precedence as dev-runner: inside a linked worktree its own `.t3`
|
||||
// outranks the shared home, so `t3 pair` in a worktree pairs with the dev
|
||||
// server under test rather than the daily-driver install.
|
||||
const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());
|
||||
if (worktreeHome !== undefined) {
|
||||
bases.push(worktreeHome);
|
||||
}
|
||||
const envHome = yield* Config.string("T3CODE_HOME").pipe(Config.option);
|
||||
bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
|
||||
}
|
||||
|
||||
const checkedStatePaths: Array<string> = [];
|
||||
for (const baseDir of new Set(bases)) {
|
||||
for (const variant of ["userdata", "dev"] as const) {
|
||||
const derivedPaths = yield* ServerConfig.deriveServerPaths(
|
||||
baseDir,
|
||||
variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
|
||||
{},
|
||||
);
|
||||
const statePath = derivedPaths.serverRuntimeStatePath;
|
||||
checkedStatePaths.push(statePath);
|
||||
const state = yield* readPersistedServerRuntimeState(statePath);
|
||||
if (Option.isNone(state)) {
|
||||
continue;
|
||||
}
|
||||
// The pid check guards against a dead server's state file whose port
|
||||
// was since reused by a different server: pairing would then mint a
|
||||
// token in the old database while the QR code points at the new server.
|
||||
if (!isProcessAlive(state.value.pid)) {
|
||||
continue;
|
||||
}
|
||||
const probed = yield* probeEnvironmentDescriptor(state.value.origin);
|
||||
if (probed._tag !== "descriptor") {
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
baseDir,
|
||||
variant,
|
||||
state: state.value,
|
||||
descriptor: probed.descriptor,
|
||||
} satisfies DiscoveredPairTarget;
|
||||
}
|
||||
}
|
||||
return yield* new NoRunningServerError({ checkedStatePaths });
|
||||
});
|
||||
|
||||
/**
|
||||
* Server config pointed at the discovered server's state directory, so the
|
||||
* minted token lands in the database the running server reads from. Built by
|
||||
* hand rather than through `resolveServerConfig` to keep the dev-vs-userdata
|
||||
* choice pinned to where the runtime state was actually found, independent of
|
||||
* ambient environment variables.
|
||||
*/
|
||||
const makePairServerConfig = Effect.fn(function* (input: {
|
||||
readonly target: DiscoveredPairTarget;
|
||||
readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
|
||||
}) {
|
||||
const { baseDir, variant, state } = input.target;
|
||||
// The state-dir variant does not imply dev-ness: a worktree dev server uses
|
||||
// an explicit home and therefore lands in `userdata`. The recorded devUrl is
|
||||
// what actually marks a dev server.
|
||||
const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
|
||||
const derivedPaths = yield* ServerConfig.deriveServerPaths(
|
||||
baseDir,
|
||||
variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
|
||||
{},
|
||||
);
|
||||
return ServerConfig.make({
|
||||
logLevel: input.logLevel,
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: false,
|
||||
traceBatchWindowMs: 1_000,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: state.port,
|
||||
host: state.host,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "headless",
|
||||
desktopBootstrapToken: undefined,
|
||||
desktopTelemetryFd: undefined,
|
||||
desktopTelemetryControlFd: undefined,
|
||||
resourceMonitorPath: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
});
|
||||
});
|
||||
|
||||
const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
|
||||
let last: EnvironmentProbeResult = { _tag: "unreachable" };
|
||||
for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
|
||||
last = yield* probeEnvironmentDescriptor(baseUrl);
|
||||
if (last._tag === "descriptor") {
|
||||
return last;
|
||||
}
|
||||
yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
|
||||
}
|
||||
return last;
|
||||
});
|
||||
|
||||
const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
|
||||
function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
|
||||
const notes: Array<string> = [];
|
||||
const status = yield* readTailscaleStatus.pipe(
|
||||
Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
|
||||
);
|
||||
if (status.magicDnsName === null) {
|
||||
return yield* new MagicDnsNameMissingError();
|
||||
}
|
||||
const baseUrl = buildTailscaleHttpsBaseUrl({
|
||||
magicDnsName: status.magicDnsName,
|
||||
servePort: input.servePort,
|
||||
});
|
||||
|
||||
// Only an unreachable port, or a mapping already fronting this exact
|
||||
// environment, is safe to (re)configure. Any other responder — T3 or not
|
||||
// — must not have its mapping silently replaced.
|
||||
const existing = yield* probeEnvironmentDescriptor(baseUrl);
|
||||
if (existing._tag === "descriptor") {
|
||||
if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
|
||||
return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
|
||||
}
|
||||
// Matching environment id proves the mapping reaches this server, but
|
||||
// not through which port: for a dev server it may front the backend
|
||||
// (whose /.well-known also answers) while /pair only renders through
|
||||
// the web origin. Reuse as-is for regular servers; fall through and
|
||||
// repoint our own mapping at the web port for dev servers.
|
||||
if (input.target.state.devUrl === undefined) {
|
||||
return { baseUrl, notes };
|
||||
}
|
||||
}
|
||||
if (existing._tag === "not-a-t3-server") {
|
||||
return yield* new ServePortOccupiedError({ servePort: input.servePort });
|
||||
}
|
||||
|
||||
const localTarget = resolveTailscaleLocalTarget(input.target.state);
|
||||
if (isDevServerNotProxiableError(localTarget)) {
|
||||
return yield* localTarget;
|
||||
}
|
||||
yield* ensureTailscaleServe({
|
||||
localPort: localTarget.localPort,
|
||||
servePort: input.servePort,
|
||||
...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
|
||||
),
|
||||
);
|
||||
notes.push(
|
||||
`Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
|
||||
);
|
||||
|
||||
const probed = yield* awaitEnvironmentDescriptor(baseUrl);
|
||||
if (probed._tag === "descriptor") {
|
||||
if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
|
||||
return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
|
||||
}
|
||||
} else {
|
||||
notes.push(
|
||||
"The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
|
||||
);
|
||||
}
|
||||
return { baseUrl, notes };
|
||||
},
|
||||
);
|
||||
|
||||
const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
|
||||
readonly config: ServerConfig.ServerConfig["Service"];
|
||||
readonly ttl: Option.Option<Duration.Duration>;
|
||||
readonly label: Option.Option<string>;
|
||||
}) {
|
||||
return yield* Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
return yield* environmentAuth.createPairingLink({
|
||||
scopes: AuthStandardClientScopes,
|
||||
subject: "one-time-token",
|
||||
label: Option.getOrElse(input.label, () => "t3 pair"),
|
||||
...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EnvironmentAuth.runtimeLayer.pipe(
|
||||
Layer.provide(ServerConfig.layer(input.config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const ttlFlag = Flag.string("ttl").pipe(
|
||||
Flag.withSchema(DurationFromString),
|
||||
Flag.withDescription(
|
||||
"Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const labelFlag = Flag.string("label").pipe(
|
||||
Flag.withDescription("Optional label shown in the server's connections list."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const tailscaleFlag = Flag.boolean("tailscale").pipe(
|
||||
Flag.withDescription(
|
||||
"Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
|
||||
),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
|
||||
Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
|
||||
);
|
||||
|
||||
export const pairCommand = Command.make("pair", {
|
||||
baseDir: baseDirFlag,
|
||||
ttl: ttlFlag,
|
||||
label: labelFlag,
|
||||
tailscale: tailscaleFlag,
|
||||
tailscaleServePort: tailscaleServePortFlag,
|
||||
}).pipe(
|
||||
Command.withDescription(
|
||||
"Mint a pairing token for a running T3 Code server and print it as a QR code.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
Effect.gen(function* () {
|
||||
const cliLogLevel = yield* GlobalFlag.LogLevel;
|
||||
// Default to Warn so storage/migration chatter cannot bury the QR code;
|
||||
// an explicit --log-level still wins.
|
||||
const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
|
||||
|
||||
const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
|
||||
|
||||
const notes: Array<string> = [];
|
||||
let pairingBaseUrl: string;
|
||||
if (flags.tailscale) {
|
||||
const resolved = yield* resolveTailscalePairingBase({
|
||||
target,
|
||||
servePort: flags.tailscaleServePort,
|
||||
});
|
||||
pairingBaseUrl = resolved.baseUrl;
|
||||
notes.push(...resolved.notes);
|
||||
} else {
|
||||
pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
|
||||
if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
|
||||
notes.push(
|
||||
"This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
|
||||
);
|
||||
}
|
||||
if (target.variant === "dev" && target.state.devUrl === undefined) {
|
||||
notes.push(
|
||||
"This dev server did not record its web URL; restart it so pairing can go through the web origin.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const config = yield* makePairServerConfig({ target, logLevel });
|
||||
const issued = yield* mintPairingLink({ config, ttl: flags.ttl, label: flags.label });
|
||||
const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
|
||||
|
||||
yield* Console.log(
|
||||
formatPairOutput({
|
||||
serverLabel: target.descriptor.label,
|
||||
origin: target.state.origin,
|
||||
pairingUrl,
|
||||
token: issued.credential,
|
||||
expiresAt: issued.expiresAt,
|
||||
notes,
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.provide(FetchHttpClient.layer)),
|
||||
),
|
||||
);
|
||||
@@ -337,7 +337,9 @@ const dispatchLiveOrchestrationCommand = (
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
// Project commands only read the project list, so use the lightweight
|
||||
// command read model instead of hydrating every thread body in the database.
|
||||
return yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
});
|
||||
|
||||
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
|
||||
|
||||
@@ -2,11 +2,14 @@ import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import { applySystemdSelfUpdatePlan } from "../cloud/systemdSelfUpdate.ts";
|
||||
import type * as ServerConfig from "../config.ts";
|
||||
import { validateAutomaticUpdateMigrationFrontier } from "../persistence/Migrations.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
@@ -142,6 +145,38 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
|
||||
),
|
||||
);
|
||||
|
||||
/** Internal entrypoint launched by systemd-run outside t3code.service. */
|
||||
const serviceApplyUpdateCommand = Command.make("_apply-update", {
|
||||
plan: Flag.string("plan"),
|
||||
}).pipe(
|
||||
Command.withHidden,
|
||||
Command.withHandler(({ plan }) =>
|
||||
applySystemdSelfUpdatePlan(plan).pipe(
|
||||
Effect.provide(Layer.mergeAll(ProcessRunner.layer, FetchHttpClient.layer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/** Target-artifact preflight used before the running server is stopped. */
|
||||
const serviceValidateUpdateCommand = Command.make("_validate-update", {
|
||||
database: Flag.string("database"),
|
||||
}).pipe(
|
||||
Command.withHidden,
|
||||
Command.withHandler(({ database }) =>
|
||||
Effect.gen(function* () {
|
||||
// Keep node:sqlite behind the same lazy bundle boundary as normal server
|
||||
// startup; most service commands never open the database.
|
||||
const NodeSqliteClient = yield* Effect.promise(
|
||||
() => import("../persistence/NodeSqliteClient.ts"),
|
||||
);
|
||||
yield* validateAutomaticUpdateMigrationFrontier().pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: database, readonly: true })),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* service.status;
|
||||
@@ -195,5 +230,7 @@ export const serviceCommand = Command.make("service").pipe(
|
||||
serviceUninstallCommand,
|
||||
serviceUpdateCommand,
|
||||
serviceStatusCommand,
|
||||
serviceApplyUpdateCommand,
|
||||
serviceValidateUpdateCommand,
|
||||
]),
|
||||
);
|
||||
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
@@ -23,36 +24,15 @@ import {
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import * as SelfUpdate from "./selfUpdate.ts";
|
||||
import {
|
||||
SYSTEMD_SELF_UPDATE_DIRECTORY,
|
||||
SYSTEMD_SELF_UPDATE_PLAN_FILE,
|
||||
SYSTEMD_SELF_UPDATE_UNIT,
|
||||
SystemdSelfUpdatePlan,
|
||||
} from "./systemdSelfUpdate.ts";
|
||||
|
||||
const NODE_PATH = "/usr/local/bin/node";
|
||||
|
||||
const eventuallyFileString = Effect.fn("test.eventuallyFileString")(function* (
|
||||
filePath: string,
|
||||
expected: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (let iteration = 0; iteration < 1_000; iteration += 1) {
|
||||
const contents = yield* fs.readFileString(filePath);
|
||||
if (contents === expected) {
|
||||
return;
|
||||
}
|
||||
// The rollback performs real filesystem I/O on a detached fiber, which
|
||||
// advancing TestClock does not await.
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.die(new Error(`Expected file contents were not observed at ${filePath}.`));
|
||||
});
|
||||
|
||||
const eventuallyTrue = Effect.fn("test.eventuallyTrue")(function* (predicate: () => boolean) {
|
||||
for (let iteration = 0; iteration < 1_000; iteration += 1) {
|
||||
if (predicate()) {
|
||||
return;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.die(new Error("Expected condition was not observed."));
|
||||
});
|
||||
|
||||
interface RecordedCommand {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -445,7 +425,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
[NODE_PATH, "npm", NODE_PATH],
|
||||
[NODE_PATH, "npm", NODE_PATH, NODE_PATH],
|
||||
);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
@@ -506,6 +486,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
[
|
||||
`npm install --prefix ${context.path.join(context.baseDir, "runtime/versions/0.0.29")} --no-fund --no-audit [email protected]`,
|
||||
`${NODE_PATH} ${pinnedEntry} --version`,
|
||||
`${NODE_PATH} ${pinnedEntry} service _validate-update --database ${context.path.join(context.baseDir, "userdata/state.sqlite")}`,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -521,9 +502,17 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rewrites the systemd unit and restarts the boot service", () =>
|
||||
it.effect("stages the systemd unit and hands activation to a transient service", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ bootService: true });
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
|
||||
@@ -531,38 +520,56 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
context.baseDir,
|
||||
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
|
||||
);
|
||||
const unit = yield* context.fs.readFileString(
|
||||
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
|
||||
// The RPC process does not rewrite the unit it is currently running
|
||||
// under. The independent transient service applies the staged unit.
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
const planPath = context.path.join(
|
||||
context.baseDir,
|
||||
"userdata",
|
||||
SYSTEMD_SELF_UPDATE_DIRECTORY,
|
||||
SYSTEMD_SELF_UPDATE_PLAN_FILE,
|
||||
);
|
||||
const plan = yield* context.fs
|
||||
.readFileString(planPath)
|
||||
.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(SystemdSelfUpdatePlan))),
|
||||
);
|
||||
assert.equal(plan.previousUnit, previousUnit);
|
||||
assert.equal(plan.serviceUnit, BOOT_SERVICE_UNIT_FILE);
|
||||
assert.include(plan.nextUnit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
|
||||
assert.equal(
|
||||
plan.runtimeStatePath,
|
||||
context.path.join(context.baseDir, "userdata/server-runtime.json"),
|
||||
);
|
||||
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl"],
|
||||
["npm", NODE_PATH, NODE_PATH, "systemd-run"],
|
||||
);
|
||||
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
|
||||
|
||||
// Restart waits until after the update acknowledgement can flush.
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.deepEqual(context.commands[3], {
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", "t3code.service"],
|
||||
});
|
||||
assert.include(context.commands[3]?.args ?? [], `--unit=${SYSTEMD_SELF_UPDATE_UNIT}`);
|
||||
assert.include(context.commands[3]?.args ?? [], planPath);
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
// systemd replaces the process; the server must not exit itself.
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
|
||||
// The lock stays held after a successful handoff because the transient
|
||||
// service is now responsible for replacing this process.
|
||||
const concurrentError = yield* context.service
|
||||
.update({ targetVersion: "0.0.30" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(concurrentError.reason, "already in progress");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
|
||||
it.effect("leaves the live unit untouched and permits a retry when the handoff fails", () =>
|
||||
Effect.gen(function* () {
|
||||
let failRestart = true;
|
||||
let failHandoff = true;
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command, args) => {
|
||||
if (command !== "systemctl" || args[1] !== "restart" || !failRestart) {
|
||||
if (command !== "systemd-run" || !failHandoff) {
|
||||
return false;
|
||||
}
|
||||
failRestart = false;
|
||||
assert.include(args, `--unit=${SYSTEMD_SELF_UPDATE_UNIT}`);
|
||||
failHandoff = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -575,29 +582,46 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
yield* eventuallyFileString(unitPath, previousUnit);
|
||||
yield* eventuallyTrue(() => context.commands.at(-1)?.args[1] === "daemon-reload");
|
||||
assert.deepEqual(
|
||||
context.commands.slice(-2).map((entry) => entry.args),
|
||||
[
|
||||
["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
["--user", "daemon-reload"],
|
||||
],
|
||||
);
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Systemd rejected the update handoff");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
|
||||
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
|
||||
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("permits a retry when the transient helper stops before replacing this process", () =>
|
||||
Effect.gen(function* () {
|
||||
let helperActive = true;
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command, args) =>
|
||||
command === "systemctl" && args.includes("is-active") && !helperActive,
|
||||
});
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
|
||||
helperActive = false;
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
|
||||
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
|
||||
assert.isTrue(
|
||||
context.commands.some(
|
||||
({ command, args }) => command === "systemctl" && args.includes("is-active"),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
|
||||
it.effect("rejects a target that cannot validate the current database", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command) => command === "systemctl",
|
||||
failWhen: (command, args) => command === NODE_PATH && args.includes("_validate-update"),
|
||||
});
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
@@ -609,16 +633,15 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "Reloading systemd units failed");
|
||||
assert.include(error.reason, "not compatible with this server's database");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
["npm", NODE_PATH, NODE_PATH],
|
||||
);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -19,13 +19,14 @@ import * as NodeChildProcess from "node:child_process";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
BOOT_SERVICE_UNIT_ENV,
|
||||
@@ -34,6 +35,14 @@ import {
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import { ensurePinnedRuntimeInstalled, removePinnedRuntimeInstallation } from "./pinnedRuntime.ts";
|
||||
import {
|
||||
SYSTEMD_SELF_UPDATE_DIRECTORY,
|
||||
SYSTEMD_SELF_UPDATE_PLAN_FILE,
|
||||
SYSTEMD_SELF_UPDATE_RECEIPT_FILE,
|
||||
SYSTEMD_SELF_UPDATE_UNIT,
|
||||
SystemdSelfUpdatePlan,
|
||||
writeSystemdSelfUpdatePlan,
|
||||
} from "./systemdSelfUpdate.ts";
|
||||
|
||||
/**
|
||||
* Lets a connected client replace this server with another published `t3`
|
||||
@@ -221,11 +230,44 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
|
||||
Effect.andThen(restart),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
const writeUnitAtomically = (filePath: string, contents: string) =>
|
||||
writeFileStringAtomically({ filePath, contents }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
/**
|
||||
* A successful systemd-run handoff normally ends by replacing this process,
|
||||
* so its in-memory lock disappears with it. If the transient helper exits
|
||||
* before that happens, release the lock so the still-healthy old server can
|
||||
* accept a retry. The fixed transient unit remains the cross-process lock.
|
||||
*/
|
||||
const releaseLockIfSystemdHelperStops = Effect.gen(function* () {
|
||||
let consecutiveProbeFailures = 0;
|
||||
for (;;) {
|
||||
yield* Effect.sleep(Duration.seconds(1));
|
||||
const probe = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "is-active", "--quiet", SYSTEMD_SELF_UPDATE_UNIT],
|
||||
timeout: Duration.seconds(5),
|
||||
})
|
||||
.pipe(Effect.exit);
|
||||
if (Exit.isFailure(probe)) {
|
||||
consecutiveProbeFailures += 1;
|
||||
if (consecutiveProbeFailures < 3) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
consecutiveProbeFailures = 0;
|
||||
if (probe.value.code === 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.logWarning(
|
||||
"Systemd self-update helper stopped before replacing this server; updates are retryable.",
|
||||
{ targetUnit: SYSTEMD_SELF_UPDATE_UNIT },
|
||||
);
|
||||
yield* Ref.set(inFlight, false);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
|
||||
"cloud.server_self_update.update",
|
||||
@@ -301,6 +343,33 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
|
||||
);
|
||||
}
|
||||
|
||||
// Run this command from the target artifact while the known-good server
|
||||
// is still alive. Older artifacts without the compatibility check, or a
|
||||
// build whose migration identities disagree with this database, cannot
|
||||
// be activated remotely.
|
||||
const databasePreflight = yield* runner
|
||||
.run({
|
||||
command: host.execPath,
|
||||
args: [
|
||||
runtimePaths.entryPath,
|
||||
"service",
|
||||
"_validate-update",
|
||||
"--database",
|
||||
serverConfig.dbPath,
|
||||
],
|
||||
timeout: PREFLIGHT_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith(`Could not verify t3@${targetVersion} against this database.`, cause),
|
||||
),
|
||||
);
|
||||
if (databasePreflight.code !== 0) {
|
||||
return yield* failWith(
|
||||
`The installed t3@${targetVersion} is not compatible with this server's database (exit code ${String(databasePreflight.code)}).`,
|
||||
);
|
||||
}
|
||||
|
||||
if (activeMethod === "boot-service") {
|
||||
const homeDir = env.HOME ?? "";
|
||||
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
|
||||
@@ -311,89 +380,65 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
|
||||
);
|
||||
// Same shape bootService.install writes, so host lifecycle commands
|
||||
// still recognize the unit as current.
|
||||
const unit = renderBootServiceUnit({
|
||||
const nextUnit = renderBootServiceUnit({
|
||||
nodePath: host.execPath,
|
||||
t3EntryPath: runtimePaths.entryPath,
|
||||
baseDir: serverConfig.baseDir,
|
||||
logPath: path.join(serverConfig.logsDir, "boot-service.log"),
|
||||
unitPath,
|
||||
});
|
||||
yield* writeUnitAtomically(unitPath, unit).pipe(
|
||||
Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
|
||||
);
|
||||
|
||||
const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
|
||||
const reload = yield* runner
|
||||
.run({ command: "systemctl", args: ["--user", "daemon-reload"] })
|
||||
.pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
|
||||
if (reload.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Reloading systemd units failed (exit code ${String(reload.code)}).`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
yield* reloadSystemd().pipe(
|
||||
Effect.catch((reloadError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.mapError((rollbackCause) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
reloadError,
|
||||
rollbackCause,
|
||||
}),
|
||||
),
|
||||
// Systemd should still have the old unit in memory after the
|
||||
// failed reload, but retry after restoring in case it applied a
|
||||
// partial update before returning an error.
|
||||
Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
|
||||
Effect.andThen(Effect.fail(reloadError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
|
||||
const updateDirectory = path.join(serverConfig.stateDir, SYSTEMD_SELF_UPDATE_DIRECTORY);
|
||||
const planPath = path.join(updateDirectory, SYSTEMD_SELF_UPDATE_PLAN_FILE);
|
||||
const plan = new SystemdSelfUpdatePlan({
|
||||
version: 1,
|
||||
fromVersion: packageJson.version,
|
||||
targetVersion,
|
||||
currentPid: process.pid,
|
||||
serviceUnit: BOOT_SERVICE_UNIT_FILE,
|
||||
unitPath,
|
||||
previousUnit,
|
||||
nextUnit,
|
||||
runtimeStatePath: serverConfig.serverRuntimeStatePath,
|
||||
receiptPath: path.join(updateDirectory, SYSTEMD_SELF_UPDATE_RECEIPT_FILE),
|
||||
});
|
||||
// Restart after the acknowledgement has had time to cross any relay
|
||||
// hop. If systemd rejects the handoff, restore the previous unit while
|
||||
// this process is still alive and log the failure for diagnostics.
|
||||
yield* scheduleRestart(
|
||||
Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.andThen(reloadSystemd()),
|
||||
Effect.mapError((rollbackError) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
restartError,
|
||||
rollbackError,
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.fail(restartError)),
|
||||
),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logError("Server self-update could not restart the boot service.").pipe(
|
||||
Effect.annotateLogs({ targetVersion, error: error.reason }),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(Ref.set(inFlight, false)),
|
||||
),
|
||||
yield* writeSystemdSelfUpdatePlan(planPath, plan).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.mapError((cause) => failWith("Could not stage the systemd update plan.", cause)),
|
||||
);
|
||||
|
||||
// The transient unit has its own cgroup, so it survives the restart of
|
||||
// t3code.service and remains responsible for readiness and rollback.
|
||||
const handoff = yield* runner
|
||||
.run({
|
||||
command: "systemd-run",
|
||||
args: [
|
||||
"--user",
|
||||
"--collect",
|
||||
"--service-type=exec",
|
||||
`--unit=${SYSTEMD_SELF_UPDATE_UNIT}`,
|
||||
host.execPath,
|
||||
host.cliEntryPath,
|
||||
"service",
|
||||
"_apply-update",
|
||||
"--plan",
|
||||
planPath,
|
||||
],
|
||||
timeout: PREFLIGHT_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) => failWith("Could not hand the update to systemd.", cause)),
|
||||
);
|
||||
if (handoff.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Systemd rejected the update handoff (exit code ${String(handoff.code)}).`,
|
||||
);
|
||||
}
|
||||
yield* releaseLockIfSystemdHelperStops.pipe(Effect.forkDetach({ startImmediately: true }));
|
||||
yield* Effect.logInfo("Server self-update staged; systemd will activate it.", {
|
||||
targetVersion,
|
||||
planPath,
|
||||
});
|
||||
} else {
|
||||
// Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
|
||||
// other launch failures leave this server alive and return a useful
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* Opt-in acceptance coverage for the real systemd handoff and rollback path.
|
||||
* Every unit and file is uniquely named; this must never target t3code.service.
|
||||
*
|
||||
* Run on Linux with a user manager:
|
||||
* T3_SYSTEMD_SELF_UPDATE_ACCEPTANCE=1 vp test run \
|
||||
* apps/server/src/cloud/systemdSelfUpdate.acceptance.test.ts
|
||||
*/
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import { quoteSystemdValue } from "./bootService.ts";
|
||||
import {
|
||||
SystemdSelfUpdatePlan,
|
||||
SystemdSelfUpdateReceipt,
|
||||
waitForSystemdSelfUpdateReadiness,
|
||||
writeSystemdSelfUpdatePlan,
|
||||
} from "./systemdSelfUpdate.ts";
|
||||
|
||||
const OLD_VERSION = "0.0.28";
|
||||
const TARGET_VERSION = "0.0.29";
|
||||
const decodeLaunch = Schema.decodeUnknownSync(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
pid: Schema.Int,
|
||||
version: Schema.String,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const fixtureServerSource = `
|
||||
import * as fs from "node:fs";
|
||||
import * as http from "node:http";
|
||||
|
||||
const [runtimeStatePath, launchesPath, version, readiness] = process.argv.slice(2);
|
||||
const descriptor = {
|
||||
environmentId: "systemd-self-update-acceptance",
|
||||
label: "Systemd self-update acceptance",
|
||||
platform: { os: "linux", arch: "x64" },
|
||||
serverVersion: version,
|
||||
capabilities: { repositoryIdentity: true },
|
||||
};
|
||||
const server = http.createServer((request, response) => {
|
||||
if (request.url === "/.well-known/t3/ready" && readiness === "ready") {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify(descriptor));
|
||||
return;
|
||||
}
|
||||
response.writeHead(503);
|
||||
response.end();
|
||||
});
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") process.exit(1);
|
||||
fs.appendFileSync(launchesPath, JSON.stringify({ pid: process.pid, version }) + "\\n");
|
||||
fs.writeFileSync(runtimeStatePath, JSON.stringify({
|
||||
version: 1,
|
||||
pid: process.pid,
|
||||
port: address.port,
|
||||
origin: "http://127.0.0.1:" + address.port,
|
||||
startedAt: new Date().toISOString(),
|
||||
}) + "\\n");
|
||||
});
|
||||
`;
|
||||
|
||||
const runAcceptanceScenario = Effect.fn("test.runSystemdSelfUpdateAcceptance")(function* (
|
||||
scenario: "healthy" | "rollback",
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const home = process.env.HOME;
|
||||
if (!home) {
|
||||
return yield* Effect.die(new Error("HOME is required for a systemd user-manager test."));
|
||||
}
|
||||
|
||||
const directory = yield* fs.makeTempDirectoryScoped({ prefix: `t3-systemd-${scenario}-` });
|
||||
const runtimeStatePath = path.join(directory, "server-runtime.json");
|
||||
const launchesPath = path.join(directory, "launches.jsonl");
|
||||
const receiptPath = path.join(directory, "receipt.json");
|
||||
const planPath = path.join(directory, "plan.json");
|
||||
const fixtureServerPath = path.join(directory, "fixture-server.mjs");
|
||||
yield* fs.writeFileString(fixtureServerPath, fixtureServerSource);
|
||||
|
||||
const suffix = `${String(process.pid)}-${String(yield* Clock.currentTimeMillis)}-${scenario}`;
|
||||
const serviceUnit = `t3code-self-update-acceptance-${suffix}.service`;
|
||||
const helperUnit = `t3code-self-update-acceptance-helper-${suffix}.service`;
|
||||
const userUnitDirectory = path.join(home, ".config", "systemd", "user");
|
||||
const unitPath = path.join(userUnitDirectory, serviceUnit);
|
||||
yield* fs.makeDirectory(userUnitDirectory, { recursive: true });
|
||||
|
||||
const renderUnit = (version: string, readiness: "ready" | "blocked") =>
|
||||
[
|
||||
"[Unit]",
|
||||
"Description=T3 self-update acceptance fixture",
|
||||
"",
|
||||
"[Service]",
|
||||
"Type=simple",
|
||||
`ExecStart=${quoteSystemdValue(process.execPath)} ${quoteSystemdValue(fixtureServerPath)} ${quoteSystemdValue(runtimeStatePath)} ${quoteSystemdValue(launchesPath)} ${version} ${readiness}`,
|
||||
"Restart=no",
|
||||
"TimeoutStopSec=5",
|
||||
"",
|
||||
].join("\n");
|
||||
const previousUnit = renderUnit(OLD_VERSION, "ready");
|
||||
const nextUnit = renderUnit(TARGET_VERSION, scenario === "healthy" ? "ready" : "blocked");
|
||||
|
||||
const systemctl = (args: ReadonlyArray<string>) =>
|
||||
runner.run({ command: "systemctl", args: ["--user", ...args] });
|
||||
const cleanup = Effect.gen(function* () {
|
||||
yield* systemctl(["stop", helperUnit, serviceUnit]).pipe(Effect.ignore);
|
||||
yield* systemctl(["reset-failed", helperUnit, serviceUnit]).pipe(Effect.ignore);
|
||||
yield* fs.remove(unitPath, { force: true }).pipe(Effect.ignore);
|
||||
yield* systemctl(["daemon-reload"]).pipe(Effect.ignore);
|
||||
});
|
||||
yield* Effect.addFinalizer(() => cleanup);
|
||||
|
||||
yield* fs.writeFileString(unitPath, previousUnit);
|
||||
const reload = yield* systemctl(["daemon-reload"]);
|
||||
assert.equal(Number(reload.code), 0);
|
||||
const start = yield* systemctl(["start", serviceUnit]);
|
||||
assert.equal(Number(start.code), 0);
|
||||
yield* waitForSystemdSelfUpdateReadiness(
|
||||
{
|
||||
expectedVersion: OLD_VERSION,
|
||||
previousPid: 0,
|
||||
runtimeStatePath,
|
||||
},
|
||||
{ timeout: Duration.seconds(10), interval: Duration.millis(100) },
|
||||
);
|
||||
const initialState = yield* readPersistedServerRuntimeState(runtimeStatePath);
|
||||
if (Option.isNone(initialState)) {
|
||||
return yield* Effect.die(
|
||||
new Error("The disposable systemd service did not publish runtime state."),
|
||||
);
|
||||
}
|
||||
|
||||
const plan = new SystemdSelfUpdatePlan({
|
||||
version: 1,
|
||||
fromVersion: OLD_VERSION,
|
||||
targetVersion: TARGET_VERSION,
|
||||
currentPid: initialState.value.pid,
|
||||
serviceUnit,
|
||||
unitPath,
|
||||
previousUnit,
|
||||
nextUnit,
|
||||
runtimeStatePath,
|
||||
receiptPath,
|
||||
});
|
||||
yield* writeSystemdSelfUpdatePlan(planPath, plan);
|
||||
|
||||
const repositoryRoot = path.resolve(import.meta.dirname, "../../../..");
|
||||
const cliEntryPath = path.join(repositoryRoot, "apps", "server", "src", "bin.ts");
|
||||
const handoff = yield* runner.run({
|
||||
command: "systemd-run",
|
||||
args: [
|
||||
"--user",
|
||||
"--wait",
|
||||
"--collect",
|
||||
"--service-type=exec",
|
||||
`--unit=${helperUnit}`,
|
||||
process.execPath,
|
||||
"--experimental-strip-types",
|
||||
cliEntryPath,
|
||||
"service",
|
||||
"_apply-update",
|
||||
"--plan",
|
||||
planPath,
|
||||
],
|
||||
timeout: Duration.seconds(90),
|
||||
});
|
||||
assert.equal(Number(handoff.code), 0, handoff.stderr);
|
||||
|
||||
const receipt = yield* fs
|
||||
.readFileString(receiptPath)
|
||||
.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(SystemdSelfUpdateReceipt))),
|
||||
);
|
||||
assert.equal(receipt.phase, scenario === "healthy" ? "healthy" : "rolled-back");
|
||||
assert.equal(
|
||||
yield* fs.readFileString(unitPath),
|
||||
scenario === "healthy" ? nextUnit : previousUnit,
|
||||
);
|
||||
|
||||
yield* waitForSystemdSelfUpdateReadiness(
|
||||
{
|
||||
expectedVersion: scenario === "healthy" ? TARGET_VERSION : OLD_VERSION,
|
||||
previousPid: initialState.value.pid,
|
||||
runtimeStatePath,
|
||||
},
|
||||
{ timeout: Duration.seconds(10), interval: Duration.millis(100) },
|
||||
);
|
||||
const launches = (yield* fs.readFileString(launchesPath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => decodeLaunch(line));
|
||||
assert.deepEqual(
|
||||
launches.map(({ version }) => version),
|
||||
scenario === "healthy"
|
||||
? [OLD_VERSION, TARGET_VERSION]
|
||||
: [OLD_VERSION, TARGET_VERSION, OLD_VERSION],
|
||||
);
|
||||
});
|
||||
|
||||
describe.runIf(process.env.T3_SYSTEMD_SELF_UPDATE_ACCEPTANCE === "1")(
|
||||
"systemd self-update acceptance",
|
||||
() => {
|
||||
const layer = ProcessRunner.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.merge(FetchHttpClient.layer),
|
||||
);
|
||||
|
||||
it.live(
|
||||
"keeps the helper alive while replacing the host service",
|
||||
() => runAcceptanceScenario("healthy").pipe(Effect.provide(layer)),
|
||||
30_000,
|
||||
);
|
||||
|
||||
it.live(
|
||||
"rolls back a server that binds HTTP without becoming runtime-ready",
|
||||
() => runAcceptanceScenario("rollback").pipe(Effect.provide(layer)),
|
||||
120_000,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,219 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { PersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import {
|
||||
SystemdSelfUpdateActivationError,
|
||||
SystemdSelfUpdatePlan,
|
||||
SystemdSelfUpdateReceipt,
|
||||
activateSystemdSelfUpdatePlan,
|
||||
waitForSystemdSelfUpdateReadiness,
|
||||
} from "./systemdSelfUpdate.ts";
|
||||
|
||||
interface RecordedCommand {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const makeRunnerLayer = (commands: Array<RecordedCommand>) =>
|
||||
Layer.succeed(
|
||||
ProcessRunner.ProcessRunner,
|
||||
ProcessRunner.ProcessRunner.of({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
commands.push({ command: input.command, args: input.args });
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("systemd self-update activation", (it) => {
|
||||
const makeFixture = Effect.fn("test.makeSystemdUpdateFixture")(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-systemd-update-test-" });
|
||||
const unitPath = path.join(directory, "t3code.service");
|
||||
const receiptPath = path.join(directory, "receipt.json");
|
||||
const previousUnit = "old unit\n";
|
||||
yield* fs.writeFileString(unitPath, previousUnit);
|
||||
return {
|
||||
fs,
|
||||
unitPath,
|
||||
receiptPath,
|
||||
previousUnit,
|
||||
plan: new SystemdSelfUpdatePlan({
|
||||
version: 1,
|
||||
fromVersion: "0.0.28",
|
||||
targetVersion: "0.0.29",
|
||||
currentPid: 123,
|
||||
serviceUnit: "t3code-self-update-test.service",
|
||||
unitPath,
|
||||
previousUnit,
|
||||
nextUnit: "new unit\n",
|
||||
runtimeStatePath: path.join(directory, "server-runtime.json"),
|
||||
receiptPath,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const readReceipt = Effect.fn("test.readSystemdUpdateReceipt")(function* (receiptPath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs
|
||||
.readFileString(receiptPath)
|
||||
.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(SystemdSelfUpdateReceipt))),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("activates and verifies the new service from the helper", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeFixture();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const readinessVersions: Array<string> = [];
|
||||
|
||||
yield* activateSystemdSelfUpdatePlan(
|
||||
fixture.plan,
|
||||
(input) => Effect.sync(() => readinessVersions.push(input.expectedVersion)),
|
||||
{ restartDelay: Duration.zero },
|
||||
).pipe(Effect.provide(makeRunnerLayer(commands)));
|
||||
|
||||
assert.equal(yield* fixture.fs.readFileString(fixture.unitPath), "new unit\n");
|
||||
assert.deepEqual(readinessVersions, ["0.0.29"]);
|
||||
assert.deepEqual(
|
||||
commands.map(({ args }) => args),
|
||||
[
|
||||
["--user", "daemon-reload"],
|
||||
["--user", "restart", "t3code-self-update-test.service"],
|
||||
],
|
||||
);
|
||||
assert.equal((yield* readReceipt(fixture.receiptPath)).phase, "healthy");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores and verifies the previous service when the target never becomes ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeFixture();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const readinessVersions: Array<string> = [];
|
||||
|
||||
yield* activateSystemdSelfUpdatePlan(
|
||||
fixture.plan,
|
||||
(input) =>
|
||||
Effect.sync(() => readinessVersions.push(input.expectedVersion)).pipe(
|
||||
Effect.andThen(
|
||||
input.expectedVersion === fixture.plan.targetVersion
|
||||
? Effect.fail(
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation: "await-readiness",
|
||||
expectedVersion: input.expectedVersion,
|
||||
}),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
{ restartDelay: Duration.zero },
|
||||
).pipe(Effect.provide(makeRunnerLayer(commands)));
|
||||
|
||||
assert.equal(yield* fixture.fs.readFileString(fixture.unitPath), fixture.previousUnit);
|
||||
assert.deepEqual(readinessVersions, ["0.0.29", "0.0.28"]);
|
||||
assert.deepEqual(
|
||||
commands.map(({ args }) => args),
|
||||
[
|
||||
["--user", "daemon-reload"],
|
||||
["--user", "restart", "t3code-self-update-test.service"],
|
||||
["--user", "daemon-reload"],
|
||||
["--user", "reset-failed", "t3code-self-update-test.service"],
|
||||
["--user", "restart", "t3code-self-update-test.service"],
|
||||
],
|
||||
);
|
||||
const receipt = yield* readReceipt(fixture.receiptPath);
|
||||
assert.equal(receipt.phase, "rolled-back");
|
||||
assert.equal(receipt.detail, "The restarted server did not become ready as [email protected].");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records a recovery failure instead of claiming the update completed", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeFixture();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const error = yield* activateSystemdSelfUpdatePlan(
|
||||
fixture.plan,
|
||||
(input) =>
|
||||
Effect.fail(
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation: "await-readiness",
|
||||
expectedVersion: input.expectedVersion,
|
||||
}),
|
||||
),
|
||||
{ restartDelay: Duration.zero },
|
||||
).pipe(Effect.provide(makeRunnerLayer(commands)), Effect.flip);
|
||||
|
||||
assert.include(error.message, "previous server could not be restored");
|
||||
assert.equal((yield* readReceipt(fixture.receiptPath)).phase, "recovery-failed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("probes the runtime-readiness endpoint on the replacement process", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-systemd-ready-test-" });
|
||||
const runtimeStatePath = path.join(directory, "server-runtime.json");
|
||||
const encodeRuntimeState = Schema.encodeEffect(
|
||||
Schema.fromJsonString(PersistedServerRuntimeState),
|
||||
);
|
||||
const encodedRuntimeState = yield* encodeRuntimeState({
|
||||
version: 1,
|
||||
pid: 456,
|
||||
port: 3210,
|
||||
origin: "http://127.0.0.1:3210",
|
||||
startedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
yield* fs.writeFileString(runtimeStatePath, `${encodedRuntimeState}\n`);
|
||||
|
||||
const requests: Array<string> = [];
|
||||
const httpClientLayer = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) => {
|
||||
requests.push(request.url);
|
||||
return Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({
|
||||
environmentId: "environment-test",
|
||||
label: "Test environment",
|
||||
platform: { os: "linux", arch: "x64" },
|
||||
serverVersion: "0.0.29",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* waitForSystemdSelfUpdateReadiness({
|
||||
expectedVersion: "0.0.29",
|
||||
previousPid: 123,
|
||||
runtimeStatePath,
|
||||
}).pipe(Effect.provide(httpClientLayer));
|
||||
|
||||
assert.deepEqual(requests, ["http://127.0.0.1:3210/.well-known/t3/ready"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,348 @@
|
||||
import { ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
|
||||
export const SYSTEMD_SELF_UPDATE_UNIT = "t3code-self-update.service";
|
||||
export const SYSTEMD_SELF_UPDATE_DIRECTORY = "self-update";
|
||||
export const SYSTEMD_SELF_UPDATE_PLAN_FILE = "plan.json";
|
||||
export const SYSTEMD_SELF_UPDATE_RECEIPT_FILE = "receipt.json";
|
||||
|
||||
const DEFAULT_RESTART_DELAY = Duration.seconds(2);
|
||||
const DEFAULT_READINESS_TIMEOUT = Duration.seconds(60);
|
||||
const DEFAULT_READINESS_INTERVAL = Duration.millis(500);
|
||||
const READINESS_REQUEST_TIMEOUT = Duration.seconds(2);
|
||||
const WELL_KNOWN_READY_PATH = "/.well-known/t3/ready";
|
||||
|
||||
export class SystemdSelfUpdatePlan extends Schema.Class<SystemdSelfUpdatePlan>(
|
||||
"SystemdSelfUpdatePlan",
|
||||
)({
|
||||
version: Schema.Literal(1),
|
||||
fromVersion: Schema.String,
|
||||
targetVersion: Schema.String,
|
||||
currentPid: Schema.Int,
|
||||
serviceUnit: Schema.String,
|
||||
unitPath: Schema.String,
|
||||
previousUnit: Schema.String,
|
||||
nextUnit: Schema.String,
|
||||
runtimeStatePath: Schema.String,
|
||||
receiptPath: Schema.String,
|
||||
}) {}
|
||||
|
||||
export const SystemdSelfUpdateReceipt = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
targetVersion: Schema.String,
|
||||
phase: Schema.Literals(["prepared", "activating", "healthy", "rolled-back", "recovery-failed"]),
|
||||
updatedAt: Schema.String,
|
||||
detail: Schema.optional(Schema.String),
|
||||
});
|
||||
export type SystemdSelfUpdateReceipt = typeof SystemdSelfUpdateReceipt.Type;
|
||||
|
||||
export const SystemdSelfUpdateOperation = Schema.Literals([
|
||||
"read-plan",
|
||||
"write-unit",
|
||||
"daemon-reload",
|
||||
"restart",
|
||||
"reset-failed",
|
||||
"await-readiness",
|
||||
"recover",
|
||||
]);
|
||||
export type SystemdSelfUpdateOperation = typeof SystemdSelfUpdateOperation.Type;
|
||||
|
||||
export class SystemdSelfUpdateActivationError extends Schema.TaggedErrorClass<SystemdSelfUpdateActivationError>()(
|
||||
"SystemdSelfUpdateActivationError",
|
||||
{
|
||||
operation: SystemdSelfUpdateOperation,
|
||||
path: Schema.optional(Schema.String),
|
||||
expectedVersion: Schema.optional(Schema.String),
|
||||
actualVersion: Schema.optional(Schema.String),
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : ` (exit code ${String(this.exitCode)})`;
|
||||
switch (this.operation) {
|
||||
case "read-plan":
|
||||
return `Could not read the staged update plan${this.path === undefined ? "" : ` at ${this.path}`}.`;
|
||||
case "write-unit":
|
||||
return "Could not write the systemd boot service unit.";
|
||||
case "daemon-reload":
|
||||
return `Could not reload systemd units${exitCode}.`;
|
||||
case "restart":
|
||||
return `Could not restart the systemd boot service${exitCode}.`;
|
||||
case "reset-failed":
|
||||
return `Could not reset the failed systemd boot service${exitCode}.`;
|
||||
case "await-readiness":
|
||||
return this.actualVersion === undefined
|
||||
? `The restarted server did not become ready${this.expectedVersion === undefined ? "" : ` as t3@${this.expectedVersion}`}.`
|
||||
: `The restarted server reported t3@${this.actualVersion}, expected t3@${this.expectedVersion ?? "unknown"}.`;
|
||||
case "recover":
|
||||
return "The update failed and the previous server could not be restored.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const decodePlan = Schema.decodeUnknownEffect(Schema.fromJsonString(SystemdSelfUpdatePlan));
|
||||
const encodePlan = Schema.encodeEffect(Schema.fromJsonString(SystemdSelfUpdatePlan));
|
||||
const encodeReceipt = Schema.encodeEffect(Schema.fromJsonString(SystemdSelfUpdateReceipt));
|
||||
|
||||
const provideFileServices = <A, E>(
|
||||
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
|
||||
fs: FileSystem.FileSystem,
|
||||
path: Path.Path,
|
||||
) =>
|
||||
effect.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
const writeAtomically = (
|
||||
filePath: string,
|
||||
contents: string,
|
||||
fs: FileSystem.FileSystem,
|
||||
path: Path.Path,
|
||||
) => provideFileServices(writeFileStringAtomically({ filePath, contents }), fs, path);
|
||||
|
||||
export const writeSystemdSelfUpdatePlan = Effect.fn("systemdSelfUpdate.writePlan")(function* (
|
||||
planPath: string,
|
||||
plan: SystemdSelfUpdatePlan,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const encoded = yield* encodePlan(plan);
|
||||
yield* writeAtomically(planPath, `${encoded}\n`, fs, path);
|
||||
yield* writeReceipt(plan, "prepared");
|
||||
});
|
||||
|
||||
const writeReceipt = Effect.fn("systemdSelfUpdate.writeReceipt")(function* (
|
||||
plan: SystemdSelfUpdatePlan,
|
||||
phase: SystemdSelfUpdateReceipt["phase"],
|
||||
detail?: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const now = yield* DateTime.now;
|
||||
const receipt = {
|
||||
version: 1,
|
||||
targetVersion: plan.targetVersion,
|
||||
phase,
|
||||
updatedAt: DateTime.formatIso(now),
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
} satisfies SystemdSelfUpdateReceipt;
|
||||
const encoded = yield* encodeReceipt(receipt);
|
||||
yield* writeAtomically(plan.receiptPath, `${encoded}\n`, fs, path);
|
||||
});
|
||||
|
||||
const runSystemctl = Effect.fn("systemdSelfUpdate.runSystemctl")(function* (
|
||||
args: ReadonlyArray<string>,
|
||||
operation: Extract<SystemdSelfUpdateOperation, "daemon-reload" | "restart" | "reset-failed">,
|
||||
) {
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const result = yield* runner.run({ command: "systemctl", args }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return yield* new SystemdSelfUpdateActivationError({
|
||||
operation,
|
||||
exitCode: Number(result.code),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const installUnit = Effect.fn("systemdSelfUpdate.installUnit")(function* (
|
||||
plan: SystemdSelfUpdatePlan,
|
||||
contents: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* writeAtomically(plan.unitPath, contents, fs, path).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation: "write-unit",
|
||||
path: plan.unitPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* runSystemctl(["--user", "daemon-reload"], "daemon-reload");
|
||||
});
|
||||
|
||||
const restartBootService = (serviceUnit: string) =>
|
||||
runSystemctl(["--user", "restart", serviceUnit], "restart");
|
||||
|
||||
export interface SystemdSelfUpdateReadinessInput {
|
||||
readonly expectedVersion: string;
|
||||
readonly previousPid: number;
|
||||
readonly runtimeStatePath: string;
|
||||
}
|
||||
|
||||
export const waitForSystemdSelfUpdateReadiness = Effect.fn("systemdSelfUpdate.waitForReadiness")(
|
||||
function* (
|
||||
input: SystemdSelfUpdateReadinessInput,
|
||||
options: {
|
||||
readonly timeout?: Duration.Input;
|
||||
readonly interval?: Duration.Input;
|
||||
} = {},
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const attempt = Effect.gen(function* () {
|
||||
const state = yield* provideFileServices(
|
||||
readPersistedServerRuntimeState(input.runtimeStatePath),
|
||||
fs,
|
||||
path,
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation: "await-readiness",
|
||||
expectedVersion: input.expectedVersion,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(state) || state.value.pid === input.previousPid) {
|
||||
return yield* new SystemdSelfUpdateActivationError({
|
||||
operation: "await-readiness",
|
||||
expectedVersion: input.expectedVersion,
|
||||
});
|
||||
}
|
||||
|
||||
const request = HttpClientRequest.get(
|
||||
new URL(WELL_KNOWN_READY_PATH, state.value.origin).toString(),
|
||||
);
|
||||
const descriptor = yield* client.execute(request).pipe(
|
||||
Effect.timeout(READINESS_REQUEST_TIMEOUT),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation: "await-readiness",
|
||||
expectedVersion: input.expectedVersion,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (descriptor.serverVersion !== input.expectedVersion) {
|
||||
return yield* new SystemdSelfUpdateActivationError({
|
||||
operation: "await-readiness",
|
||||
expectedVersion: input.expectedVersion,
|
||||
actualVersion: descriptor.serverVersion,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const ready = yield* attempt.pipe(
|
||||
Effect.retry(Schedule.spaced(options.interval ?? DEFAULT_READINESS_INTERVAL)),
|
||||
Effect.timeoutOption(options.timeout ?? DEFAULT_READINESS_TIMEOUT),
|
||||
);
|
||||
if (Option.isNone(ready)) {
|
||||
return yield* new SystemdSelfUpdateActivationError({
|
||||
operation: "await-readiness",
|
||||
expectedVersion: input.expectedVersion,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const activateSystemdSelfUpdatePlan = Effect.fn("systemdSelfUpdate.activatePlan")(function* <
|
||||
R,
|
||||
>(
|
||||
plan: SystemdSelfUpdatePlan,
|
||||
waitForReadiness: (
|
||||
input: SystemdSelfUpdateReadinessInput,
|
||||
) => Effect.Effect<void, SystemdSelfUpdateActivationError, R>,
|
||||
options: { readonly restartDelay?: Duration.Input } = {},
|
||||
) {
|
||||
const activate = Effect.gen(function* () {
|
||||
yield* writeReceipt(plan, "activating").pipe(Effect.ignore);
|
||||
yield* Effect.sleep(options.restartDelay ?? DEFAULT_RESTART_DELAY);
|
||||
yield* installUnit(plan, plan.nextUnit);
|
||||
yield* restartBootService(plan.serviceUnit);
|
||||
yield* waitForReadiness({
|
||||
expectedVersion: plan.targetVersion,
|
||||
previousPid: plan.currentPid,
|
||||
runtimeStatePath: plan.runtimeStatePath,
|
||||
});
|
||||
yield* writeReceipt(plan, "healthy").pipe(Effect.ignore);
|
||||
});
|
||||
|
||||
yield* activate.pipe(
|
||||
Effect.catch((activationError) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logError("Systemd self-update failed; restoring the previous version.").pipe(
|
||||
Effect.annotateLogs({
|
||||
targetVersion: plan.targetVersion,
|
||||
operation: activationError.operation,
|
||||
error: activationError.message,
|
||||
}),
|
||||
);
|
||||
const recovery = Effect.gen(function* () {
|
||||
yield* installUnit(plan, plan.previousUnit);
|
||||
yield* runSystemctl(["--user", "reset-failed", plan.serviceUnit], "reset-failed");
|
||||
yield* restartBootService(plan.serviceUnit);
|
||||
yield* waitForReadiness({
|
||||
expectedVersion: plan.fromVersion,
|
||||
previousPid: plan.currentPid,
|
||||
runtimeStatePath: plan.runtimeStatePath,
|
||||
});
|
||||
yield* writeReceipt(plan, "rolled-back", activationError.message).pipe(Effect.ignore);
|
||||
});
|
||||
|
||||
yield* recovery.pipe(
|
||||
Effect.catch((recoveryError) =>
|
||||
writeReceipt(plan, "recovery-failed", recoveryError.message).pipe(
|
||||
Effect.ignore,
|
||||
Effect.andThen(
|
||||
Effect.fail(
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation: "recover",
|
||||
cause: { activationError, recoveryError },
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
export const applySystemdSelfUpdatePlan = Effect.fn("systemdSelfUpdate.applyPlan")(function* (
|
||||
planPath: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const plan = yield* fs.readFileString(planPath).pipe(
|
||||
Effect.flatMap(decodePlan),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SystemdSelfUpdateActivationError({
|
||||
operation: "read-plan",
|
||||
path: planPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* activateSystemdSelfUpdatePlan(plan, waitForSystemdSelfUpdateReadiness);
|
||||
});
|
||||
+18
-7
@@ -40,6 +40,7 @@ import {
|
||||
} from "./auth/http.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
@@ -177,13 +178,23 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
|
||||
"metadata",
|
||||
Effect.fnUntraced(function* (handlers) {
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
return handlers.handle(
|
||||
"descriptor",
|
||||
Effect.fn("environment.metadata.descriptor")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}, traceRelayRequest),
|
||||
);
|
||||
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
|
||||
return handlers
|
||||
.handle(
|
||||
"descriptor",
|
||||
Effect.fn("environment.metadata.descriptor")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}, traceRelayRequest),
|
||||
)
|
||||
.handle(
|
||||
"ready",
|
||||
Effect.fn("environment.metadata.ready")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* startup.awaitReady.pipe(Effect.orDie);
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}, traceRelayRequest),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -277,6 +277,9 @@ describe("CheckpointReactor", () => {
|
||||
readonly seedFilesystemCheckpoints?: boolean;
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly threadBranch?: string | null;
|
||||
readonly secondThreadSharingWorktree?: boolean;
|
||||
readonly localStatusRefName?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: ProviderDriverKind;
|
||||
readonly gitStatusRefreshCalls?: Array<string>;
|
||||
@@ -315,7 +318,8 @@ describe("CheckpointReactor", () => {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
refName:
|
||||
options?.localStatusRefName !== undefined ? options.localStatusRefName : "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -370,22 +374,45 @@ describe("CheckpointReactor", () => {
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: options?.threadWorktreePath ?? cwd,
|
||||
createdAt,
|
||||
}),
|
||||
engine
|
||||
.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: options?.threadBranch ?? null,
|
||||
worktreePath: options?.threadWorktreePath ?? cwd,
|
||||
createdAt,
|
||||
})
|
||||
.pipe(
|
||||
options?.secondThreadSharingWorktree
|
||||
? Effect.andThen(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create-2"),
|
||||
threadId: ThreadId.make("thread-2"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 2",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: options?.threadWorktreePath ?? cwd,
|
||||
createdAt,
|
||||
}),
|
||||
)
|
||||
: Effect.asVoid,
|
||||
),
|
||||
);
|
||||
|
||||
if (options?.seedFilesystemCheckpoints ?? true) {
|
||||
@@ -518,6 +545,86 @@ describe("CheckpointReactor", () => {
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
});
|
||||
|
||||
it("adopts a drifted checkout as the thread branch on a dedicated worktree", async () => {
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
threadBranch: "t3code/original-branch",
|
||||
localStatusRefName: "t3code/renamed-by-agent",
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-branch-drift"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-branch-drift"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
await waitForEvent(
|
||||
harness.engine,
|
||||
(event) =>
|
||||
event.type === "thread.meta-updated" &&
|
||||
(event as unknown as { payload: { branch?: string } }).payload.branch ===
|
||||
"t3code/renamed-by-agent",
|
||||
);
|
||||
|
||||
const snapshot = await harness.readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.branch).toBe("t3code/renamed-by-agent");
|
||||
});
|
||||
|
||||
it("does not adopt a drifted checkout when the worktree is shared by another thread", async () => {
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
threadBranch: "t3code/original-branch",
|
||||
localStatusRefName: "t3code/renamed-by-agent",
|
||||
secondThreadSharingWorktree: true,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-branch-drift-shared"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-branch-drift-shared"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const snapshot = await harness.readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.branch).toBe("t3code/original-branch");
|
||||
});
|
||||
|
||||
it("does not adopt a temporary placeholder checkout as the thread branch", async () => {
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
threadBranch: "t3code/original-branch",
|
||||
localStatusRefName: "t3code/0a1b2c3d",
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-branch-drift-temp"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-branch-drift-temp"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const snapshot = await harness.readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.branch).toBe("t3code/original-branch");
|
||||
});
|
||||
|
||||
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
type VcsStatusLocalResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -18,6 +19,7 @@ import * as Option from "effect/Option";
|
||||
import type * as PlatformError from "effect/PlatformError";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
|
||||
import {
|
||||
@@ -534,16 +536,93 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||
const local = yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
detail: error.message,
|
||||
}),
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
if (local !== null) {
|
||||
yield* followWorktreeBranchDrift({
|
||||
threadId: event.threadId,
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
local,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// A `git checkout` run inside a thread's dedicated worktree (by an agent or
|
||||
// the user) bypasses T3's commands, so the thread's recorded branch goes
|
||||
// stale. Since #4460 the client only attributes PR state to a thread when
|
||||
// the checked-out branch equals the recorded one, so stale metadata silently
|
||||
// orphans the thread's PR. Follow the drift here: adopt the checked-out
|
||||
// branch as the thread's branch, but only when the worktree belongs to
|
||||
// exactly this thread — for shared cwds the strict matching is the point.
|
||||
const followWorktreeBranchDrift = Effect.fn("followWorktreeBranchDrift")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly cwd: string;
|
||||
readonly local: VcsStatusLocalResult;
|
||||
}) {
|
||||
// Detached HEAD has no branch to adopt; a temporary placeholder checkout
|
||||
// means the first-turn auto-rename is still in flight — don't race it.
|
||||
const checkedOutBranch = input.local.refName;
|
||||
if (checkedOutBranch === null || isTemporaryWorktreeBranch(checkedOutBranch)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(input.threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
if (
|
||||
!thread ||
|
||||
thread.branch === null ||
|
||||
thread.branch === checkedOutBranch ||
|
||||
thread.worktreePath === null ||
|
||||
thread.worktreePath !== input.cwd ||
|
||||
isTemporaryWorktreeBranch(thread.branch)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const shell = yield* projectionSnapshotQuery.getShellSnapshot();
|
||||
const worktreeIsShared = shell.threads.some(
|
||||
(other) => other.id !== thread.id && other.worktreePath === thread.worktreePath,
|
||||
);
|
||||
if (worktreeIsShared) {
|
||||
return;
|
||||
}
|
||||
|
||||
// expectedBranch makes this a compare-and-swap in the decider: if the
|
||||
// recorded branch moved between our read and the dispatch (rename,
|
||||
// concurrent drift-follow), the stale update is dropped.
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: yield* serverCommandId("worktree-branch-drift"),
|
||||
threadId: thread.id,
|
||||
branch: checkedOutBranch,
|
||||
expectedBranch: thread.branch,
|
||||
});
|
||||
yield* Effect.logInfo("thread branch followed worktree checkout", {
|
||||
threadId: thread.id,
|
||||
previousBranch: thread.branch,
|
||||
branch: checkedOutBranch,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("failed to follow worktree branch drift", {
|
||||
threadId: input.threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
|
||||
|
||||
@@ -32,8 +32,13 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
|
||||
Effect.fn("environment.orchestration.snapshot")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
|
||||
// Serve the lightweight command read model (thread bodies empty)
|
||||
// instead of the fully hydrated snapshot. Hydrating every message
|
||||
// and activity payload in the database has OOM-killed servers, and
|
||||
// the route's only consumer (the project CLI) reads projects alone —
|
||||
// UI clients load the shell and per-thread snapshots instead.
|
||||
return yield* projectionSnapshotQuery
|
||||
.getSnapshot()
|
||||
.getCommandReadModel()
|
||||
.pipe(
|
||||
Effect.catch((cause) =>
|
||||
failEnvironmentInternal("orchestration_snapshot_failed", cause),
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import {
|
||||
AutomaticUpdateMigrationFrontierError,
|
||||
MigrationIdentityMismatchError,
|
||||
validateAutomaticUpdateMigrationFrontier,
|
||||
validateMigrationIdentities,
|
||||
} from "./Migrations.ts";
|
||||
import * as NodeSqliteClient from "./NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("migration identity validation", (it) => {
|
||||
const createTrackingTable = Effect.fn("test.createMigrationTrackingTable")(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS effect_sql_migrations (
|
||||
migration_id integer PRIMARY KEY NOT NULL,
|
||||
name varchar(255) NOT NULL,
|
||||
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`;
|
||||
yield* sql`DELETE FROM effect_sql_migrations`;
|
||||
});
|
||||
|
||||
it.effect("rejects a reused migration ID before migrations run", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* createTrackingTable();
|
||||
yield* sql`
|
||||
INSERT INTO effect_sql_migrations (migration_id, name)
|
||||
VALUES (35, 'DifferentMigration')
|
||||
`;
|
||||
|
||||
const error = yield* validateMigrationIdentities().pipe(Effect.flip);
|
||||
assert.instanceOf(error, MigrationIdentityMismatchError);
|
||||
assert.equal(error.migrationId, 35);
|
||||
assert.equal(error.expectedName, "ProjectionThreadTitleRegeneration");
|
||||
assert.equal(error.actualName, "DifferentMigration");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows migration IDs this build does not know about", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* createTrackingTable();
|
||||
yield* sql`
|
||||
INSERT INTO effect_sql_migrations (migration_id, name)
|
||||
VALUES (999, 'FutureMigration')
|
||||
`;
|
||||
|
||||
yield* validateMigrationIdentities();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects automatic downgrade when the database has a newer migration", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* createTrackingTable();
|
||||
yield* sql`
|
||||
INSERT INTO effect_sql_migrations (migration_id, name)
|
||||
VALUES (999, 'FutureMigration')
|
||||
`;
|
||||
|
||||
const error = yield* validateAutomaticUpdateMigrationFrontier().pipe(Effect.flip);
|
||||
assert.instanceOf(error, AutomaticUpdateMigrationFrontierError);
|
||||
assert.equal(error.databaseMigrationId, 999);
|
||||
assert.equal(error.targetMigrationId, 35);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects automatic updates that would run migrations", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* createTrackingTable();
|
||||
yield* sql`
|
||||
INSERT INTO effect_sql_migrations (migration_id, name)
|
||||
VALUES (34, 'ProjectionThreadsSnoozed')
|
||||
`;
|
||||
|
||||
const error = yield* validateAutomaticUpdateMigrationFrontier().pipe(Effect.flip);
|
||||
assert.instanceOf(error, AutomaticUpdateMigrationFrontierError);
|
||||
assert.equal(error.databaseMigrationId, 34);
|
||||
assert.equal(error.targetMigrationId, 35);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows automatic updates on the same migration frontier", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* createTrackingTable();
|
||||
yield* sql`
|
||||
INSERT INTO effect_sql_migrations (migration_id, name)
|
||||
VALUES (35, 'ProjectionThreadTitleRegeneration')
|
||||
`;
|
||||
|
||||
yield* validateAutomaticUpdateMigrationFrontier();
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -11,6 +11,8 @@
|
||||
import * as Migrator from "effect/unstable/sql/Migrator";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
// Import all migrations statically
|
||||
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
|
||||
@@ -112,6 +114,99 @@ export const makeMigrationLoader = (throughId?: number) =>
|
||||
*/
|
||||
const run = Migrator.make({});
|
||||
|
||||
export class MigrationIdentityMismatchError extends Schema.TaggedErrorClass<MigrationIdentityMismatchError>()(
|
||||
"MigrationIdentityMismatchError",
|
||||
{
|
||||
migrationId: Schema.Int,
|
||||
expectedName: Schema.String,
|
||||
actualName: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Migration ${String(this.migrationId)} is recorded as '${this.actualName}', but this t3 build expects '${this.expectedName}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AutomaticUpdateMigrationFrontierError extends Schema.TaggedErrorClass<AutomaticUpdateMigrationFrontierError>()(
|
||||
"AutomaticUpdateMigrationFrontierError",
|
||||
{
|
||||
databaseMigrationId: Schema.Int,
|
||||
targetMigrationId: Schema.Int,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.databaseMigrationId > this.targetMigrationId
|
||||
? `This database is newer than the requested t3 build (migration ${String(this.databaseMigrationId)} vs ${String(this.targetMigrationId)}).`
|
||||
: `The requested t3 build would migrate this database (migration ${String(this.databaseMigrationId)} to ${String(this.targetMigrationId)}), which is not safe during an automatic update.`;
|
||||
}
|
||||
}
|
||||
|
||||
const readPersistedMigrationIdentities = Effect.fn("readPersistedMigrationIdentities")(
|
||||
function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const tables = yield* sql<{ readonly name: string }>`
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'effect_sql_migrations'
|
||||
`;
|
||||
if (tables.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return yield* sql<{
|
||||
readonly migration_id: number;
|
||||
readonly name: string;
|
||||
}>`
|
||||
SELECT migration_id, name
|
||||
FROM effect_sql_migrations
|
||||
ORDER BY migration_id
|
||||
`;
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Refuse to run a build whose migration history disagrees with the database.
|
||||
* Unknown newer IDs are intentionally allowed so a compatible older build can
|
||||
* inspect a database created by a newer release without rewriting its history.
|
||||
*/
|
||||
export const validateMigrationIdentities = Effect.fn("validateMigrationIdentities")(function* () {
|
||||
const expectedNames = new Map<number, string>(
|
||||
migrationEntries.map(([migrationId, name]) => [migrationId, name]),
|
||||
);
|
||||
const persisted = yield* readPersistedMigrationIdentities();
|
||||
|
||||
for (const migration of persisted) {
|
||||
const expectedName = expectedNames.get(migration.migration_id);
|
||||
if (expectedName !== undefined && expectedName !== migration.name) {
|
||||
return yield* new MigrationIdentityMismatchError({
|
||||
migrationId: migration.migration_id,
|
||||
expectedName,
|
||||
actualName: migration.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Automatic activation is safe only when the target and database are already
|
||||
* on the same schema. A binary rollback cannot undo a migration, and an older
|
||||
* target cannot safely interpret migration IDs that it does not know about.
|
||||
*/
|
||||
export const validateAutomaticUpdateMigrationFrontier = Effect.fn(
|
||||
"validateAutomaticUpdateMigrationFrontier",
|
||||
)(function* () {
|
||||
yield* validateMigrationIdentities();
|
||||
const persisted = yield* readPersistedMigrationIdentities();
|
||||
const databaseMigrationId = persisted.at(-1)?.migration_id ?? 0;
|
||||
const targetMigrationId = migrationEntries.at(-1)?.[0] ?? 0;
|
||||
if (databaseMigrationId !== targetMigrationId) {
|
||||
return yield* new AutomaticUpdateMigrationFrontierError({
|
||||
databaseMigrationId,
|
||||
targetMigrationId,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export interface RunMigrationsOptions {
|
||||
readonly toMigrationInclusive?: number | undefined;
|
||||
}
|
||||
@@ -129,6 +224,7 @@ export interface RunMigrationsOptions {
|
||||
export const runMigrations = Effect.fn("runMigrations")(function* ({
|
||||
toMigrationInclusive,
|
||||
}: RunMigrationsOptions = {}) {
|
||||
yield* validateMigrationIdentities();
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);
|
||||
yield* migrations.length === 0
|
||||
|
||||
@@ -782,6 +782,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(
|
||||
Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({
|
||||
awaitCommandReady: Effect.void,
|
||||
awaitReady: Effect.void,
|
||||
markHttpListening: Effect.void,
|
||||
enqueueCommand: (effect) => effect,
|
||||
...options?.layers?.serverRuntimeStartup,
|
||||
@@ -1361,6 +1362,30 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("does not report update readiness before the runtime publishes ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtimeReady = yield* Deferred.make<void>();
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
serverRuntimeStartup: {
|
||||
awaitReady: Deferred.await(runtimeReady),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const url = yield* getHttpServerUrl("/.well-known/t3/ready");
|
||||
const responseFiber = yield* fetchEffect(url).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
assert.isUndefined(responseFiber.pollUnsafe());
|
||||
|
||||
yield* Deferred.succeed(runtimeReady, undefined);
|
||||
const response = yield* Fiber.join(responseFiber);
|
||||
const body = yield* responseJsonEffect<typeof testEnvironmentDescriptor>(response);
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(body, testEnvironmentDescriptor);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("compresses large JSON responses through the composed routes", () =>
|
||||
Effect.gen(function* () {
|
||||
const descriptor = {
|
||||
@@ -6005,6 +6030,149 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("subscribeThread sends a fresh snapshot instead of replaying a large gap", () =>
|
||||
Effect.gen(function* () {
|
||||
let readEventsCalls = 0;
|
||||
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
// Head is far ahead of the client's afterSequence (gap > 1000).
|
||||
latestSequence: Effect.succeed(100_000),
|
||||
readEvents: () =>
|
||||
Stream.sync(() => {
|
||||
readEventsCalls += 1;
|
||||
return {} as OrchestrationEvent;
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadDetailSnapshot: () =>
|
||||
Effect.succeed(Option.some({ snapshotSequence: 100_000, thread })),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const items = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
|
||||
threadId: defaultThreadId,
|
||||
afterSequence: 5,
|
||||
requestCompletionMarker: true,
|
||||
}).pipe(Stream.take(2), Stream.runCollect),
|
||||
),
|
||||
);
|
||||
|
||||
const [first, second] = Array.from(items);
|
||||
// Large gap => fresh thread snapshot, and the global replay never starts.
|
||||
assert.equal(first?.kind, "snapshot");
|
||||
if (first?.kind === "snapshot") {
|
||||
assert.equal(first.snapshot.thread.id, defaultThreadId);
|
||||
assert.equal(first.snapshot.snapshotSequence, 100_000);
|
||||
}
|
||||
assert.equal(second?.kind, "synchronized");
|
||||
assert.equal(readEventsCalls, 0);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("subscribeThread replaces a cursor ahead of the authoritative head", () =>
|
||||
Effect.gen(function* () {
|
||||
let readEventsCalls = 0;
|
||||
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
latestSequence: Effect.succeed(5),
|
||||
readEvents: () =>
|
||||
Stream.sync(() => {
|
||||
readEventsCalls += 1;
|
||||
return {} as OrchestrationEvent;
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadDetailSnapshot: () =>
|
||||
Effect.succeed(Option.some({ snapshotSequence: 5, thread })),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const first = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
|
||||
threadId: defaultThreadId,
|
||||
afterSequence: 10,
|
||||
}).pipe(Stream.runHead),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(Option.getOrThrow(first).kind, "snapshot");
|
||||
assert.equal(readEventsCalls, 0);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("subscribeThread bounds catch-up replay to the captured head", () =>
|
||||
Effect.gen(function* () {
|
||||
let replayLimit: number | undefined;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const messageEvent = {
|
||||
sequence: 3,
|
||||
eventId: EventId.make("event-replay-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: defaultThreadId,
|
||||
occurredAt: now,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: defaultThreadId,
|
||||
messageId: MessageId.make("message-replay"),
|
||||
role: "user",
|
||||
text: "Replayed message",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "thread.message-sent" }>;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
latestSequence: Effect.succeed(50),
|
||||
readEvents: (_afterSequence, limit) => {
|
||||
replayLimit = limit;
|
||||
return Stream.make(messageEvent);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const items = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
|
||||
threadId: defaultThreadId,
|
||||
afterSequence: 0,
|
||||
requestCompletionMarker: true,
|
||||
}).pipe(Stream.take(2), Stream.runCollect),
|
||||
),
|
||||
);
|
||||
|
||||
const [first, second] = Array.from(items);
|
||||
assert.equal(first?.kind, "event");
|
||||
assert.equal(first?.kind === "event" ? first.event.sequence : null, 3);
|
||||
assert.equal(second?.kind, "synchronized");
|
||||
// The replay is bounded to the head captured before the read, not
|
||||
// Number.MAX_SAFE_INTEGER.
|
||||
assert.equal(replayLimit, 50);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("subscribeShell sends a fresh snapshot instead of replaying a large gap", () =>
|
||||
Effect.gen(function* () {
|
||||
let readEventsCalls = 0;
|
||||
|
||||
@@ -59,6 +59,7 @@ export class ServerRuntimeStartup extends Context.Service<
|
||||
ServerRuntimeStartup,
|
||||
{
|
||||
readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
|
||||
readonly awaitReady: Effect.Effect<void, ServerRuntimeStartupError>;
|
||||
readonly markHttpListening: Effect.Effect<void>;
|
||||
readonly enqueueCommand: <A, E>(
|
||||
effect: Effect.Effect<A, E>,
|
||||
@@ -300,6 +301,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const commandGate = yield* makeCommandGate;
|
||||
const httpListening = yield* Deferred.make<void>();
|
||||
const runtimeReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
|
||||
const reactorScope = yield* Scope.make("sequential");
|
||||
|
||||
yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
|
||||
@@ -425,6 +427,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause });
|
||||
yield* commandGate.failCommandReady(error);
|
||||
yield* Deferred.fail(runtimeReady, error).pipe(Effect.orDie);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -444,6 +447,7 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* Deferred.succeed(runtimeReady, undefined).pipe(Effect.orDie);
|
||||
|
||||
yield* Effect.logDebug("startup phase: recording startup heartbeat");
|
||||
yield* launchStartupHeartbeat;
|
||||
@@ -470,6 +474,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return {
|
||||
awaitCommandReady: commandGate.awaitCommandReady,
|
||||
awaitReady: Deferred.await(runtimeReady),
|
||||
markHttpListening: Deferred.succeed(httpListening, undefined),
|
||||
enqueueCommand: commandGate.enqueueCommand,
|
||||
} satisfies ServerRuntimeStartup["Service"];
|
||||
|
||||
@@ -33,6 +33,7 @@ describe("serverRuntimeState", () => {
|
||||
host: "127.0.0.1",
|
||||
port: 4_971,
|
||||
origin: "http://127.0.0.1:4971",
|
||||
devUrl: "http://localhost:5733/",
|
||||
startedAt: "2026-06-20T00:00:00.000Z",
|
||||
};
|
||||
|
||||
@@ -43,6 +44,24 @@ describe("serverRuntimeState", () => {
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("records the dev web URL when the server fronts a dev server", () =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
|
||||
config: { host: undefined, devUrl: new URL("http://localhost:5733") },
|
||||
port: 13_773,
|
||||
});
|
||||
|
||||
assert.equal(state.devUrl, "http://localhost:5733/");
|
||||
assert.equal(state.origin, "http://127.0.0.1:13773");
|
||||
|
||||
const withoutDev = yield* ServerRuntimeState.makePersistedServerRuntimeState({
|
||||
config: { host: undefined, devUrl: undefined },
|
||||
port: 13_773,
|
||||
});
|
||||
assert.isFalse("devUrl" in withoutDev);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("treats a missing runtime state file as absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -14,6 +14,9 @@ export const PersistedServerRuntimeState = Schema.Struct({
|
||||
host: Schema.optional(Schema.String),
|
||||
port: Schema.Int,
|
||||
origin: Schema.String,
|
||||
// Present when the server fronts a dev web server (VITE_DEV_SERVER_URL).
|
||||
// Dev is single-origin: browsers must pair through this URL, not `origin`.
|
||||
devUrl: Schema.optional(Schema.String),
|
||||
startedAt: Schema.String,
|
||||
});
|
||||
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
|
||||
@@ -45,7 +48,7 @@ const runtimeOriginForConfig = (
|
||||
};
|
||||
|
||||
export const makePersistedServerRuntimeState = (input: {
|
||||
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host">;
|
||||
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
|
||||
readonly port: number;
|
||||
}): Effect.Effect<PersistedServerRuntimeState> =>
|
||||
Effect.map(DateTime.now, (now) => ({
|
||||
@@ -54,6 +57,7 @@ export const makePersistedServerRuntimeState = (input: {
|
||||
...(input.config.host ? { host: input.config.host } : {}),
|
||||
port: input.port,
|
||||
origin: runtimeOriginForConfig(input.config, input.port),
|
||||
...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
|
||||
startedAt: DateTime.formatIso(now),
|
||||
}));
|
||||
|
||||
|
||||
@@ -153,6 +153,51 @@ it.effect("uses stable diagnostics for every parsed non-repository command", ()
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("invalidates origin remote cache when a driver mutation adds origin", () =>
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
const before = yield* driver.statusDetailsLocal(cwd);
|
||||
assert.equal(before.hasOriginRemote, false);
|
||||
|
||||
yield* driver.ensureRemote({ cwd, preferredName: "origin", url: remote });
|
||||
|
||||
const after = yield* driver.statusDetailsLocal(cwd);
|
||||
assert.equal(after.hasOriginRemote, true);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("re-reads origin remote status after cache TTL expiry and bypassed invalidation", () =>
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
// First call caches hasOriginRemote = false (5-min TTL)
|
||||
assert.equal((yield* driver.statusDetailsLocal(cwd)).hasOriginRemote, false);
|
||||
|
||||
// Add origin via raw git (bypasses invalidation hook)
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
|
||||
// Cache still has the stale false (TTL not yet expired)
|
||||
const stillCached = yield* driver.statusDetailsLocal(cwd);
|
||||
assert.equal(stillCached.hasOriginRemote, false);
|
||||
|
||||
// Advance past the 5-minute TTL so the cache entry expires
|
||||
yield* TestClock.adjust("6 minutes");
|
||||
|
||||
// After expiry, the next call re-executes and picks up the remote
|
||||
const afterExpiry = yield* driver.statusDetailsLocal(cwd);
|
||||
assert.equal(afterExpiry.hasOriginRemote, true);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("coalesces concurrent ref pages into one repository snapshot", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -61,6 +61,8 @@ const LIST_REFS_SNAPSHOT_CACHE_CAPACITY = 64;
|
||||
const LIST_REFS_SNAPSHOT_CACHE_TTL = Duration.minutes(2);
|
||||
const LIST_REFS_REFRESH_COALESCE_TTL = Duration.seconds(5);
|
||||
const LIST_REFS_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);
|
||||
const STATUS_DEFAULT_BRANCH_CACHE_TTL = Duration.minutes(5);
|
||||
const STATUS_ORIGIN_EXISTS_CACHE_TTL = Duration.minutes(5);
|
||||
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
|
||||
GCM_INTERACTIVE: "never",
|
||||
GIT_ASKPASS: "",
|
||||
@@ -1119,6 +1121,63 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return Cache.get(refresh ? repositoryPathsRefreshCache : repositoryPathsCache, cacheKey);
|
||||
};
|
||||
|
||||
const defaultBranchCache = yield* Cache.makeWith(
|
||||
(gitCommonDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return yield* executeGit(
|
||||
"GitVcsDriver.statusDetails.defaultBranch",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{ allowNonZeroExit: true },
|
||||
).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) return null;
|
||||
return parseDefaultBranchFromRemoteHeadRef(result.stdout, "origin");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{
|
||||
capacity: 2_048,
|
||||
timeToLive: Exit.match({
|
||||
onSuccess: () => STATUS_DEFAULT_BRANCH_CACHE_TTL,
|
||||
onFailure: () => Duration.zero,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const originExistsCache = yield* Cache.makeWith(
|
||||
(gitCommonDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return yield* executeGit(
|
||||
"GitVcsDriver.statusDetails.originExists",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "remote", "get-url", "origin"],
|
||||
{ allowNonZeroExit: true },
|
||||
).pipe(Effect.map((result) => result.exitCode === 0));
|
||||
}),
|
||||
{
|
||||
capacity: 2_048,
|
||||
timeToLive: Exit.match({
|
||||
onSuccess: () => STATUS_ORIGIN_EXISTS_CACHE_TTL,
|
||||
onFailure: () => Duration.zero,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const invalidateStatusStaticCaches = (cwd: string) =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(
|
||||
Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
|
||||
);
|
||||
const cacheKey = repositoryPaths?.gitCommonDir ?? normalizeRepositoryPathsCacheKey(cwd);
|
||||
yield* Cache.invalidate(defaultBranchCache, cacheKey);
|
||||
yield* Cache.invalidate(originExistsCache, cacheKey);
|
||||
});
|
||||
|
||||
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
|
||||
const repositoryPaths = yield* resolveRepositoryPaths(cwd);
|
||||
if (repositoryPaths !== null) {
|
||||
@@ -1517,7 +1576,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
});
|
||||
}
|
||||
|
||||
const [numstatStdout, defaultRefResult, hasPrimaryRemote] = yield* Effect.all(
|
||||
const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(
|
||||
Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
|
||||
);
|
||||
const statusCacheKey = repositoryPaths?.gitCommonDir;
|
||||
const [numstatStdout, defaultBranch, hasPrimaryRemote] = yield* Effect.all(
|
||||
[
|
||||
executeGitWithStableDiagnostics(
|
||||
"GitVcsDriver.statusDetails.numstat",
|
||||
@@ -1574,21 +1637,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
);
|
||||
}),
|
||||
),
|
||||
executeGit(
|
||||
"GitVcsDriver.statusDetails.defaultRef",
|
||||
cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{ allowNonZeroExit: true },
|
||||
),
|
||||
originRemoteExists(cwd).pipe(Effect.orElseSucceed(() => false)),
|
||||
statusCacheKey
|
||||
? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null))
|
||||
: resolveDefaultBranchName(cwd, "origin").pipe(Effect.orElseSucceed(() => null)),
|
||||
statusCacheKey
|
||||
? Cache.get(originExistsCache, statusCacheKey).pipe(Effect.orElseSucceed(() => false))
|
||||
: originRemoteExists(cwd).pipe(Effect.orElseSucceed(() => false)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const statusStdout = statusResult.stdout;
|
||||
const defaultBranch =
|
||||
defaultRefResult.exitCode === 0
|
||||
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
let refName: string | null = null;
|
||||
let upstreamRef: string | null = null;
|
||||
@@ -2809,7 +2867,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
cwd: string,
|
||||
effect: Effect.Effect<A, E>,
|
||||
): Effect.Effect<A, E> =>
|
||||
effect.pipe(Effect.ensuring(invalidateListRefsSnapshot(cwd).pipe(Effect.ignore)));
|
||||
effect.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.all([
|
||||
invalidateListRefsSnapshot(cwd).pipe(Effect.ignore),
|
||||
invalidateStatusStaticCaches(cwd).pipe(Effect.ignore),
|
||||
]),
|
||||
),
|
||||
);
|
||||
const initRepoWithListRefsInvalidation: GitVcsDriver.GitVcsDriver["Service"]["initRepo"] = (
|
||||
input,
|
||||
) =>
|
||||
|
||||
+49
-30
@@ -298,6 +298,13 @@ const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).
|
||||
const SHELL_RESUME_MAX_GAP = 1_000;
|
||||
|
||||
// Same bound for thread resume. The replay reads the *global* event range and
|
||||
// filters per-thread afterwards, so a stale cursor far behind the head would
|
||||
// otherwise decode every intervening event's payload — reconnects with cursors
|
||||
// hundreds of thousands of events behind have OOM-killed servers on large
|
||||
// databases. Past this gap the client is reset with a fresh thread snapshot.
|
||||
const THREAD_RESUME_MAX_GAP = 1_000;
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
|
||||
revision: number,
|
||||
@@ -1281,38 +1288,50 @@ const makeWsRpcLayer = (
|
||||
// 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.
|
||||
// The replay is bounded to the projection head captured below. The
|
||||
// catch-up range is normally tiny (a fresh HTTP snapshot sequence),
|
||||
// but a stale cached cursor can sit hundreds of thousands of global
|
||||
// events behind — replaying that decodes every intervening event
|
||||
// (including every other thread's tool payloads) only to discard
|
||||
// almost all of them, which has OOM-killed servers on large
|
||||
// databases. A truncated replay would silently drop this thread's
|
||||
// events, so past the gap cap we reset the client with a fresh
|
||||
// thread snapshot instead, exactly like subscribeShell above.
|
||||
if (input.afterSequence !== undefined) {
|
||||
const afterSequence = input.afterSequence;
|
||||
const catchUpStream = orchestrationEngine
|
||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
||||
.pipe(
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event: projectActivityEvent(event),
|
||||
})),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: `Failed to replay thread ${input.threadId} events`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const afterCatchUp =
|
||||
input.requestCompletionMarker === true
|
||||
? Stream.concat(
|
||||
Stream.fromEffect(
|
||||
Queue.offer(liveBuffer, { kind: "synchronized" as const }),
|
||||
).pipe(Stream.drain),
|
||||
bufferedLiveStream,
|
||||
)
|
||||
: bufferedLiveStream;
|
||||
return Stream.concat(catchUpStream, afterCatchUp);
|
||||
const headSequence = yield* orchestrationEngine.latestSequence;
|
||||
const replayGap = headSequence - afterSequence;
|
||||
if (replayGap >= 0 && replayGap <= THREAD_RESUME_MAX_GAP) {
|
||||
const catchUpStream = orchestrationEngine
|
||||
.readEvents(afterSequence, replayGap)
|
||||
.pipe(
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event: projectActivityEvent(event),
|
||||
})),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: `Failed to replay thread ${input.threadId} events`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const afterCatchUp =
|
||||
input.requestCompletionMarker === true
|
||||
? Stream.concat(
|
||||
Stream.fromEffect(
|
||||
Queue.offer(liveBuffer, { kind: "synchronized" as const }),
|
||||
).pipe(Stream.drain),
|
||||
bufferedLiveStream,
|
||||
)
|
||||
: bufferedLiveStream;
|
||||
return Stream.concat(catchUpStream, afterCatchUp);
|
||||
}
|
||||
// Gap too large (or cursor ahead of authoritative state): fall
|
||||
// through to the snapshot path so the client converges from a
|
||||
// fresh thread detail instead of an unbounded replay.
|
||||
}
|
||||
|
||||
const snapshot = yield* projectionSnapshotQuery
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build:ghostty-wasm": "bash scripts/build-libghostty-wasm.sh",
|
||||
"dev": "vp dev",
|
||||
"build": "vp build",
|
||||
"preview": "vp preview",
|
||||
@@ -31,8 +32,6 @@
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"jose": "catalog:",
|
||||
|
||||
Executable
+123
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
WEB_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
REPO_DIR="$(cd "${WEB_DIR}/../.." && pwd)"
|
||||
CANONICAL_VENDOR_DIR="${REPO_DIR}/native/libghostty-vt"
|
||||
VENDOR_DIR="${WEB_DIR}/src/terminal/ghostty/vendor"
|
||||
|
||||
GHOSTTY_REVISION="$(tr -d '[:space:]' < "${CANONICAL_VENDOR_DIR}/VERSION")"
|
||||
GHOSTTY_SOURCE_DIR="${GHOSTTY_SOURCE_DIR:-${HOME}/.cache/t3code/ghostty-${GHOSTTY_REVISION:0:8}}"
|
||||
GHOSTTY_ZIG_VERSION="${GHOSTTY_ZIG_VERSION:-0.15.2}"
|
||||
GHOSTTY_ZIG="${GHOSTTY_ZIG:-}"
|
||||
|
||||
log() {
|
||||
printf '[libghostty-vt-wasm] %s\n' "$*"
|
||||
}
|
||||
|
||||
die() {
|
||||
printf '[libghostty-vt-wasm] error: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
require_cmd() {
|
||||
command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"
|
||||
}
|
||||
|
||||
ensure_zig() {
|
||||
if [[ -n "${GHOSTTY_ZIG}" ]]; then
|
||||
[[ -x "${GHOSTTY_ZIG}" ]] || die "GHOSTTY_ZIG is not executable: ${GHOSTTY_ZIG}"
|
||||
return
|
||||
fi
|
||||
if command -v zig >/dev/null 2>&1 && [[ "$(zig version)" == "${GHOSTTY_ZIG_VERSION}" ]]; then
|
||||
GHOSTTY_ZIG="$(command -v zig)"
|
||||
return
|
||||
fi
|
||||
|
||||
local host_os host_arch cache_dir
|
||||
host_os="$(uname -s | tr '[:upper:]' '[:lower:]')"
|
||||
host_arch="$(uname -m)"
|
||||
case "${host_os}" in
|
||||
darwin) host_os="macos" ;;
|
||||
linux) ;;
|
||||
*) die "unsupported host OS for Zig download: ${host_os}" ;;
|
||||
esac
|
||||
case "${host_arch}" in
|
||||
arm64) host_arch="aarch64" ;;
|
||||
aarch64 | x86_64) ;;
|
||||
*) die "unsupported host architecture: ${host_arch}" ;;
|
||||
esac
|
||||
|
||||
cache_dir="${HOME}/.cache/t3code/zig-${GHOSTTY_ZIG_VERSION}"
|
||||
GHOSTTY_ZIG="${cache_dir}/zig"
|
||||
if [[ -x "${GHOSTTY_ZIG}" ]]; then
|
||||
return
|
||||
fi
|
||||
|
||||
require_cmd curl
|
||||
require_cmd tar
|
||||
mkdir -p "${cache_dir}"
|
||||
log "downloading Zig ${GHOSTTY_ZIG_VERSION}"
|
||||
curl -fsSL \
|
||||
"https://ziglang.org/download/${GHOSTTY_ZIG_VERSION}/zig-${host_arch}-${host_os}-${GHOSTTY_ZIG_VERSION}.tar.xz" \
|
||||
| tar -xJ --strip-components=1 -C "${cache_dir}"
|
||||
}
|
||||
|
||||
ensure_ghostty_source() {
|
||||
require_cmd git
|
||||
if [[ ! -d "${GHOSTTY_SOURCE_DIR}/.git" ]]; then
|
||||
mkdir -p "$(dirname "${GHOSTTY_SOURCE_DIR}")"
|
||||
log "cloning Ghostty ${GHOSTTY_REVISION}"
|
||||
git clone --filter=blob:none --no-checkout https://github.com/ghostty-org/ghostty.git \
|
||||
"${GHOSTTY_SOURCE_DIR}"
|
||||
fi
|
||||
|
||||
# A cached checkout may still be on a previously pinned revision; converge on
|
||||
# the pinned one instead of failing the rebuild.
|
||||
local actual_revision
|
||||
actual_revision="$(git -C "${GHOSTTY_SOURCE_DIR}" rev-parse HEAD 2>/dev/null || echo none)"
|
||||
if [[ "${actual_revision}" != "${GHOSTTY_REVISION}" ]]; then
|
||||
log "checking out Ghostty ${GHOSTTY_REVISION}"
|
||||
git -C "${GHOSTTY_SOURCE_DIR}" fetch --depth=1 origin "${GHOSTTY_REVISION}"
|
||||
git -C "${GHOSTTY_SOURCE_DIR}" checkout --detach "${GHOSTTY_REVISION}"
|
||||
fi
|
||||
|
||||
actual_revision="$(git -C "${GHOSTTY_SOURCE_DIR}" rev-parse HEAD)"
|
||||
[[ "${actual_revision}" == "${GHOSTTY_REVISION}" ]] || \
|
||||
die "expected Ghostty ${GHOSTTY_REVISION}, found ${actual_revision}"
|
||||
}
|
||||
|
||||
ensure_zig
|
||||
ensure_ghostty_source
|
||||
|
||||
build_root="$(mktemp -d)"
|
||||
trap 'rm -rf "${build_root}"' EXIT
|
||||
|
||||
log "building ${GHOSTTY_REVISION} for wasm32-freestanding"
|
||||
(
|
||||
cd "${GHOSTTY_SOURCE_DIR}"
|
||||
# The pinned revision rides along as semver build metadata so the artifact
|
||||
# identifies its own provenance through ghostty_build_info(); mobile's
|
||||
# VERSION file stays the single source of truth for the pin.
|
||||
"${GHOSTTY_ZIG}" build \
|
||||
-Demit-lib-vt \
|
||||
-Dtarget=wasm32-freestanding \
|
||||
-Doptimize=ReleaseSmall \
|
||||
-Dstrip=true \
|
||||
-Dlib-version-string="0.1.0-dev+${GHOSTTY_REVISION}" \
|
||||
-p "${build_root}"
|
||||
)
|
||||
|
||||
mkdir -p "${VENDOR_DIR}"
|
||||
cp "${build_root}/bin/ghostty-vt.wasm" "${VENDOR_DIR}/ghostty-vt.wasm"
|
||||
"${GHOSTTY_ZIG}" build-exe \
|
||||
"${SCRIPT_DIR}/ghostty-write-pty.zig" \
|
||||
-target wasm32-freestanding \
|
||||
-O ReleaseSmall \
|
||||
-fno-entry \
|
||||
-rdynamic \
|
||||
-femit-bin="${VENDOR_DIR}/ghostty-write-pty.wasm"
|
||||
chmod 0644 "${VENDOR_DIR}/ghostty-write-pty.wasm"
|
||||
log "wrote ${VENDOR_DIR}/ghostty-vt.wasm"
|
||||
@@ -0,0 +1,5 @@
|
||||
extern "env" fn t3_write_pty(terminal: u32, userdata: u32, data: u32, len: u32) void;
|
||||
|
||||
export fn ghostty_write_pty(terminal: u32, userdata: u32, data: u32, len: u32) void {
|
||||
t3_write_pty(terminal, userdata, data, len);
|
||||
}
|
||||
@@ -704,6 +704,19 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
() => drawerTerminalSessions.map((session) => session.target.terminalId),
|
||||
[drawerTerminalSessions],
|
||||
);
|
||||
// Every client-side id source participates in allocation: the server list
|
||||
// lags fresh opens, and panel terminals are filtered out of the drawer's
|
||||
// sessions — an id collision attaches two viewports to one PTY session.
|
||||
const allocatableTerminalIds = useMemo(
|
||||
() => [
|
||||
...new Set([
|
||||
...serverOrderedTerminalIds,
|
||||
...terminalUiState.terminalIds,
|
||||
...panelTerminalIds,
|
||||
]),
|
||||
],
|
||||
[panelTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds],
|
||||
);
|
||||
const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight);
|
||||
const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal);
|
||||
const storeSplitTerminalVertical = useTerminalUiStateStore(
|
||||
@@ -773,7 +786,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(serverOrderedTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableTerminalIds);
|
||||
storeSplitTerminal(threadRef, terminalId);
|
||||
bumpFocusRequestId();
|
||||
void openTerminal({
|
||||
@@ -787,11 +800,11 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
},
|
||||
});
|
||||
}, [
|
||||
allocatableTerminalIds,
|
||||
bumpFocusRequestId,
|
||||
cwd,
|
||||
effectiveWorktreePath,
|
||||
runtimeEnv,
|
||||
serverOrderedTerminalIds,
|
||||
storeSplitTerminal,
|
||||
threadId,
|
||||
threadRef,
|
||||
@@ -801,7 +814,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(serverOrderedTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableTerminalIds);
|
||||
storeSplitTerminalVertical(threadRef, terminalId);
|
||||
bumpFocusRequestId();
|
||||
void openTerminal({
|
||||
@@ -815,12 +828,12 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
},
|
||||
});
|
||||
}, [
|
||||
allocatableTerminalIds,
|
||||
bumpFocusRequestId,
|
||||
cwd,
|
||||
effectiveWorktreePath,
|
||||
openTerminal,
|
||||
runtimeEnv,
|
||||
serverOrderedTerminalIds,
|
||||
storeSplitTerminalVertical,
|
||||
threadId,
|
||||
threadRef,
|
||||
@@ -830,7 +843,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(serverOrderedTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableTerminalIds);
|
||||
storeNewTerminal(threadRef, terminalId);
|
||||
bumpFocusRequestId();
|
||||
void openTerminal({
|
||||
@@ -847,8 +860,8 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
bumpFocusRequestId,
|
||||
cwd,
|
||||
effectiveWorktreePath,
|
||||
allocatableTerminalIds,
|
||||
runtimeEnv,
|
||||
serverOrderedTerminalIds,
|
||||
storeNewTerminal,
|
||||
threadId,
|
||||
threadRef,
|
||||
@@ -1521,6 +1534,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
),
|
||||
[rightPanelState.surfaces],
|
||||
);
|
||||
const allocatableActiveTerminalIds = useMemo(
|
||||
() => [...new Set([...activeKnownTerminalIds, ...panelTerminalIds])],
|
||||
[activeKnownTerminalIds, panelTerminalIds],
|
||||
);
|
||||
const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime();
|
||||
const rightPanelOpen = rightPanelState.isOpen;
|
||||
const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet;
|
||||
@@ -2628,7 +2645,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!cwdForOpen) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId([...activeKnownTerminalIds, ...panelTerminalIds]);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
storeEnsureTerminal(activeThreadRef, terminalId, { open: true });
|
||||
void openTerminal({
|
||||
environmentId,
|
||||
@@ -2647,15 +2664,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
setTerminalOpen(nextOpen);
|
||||
}, [
|
||||
activeKnownTerminalIds,
|
||||
activeProject,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
allocatableActiveTerminalIds,
|
||||
environmentId,
|
||||
gitCwd,
|
||||
openTerminal,
|
||||
panelTerminalIds,
|
||||
setTerminalOpen,
|
||||
storeEnsureTerminal,
|
||||
terminalUiState.terminalIds.length,
|
||||
@@ -2670,7 +2686,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!cwdForOpen) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(activeKnownTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
if (direction === "vertical") {
|
||||
storeSplitTerminalVertical(activeThreadRef, terminalId);
|
||||
} else {
|
||||
@@ -2693,8 +2709,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
[
|
||||
activeProject,
|
||||
activeKnownTerminalIds,
|
||||
activeThreadId,
|
||||
allocatableActiveTerminalIds,
|
||||
activeThreadRef,
|
||||
openTerminal,
|
||||
activeThreadWorktreePath,
|
||||
@@ -2713,7 +2729,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!cwdForOpen) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(activeKnownTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
storeNewTerminal(activeThreadRef, terminalId);
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
void openTerminal({
|
||||
@@ -2731,8 +2747,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
}, [
|
||||
activeProject,
|
||||
activeKnownTerminalIds,
|
||||
activeThreadId,
|
||||
allocatableActiveTerminalIds,
|
||||
activeThreadRef,
|
||||
openTerminal,
|
||||
activeThreadWorktreePath,
|
||||
@@ -2818,7 +2834,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
...(options?.env ? { extraEnv: options.env } : {}),
|
||||
});
|
||||
const targetTerminalId = shouldCreateNewTerminal
|
||||
? nextTerminalId(activeKnownTerminalIds)
|
||||
? nextTerminalId(allocatableActiveTerminalIds)
|
||||
: baseTerminalId;
|
||||
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
|
||||
? {
|
||||
@@ -2886,6 +2902,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
environmentId,
|
||||
openTerminal,
|
||||
activeKnownTerminalIds,
|
||||
allocatableActiveTerminalIds,
|
||||
runningTerminalIds,
|
||||
terminalUiState.activeTerminalId,
|
||||
writeTerminal,
|
||||
@@ -3144,7 +3161,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const addTerminalSurface = useCallback(() => {
|
||||
if (!activeThreadRef || !activeThreadId || !activeProject) return;
|
||||
const cwd = gitCwd ?? activeProject.workspaceRoot;
|
||||
const terminalId = nextTerminalId([...activeKnownTerminalIds, ...panelTerminalIds]);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId);
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
void openTerminal({
|
||||
@@ -3161,14 +3178,13 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
});
|
||||
}, [
|
||||
activeKnownTerminalIds,
|
||||
activeProject,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
allocatableActiveTerminalIds,
|
||||
gitCwd,
|
||||
openTerminal,
|
||||
panelTerminalIds,
|
||||
]);
|
||||
const splitPanelTerminal = useCallback(
|
||||
(direction: "horizontal" | "vertical" = "horizontal") => {
|
||||
@@ -3181,7 +3197,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId([...activeKnownTerminalIds, ...panelTerminalIds]);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
const cwd = gitCwd ?? activeProject.workspaceRoot;
|
||||
useRightPanelStore
|
||||
.getState()
|
||||
@@ -3202,15 +3218,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
},
|
||||
[
|
||||
activeKnownTerminalIds,
|
||||
activeProject,
|
||||
activeRightPanelSurface,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
allocatableActiveTerminalIds,
|
||||
gitCwd,
|
||||
openTerminal,
|
||||
panelTerminalIds,
|
||||
],
|
||||
);
|
||||
const splitPanelTerminalVertical = useCallback(() => {
|
||||
@@ -5829,7 +5844,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
aria-label="Scroll to end"
|
||||
title="Scroll to end"
|
||||
onClick={() => scrollToEnd(true)}
|
||||
className="pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:border-border hover:text-foreground hover:cursor-pointer"
|
||||
className="chat-composer-glass pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:border-border hover:text-foreground hover:cursor-pointer"
|
||||
>
|
||||
<ChevronDownIcon className="size-3.5" />
|
||||
Scroll to end
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ProjectScript, ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import ProjectScriptsControl from "./ProjectScriptsControl";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const PRIMARY_SCRIPT: ProjectScript = {
|
||||
id: "dev",
|
||||
name: "Dev",
|
||||
command: "vp dev",
|
||||
icon: "play",
|
||||
runOnWorktreeCreate: false,
|
||||
};
|
||||
|
||||
function renderControl(scripts: ReadonlyArray<ProjectScript>) {
|
||||
return renderToStaticMarkup(
|
||||
<ProjectScriptsControl
|
||||
scripts={scripts}
|
||||
keybindings={EMPTY_KEYBINDINGS}
|
||||
onRunScript={() => {}}
|
||||
onAddScript={async () => undefined as never}
|
||||
onUpdateScript={async () => undefined as never}
|
||||
onDeleteScript={async () => undefined as never}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
function buttonTag(html: string, ariaLabel: string) {
|
||||
return html.match(new RegExp(`<button[^>]*aria-label="${ariaLabel}"[^>]*>`))?.[0];
|
||||
}
|
||||
|
||||
function expectResponsiveXsControl(markup: string | undefined) {
|
||||
expect(markup).toBeDefined();
|
||||
expect(markup).toContain("h-7");
|
||||
expect(markup).toContain("gap-1");
|
||||
expect(markup).toContain("text-sm");
|
||||
expect(markup).toContain("sm:h-6");
|
||||
expect(markup).toContain("sm:text-xs");
|
||||
expect(markup).toContain("w-7");
|
||||
expect(markup).toContain("px-0");
|
||||
expect(markup).toContain("sm:w-6");
|
||||
expect(markup).toContain("@3xl/header-actions:w-auto!");
|
||||
expect(markup).toContain("@3xl/header-actions:px-[calc(--spacing(2)-1px)]");
|
||||
}
|
||||
|
||||
describe("ProjectScriptsControl compact controls", () => {
|
||||
it("keeps the primary Run control compact and expands it with its label", () => {
|
||||
const html = renderControl([PRIMARY_SCRIPT]);
|
||||
|
||||
expectResponsiveXsControl(buttonTag(html, "Run Dev"));
|
||||
expect(html).toContain(
|
||||
'class="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5"',
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the standalone Add control compact and expands it with its label", () => {
|
||||
const html = renderControl([]);
|
||||
|
||||
expectResponsiveXsControl(buttonTag(html, "Add action"));
|
||||
expect(html).toContain(
|
||||
'class="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5"',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -341,6 +341,7 @@ export default function ProjectScriptsControl({
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
|
||||
aria-label={`Run ${primaryScript.name}`}
|
||||
onClick={() => onRunScript(primaryScript)}
|
||||
/>
|
||||
@@ -441,7 +442,13 @@ export default function ProjectScriptsControl({
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button size="xs" variant="outline" aria-label="Add action" onClick={openAddDialog} />
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
|
||||
aria-label="Add action"
|
||||
onClick={openAddDialog}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
resolveSidebarV2Status,
|
||||
resolveThreadStatusPill,
|
||||
resolveWorkingStartedAt,
|
||||
searchSidebarThreadsByTitle,
|
||||
formatWorkingDurationLabel,
|
||||
shouldNavigateAfterProjectRemoval,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
@@ -691,6 +692,26 @@ describe("resolveSidebarV2Status", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("searchSidebarThreadsByTitle", () => {
|
||||
const threads = [
|
||||
{ id: "thread-1", title: "Fix workspace search", project: "Alpha" },
|
||||
{ id: "thread-2", title: "Review providers", project: "Workspace" },
|
||||
{ id: "thread-3", title: "WORKTREE cleanup", project: "Beta" },
|
||||
];
|
||||
|
||||
it("matches thread titles case-insensitively and preserves their order", () => {
|
||||
expect(searchSidebarThreadsByTitle(threads, "work")).toEqual([threads[0], threads[2]]);
|
||||
});
|
||||
|
||||
it("does not match project metadata", () => {
|
||||
expect(searchSidebarThreadsByTitle(threads, "workspace")).toEqual([threads[0]]);
|
||||
});
|
||||
|
||||
it("returns no results for an empty query", () => {
|
||||
expect(searchSidebarThreadsByTitle(threads, " ")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForSidebarV2", () => {
|
||||
const sortable = (input: { id: string; createdAt: string }) => ({
|
||||
id: input.id,
|
||||
|
||||
@@ -490,6 +490,20 @@ export function sortThreadsForSidebarV2<
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the already-ordered sidebar thread collection by title only.
|
||||
* Keeping the input order means lifecycle ordering (active, snoozed, settled)
|
||||
* remains stable while the user narrows the list.
|
||||
*/
|
||||
export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
|
||||
threads: readonly T[],
|
||||
query: string,
|
||||
): T[] {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
if (normalizedQuery.length === 0) return [];
|
||||
return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
|
||||
}
|
||||
|
||||
type SettledTimestampInput = Pick<
|
||||
SidebarThreadSummary,
|
||||
"settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
|
||||
import { resolveSnoozePresets, snoozeWakeDescription } from "./Sidebar.snooze";
|
||||
|
||||
// Local-time constructor so preset math is timezone-stable in tests.
|
||||
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
|
||||
@@ -64,21 +64,6 @@ describe("resolveSnoozePresets", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeLabel", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("formats minutes, hours, and days, rounding up", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
|
||||
});
|
||||
|
||||
it("reports now for past and malformed wake times", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
|
||||
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeDescription", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
|
||||
@@ -1,111 +1,13 @@
|
||||
/**
|
||||
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
|
||||
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
|
||||
* without a DOM.
|
||||
*
|
||||
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
|
||||
* run, a teammate review, the next work session), not days.
|
||||
*/
|
||||
import { snoozeWakeLabel } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { parseTimestampDate } from "../timestampFormat";
|
||||
|
||||
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
|
||||
export {
|
||||
resolveSnoozePresets,
|
||||
type SnoozePreset,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
export { snoozeWakeLabel };
|
||||
|
||||
export interface SnoozePreset {
|
||||
readonly id: SnoozePresetId;
|
||||
readonly label: string;
|
||||
/** Menu-row time column. Complements the label instead of repeating it:
|
||||
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
|
||||
readonly whenLabel: string;
|
||||
/** ISO wake time. */
|
||||
readonly snoozedUntil: string;
|
||||
}
|
||||
|
||||
function timeOfDayLabel(date: Date): string {
|
||||
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
|
||||
const EVENING_HOUR = 18;
|
||||
const MORNING_HOUR = 9;
|
||||
const HOUR_MS = 60 * 60 * 1_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
function atHour(base: Date, hour: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setHours(hour, 0, 0, 0);
|
||||
return next;
|
||||
}
|
||||
|
||||
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
|
||||
// land on the wrong local day across DST transitions (a spring-forward day
|
||||
// is 23 hours, so 23:30 + 24h skips the whole next day).
|
||||
function addDays(base: Date, days: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presets for "snooze until", computed against local time. "This evening"
|
||||
* only appears while it is still meaningfully before evening; after that
|
||||
* the list starts at "Tomorrow".
|
||||
*/
|
||||
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
|
||||
const inAnHour = new Date(now.getTime() + HOUR_MS);
|
||||
const presets: SnoozePreset[] = [
|
||||
{
|
||||
id: "hour",
|
||||
label: "In 1 hour",
|
||||
whenLabel: timeOfDayLabel(inAnHour),
|
||||
snoozedUntil: inAnHour.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const evening = atHour(now, EVENING_HOUR);
|
||||
// Suppress the evening preset once it is within an hour (or past): it
|
||||
// would duplicate "In 1 hour" or point at the past.
|
||||
if (evening.getTime() - now.getTime() > HOUR_MS) {
|
||||
presets.push({
|
||||
id: "evening",
|
||||
label: "This evening",
|
||||
whenLabel: timeOfDayLabel(evening),
|
||||
snoozedUntil: evening.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "tomorrow",
|
||||
label: "Tomorrow",
|
||||
whenLabel: timeOfDayLabel(tomorrow),
|
||||
snoozedUntil: tomorrow.toISOString(),
|
||||
});
|
||||
|
||||
// Next Monday 9:00 (a week out when today is Monday).
|
||||
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
|
||||
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "next-week",
|
||||
label: "Next week",
|
||||
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
|
||||
snoozedUntil: nextWeek.toISOString(),
|
||||
});
|
||||
|
||||
return presets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
|
||||
* round up so a snooze never reads "0m" while still hidden.
|
||||
*/
|
||||
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "now";
|
||||
const remainingMs = wake.getTime() - now.getTime();
|
||||
if (remainingMs <= 0) return "now";
|
||||
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
|
||||
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
|
||||
return `${Math.ceil(remainingMs / DAY_MS)}d`;
|
||||
}
|
||||
const DAY_MS = 24 * 60 * 60 * 1_000;
|
||||
|
||||
/**
|
||||
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
|
||||
|
||||
@@ -133,6 +133,7 @@ import {
|
||||
shouldShowArm64IntelBuildWarning,
|
||||
shouldToastDesktopUpdateActionResult,
|
||||
} from "./desktopUpdate.logic";
|
||||
import { showDesktopUpdateDownloadedToast } from "./desktopUpdate.toast";
|
||||
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
@@ -164,7 +165,6 @@ import {
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarSeparator,
|
||||
useSidebar,
|
||||
} from "./ui/sidebar";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
@@ -3509,11 +3509,7 @@ export default function Sidebar() {
|
||||
.downloadUpdate()
|
||||
.then((result) => {
|
||||
if (result.completed) {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Update downloaded",
|
||||
description: "Restart the app from the update button to install it.",
|
||||
});
|
||||
showDesktopUpdateDownloadedToast(bridge, result.state);
|
||||
}
|
||||
if (!shouldToastDesktopUpdateActionResult(result)) return;
|
||||
const actionError = getDesktopUpdateActionError(result);
|
||||
@@ -3634,8 +3630,6 @@ export default function Sidebar() {
|
||||
attachProjectListAutoAnimateRef={attachProjectListAutoAnimateRef}
|
||||
projectsLength={projects.length}
|
||||
/>
|
||||
|
||||
<SidebarSeparator />
|
||||
<SidebarChromeFooter />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
TerminalIcon,
|
||||
Trash2Icon,
|
||||
Undo2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
memo,
|
||||
@@ -115,6 +116,7 @@ import {
|
||||
resolveAdjacentThreadId,
|
||||
resolveSettledTimestamp,
|
||||
resolveSidebarV2Status,
|
||||
searchSidebarThreadsByTitle,
|
||||
resolveWorkingStartedAt,
|
||||
shouldNavigateAfterProjectRemoval,
|
||||
sortLogicalProjectsForSidebar,
|
||||
@@ -142,7 +144,6 @@ import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../pr
|
||||
import { primaryServerProvidersAtom } from "../state/server";
|
||||
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -154,7 +155,6 @@ import {
|
||||
DialogTitle,
|
||||
} from "./ui/dialog";
|
||||
import { Input } from "./ui/input";
|
||||
import { Kbd } from "./ui/kbd";
|
||||
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
|
||||
import { SidebarContent, SidebarGroup, SidebarMenuButton, useSidebar } from "./ui/sidebar";
|
||||
@@ -261,9 +261,9 @@ function SidebarV2ThreadTooltip({
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
variant="glass"
|
||||
className="max-w-80 text-left whitespace-normal"
|
||||
className="max-w-80 text-left whitespace-normal [&_[data-slot=tooltip-viewport]]:p-0"
|
||||
>
|
||||
<div className="flex min-w-0 max-w-80 flex-col gap-2 px-0.5 py-1.5">
|
||||
<div className="flex min-w-0 max-w-80 flex-col gap-2 p-[var(--floating-content-inset)]">
|
||||
<div className="min-w-0 truncate text-xs leading-none font-medium text-foreground">
|
||||
{thread.title}
|
||||
</div>
|
||||
@@ -918,7 +918,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className="relative z-10 h-[4.875rem] px-2.5 py-2">
|
||||
<div className="relative z-10 h-[4.875rem] px-[var(--sidebar-row-content-inset)] py-[var(--sidebar-content-inset)]">
|
||||
<div className="flex h-5 min-w-0 items-center gap-1.5">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
@@ -1068,6 +1068,106 @@ function latestTurnDiff(
|
||||
return null;
|
||||
}
|
||||
|
||||
const SidebarV2SearchResultRow = memo(function SidebarV2SearchResultRow(props: {
|
||||
thread: SidebarThreadSummary;
|
||||
projectCwd: string | null;
|
||||
projectTitle: string | null;
|
||||
environmentLabel: string | null;
|
||||
providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
|
||||
isHighlighted: boolean;
|
||||
isRouteActive: boolean;
|
||||
resultId: string;
|
||||
onHighlight: () => void;
|
||||
onSelect: () => void;
|
||||
}) {
|
||||
const { thread } = props;
|
||||
// Same details tooltip as the regular rows: a search hit is still a thread,
|
||||
// and the hover card is how you disambiguate identically-titled results.
|
||||
const gitCwd = thread.worktreePath ?? props.projectCwd;
|
||||
const gitStatus = useEnvironmentQuery(
|
||||
(thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
|
||||
? vcsEnvironment.status({
|
||||
environmentId: thread.environmentId,
|
||||
input: { cwd: gitCwd },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const branchMismatch = resolveLocalCheckoutBranchMismatch({
|
||||
effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree",
|
||||
activeWorktreePath: thread.worktreePath,
|
||||
activeThreadBranch: thread.branch,
|
||||
currentGitBranch: gitStatus.data?.refName ?? null,
|
||||
});
|
||||
const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;
|
||||
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
|
||||
const driverKind = providerEntry?.driverKind ?? null;
|
||||
const selectedModel = providerEntry?.models.find(
|
||||
(model) => model.slug === thread.modelSelection.model,
|
||||
);
|
||||
const modelLabel = selectedModel
|
||||
? getTriggerDisplayModelLabel(selectedModel)
|
||||
: thread.modelSelection.model;
|
||||
const runningTerminalIds = useThreadRunningTerminalIds({
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
});
|
||||
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
|
||||
return (
|
||||
<li role="presentation" className="list-none">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
id={props.resultId}
|
||||
type="button"
|
||||
role="option"
|
||||
// aria-activedescendant options: focus stays on the search input,
|
||||
// which owns all keyboard interaction for the listbox.
|
||||
tabIndex={-1}
|
||||
aria-selected={props.isHighlighted}
|
||||
aria-current={props.isRouteActive ? "page" : undefined}
|
||||
aria-label={
|
||||
props.projectTitle ? `${thread.title}, ${props.projectTitle}` : thread.title
|
||||
}
|
||||
onMouseMove={props.onHighlight}
|
||||
onClick={props.onSelect}
|
||||
className={cn(
|
||||
"flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm outline-none",
|
||||
props.isHighlighted || props.isRouteActive
|
||||
? "bg-sidebar-row-active text-sidebar-foreground"
|
||||
: "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
cwd={props.projectCwd ?? ""}
|
||||
className="size-4 shrink-0"
|
||||
fallbackIcon={MessageSquareIcon}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate">{thread.title}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground/55 tabular-nums">
|
||||
{threadTimeLabel(thread)}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<SidebarV2ThreadTooltip
|
||||
thread={thread}
|
||||
projectTitle={props.projectTitle}
|
||||
projectCwd={props.projectCwd}
|
||||
environmentLabel={props.environmentLabel}
|
||||
driverKind={driverKind}
|
||||
modelInstanceId={modelInstanceId}
|
||||
modelLabel={modelLabel}
|
||||
branchMismatch={branchMismatch}
|
||||
terminalStatus={terminalStatus}
|
||||
terminalProcessCount={runningTerminalIds.length}
|
||||
/>
|
||||
</Tooltip>
|
||||
</li>
|
||||
);
|
||||
});
|
||||
|
||||
export default function SidebarV2() {
|
||||
const projects = useProjects();
|
||||
const projectOrder = useUiStateStore((store) => store.projectOrder);
|
||||
@@ -1520,6 +1620,33 @@ export default function SidebarV2() {
|
||||
threads,
|
||||
]);
|
||||
|
||||
const threadSearchInputRef = useRef<HTMLInputElement>(null);
|
||||
const [threadSearchQuery, setThreadSearchQuery] = useState("");
|
||||
const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0);
|
||||
const isSearchingThreads = threadSearchQuery.trim().length > 0;
|
||||
const searchableThreads = useMemo(
|
||||
() => [...activeThreads, ...snoozedThreads, ...settledThreads],
|
||||
[activeThreads, settledThreads, snoozedThreads],
|
||||
);
|
||||
const threadSearchResults = useMemo(
|
||||
() => searchSidebarThreadsByTitle(searchableThreads, threadSearchQuery),
|
||||
[searchableThreads, threadSearchQuery],
|
||||
);
|
||||
const threadSearchResultOrderKey = threadSearchResults
|
||||
.map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)))
|
||||
.join("\0");
|
||||
|
||||
useEffect(() => {
|
||||
setActiveSearchResultIndex(0);
|
||||
}, [threadSearchResultOrderKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSearchingThreads) return;
|
||||
document
|
||||
.getElementById(`sidebar-thread-search-result-${activeSearchResultIndex}`)
|
||||
?.scrollIntoView({ block: "nearest" });
|
||||
}, [activeSearchResultIndex, isSearchingThreads, threadSearchResultOrderKey]);
|
||||
|
||||
// Arm a timeout for the earliest upcoming wake so the shelf empties the
|
||||
// moment a snooze expires instead of on the next minute tick. Sorted
|
||||
// soonest-first, so entry 0 is the boundary.
|
||||
@@ -1693,6 +1820,56 @@ export default function SidebarV2() {
|
||||
[clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor],
|
||||
);
|
||||
|
||||
const clearThreadSearch = useCallback(() => {
|
||||
setThreadSearchQuery("");
|
||||
setActiveSearchResultIndex(0);
|
||||
}, []);
|
||||
const selectThreadSearchResult = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
clearThreadSearch();
|
||||
navigateToThread(scopeThreadRef(thread.environmentId, thread.id));
|
||||
},
|
||||
[clearThreadSearch, navigateToThread],
|
||||
);
|
||||
const handleThreadSearchKeyDown = useCallback(
|
||||
(event: ReactKeyboardEvent<HTMLInputElement>) => {
|
||||
// IME composition (Japanese/Chinese input) uses the same keys; committing
|
||||
// a candidate must not move the highlight or navigate away mid-compose.
|
||||
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
|
||||
if (event.key === "Escape" && isSearchingThreads) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
clearThreadSearch();
|
||||
return;
|
||||
}
|
||||
if (threadSearchResults.length === 0) return;
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length);
|
||||
return;
|
||||
}
|
||||
if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
setActiveSearchResultIndex(
|
||||
(index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
const result = threadSearchResults[activeSearchResultIndex];
|
||||
if (result) selectThreadSearchResult(result);
|
||||
}
|
||||
},
|
||||
[
|
||||
activeSearchResultIndex,
|
||||
clearThreadSearch,
|
||||
isSearchingThreads,
|
||||
selectThreadSearchResult,
|
||||
threadSearchResults,
|
||||
],
|
||||
);
|
||||
|
||||
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
|
||||
const [renamingTitle, setRenamingTitle] = useState("");
|
||||
const startThreadRename = useCallback((threadRef: ScopedThreadRef, title: string) => {
|
||||
@@ -2398,7 +2575,6 @@ export default function SidebarV2() {
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
}, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]);
|
||||
|
||||
const commandPaletteShortcutLabel = shortcutLabelForCommand(keybindings, "commandPalette.toggle");
|
||||
// Same resolution as v1: prefer the local-thread binding, fall back to
|
||||
// chat.new, no platform gating — web users have working shortcuts too.
|
||||
const newThreadShortcutLabel =
|
||||
@@ -2410,27 +2586,53 @@ export default function SidebarV2() {
|
||||
<SidebarContent
|
||||
className="gap-0"
|
||||
fixedHeader={
|
||||
<SidebarGroup className="gap-1 p-2">
|
||||
<SidebarGroup className="gap-1 p-[var(--sidebar-content-inset)]">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
type="button"
|
||||
aria-label="Search threads and commands"
|
||||
className="focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
<div className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground">
|
||||
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<Input
|
||||
ref={threadSearchInputRef}
|
||||
nativeInput
|
||||
unstyled
|
||||
type="search"
|
||||
value={threadSearchQuery}
|
||||
onChange={(event) => {
|
||||
setThreadSearchQuery(event.currentTarget.value);
|
||||
setActiveSearchResultIndex(0);
|
||||
}}
|
||||
onKeyDown={handleThreadSearchKeyDown}
|
||||
placeholder="Search"
|
||||
aria-label="Search threads"
|
||||
role="combobox"
|
||||
aria-autocomplete="list"
|
||||
aria-expanded={isSearchingThreads && threadSearchResults.length > 0}
|
||||
aria-controls={
|
||||
isSearchingThreads && threadSearchResults.length > 0
|
||||
? "sidebar-thread-search-results"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<SearchIcon />
|
||||
<div className="flex-1 truncate text-left">Search</div>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="mr-px h-4 min-w-0 rounded-sm bg-sidebar-control-surface px-1.5 text-[10px] text-sidebar-muted-foreground ring-1 ring-sidebar-border">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
aria-activedescendant={
|
||||
isSearchingThreads && threadSearchResults[activeSearchResultIndex]
|
||||
? `sidebar-thread-search-result-${activeSearchResultIndex}`
|
||||
: undefined
|
||||
}
|
||||
className="min-w-0 flex-1 [&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:placeholder:text-sidebar-muted-foreground"
|
||||
/>
|
||||
{isSearchingThreads ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 shrink-0 rounded-sm text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
|
||||
aria-label="Clear thread search"
|
||||
onClick={() => {
|
||||
clearThreadSearch();
|
||||
threadSearchInputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<Tooltip>
|
||||
@@ -2558,178 +2760,246 @@ export default function SidebarV2() {
|
||||
</SidebarGroup>
|
||||
}
|
||||
>
|
||||
<SidebarGroup className="px-2 pb-1 pt-0">
|
||||
<TooltipProvider
|
||||
key="sidebar-thread-tooltips-150"
|
||||
delay={150}
|
||||
closeDelay={0}
|
||||
timeout={400}
|
||||
>
|
||||
<ul ref={attachListAutoAnimateRef} role="list" className="flex flex-col gap-px">
|
||||
{(() => {
|
||||
const renderThreadRow = (
|
||||
thread: EnvironmentThreadShell,
|
||||
section: "active" | "snoozed" | "settled",
|
||||
) => {
|
||||
const threadKey = scopedThreadKey(
|
||||
scopeThreadRef(thread.environmentId, thread.id),
|
||||
<SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-0">
|
||||
{isSearchingThreads ? (
|
||||
threadSearchResults.length > 0 ? (
|
||||
<TooltipProvider
|
||||
key="sidebar-thread-search-tooltips-150"
|
||||
delay={150}
|
||||
closeDelay={0}
|
||||
timeout={400}
|
||||
>
|
||||
<ul
|
||||
id="sidebar-thread-search-results"
|
||||
role="listbox"
|
||||
aria-label="Thread search results"
|
||||
className="flex flex-col gap-px"
|
||||
>
|
||||
{threadSearchResults.map((thread, index) => {
|
||||
const threadKey = scopedThreadKey(
|
||||
scopeThreadRef(thread.environmentId, thread.id),
|
||||
);
|
||||
return (
|
||||
<SidebarV2SearchResultRow
|
||||
key={threadKey}
|
||||
thread={thread}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
|
||||
}
|
||||
projectTitle={
|
||||
projectDisplayNameByKey.get(
|
||||
`${thread.environmentId}:${thread.projectId}`,
|
||||
) ?? null
|
||||
}
|
||||
environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
|
||||
providerEntryByInstanceId={providerEntryByInstanceId}
|
||||
isHighlighted={activeSearchResultIndex === index}
|
||||
isRouteActive={routeThreadKey === threadKey}
|
||||
resultId={`sidebar-thread-search-result-${index}`}
|
||||
onHighlight={() => setActiveSearchResultIndex(index)}
|
||||
onSelect={() => selectThreadSearchResult(thread)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</TooltipProvider>
|
||||
) : (
|
||||
<p
|
||||
role="status"
|
||||
className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
|
||||
>
|
||||
No threads found
|
||||
</p>
|
||||
)
|
||||
) : null}
|
||||
{!isSearchingThreads ? (
|
||||
<TooltipProvider
|
||||
key="sidebar-thread-tooltips-150"
|
||||
delay={150}
|
||||
closeDelay={0}
|
||||
timeout={400}
|
||||
>
|
||||
<ul ref={attachListAutoAnimateRef} role="list" className="flex flex-col gap-px">
|
||||
{(() => {
|
||||
const renderThreadRow = (
|
||||
thread: EnvironmentThreadShell,
|
||||
section: "active" | "snoozed" | "settled",
|
||||
) => {
|
||||
const threadKey = scopedThreadKey(
|
||||
scopeThreadRef(thread.environmentId, thread.id),
|
||||
);
|
||||
// Settled and snoozed are the ONLY things that collapse a
|
||||
// row: every other thread is a full card. Density comes
|
||||
// from users (or the auto rules) actually parking work,
|
||||
// not from the sidebar second-guessing what still matters.
|
||||
const isCard = section === "active";
|
||||
const rowVariant = isCard ? "card" : "slim";
|
||||
return (
|
||||
<SidebarV2Row
|
||||
// Keyed per variant on purpose: when a thread settles,
|
||||
// the card fades out in place and the slim row fades
|
||||
// in at its settled position instead of one element
|
||||
// FLIP-sliding through every row in between (rows here
|
||||
// are translucent, so a crossing row reads as text
|
||||
// painted over text).
|
||||
key={`${threadKey}:${rowVariant}`}
|
||||
thread={thread}
|
||||
variant={rowVariant}
|
||||
// Snoozed rows wake; settled rows un-settle (explicit
|
||||
// settles clear the override, auto-settled rows get
|
||||
// pinned active); cards settle.
|
||||
variantAction={
|
||||
section === "snoozed"
|
||||
? "unsnooze"
|
||||
: section === "settled"
|
||||
? "unsettle"
|
||||
: "settle"
|
||||
}
|
||||
settlementSupported={
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadSettlement === true
|
||||
}
|
||||
snoozeSupported={
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
}
|
||||
snoozeWakeLabelText={
|
||||
section === "snoozed" && thread.snoozedUntil != null
|
||||
? snoozeWakeLabel(thread.snoozedUntil, {
|
||||
now: new Date().toISOString(),
|
||||
})
|
||||
: null
|
||||
}
|
||||
// All sections: a woken thread can classify straight
|
||||
// into the settled tail (PR merged while snoozed), and
|
||||
// the wake signal must survive the trip. Still-snoozed
|
||||
// rows resolve to null on their own.
|
||||
wokeAt={threadWokeAt(thread, { now: snoozeNow })}
|
||||
isActive={routeThreadKey === threadKey}
|
||||
jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null}
|
||||
currentEnvironmentId={primaryEnvironmentId}
|
||||
environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
|
||||
}
|
||||
projectTitle={
|
||||
projectDisplayNameByKey.get(
|
||||
`${thread.environmentId}:${thread.projectId}`,
|
||||
) ?? null
|
||||
}
|
||||
providerEntryByInstanceId={providerEntryByInstanceId}
|
||||
onThreadClick={handleThreadClick}
|
||||
onThreadActivate={navigateToThread}
|
||||
onStartRename={startThreadRename}
|
||||
onRenameTitleChange={setRenamingTitle}
|
||||
onCommitRename={commitThreadRename}
|
||||
onCancelRename={cancelThreadRename}
|
||||
isRenaming={renamingThreadKey === threadKey}
|
||||
renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""}
|
||||
onContextMenu={handleThreadContextMenu}
|
||||
onSettle={attemptSettle}
|
||||
onUnsettle={attemptUnsettle}
|
||||
onSnooze={attemptSnooze}
|
||||
onUnsnooze={attemptUnsnooze}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
/>
|
||||
);
|
||||
};
|
||||
const items: ReactNode[] = activeThreads.map((thread) =>
|
||||
renderThreadRow(thread, "active"),
|
||||
);
|
||||
// Settled and snoozed are the ONLY things that collapse a
|
||||
// row: every other thread is a full card. Density comes
|
||||
// from users (or the auto rules) actually parking work,
|
||||
// not from the sidebar second-guessing what still matters.
|
||||
const isCard = section === "active";
|
||||
const rowVariant = isCard ? "card" : "slim";
|
||||
return (
|
||||
<SidebarV2Row
|
||||
// Keyed per variant on purpose: when a thread settles,
|
||||
// the card fades out in place and the slim row fades
|
||||
// in at its settled position instead of one element
|
||||
// FLIP-sliding through every row in between (rows here
|
||||
// are translucent, so a crossing row reads as text
|
||||
// painted over text).
|
||||
key={`${threadKey}:${rowVariant}`}
|
||||
thread={thread}
|
||||
variant={rowVariant}
|
||||
// Snoozed rows wake; settled rows un-settle (explicit
|
||||
// settles clear the override, auto-settled rows get
|
||||
// pinned active); cards settle.
|
||||
variantAction={
|
||||
section === "snoozed"
|
||||
? "unsnooze"
|
||||
: section === "settled"
|
||||
? "unsettle"
|
||||
: "settle"
|
||||
}
|
||||
settlementSupported={
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadSettlement === true
|
||||
}
|
||||
snoozeSupported={
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
}
|
||||
snoozeWakeLabelText={
|
||||
section === "snoozed" && thread.snoozedUntil != null
|
||||
? snoozeWakeLabel(thread.snoozedUntil, new Date())
|
||||
: null
|
||||
}
|
||||
// All sections: a woken thread can classify straight
|
||||
// into the settled tail (PR merged while snoozed), and
|
||||
// the wake signal must survive the trip. Still-snoozed
|
||||
// rows resolve to null on their own.
|
||||
wokeAt={threadWokeAt(thread, { now: snoozeNow })}
|
||||
isActive={routeThreadKey === threadKey}
|
||||
jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null}
|
||||
currentEnvironmentId={primaryEnvironmentId}
|
||||
environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
|
||||
}
|
||||
projectTitle={
|
||||
projectDisplayNameByKey.get(
|
||||
`${thread.environmentId}:${thread.projectId}`,
|
||||
) ?? null
|
||||
}
|
||||
providerEntryByInstanceId={providerEntryByInstanceId}
|
||||
onThreadClick={handleThreadClick}
|
||||
onThreadActivate={navigateToThread}
|
||||
onStartRename={startThreadRename}
|
||||
onRenameTitleChange={setRenamingTitle}
|
||||
onCommitRename={commitThreadRename}
|
||||
onCancelRename={cancelThreadRename}
|
||||
isRenaming={renamingThreadKey === threadKey}
|
||||
renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""}
|
||||
onContextMenu={handleThreadContextMenu}
|
||||
onSettle={attemptSettle}
|
||||
onUnsettle={attemptUnsettle}
|
||||
onSnooze={attemptSnooze}
|
||||
onUnsnooze={attemptUnsnooze}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
/>
|
||||
);
|
||||
};
|
||||
const items: ReactNode[] = activeThreads.map((thread) =>
|
||||
renderThreadRow(thread, "active"),
|
||||
);
|
||||
// Snoozed shelf: between the inbox and Settled — out of the
|
||||
// way, never gone. The header always renders while anything
|
||||
// is snoozed (the count is the whole footprint when
|
||||
// collapsed); rows only when expanded. Vanishes entirely at
|
||||
// count 0.
|
||||
if (snoozedThreads.length > 0) {
|
||||
items.push(
|
||||
<li key="snoozed-shelf-header" data-thread-selection-safe className="list-none">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleSnoozedShelf}
|
||||
aria-expanded={snoozedShelfExpanded}
|
||||
data-testid="sidebar-v2-snoozed-shelf-toggle"
|
||||
className="mb-1 mt-3 flex w-full cursor-pointer items-center gap-2 px-2.5 text-left"
|
||||
// Snoozed shelf: between the inbox and Settled — out of the
|
||||
// way, never gone. The header always renders while anything
|
||||
// is snoozed (the count is the whole footprint when
|
||||
// collapsed); rows only when expanded. Vanishes entirely at
|
||||
// count 0.
|
||||
if (snoozedThreads.length > 0) {
|
||||
items.push(
|
||||
<li
|
||||
key="snoozed-shelf-header"
|
||||
data-thread-selection-safe
|
||||
className="list-none"
|
||||
>
|
||||
<span className="text-xs font-medium text-blue-600 dark:text-blue-400">
|
||||
{snoozedShelfExpanded ? "Snoozed" : `Snoozed (${snoozedThreads.length})`}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"size-3 text-blue-600 transition-transform dark:text-blue-400",
|
||||
snoozedShelfExpanded && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</li>,
|
||||
);
|
||||
for (const thread of visibleSnoozedThreads) {
|
||||
items.push(renderThreadRow(thread, "snoozed"));
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleSnoozedShelf}
|
||||
aria-expanded={snoozedShelfExpanded}
|
||||
data-testid="sidebar-v2-snoozed-shelf-toggle"
|
||||
className="mb-1 mt-3 flex w-full cursor-pointer items-center gap-2 px-2.5 text-left"
|
||||
>
|
||||
<span className="text-xs font-medium text-blue-600 dark:text-blue-400">
|
||||
{snoozedShelfExpanded
|
||||
? "Snoozed"
|
||||
: `Snoozed (${snoozedThreads.length})`}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"size-3 text-blue-600 transition-transform dark:text-blue-400",
|
||||
snoozedShelfExpanded && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</li>,
|
||||
);
|
||||
for (const thread of visibleSnoozedThreads) {
|
||||
items.push(renderThreadRow(thread, "snoozed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (settledThreads.length > 0) {
|
||||
items.push(
|
||||
<li key="settled-shelf-header" data-thread-selection-safe className="list-none">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleSettledShelf}
|
||||
aria-expanded={settledShelfExpanded}
|
||||
data-testid="sidebar-v2-settled-shelf-toggle"
|
||||
className="mb-1 mt-3 flex w-full cursor-pointer items-center gap-2 px-2.5 text-left"
|
||||
if (settledThreads.length > 0) {
|
||||
items.push(
|
||||
<li
|
||||
key="settled-shelf-header"
|
||||
data-thread-selection-safe
|
||||
className="list-none"
|
||||
>
|
||||
<span className="text-xs font-medium text-muted-foreground/50">
|
||||
{settledShelfExpanded ? "Settled" : `Settled (${settledThreads.length})`}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-sidebar-border/60" />
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"size-3 text-muted-foreground/50 transition-transform",
|
||||
settledShelfExpanded && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</li>,
|
||||
);
|
||||
}
|
||||
for (const thread of renderedSettledThreads) {
|
||||
items.push(renderThreadRow(thread, "settled"));
|
||||
}
|
||||
return items;
|
||||
})()}
|
||||
{settledShelfExpanded && hiddenSettledCount > 0 ? (
|
||||
<li className="list-none">
|
||||
<button
|
||||
type="button"
|
||||
onClick={showMoreSettled}
|
||||
className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground/55 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
>
|
||||
<PlusIcon aria-hidden className="size-4 shrink-0" />
|
||||
Show {Math.min(hiddenSettledCount, SETTLED_TAIL_PAGE_COUNT)} more
|
||||
</button>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
</TooltipProvider>
|
||||
{activeThreads.length + snoozedThreads.length + settledThreads.length === 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleSettledShelf}
|
||||
aria-expanded={settledShelfExpanded}
|
||||
data-testid="sidebar-v2-settled-shelf-toggle"
|
||||
className="mb-1 mt-3 flex w-full cursor-pointer items-center gap-2 px-2.5 text-left"
|
||||
>
|
||||
<span className="text-xs font-medium text-muted-foreground/50">
|
||||
{settledShelfExpanded
|
||||
? "Settled"
|
||||
: `Settled (${settledThreads.length})`}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-sidebar-border/60" />
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"size-3 text-muted-foreground/50 transition-transform",
|
||||
settledShelfExpanded && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</li>,
|
||||
);
|
||||
}
|
||||
for (const thread of renderedSettledThreads) {
|
||||
items.push(renderThreadRow(thread, "settled"));
|
||||
}
|
||||
return items;
|
||||
})()}
|
||||
{settledShelfExpanded && hiddenSettledCount > 0 ? (
|
||||
<li className="list-none">
|
||||
<button
|
||||
type="button"
|
||||
onClick={showMoreSettled}
|
||||
className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground/55 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
>
|
||||
<PlusIcon aria-hidden className="size-4 shrink-0" />
|
||||
Show {Math.min(hiddenSettledCount, SETTLED_TAIL_PAGE_COUNT)} more
|
||||
</button>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
</TooltipProvider>
|
||||
) : null}
|
||||
{!isSearchingThreads &&
|
||||
activeThreads.length + snoozedThreads.length + settledThreads.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-2 px-2 py-6 text-center text-xs text-muted-foreground/60">
|
||||
{projects.length === 0 ? (
|
||||
<>
|
||||
|
||||
@@ -2,8 +2,10 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
resolveTerminalSelectionActionPosition,
|
||||
shouldHandleTerminalExit,
|
||||
shouldHandleTerminalSelectionMouseUp,
|
||||
terminalSelectionActionDelayForClickCount,
|
||||
terminalSelectionLineRange,
|
||||
} from "./ThreadTerminalDrawer";
|
||||
|
||||
describe("resolveTerminalSelectionActionPosition", () => {
|
||||
@@ -72,4 +74,19 @@ describe("resolveTerminalSelectionActionPosition", () => {
|
||||
expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
|
||||
expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses Ghostty's physical screen range for visually wrapped selections", () => {
|
||||
expect(
|
||||
terminalSelectionLineRange({
|
||||
start: { y: 4 },
|
||||
end: { y: 6 },
|
||||
}),
|
||||
).toEqual({ lineStart: 5, lineEnd: 7 });
|
||||
});
|
||||
|
||||
it("handles an exit that lands while the terminal surface is still loading", () => {
|
||||
expect(shouldHandleTerminalExit("exited", "running", false)).toBe(true);
|
||||
expect(shouldHandleTerminalExit("exited", "exited", false)).toBe(false);
|
||||
expect(shouldHandleTerminalExit("closed", "running", true)).toBe(false);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@ import {
|
||||
getDesktopUpdateActionError,
|
||||
getDesktopUpdateButtonTooltip,
|
||||
getDesktopUpdateInstallConfirmationMessage,
|
||||
getDesktopUpdateReleaseUrl,
|
||||
isDesktopUpdateButtonDisabled,
|
||||
resolveDesktopUpdateButtonAction,
|
||||
shouldShowArm64IntelBuildWarning,
|
||||
@@ -158,6 +159,23 @@ describe("getDesktopUpdateActionError", () => {
|
||||
});
|
||||
|
||||
describe("desktop update UI helpers", () => {
|
||||
it("builds the stable release URL for a downloaded version", () => {
|
||||
expect(getDesktopUpdateReleaseUrl("0.0.30")).toBe(
|
||||
"https://github.com/pingdotgg/t3code/releases/tag/v0.0.30",
|
||||
);
|
||||
});
|
||||
|
||||
it("builds the nightly release URL without dropping its version suffix", () => {
|
||||
expect(getDesktopUpdateReleaseUrl("0.0.30-nightly.20260728.931")).toBe(
|
||||
"https://github.com/pingdotgg/t3code/releases/tag/v0.0.30-nightly.20260728.931",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the release URL when the updater does not report a version", () => {
|
||||
expect(getDesktopUpdateReleaseUrl(null)).toBeNull();
|
||||
expect(getDesktopUpdateReleaseUrl(" ")).toBeNull();
|
||||
});
|
||||
|
||||
it("toasts only for actionable updater errors", () => {
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
|
||||
@@ -3,6 +3,24 @@ import { isWindowsPlatform } from "../lib/utils";
|
||||
|
||||
export type DesktopUpdateButtonAction = "download" | "install" | "none";
|
||||
|
||||
const DESKTOP_RELEASE_TAG_URL = "https://github.com/pingdotgg/t3code/releases/tag";
|
||||
|
||||
/**
|
||||
* The main process fills `downloadedVersion` from the updater's `update-downloaded`
|
||||
* event, which is dispatched on its own fiber. A download RPC can therefore resolve
|
||||
* before that write lands, so fall back to the version the download was started for.
|
||||
*/
|
||||
export function getDesktopUpdateDownloadedVersion(state: DesktopUpdateState): string | null {
|
||||
return state.downloadedVersion ?? state.availableVersion;
|
||||
}
|
||||
|
||||
/** Release notes for an exact downloaded build; nightly suffixes are part of the tag. */
|
||||
export function getDesktopUpdateReleaseUrl(version: string | null): string | null {
|
||||
const normalizedVersion = version?.trim();
|
||||
if (!normalizedVersion) return null;
|
||||
return `${DESKTOP_RELEASE_TAG_URL}/v${encodeURIComponent(normalizedVersion)}`;
|
||||
}
|
||||
|
||||
export function resolveDesktopUpdateButtonAction(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateButtonAction {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { isValidElement, type ReactElement, type ReactNode } from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
addToast: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./ui/toast", () => ({
|
||||
toastManager: { add: testState.addToast },
|
||||
}));
|
||||
|
||||
import { showDesktopUpdateDownloadedToast } from "./desktopUpdate.toast";
|
||||
|
||||
type ClickableElement = ReactElement<{ readonly onClick?: () => void }>;
|
||||
|
||||
/** Walks the rendered description, invoking function components, to find the link button. */
|
||||
function findReleaseNotesLink(node: ReactNode): ClickableElement | null {
|
||||
if (Array.isArray(node)) {
|
||||
for (const child of node) {
|
||||
const found = findReleaseNotesLink(child);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!isValidElement(node)) return null;
|
||||
const element = node as ReactElement<{ readonly children?: ReactNode }>;
|
||||
if (element.type === "button") return element as ClickableElement;
|
||||
if (typeof element.type === "function") {
|
||||
const render = element.type as (props: unknown) => ReactNode;
|
||||
return findReleaseNotesLink(render(element.props));
|
||||
}
|
||||
return findReleaseNotesLink(element.props.children);
|
||||
}
|
||||
|
||||
function getDescription(): ReactNode {
|
||||
const toast = testState.addToast.mock.calls[0]?.[0] as { description?: ReactNode } | undefined;
|
||||
return toast?.description ?? null;
|
||||
}
|
||||
|
||||
function downloadedState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {
|
||||
return {
|
||||
enabled: true,
|
||||
status: "downloaded",
|
||||
channel: "latest",
|
||||
currentVersion: "0.0.29",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: "0.0.30",
|
||||
downloadedVersion: "0.0.30",
|
||||
releaseNotes: [],
|
||||
downloadPercent: 100,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("showDesktopUpdateDownloadedToast", () => {
|
||||
beforeEach(() => {
|
||||
testState.addToast.mockReset();
|
||||
});
|
||||
|
||||
it("opens the downloaded version's release notes", async () => {
|
||||
const openExternal = vi.fn().mockResolvedValue(true);
|
||||
|
||||
showDesktopUpdateDownloadedToast({ openExternal }, downloadedState());
|
||||
const link = findReleaseNotesLink(getDescription());
|
||||
link?.props.onClick?.();
|
||||
await vi.waitFor(() => {
|
||||
expect(openExternal).toHaveBeenCalledWith(
|
||||
"https://github.com/pingdotgg/t3code/releases/tag/v0.0.30",
|
||||
);
|
||||
});
|
||||
expect(testState.addToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("falls back to the version the download was started for", async () => {
|
||||
const openExternal = vi.fn().mockResolvedValue(true);
|
||||
|
||||
// The `update-downloaded` event can land after the download RPC resolves.
|
||||
showDesktopUpdateDownloadedToast(
|
||||
{ openExternal },
|
||||
downloadedState({ downloadedVersion: null }),
|
||||
);
|
||||
findReleaseNotesLink(getDescription())?.props.onClick?.();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(openExternal).toHaveBeenCalledWith(
|
||||
"https://github.com/pingdotgg/t3code/releases/tag/v0.0.30",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("omits the link when the updater reports no version at all", () => {
|
||||
showDesktopUpdateDownloadedToast(
|
||||
{ openExternal: vi.fn() },
|
||||
downloadedState({ availableVersion: null, downloadedVersion: null }),
|
||||
);
|
||||
|
||||
expect(findReleaseNotesLink(getDescription())).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["returns false", vi.fn().mockResolvedValue(false)],
|
||||
["rejects", vi.fn().mockRejectedValue(new Error("open failed"))],
|
||||
])("shows an error when opening release notes %s", async (_description, openExternal) => {
|
||||
showDesktopUpdateDownloadedToast({ openExternal }, downloadedState());
|
||||
findReleaseNotesLink(getDescription())?.props.onClick?.();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(testState.addToast).toHaveBeenLastCalledWith({
|
||||
type: "error",
|
||||
title: "Unable to open release notes",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
|
||||
import { ArrowRightIcon } from "lucide-react";
|
||||
|
||||
import {
|
||||
getDesktopUpdateDownloadedVersion,
|
||||
getDesktopUpdateReleaseUrl,
|
||||
} from "./desktopUpdate.logic";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
type DesktopUpdateShell = Pick<DesktopBridge, "openExternal">;
|
||||
|
||||
function ReleaseNotesLink({
|
||||
shell,
|
||||
releaseUrl,
|
||||
}: {
|
||||
shell: DesktopUpdateShell;
|
||||
releaseUrl: string;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className="ml-2 inline-flex cursor-pointer items-center gap-1 align-baseline text-muted-foreground underline decoration-dotted underline-offset-4 transition-colors hover:text-foreground"
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
try {
|
||||
if (await shell.openExternal(releaseUrl)) return;
|
||||
} catch {
|
||||
// Surface rejected IPC calls through the same user-visible fallback.
|
||||
}
|
||||
toastManager.add({ type: "error", title: "Unable to open release notes" });
|
||||
})();
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
Read more
|
||||
<ArrowRightIcon aria-hidden className="size-3 -rotate-45" strokeWidth={2.25} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function showDesktopUpdateDownloadedToast(
|
||||
shell: DesktopUpdateShell,
|
||||
state: DesktopUpdateState,
|
||||
): void {
|
||||
const releaseUrl = getDesktopUpdateReleaseUrl(getDesktopUpdateDownloadedVersion(state));
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Update downloaded",
|
||||
description: (
|
||||
<>
|
||||
Restart the app from the update button to install it.
|
||||
{releaseUrl ? <ReleaseNotesLink releaseUrl={releaseUrl} shell={shell} /> : null}
|
||||
</>
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { Input } from "../ui/input";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
import { searchableSetting } from "./settingsSearch";
|
||||
|
||||
const AUTO_SETTLE_MIN_DAYS = 1;
|
||||
const AUTO_SETTLE_MAX_DAYS = 90;
|
||||
@@ -65,7 +66,7 @@ export function BetaSettingsPanel() {
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="Beta features">
|
||||
<SettingsRow
|
||||
title="Sidebar v2"
|
||||
{...searchableSetting("sidebar-v2")}
|
||||
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
|
||||
control={
|
||||
<Switch
|
||||
@@ -85,7 +86,7 @@ export function BetaSettingsPanel() {
|
||||
{sidebarV2Enabled ? (
|
||||
<>
|
||||
<SettingsRow
|
||||
title="Auto-settle inactive threads"
|
||||
title={searchableSetting("auto-settle-inactive-threads").title}
|
||||
description="Threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
|
||||
control={
|
||||
<Switch
|
||||
|
||||
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user