mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-16 21:34:59 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
038a9ca00d | ||
|
|
3a7e216b7d | ||
|
|
6ef188416f | ||
|
|
791bbd3596 | ||
|
|
b95f1bbf31 | ||
|
|
c2a24ae81e | ||
|
|
6eb94611b3 | ||
|
|
a8cadae0ee | ||
|
|
5a78c1cd16 |
@@ -590,6 +590,16 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host
|
||||
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
|
||||
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
|
||||
|
||||
### Saved hosts
|
||||
|
||||
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
|
||||
|
||||
Every app build on a device shares this key, including an older build after a downgrade and a newer
|
||||
one that saves a connection kind this build doesn't know. The key holds every saved host and its
|
||||
password, so never remove it. Read each host and connection on its own, skip the ones this build
|
||||
can't read, and write them back on every save. A value that isn't a JSON array is copied to
|
||||
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
|
||||
|
||||
### Draft Store
|
||||
|
||||
**AsyncStorage key:** `paseo-drafts` (version 2)
|
||||
|
||||
@@ -2,10 +2,16 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { expect, test as base, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
|
||||
|
||||
async function openExample(page: Page, example: string) {
|
||||
await page.getByRole("button", { name: `Open ${example}`, exact: true }).click();
|
||||
await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible();
|
||||
const title = page.getByText(`Modal example: ${example}`, { exact: true });
|
||||
// A compact sheet holds below the viewport and then slides up, so a pointer placed before it
|
||||
// stops lands on whatever slides under it. The settle check starts once the slide has begun;
|
||||
// two equal reads during the hold would otherwise count as settled.
|
||||
await expect(title).toBeInViewport();
|
||||
await waitForSettledPosition(title);
|
||||
}
|
||||
|
||||
async function closeExample(page: Page) {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { renameHostFromSettings } from "../support/helpers/hosts";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
|
||||
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
|
||||
|
||||
// What a build with a connection kind this one doesn't know leaves in the registry: an extra
|
||||
// connection on a host this build can reach, and a host reached only through it.
|
||||
const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" };
|
||||
const UNKNOWN_HOST = {
|
||||
serverId: "srv_e2e_unknown_connection_host",
|
||||
label: "Unknown connection host",
|
||||
connections: [{ id: "future:roof", type: "futureKind", address: "roof" }],
|
||||
preferredConnectionId: "future:roof",
|
||||
};
|
||||
const OFFLINE_HOST = {
|
||||
serverId: "srv_e2e_saved_offline_host",
|
||||
label: "Saved offline host",
|
||||
password: "e2e-fake-password",
|
||||
connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }],
|
||||
preferredConnectionId: "direct:127.0.0.1:59999",
|
||||
};
|
||||
|
||||
interface StoredHost {
|
||||
serverId: string;
|
||||
label?: string;
|
||||
password?: string;
|
||||
connections: unknown[];
|
||||
}
|
||||
|
||||
async function addUnreadableEntriesAndReload(page: Page): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => {
|
||||
const nonce = localStorage.getItem(keys.nonce);
|
||||
if (!nonce) {
|
||||
throw new Error("Expected the e2e seed nonce before overriding the host registry.");
|
||||
}
|
||||
const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]");
|
||||
registry
|
||||
.find((host) => host.serverId === primaryServerId)
|
||||
?.connections.push(unknownConnection);
|
||||
registry.push(offlineHost, unknownHost);
|
||||
localStorage.setItem(keys.registry, JSON.stringify(registry));
|
||||
localStorage.setItem(keys.disableSeedOnce, nonce);
|
||||
},
|
||||
{
|
||||
keys: {
|
||||
registry: REGISTRY_KEY,
|
||||
nonce: SEED_NONCE_KEY,
|
||||
disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY,
|
||||
},
|
||||
primaryServerId: getServerId(),
|
||||
unknownConnection: UNKNOWN_CONNECTION,
|
||||
offlineHost: OFFLINE_HOST,
|
||||
unknownHost: UNKNOWN_HOST,
|
||||
},
|
||||
);
|
||||
await page.reload();
|
||||
}
|
||||
|
||||
async function readStoredRegistry(page: Page): Promise<StoredHost[] | null> {
|
||||
return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY);
|
||||
}
|
||||
|
||||
async function readStoredHost(page: Page, serverId: string): Promise<StoredHost | undefined> {
|
||||
return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId);
|
||||
}
|
||||
|
||||
test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await addUnreadableEntriesAndReload(page);
|
||||
|
||||
await test.step("both readable hosts are listed", async () => {
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
|
||||
await openSettings(page);
|
||||
await selectSettingsHost(page, OFFLINE_HOST.serverId);
|
||||
await openHostSection(page, OFFLINE_HOST.serverId, "host");
|
||||
await renameHostFromSettings(page, "Renamed offline host");
|
||||
|
||||
await expect
|
||||
.poll(() => readStoredHost(page, OFFLINE_HOST.serverId))
|
||||
.toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password });
|
||||
const stored = await readStoredRegistry(page);
|
||||
expect(stored?.map((host) => host.serverId)).toEqual([
|
||||
getServerId(),
|
||||
OFFLINE_HOST.serverId,
|
||||
UNKNOWN_HOST.serverId,
|
||||
]);
|
||||
expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION);
|
||||
expect(stored?.[2]).toEqual(UNKNOWN_HOST);
|
||||
});
|
||||
});
|
||||
@@ -33,6 +33,8 @@ import {
|
||||
expectNoHostPasswordControls,
|
||||
removeHostFromHostPage,
|
||||
addDirectHostFromSettings,
|
||||
expectAddHostFieldDrawnAsInput,
|
||||
selectHostConnectionType,
|
||||
expectHostOnlineWithoutError,
|
||||
expectIdleAgentRelease,
|
||||
editRestartRecoveryPrompt,
|
||||
@@ -307,6 +309,24 @@ async function closeAddHostAndChangeTheme(page: import("@playwright/test").Page)
|
||||
await page.keyboard.press("Control+Alt+t");
|
||||
}
|
||||
|
||||
test("Add host draws its text fields as bordered inputs", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
|
||||
await test.step("the pairing link field", async () => {
|
||||
await openSidebarAddHost(page);
|
||||
await selectHostConnectionType(page, "relay");
|
||||
await expectAddHostFieldDrawnAsInput(page, "pair-link-input");
|
||||
await page.getByTestId("pair-link-cancel").click();
|
||||
});
|
||||
|
||||
await test.step("the direct connection fields", async () => {
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-host-input");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-port-input");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-password-input");
|
||||
});
|
||||
});
|
||||
|
||||
test("sidebar Add host completes without navigating", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await expect(page).toHaveURL(/\/open-project$/);
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type ChildProcess,
|
||||
type SpawnOptions,
|
||||
} from "node:child_process";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -59,7 +59,17 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
||||
return port;
|
||||
}
|
||||
|
||||
async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
/**
|
||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||
* enough: the port is released before the daemon binds it, and whatever takes
|
||||
* it in between also accepts connections while the daemon exits with
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id.
|
||||
*/
|
||||
async function waitForServer(
|
||||
port: number,
|
||||
child: ChildProcess,
|
||||
identity: { serverId: string; paseoHome: string },
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let lastError: unknown = null;
|
||||
|
||||
@@ -70,22 +80,13 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
);
|
||||
}
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const socket = net.connect(port, "127.0.0.1", () => {
|
||||
socket.end();
|
||||
resolve();
|
||||
});
|
||||
socket.setTimeout(1_000, () => {
|
||||
socket.destroy();
|
||||
reject(new Error(`Connection timed out to isolated daemon port ${port}`));
|
||||
});
|
||||
socket.on("error", reject);
|
||||
});
|
||||
return;
|
||||
const serverId = await readServerId(port, identity.paseoHome);
|
||||
if (serverId === identity.serverId) return;
|
||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
@@ -95,6 +96,25 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||
* on a password-protected daemon; the daemon accepts the local credential it
|
||||
* writes into its home before listening, as the CLI does for local status.
|
||||
*/
|
||||
async function readServerId(port: number, paseoHome: string): Promise<string> {
|
||||
const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then(
|
||||
(token) => token.trim(),
|
||||
() => null,
|
||||
);
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/status`, {
|
||||
headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {},
|
||||
signal: AbortSignal.timeout(1_000),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`);
|
||||
const status = (await response.json()) as { serverId?: unknown };
|
||||
return String(status.serverId);
|
||||
}
|
||||
|
||||
function withMutableRelay(
|
||||
config: NonNullable<IsolatedHostDaemonOptions["config"]>,
|
||||
relay: NonNullable<IsolatedHostDaemonOptions["mutableRelay"]>,
|
||||
@@ -221,7 +241,7 @@ export async function startIsolatedHostDaemon(
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServer(port, spawned);
|
||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||
return spawned;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
|
||||
@@ -223,6 +223,14 @@ export async function addDirectHostFromSettings(
|
||||
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string): Promise<void> {
|
||||
const field = page.getByTestId(testId);
|
||||
await expect(field).toBeVisible();
|
||||
await expect(field).toHaveCSS("border-top-width", "1px");
|
||||
await expect(field).not.toHaveCSS("padding-left", "0px");
|
||||
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
export async function toggleHostAdvanced(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-advanced-toggle").click();
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
group = 'sh.paseo.pressfeedback'
|
||||
version = '0.1.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useExpoPublishing()
|
||||
useDefaultAndroidSdkVersions()
|
||||
|
||||
android {
|
||||
namespace "sh.paseo.pressfeedback"
|
||||
defaultConfig {
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package sh.paseo.pressfeedback
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
import expo.modules.kotlin.types.ColorCompat
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class PaseoPressFeedbackModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView::class) {
|
||||
Prop("tint") { view: PaseoPressFeedbackView, color: Color -> view.paint.color = ColorCompat.toArgb(color) }
|
||||
Prop("radius") { view: PaseoPressFeedbackView, radius: Double -> view.radius = radius.toFloat() * view.resources.displayMetrics.density }
|
||||
Prop("resetKey") { view: PaseoPressFeedbackView, key: String -> view.reset(key) }
|
||||
AsyncFunction("acknowledge") { view: PaseoPressFeedbackView -> view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class PaseoPressFeedbackView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
var radius = 0f
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
init { setWillNotDraw(false); importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO }
|
||||
fun acknowledge() { acknowledged = true; invalidate() }
|
||||
fun reset(key: String) {
|
||||
if (key != resetKey) { resetKey = key; acknowledged = false; invalidate() }
|
||||
}
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
if (acknowledged) canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, paint)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"platforms": ["android", "ios"],
|
||||
"android": { "modules": ["sh.paseo.pressfeedback.PaseoPressFeedbackModule"] },
|
||||
"ios": { "modules": ["PaseoPressFeedbackModule"] }
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { useWorkspaceRowPress } from "./src/ui";
|
||||
@@ -1,22 +0,0 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'PaseoPressFeedback'
|
||||
s.version = '0.1.0'
|
||||
s.summary = 'Native accepted press feedback for Paseo'
|
||||
s.description = 'Paints accepted press feedback independently of React commits'
|
||||
s.license = 'Apache-2.0'
|
||||
s.author = 'Paseo'
|
||||
s.homepage = 'https://paseo.sh'
|
||||
s.platforms = { :ios => '15.1' }
|
||||
s.swift_version = '5.4'
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
'SWIFT_COMPILATION_MODE' => 'wholemodule'
|
||||
}
|
||||
|
||||
s.source_files = "**/*.{h,m,swift}"
|
||||
end
|
||||
@@ -1,33 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public class PaseoPressFeedbackModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView.self) {
|
||||
Prop("tint") { (view: PaseoPressFeedbackView, color: UIColor) in view.tint = color }
|
||||
Prop("radius") { (view: PaseoPressFeedbackView, radius: Double) in view.radius = radius }
|
||||
Prop("resetKey") { (view: PaseoPressFeedbackView, key: String) in view.reset(key) }
|
||||
AsyncFunction("acknowledge") { (view: PaseoPressFeedbackView) in view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class PaseoPressFeedbackView: ExpoView {
|
||||
var tint = UIColor.clear
|
||||
var radius: Double = 0
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
isOpaque = false
|
||||
isUserInteractionEnabled = false
|
||||
}
|
||||
func acknowledge() { acknowledged = true; setNeedsDisplay() }
|
||||
func reset(_ key: String) {
|
||||
if key != resetKey { resetKey = key; acknowledged = false; setNeedsDisplay() }
|
||||
}
|
||||
override func draw(_ rect: CGRect) {
|
||||
if acknowledged { tint.setFill(); UIBezierPath(roundedRect: bounds, cornerRadius: radius).fill() }
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "paseo-press-feedback",
|
||||
"version": "0.1.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { acceptWorkspaceRowPress, type WorkspaceRowPress } from "./accept";
|
||||
|
||||
function rowPress(overrides: Partial<WorkspaceRowPress> = {}) {
|
||||
const visible: string[] = [];
|
||||
const press: WorkspaceRowPress = {
|
||||
cancelled: false,
|
||||
native: true,
|
||||
selected: false,
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
acknowledge: () => visible.push("row"),
|
||||
navigate: () => visible.push("workspace"),
|
||||
...overrides,
|
||||
};
|
||||
return { press, visible };
|
||||
}
|
||||
|
||||
it("acknowledges an accepted row before navigation starts", () => {
|
||||
const { press, visible } = rowPress();
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
|
||||
it("does not acknowledge or navigate after scrolling or a long press claims the touch", () => {
|
||||
const { press, visible } = rowPress({ cancelled: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts only the first row while its selection closes the sidebar", () => {
|
||||
const { press, visible } = rowPress();
|
||||
press.navigate = () => {
|
||||
press.target = "agent";
|
||||
visible.push("workspace B");
|
||||
};
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual(["row", "workspace B"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "open phone or tablet overlay",
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "closing overlay", sidebar: "overlay", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "explorer covering an overlay",
|
||||
sidebar: "overlay",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{ name: "docked sidebar", sidebar: "dock", target: "agent", native: true, accepted: true },
|
||||
{
|
||||
name: "docked sidebar beside explorer",
|
||||
sidebar: "dock",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "hidden sidebar", sidebar: "hidden", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "suspended open overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{
|
||||
name: "suspended closed overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{
|
||||
name: "web sidebar independent of native panel target",
|
||||
sidebar: "overlay",
|
||||
target: "agent",
|
||||
native: false,
|
||||
accepted: true,
|
||||
},
|
||||
] as const)("uses the panel state for $name", ({ accepted, name: _, ...state }) => {
|
||||
const { press, visible } = rowPress(state);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(accepted);
|
||||
expect(visible).toEqual(accepted ? ["row", "workspace"] : []);
|
||||
});
|
||||
|
||||
it("does not leave an acknowledgement over an already selected docked row", () => {
|
||||
const { press, visible } = rowPress({ selected: true, sidebar: "dock", target: "agent" });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["workspace"]);
|
||||
});
|
||||
|
||||
it("still acknowledges a selected overlay row before the sidebar leaves", () => {
|
||||
const { press, visible } = rowPress({ selected: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { LeftSidebarPresentation, MobilePanelView } from "@/stores/panel-store";
|
||||
|
||||
export interface WorkspaceRowPress {
|
||||
cancelled: boolean;
|
||||
native: boolean;
|
||||
selected: boolean;
|
||||
sidebar: LeftSidebarPresentation;
|
||||
target: MobilePanelView;
|
||||
acknowledge(): void;
|
||||
navigate(): void;
|
||||
}
|
||||
|
||||
export function acceptWorkspaceRowPress(press: WorkspaceRowPress): boolean {
|
||||
if (press.cancelled) return false;
|
||||
if (press.native && press.sidebar !== "dock" && press.target !== "agent-list") return false;
|
||||
// A selected docked row neither changes selection nor leaves the screen to clear the fill.
|
||||
if (!press.selected || press.sidebar !== "dock") press.acknowledge();
|
||||
press.navigate();
|
||||
return true;
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { requireNativeView } from "expo";
|
||||
import { type Ref } from "react";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { View, StyleSheet, type ViewProps } from "react-native";
|
||||
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
interface FeedbackProps extends ViewProps {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
resetKey: string;
|
||||
tint?: string;
|
||||
radius?: number;
|
||||
}
|
||||
const NativeFeedback = withUnistyles(requireNativeView<FeedbackProps>("PaseoPressFeedback"));
|
||||
const mapTheme = (theme: import("@/styles/theme").Theme) => ({
|
||||
tint: theme.colors.interactionHighlight,
|
||||
radius: theme.borderRadius.lg,
|
||||
});
|
||||
export function RowFeedback({
|
||||
ref,
|
||||
selected,
|
||||
}: {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const revision = usePanelStore((state) => state.mobilePanel.revision);
|
||||
// Selection takes over the fill; a new panel transition clears it before reopening.
|
||||
const resetKey = `${selected}:${revision}`;
|
||||
return (
|
||||
<View pointerEvents="none" style={styles.overlay}>
|
||||
<NativeFeedback
|
||||
ref={ref}
|
||||
resetKey={resetKey}
|
||||
pointerEvents="none"
|
||||
style={styles.fill}
|
||||
uniProps={mapTheme}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
overlay: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 },
|
||||
fill: { flex: 1 },
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { Ref } from "react";
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
|
||||
return null;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { useCallback, useRef, type RefObject } from "react";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { acceptWorkspaceRowPress } from "../accept";
|
||||
import { RowFeedback, type RowFeedbackHandle } from "./feedback";
|
||||
|
||||
export function useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
}: {
|
||||
didLongPressRef?: RefObject<boolean>;
|
||||
onPress(): void;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const feedback = useRef<RowFeedbackHandle>(null);
|
||||
const handlePress = useCallback(() => {
|
||||
const cancelled = didLongPressRef?.current ?? false;
|
||||
if (didLongPressRef) didLongPressRef.current = false;
|
||||
const panel = usePanelStore.getState();
|
||||
acceptWorkspaceRowPress({
|
||||
cancelled,
|
||||
native: isNative,
|
||||
selected,
|
||||
sidebar: panel.layout.leftSidebar,
|
||||
target: panel.mobilePanel.target,
|
||||
// Paint on the native UI thread before navigation occupies JS; never wait for paint.
|
||||
acknowledge: () => {
|
||||
void feedback.current?.acknowledge();
|
||||
},
|
||||
navigate: onPress,
|
||||
});
|
||||
}, [didLongPressRef, onPress, selected]);
|
||||
return {
|
||||
onPress: handlePress,
|
||||
feedback: <RowFeedback ref={feedback} selected={selected} />,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useWorkspaceRowPress } from "../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import {
|
||||
@@ -1091,11 +1090,13 @@ function WorkspaceRowInner({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef: interaction.didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
const handlePress = useCallback(() => {
|
||||
if (interaction.didLongPressRef.current) {
|
||||
interaction.didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [interaction.didLongPressRef, onPress]);
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
@@ -1190,7 +1191,6 @@ function WorkspaceRowInner({
|
||||
onTogglePin={onTogglePin}
|
||||
/>
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useWorkspaceRowPress } from "../../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
memo,
|
||||
@@ -847,11 +846,13 @@ function StatusWorkspaceRowInnerContent({
|
||||
const startDragPress = dragInteraction?.handlePressIn;
|
||||
const moveDragPress = dragInteraction?.handleTouchMove;
|
||||
const endDragPress = dragInteraction?.handlePressOut;
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
const handlePress = useCallback(() => {
|
||||
if (didLongPressRef?.current) {
|
||||
didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [didLongPressRef, onPress]);
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
@@ -964,7 +965,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
/>
|
||||
) : null}
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -431,7 +431,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<View style={styles.portRow}>
|
||||
<View style={hostFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-input"
|
||||
nativeID="direct-host-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.host")}
|
||||
@@ -449,7 +449,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
</View>
|
||||
<View style={portFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-port-input"
|
||||
nativeID="direct-port-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.port")}
|
||||
@@ -491,7 +491,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
|
||||
<View style={styles.passwordRow}>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-password-input"
|
||||
nativeID="direct-password-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.password")}
|
||||
@@ -539,7 +539,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
|
||||
</PressHighlight>
|
||||
{isAdvancedOpen ? (
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
@@ -598,7 +598,3 @@ const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
|
||||
placeholderTextColor: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
@@ -212,7 +212,7 @@ function PairLinkModalContent({
|
||||
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>{t("pairing.link.label")}</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
ref={inputRef}
|
||||
initialValue={initialUrl}
|
||||
testID="pair-link-input"
|
||||
@@ -234,11 +234,13 @@ function PairLinkModalContent({
|
||||
<Text style={styles.label}>
|
||||
{t("pairing.hostPassword.title", { host: parsedHostLabel(offerUrlRef.current) })}
|
||||
</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="pair-link-password-input"
|
||||
resetKey={`pair-link-password-${passwordResetKey}`}
|
||||
accessibilityLabel={t("pairing.hostPassword.label")}
|
||||
placeholder={t("pairing.hostPassword.label")}
|
||||
onChangeText={setPassword}
|
||||
autoFocus
|
||||
secureTextEntry
|
||||
style={styles.input}
|
||||
/>
|
||||
@@ -275,7 +277,3 @@ function PairLinkModalContent({
|
||||
}
|
||||
|
||||
const ThemedLink = withUnistyles(Link, (theme) => ({ color: theme.colors.accentForeground }));
|
||||
|
||||
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
|
||||
placeholderTextColor: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
@@ -2256,6 +2256,59 @@ describe("HostRuntimeController", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
const directA: HostConnection = {
|
||||
id: "direct:lan-a:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-a:6767",
|
||||
};
|
||||
const directB: HostConnection = {
|
||||
id: "direct:lan-b:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-b:6767",
|
||||
};
|
||||
// What a build with a connection kind this one doesn't know leaves behind: an extra connection
|
||||
// on a host this build can reach, and a host reached only through it.
|
||||
const storedWithUnreadableEntries = [
|
||||
{
|
||||
...makeHost({ serverId: "srv_a", password: "secret-a" }),
|
||||
connections: [futureConnection, directA],
|
||||
},
|
||||
makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }),
|
||||
{ serverId: "srv_future", label: "future host", connections: [futureConnection] },
|
||||
];
|
||||
|
||||
async function bootWithRegistry(registry: string): Promise<{
|
||||
store: HostRuntimeStore;
|
||||
storage: HostRuntimeStorage;
|
||||
}> {
|
||||
const storage = createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: registry,
|
||||
"@paseo:e2e": "1",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host }) => ({
|
||||
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: host.label ?? null,
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
revokePushNotifications: async () => undefined,
|
||||
});
|
||||
await store.boot();
|
||||
return { store, storage };
|
||||
}
|
||||
|
||||
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
|
||||
const raw = await storage.getItem(REGISTRY_KEY);
|
||||
return raw === null ? null : JSON.parse(raw);
|
||||
}
|
||||
|
||||
describe("HostRuntimeStore", () => {
|
||||
function gatewayRecoveryFixture() {
|
||||
const parent = new FakeDaemonClient();
|
||||
@@ -2686,6 +2739,98 @@ describe("HostRuntimeStore", () => {
|
||||
session.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_a", "secret-a"],
|
||||
["srv_b", "secret-b"],
|
||||
]);
|
||||
expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([
|
||||
directA.id,
|
||||
]);
|
||||
expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("keeps the entries it can't read when it saves the registry", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
await store.renameHost("srv_b", "renamed");
|
||||
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{
|
||||
serverId: "srv_a",
|
||||
password: "secret-a",
|
||||
connections: [{ id: directA.id }, futureConnection],
|
||||
},
|
||||
{ serverId: "srv_b", password: "secret-b", label: "renamed" },
|
||||
storedWithUnreadableEntries[2],
|
||||
]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("moves a stored connection password to its host and keeps the connection it can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [
|
||||
{ type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" },
|
||||
futureConnection,
|
||||
],
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_legacy", "old-secret"],
|
||||
]);
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_legacy", password: "old-secret" },
|
||||
]),
|
||||
);
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ connections: [{ ...directA, useTls: false }, futureConnection] },
|
||||
]);
|
||||
const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>;
|
||||
expect(written?.connections[0]).not.toHaveProperty("password");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("forgets an entry it can't read once that host is paired again and removed", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
|
||||
);
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
|
||||
await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint });
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_future", connections: [{ id: directA.id }] },
|
||||
]),
|
||||
);
|
||||
|
||||
await store.removeHost("srv_future");
|
||||
expect(await readRegistry(storage)).toEqual([]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("copies a registry that isn't JSON aside instead of deleting it", async () => {
|
||||
const { store, storage } = await bootWithRegistry("{not json");
|
||||
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json");
|
||||
expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("marks the host registry loaded after boot reads storage", async () => {
|
||||
const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON;
|
||||
process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint";
|
||||
|
||||
@@ -17,14 +17,16 @@ import {
|
||||
import {
|
||||
connectionFromListen,
|
||||
createRemoteSshHostConnection,
|
||||
normalizeStoredHostProfile,
|
||||
forgetUnreadableHost,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
upsertHostConnectionInProfiles,
|
||||
registryHasConnection,
|
||||
relayConnectionFromOffer,
|
||||
StoredHostRegistrySchema,
|
||||
writeHostRegistry,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
type UnreadableHostEntries,
|
||||
} from "@/types/host-connection";
|
||||
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
|
||||
import {
|
||||
@@ -43,7 +45,7 @@ import { isWeb } from "@/constants/platform";
|
||||
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { z } from "zod";
|
||||
import { readValidatedJson, readValidatedString } from "@/storage/validated-storage";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
import {
|
||||
selectBestConnection,
|
||||
type ConnectionCandidate,
|
||||
@@ -1692,6 +1694,7 @@ export class HostRuntimeStore {
|
||||
private hostListVersion = 0;
|
||||
private hostRegistryLoaded = false;
|
||||
private hosts: HostProfile[] = [];
|
||||
private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
private hostAppearanceMutationTail: Promise<void> = Promise.resolve();
|
||||
private hostRegistryStatus: HostRegistryStatus = "loading";
|
||||
private deps: HostRuntimeControllerDeps;
|
||||
@@ -1799,32 +1802,17 @@ export class HostRuntimeStore {
|
||||
let shouldPersistHosts = false;
|
||||
let profiles: HostProfile[] = [];
|
||||
try {
|
||||
const stored = await readValidatedJson(
|
||||
this.storage,
|
||||
REGISTRY_STORAGE_KEY,
|
||||
StoredHostRegistrySchema,
|
||||
);
|
||||
const stored = await this.readStoredRegistry();
|
||||
if (stored) {
|
||||
const normalizedProfiles: HostProfile[] = [];
|
||||
for (const entry of stored) {
|
||||
const profile = normalizeStoredHostProfile(entry);
|
||||
if (!profile) {
|
||||
await this.storage.removeItem(REGISTRY_STORAGE_KEY);
|
||||
normalizedProfiles.length = 0;
|
||||
break;
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (
|
||||
entry.connections.some(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
)
|
||||
) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
normalizedProfiles.push(profile);
|
||||
// An entry this build can't read skips only that host or connection, and stays stored.
|
||||
const registry = readHostRegistry(stored);
|
||||
this.unreadableHosts = registry.unreadable;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (registry.movedConnectionPassword) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== normalizedProfiles.length) {
|
||||
profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== registry.hosts.length) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
}
|
||||
@@ -2320,6 +2308,7 @@ export class HostRuntimeStore {
|
||||
async removeHost(serverId: string): Promise<void> {
|
||||
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
|
||||
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
|
||||
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
|
||||
this.setHostsAndSync(remaining);
|
||||
await this.persistHosts();
|
||||
}
|
||||
@@ -2408,7 +2397,27 @@ export class HostRuntimeStore {
|
||||
}
|
||||
|
||||
private async persistHosts(hosts = this.hosts): Promise<void> {
|
||||
await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts));
|
||||
await this.storage.setItem(
|
||||
REGISTRY_STORAGE_KEY,
|
||||
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the stored registry without removing it. A value that isn't a JSON array is copied to
|
||||
* `<key>:unreadable` first, because the next save overwrites the key.
|
||||
*/
|
||||
private async readStoredRegistry(): Promise<unknown[] | null> {
|
||||
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
|
||||
if (raw === null) return null;
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(value)) return value;
|
||||
} catch {
|
||||
// Not JSON: copied aside below.
|
||||
}
|
||||
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
|
||||
return null;
|
||||
}
|
||||
|
||||
private emitHostList(): void {
|
||||
|
||||
@@ -106,6 +106,79 @@ describe("workspace-pane-state", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not locate a file by an id retained from a previous target", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabIds: ["file_/repo/a.ts", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" };
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "split-side-pane",
|
||||
paneId: "main",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"agent_agent-a",
|
||||
);
|
||||
});
|
||||
|
||||
it("matches a retained file instance when only the requested line range differs", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["retained-file", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
};
|
||||
const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" };
|
||||
const tabs = [
|
||||
createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = {
|
||||
kind: "file",
|
||||
path: "/repo/a.ts",
|
||||
lineStart: 12,
|
||||
lineEnd: 20,
|
||||
};
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "open-in-source",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"retained-file",
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers an exact file navigation target over another instance of the same resource", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["first", "second"],
|
||||
focusedTabId: "first",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }),
|
||||
];
|
||||
|
||||
expect(
|
||||
deriveWorkspacePaneState({
|
||||
pane,
|
||||
tabs,
|
||||
preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 },
|
||||
}).activeTabId,
|
||||
).toBe("second");
|
||||
});
|
||||
|
||||
it("resolves side file opens to an existing file tab", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
|
||||
@@ -5,12 +5,9 @@ import {
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
normalizeWorkspaceTabTarget,
|
||||
workspaceTabTargetsEqual,
|
||||
} from "@/workspace-tabs/identity";
|
||||
import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity";
|
||||
import { findAdjacentPane } from "@/utils/split-navigation";
|
||||
import { panelResourceKey } from "@/panels/panel-manifest";
|
||||
|
||||
export interface WorkspaceDerivedTab {
|
||||
descriptor: WorkspaceTabDescriptor;
|
||||
@@ -124,8 +121,10 @@ function getActiveTabId(input: {
|
||||
}
|
||||
const matchingTab =
|
||||
input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ??
|
||||
null;
|
||||
return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget);
|
||||
input.tabs.find(
|
||||
(tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget),
|
||||
);
|
||||
return matchingTab?.descriptor.tabId ?? null;
|
||||
})();
|
||||
|
||||
if (preferredTabId && input.openTabIds.has(preferredTabId)) {
|
||||
@@ -211,10 +210,8 @@ export function resolveSideFileOpenPlacement(input: {
|
||||
tabs: WorkspaceTab[];
|
||||
target: WorkspaceTabTarget;
|
||||
}): WorkspaceSideFileOpenPlacement {
|
||||
const targetTabId = buildDeterministicWorkspaceTabId(input.target);
|
||||
const existingTab = input.tabs.find(
|
||||
(tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target),
|
||||
);
|
||||
const targetKey = panelResourceKey(input.target);
|
||||
const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey);
|
||||
if (existingTab) {
|
||||
return { kind: "open-in-source" };
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants";
|
||||
import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest";
|
||||
import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
@@ -137,6 +137,8 @@ interface OpenTabInLayoutInput {
|
||||
placement: WorkspaceTabPlacement;
|
||||
/** Required so a new caller cannot silently opt out of Explorer placement rules. */
|
||||
explorerSidebarPaneId: string | null;
|
||||
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
|
||||
@@ -261,6 +263,7 @@ interface ReorderPaneTabsInLayoutInput {
|
||||
|
||||
export interface WorkspaceTabReconcileState {
|
||||
layout: WorkspaceLayout;
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
pinnedAgentIds?: ReadonlySet<string> | null;
|
||||
hiddenAgentIds?: ReadonlySet<string> | null;
|
||||
explorerSidebarPaneId: string | null;
|
||||
@@ -398,15 +401,11 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] {
|
||||
if (!Array.isArray(input)) {
|
||||
return [];
|
||||
}
|
||||
// Preserve colliding entries until the whole layout can assign each an identity.
|
||||
const next: WorkspaceTab[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const value of input) {
|
||||
const tab = normalizeWorkspaceTab(value);
|
||||
if (!tab || seen.has(tab.tabId)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(tab.tabId);
|
||||
next.push(tab);
|
||||
if (tab) next.push(tab);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1022,13 +1021,65 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
|
||||
};
|
||||
}
|
||||
|
||||
function repairDuplicateTabIds(root: SplitNodeInternal): {
|
||||
root: SplitNodeInternal;
|
||||
ambiguousIds: ReadonlySet<string>;
|
||||
} {
|
||||
const keepers = new Map<string, WorkspaceTab>();
|
||||
const ambiguousIds = new Set<string>();
|
||||
for (const tab of collectAllTabs(root)) {
|
||||
const keeper = keepers.get(tab.tabId);
|
||||
if (!keeper) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
continue;
|
||||
}
|
||||
ambiguousIds.add(tab.tabId);
|
||||
if (
|
||||
buildDeterministicWorkspaceTabId(tab.target) === tab.tabId &&
|
||||
buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId
|
||||
) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
}
|
||||
}
|
||||
if (ambiguousIds.size === 0) return { root, ambiguousIds };
|
||||
|
||||
// Reserve every original id before assigning replacements, including hidden panes.
|
||||
const occupiedIds = new Set(keepers.keys());
|
||||
function repair(node: SplitNodeInternal): SplitNodeInternal {
|
||||
if (node.kind === "group") {
|
||||
return { ...node, group: { ...node.group, children: node.group.children.map(repair) } };
|
||||
}
|
||||
const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId);
|
||||
const focusedTab =
|
||||
focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0];
|
||||
let focusedTabId = node.pane.focusedTabId;
|
||||
const tabs = node.pane.tabs.map((tab) => {
|
||||
if (keepers.get(tab.tabId) === tab) return tab;
|
||||
const tabId = allocateWorkspaceTabId(
|
||||
buildDeterministicWorkspaceTabId(tab.target),
|
||||
occupiedIds,
|
||||
);
|
||||
occupiedIds.add(tabId);
|
||||
if (tab === focusedTab) focusedTabId = tabId;
|
||||
return { ...tab, tabId };
|
||||
});
|
||||
return {
|
||||
...node,
|
||||
pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId },
|
||||
};
|
||||
}
|
||||
return { root: repair(root), ambiguousIds };
|
||||
}
|
||||
|
||||
export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
if (!layout || typeof layout !== "object") {
|
||||
return createDefaultLayout();
|
||||
}
|
||||
|
||||
const rawLayout = layout as WorkspaceLayout;
|
||||
const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root);
|
||||
const { root, ambiguousIds } = repairDuplicateTabIds(
|
||||
normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root),
|
||||
);
|
||||
const focusedPaneId =
|
||||
rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId);
|
||||
const resolvedFocusedPaneId =
|
||||
@@ -1047,7 +1098,16 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)),
|
||||
});
|
||||
|
||||
return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout;
|
||||
if (parentTabIdByTabId) {
|
||||
// A duplicated id cannot identify either end of a parent relationship unambiguously.
|
||||
for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) {
|
||||
if (ambiguousIds.has(childId) || ambiguousIds.has(parentId))
|
||||
delete parentTabIdByTabId[childId];
|
||||
}
|
||||
if (Object.keys(parentTabIdByTabId).length > 0)
|
||||
return { ...normalizedLayout, parentTabIdByTabId };
|
||||
}
|
||||
return normalizedLayout;
|
||||
}
|
||||
|
||||
export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null {
|
||||
@@ -1364,7 +1424,9 @@ function insertNewTabIntoPane(
|
||||
return null;
|
||||
}
|
||||
|
||||
const tabId = input.createTabId();
|
||||
const occupiedIds = new Set(input.reservedTabIds);
|
||||
for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId);
|
||||
const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds);
|
||||
const nextTab: WorkspaceTab = {
|
||||
tabId,
|
||||
target: input.target,
|
||||
@@ -2284,6 +2346,7 @@ function openEntityTabWithoutFocusing(input: {
|
||||
layout: WorkspaceLayout;
|
||||
target: WorkspaceTabTarget;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
return (
|
||||
insertNewTabIntoPane({
|
||||
@@ -2292,6 +2355,7 @@ function openEntityTabWithoutFocusing(input: {
|
||||
now: Date.now(),
|
||||
placement: AMBIENT_PLACEMENT,
|
||||
explorerSidebarPaneId: input.explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
createTabId: () => buildDeterministicWorkspaceTabId(input.target),
|
||||
focus: false,
|
||||
})?.layout ?? input.layout
|
||||
@@ -2382,6 +2446,7 @@ function addMissingEntityTabs(input: {
|
||||
hasActivePendingTerminalCreate: boolean;
|
||||
hasActivePendingDraftCreate: boolean;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
const {
|
||||
autoOpenAgentIds,
|
||||
@@ -2412,6 +2477,7 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "agent", agentId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentAgentIds.add(agentId);
|
||||
}
|
||||
@@ -2426,6 +2492,7 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "terminal", terminalId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentTerminalIds.add(terminalId);
|
||||
}
|
||||
@@ -2525,6 +2592,7 @@ export function reconcileWorkspaceTabs(
|
||||
hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false,
|
||||
hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false,
|
||||
explorerSidebarPaneId: state.explorerSidebarPaneId,
|
||||
reservedTabIds: state.reservedTabIds,
|
||||
});
|
||||
|
||||
if (reconciledFocusedTabId) {
|
||||
|
||||
@@ -11,6 +11,22 @@ function createRandomIdValue(): string {
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
export function createWorkspaceTabInstanceId(): string {
|
||||
return `tab_${createRandomIdValue()}`;
|
||||
}
|
||||
|
||||
/** A resource-derived id may still belong to a preview slot showing another target. */
|
||||
export function allocateWorkspaceTabId(
|
||||
preferredId: string,
|
||||
occupiedIds: ReadonlySet<string>,
|
||||
): string {
|
||||
let tabId = preferredId;
|
||||
for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) {
|
||||
tabId = `${preferredId}:${suffix}`;
|
||||
}
|
||||
return tabId;
|
||||
}
|
||||
|
||||
export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = {
|
||||
createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`,
|
||||
createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`,
|
||||
|
||||
@@ -59,6 +59,84 @@ it("skips unchanged reconciliations and immediately saves real layout changes",
|
||||
);
|
||||
});
|
||||
|
||||
it("hydrates a saved preview collision and persists the repaired identities", async () => {
|
||||
const workspaceKey = "server:workspace";
|
||||
const duplicateId = "file_a.ts";
|
||||
const values = new Map([
|
||||
[
|
||||
"workspace-layout-state",
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
state: {
|
||||
layoutByWorkspace: {
|
||||
[workspaceKey]: {
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "split",
|
||||
direction: "horizontal",
|
||||
sizes: [0.5, 0.5],
|
||||
children: [
|
||||
{ id: "main", path: "b.ts" },
|
||||
{ id: "right", path: "a.ts" },
|
||||
].map(({ id, path }) => ({
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id,
|
||||
tabIds: [duplicateId],
|
||||
focusedTabId: duplicateId,
|
||||
tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }],
|
||||
},
|
||||
})),
|
||||
},
|
||||
},
|
||||
focusedPaneId: "right",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
]);
|
||||
const storage: StateStorage = {
|
||||
getItem: (name) => values.get(name) ?? null,
|
||||
setItem: (name, value) => {
|
||||
values.set(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
values.delete(name);
|
||||
},
|
||||
};
|
||||
const store = createWorkspaceLayoutStore(undefined, storage);
|
||||
await store.persist.rehydrate();
|
||||
const layout = store.getState().layoutByWorkspace[workspaceKey];
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([
|
||||
"file_b.ts",
|
||||
"file_a.ts",
|
||||
]);
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "b.ts",
|
||||
});
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "a.ts",
|
||||
});
|
||||
store.getState().focusTab(workspaceKey, "file_b.ts");
|
||||
expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main");
|
||||
|
||||
const reloaded = createWorkspaceLayoutStore(undefined, storage);
|
||||
await reloaded.persist.rehydrate();
|
||||
expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual(
|
||||
store.getState().layoutByWorkspace[workspaceKey],
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => {
|
||||
const values = new Map<string, string>();
|
||||
const storage: StateStorage = {
|
||||
|
||||
@@ -906,6 +906,91 @@ describe("workspace-layout-store actions", () => {
|
||||
).toEqual(override);
|
||||
});
|
||||
|
||||
it("keeps reused file tabs unique and focuses the matching split pane", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
const firstTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" });
|
||||
const rightPaneId = store.splitPaneEmpty(workspaceKey, {
|
||||
targetPaneId: "main",
|
||||
position: "right",
|
||||
});
|
||||
if (!rightPaneId) throw new Error("Expected a right split pane");
|
||||
const rightTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
placement: { mode: "pane", paneId: rightPaneId },
|
||||
})!;
|
||||
|
||||
store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/b.ts" },
|
||||
intent: "reveal",
|
||||
});
|
||||
store.focusTab(workspaceKey, rightTabId);
|
||||
|
||||
const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
|
||||
const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file");
|
||||
expect({
|
||||
fileTabCount: fileTabs.length,
|
||||
uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size,
|
||||
fileTargets: fileTabs.map((tab) => tab.target),
|
||||
focusedPaneId: layout.focusedPaneId,
|
||||
}).toEqual({
|
||||
fileTabCount: 2,
|
||||
uniqueFileTabCount: 2,
|
||||
fileTargets: [
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
],
|
||||
focusedPaneId: rightPaneId,
|
||||
});
|
||||
});
|
||||
|
||||
it("allocates distinct ids across retained tabs, sheets, and background opens", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds);
|
||||
const store = layoutStore.getState();
|
||||
const fileTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" });
|
||||
layoutStore.setState({ layoutMode: "compact" });
|
||||
const sheetTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
const selectedSheet = selectSheetTab(layoutStore.getState(), {
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
});
|
||||
expect(selectedSheet?.tab.tabId).toBe(sheetTabId);
|
||||
const backgroundTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "background",
|
||||
})!;
|
||||
|
||||
expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3);
|
||||
expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1);
|
||||
expect(
|
||||
collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root)
|
||||
.filter((tab) => tab.target.kind === "file")
|
||||
.map((tab) => tab.target),
|
||||
).toEqual([
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the tab instance when a panel receives a same-kind replacement", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
@@ -3200,6 +3285,75 @@ describe("workspace-layout-store actions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => {
|
||||
const file = (tabId: string, path: string) => ({
|
||||
tabId,
|
||||
target: { kind: "file", path },
|
||||
createdAt: 1,
|
||||
state: { treeVisible: true, treeWidth: 280 },
|
||||
});
|
||||
const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")];
|
||||
const rightTabs = [
|
||||
file("file_a.ts", "a.ts"),
|
||||
file("file_b.ts", "b.ts"),
|
||||
file("file_b.ts:2", "b.ts"),
|
||||
file("child", "child.ts"),
|
||||
file("parent", "parent.ts"),
|
||||
];
|
||||
const layout = normalizeLayout({
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "root",
|
||||
direction: "horizontal",
|
||||
sizes: [0.4, 0.6],
|
||||
children: [
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabs: leftTabs,
|
||||
tabIds: leftTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "right",
|
||||
tabs: rightTabs,
|
||||
tabIds: rightTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
hidden: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
parentTabIdByTabId: {
|
||||
"file_a.ts": "parent",
|
||||
"file_b.ts": "file_a.ts",
|
||||
child: "parent",
|
||||
},
|
||||
});
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs).toHaveLength(7);
|
||||
expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7);
|
||||
expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" });
|
||||
expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" });
|
||||
expect(tabs.slice(2)).toEqual(rightTabs);
|
||||
expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]);
|
||||
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3");
|
||||
expect(findPaneById(layout.root, "right")).toMatchObject({
|
||||
hidden: true,
|
||||
focusedTabId: "file_a.ts",
|
||||
});
|
||||
expect(layout.parentTabIdByTabId).toEqual({ child: "parent" });
|
||||
expect(normalizeLayout(layout)).toEqual(layout);
|
||||
});
|
||||
|
||||
it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => {
|
||||
const tabs = [
|
||||
{
|
||||
@@ -5110,6 +5264,50 @@ describe("compact workspace sheet", () => {
|
||||
expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]);
|
||||
});
|
||||
|
||||
it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
const store = createCompactStore();
|
||||
store.getState().openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child-a" },
|
||||
intent: "reveal",
|
||||
});
|
||||
const sheetId = requireTopSheet(store).tab.tabId;
|
||||
store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" });
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
|
||||
store.getState().reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["root", "child-a", "child-b"],
|
||||
autoOpenAgentIds: ["child-a"],
|
||||
knownTerminalIds: ["term-1"],
|
||||
standaloneTerminalIds: ["term-1"],
|
||||
});
|
||||
const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find(
|
||||
(candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a",
|
||||
);
|
||||
if (!tab) throw new Error("Expected the root agent's tab");
|
||||
expect(tab.tabId).not.toBe(sheetId);
|
||||
|
||||
store.getState().closeTab(workspaceKey, tab.tabId);
|
||||
expect(requireTopSheet(store).tab).toMatchObject({
|
||||
tabId: sheetId,
|
||||
target: { kind: "agent", agentId: "child-b" },
|
||||
});
|
||||
expect(
|
||||
collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root),
|
||||
).not.toContainEqual(tab);
|
||||
});
|
||||
|
||||
it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
|
||||
@@ -7,6 +7,8 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage"
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import {
|
||||
allocateWorkspaceTabId,
|
||||
createWorkspaceTabInstanceId,
|
||||
defaultWorkspaceLayoutIds,
|
||||
type WorkspaceLayoutIdSource,
|
||||
} from "@/stores/workspace-layout-ids";
|
||||
@@ -431,14 +433,6 @@ function trimNonEmpty(value: string | null | undefined): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function createWorkspaceTabInstanceId(): string {
|
||||
const value =
|
||||
typeof globalThis.crypto?.randomUUID === "function"
|
||||
? globalThis.crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
return `tab_${value}`;
|
||||
}
|
||||
|
||||
function addAgentIdToWorkspaceSet(
|
||||
state: Record<string, Set<string>>,
|
||||
workspaceKey: string,
|
||||
@@ -531,7 +525,10 @@ export function selectExplorerSidebarPaneId(
|
||||
*/
|
||||
export function selectSheetTab(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutMode" | "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId">,
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId"> & {
|
||||
/** A host outside the sheet stack owns its instance identity. */
|
||||
preferredTabId?: string;
|
||||
},
|
||||
): SheetTab | null {
|
||||
const workspaceKey = trimNonEmpty(input.workspaceKey);
|
||||
const target = normalizeWorkspaceTabTarget(input.target);
|
||||
@@ -539,9 +536,14 @@ export function selectSheetTab(
|
||||
const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal");
|
||||
if (!policy) return null;
|
||||
return placeTargetInSheet({
|
||||
kept: undefined,
|
||||
occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey),
|
||||
kept: input.preferredTabId
|
||||
? undefined
|
||||
: getSheets(state, workspaceKey).find(
|
||||
(sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target),
|
||||
),
|
||||
target,
|
||||
intent: "reveal",
|
||||
createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target),
|
||||
policy,
|
||||
parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId),
|
||||
state: undefined,
|
||||
@@ -638,6 +640,7 @@ function getOpenTabPlacement(
|
||||
layout: WorkspaceLayout;
|
||||
placement: WorkspaceTabPlacement;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: Set<string>;
|
||||
} {
|
||||
const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey);
|
||||
const explorerSidebarPaneId = resolveExplorerSidebarPaneId(
|
||||
@@ -670,6 +673,7 @@ function getOpenTabPlacement(
|
||||
layout,
|
||||
placement: resolvedPlacement,
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -815,11 +819,23 @@ function resolveOpenParentTabId(
|
||||
return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId;
|
||||
}
|
||||
|
||||
function collectWorkspaceTabIds(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
workspaceKey: string,
|
||||
): Set<string> {
|
||||
const layout = state.layoutByWorkspace[workspaceKey];
|
||||
return new Set([
|
||||
...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []),
|
||||
...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId),
|
||||
]);
|
||||
}
|
||||
|
||||
function placeTargetInSheet(input: {
|
||||
occupiedTabIds: ReadonlySet<string>;
|
||||
/** The sheet whose tab the target keeps, if any. */
|
||||
kept: SheetTab | undefined;
|
||||
target: WorkspaceTabTarget;
|
||||
intent: WorkspaceTabOpenIntent;
|
||||
createTabId: () => string;
|
||||
policy: CompactSheetPolicy;
|
||||
parentTabId: string | null;
|
||||
state: JsonValue | undefined;
|
||||
@@ -829,10 +845,7 @@ function placeTargetInSheet(input: {
|
||||
}
|
||||
return {
|
||||
tab: {
|
||||
tabId:
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(input.target)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds),
|
||||
target: input.target,
|
||||
createdAt: Date.now(),
|
||||
...(input.state !== undefined ? { state: input.state } : {}),
|
||||
@@ -853,6 +866,7 @@ function promoteSheetToTab(
|
||||
): { tabId: string; patch: Partial<WorkspaceLayoutStore> } | null {
|
||||
const { tab } = sheet;
|
||||
const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT);
|
||||
placement.reservedTabIds.delete(tab.tabId);
|
||||
const input = {
|
||||
...placement,
|
||||
target: tab.target,
|
||||
@@ -1122,9 +1136,13 @@ export function createWorkspaceLayoutStore(
|
||||
const sheets = getSheets(get(), normalizedWorkspaceKey);
|
||||
const { keptIndex } = sheetPlacement;
|
||||
const sheet = placeTargetInSheet({
|
||||
occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey),
|
||||
kept: keptIndex === null ? undefined : sheets[keptIndex],
|
||||
target: normalizedTarget,
|
||||
intent: input.intent,
|
||||
createTabId: () =>
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(normalizedTarget)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
policy: sheetPlacement.policy,
|
||||
parentTabId,
|
||||
state: input.state,
|
||||
@@ -1706,9 +1724,14 @@ export function createWorkspaceLayoutStore(
|
||||
explorerSidebarPaneId,
|
||||
rawLayout.focusedPaneId,
|
||||
);
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const nextState = reconcileWorkspaceTabs(
|
||||
{
|
||||
layout: currentLayout,
|
||||
reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)),
|
||||
pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
explorerSidebarPaneId,
|
||||
@@ -1730,10 +1753,6 @@ export function createWorkspaceLayoutStore(
|
||||
);
|
||||
}
|
||||
}
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const sheetAgentGone = fittingSheets.length !== sheets.length;
|
||||
if (
|
||||
state.layoutByWorkspace[normalizedWorkspaceKey] &&
|
||||
|
||||
@@ -138,6 +138,88 @@ describe("useSubagentSheetTab", () => {
|
||||
expect(result.current?.tab.tabId).toBe(tabId);
|
||||
});
|
||||
|
||||
it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
const reusedId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
intent: "reveal",
|
||||
asTab: true,
|
||||
});
|
||||
if (!reusedId) throw new Error("Expected a child tab");
|
||||
store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" });
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheetId = result.current?.tab.tabId;
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(sheetId).not.toBe(reusedId);
|
||||
|
||||
act(() => {
|
||||
store.reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["parent", "child"],
|
||||
autoOpenAgentIds: [],
|
||||
knownTerminalIds: [],
|
||||
standaloneTerminalIds: [],
|
||||
});
|
||||
});
|
||||
expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId);
|
||||
expect(result.current?.tab.tabId).toBe(sheetId);
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
});
|
||||
|
||||
it("promotes a menu sheet to the subagent's own tab", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
|
||||
let promotedId: string | null = null;
|
||||
act(() => {
|
||||
promotedId = store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(promotedId).toBe("agent_child");
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: "agent_child",
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not reuse a menu id retained by a promoted tab showing another target", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
act(() => {
|
||||
store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(result.current).toBeNull();
|
||||
|
||||
act(() => {
|
||||
store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" });
|
||||
});
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId);
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: sheet.tab.tabId,
|
||||
target: { kind: "agent", agentId: "other" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("hands a re-rendered row the same sheet", () => {
|
||||
const row = seedParentWithChild();
|
||||
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
useWorkspaceLayoutStore,
|
||||
type SheetTab,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { SubagentRow } from "./select";
|
||||
|
||||
@@ -32,6 +33,9 @@ export function useSubagentSheetTab(
|
||||
const sheets = useWorkspaceLayoutStore((state) =>
|
||||
workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined,
|
||||
);
|
||||
// Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening
|
||||
// it as a tab lands on that id, and keeps the id it was given across layout updates.
|
||||
const tabIds = useMemo(() => new Map<string, string>(), []);
|
||||
return useMemo(() => {
|
||||
// One answer per row until the state it reads changes, so a re-render of the list hands an
|
||||
// open sheet the same tab rather than a fresh one.
|
||||
@@ -43,16 +47,19 @@ export function useSubagentSheetTab(
|
||||
layoutByWorkspace: layout ? { [workspaceKey]: layout } : {},
|
||||
sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {},
|
||||
};
|
||||
const key = `${row.kind}:${row.id}`;
|
||||
const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]);
|
||||
const known = answers.get(key);
|
||||
if (known !== undefined) return known;
|
||||
const target = subagentRowTarget(row);
|
||||
const sheet = selectSheetTab(state, {
|
||||
workspaceKey,
|
||||
target: subagentRowTarget(row),
|
||||
target,
|
||||
parentTabId,
|
||||
preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target),
|
||||
});
|
||||
if (sheet) tabIds.set(key, sheet.tab.tabId);
|
||||
answers.set(key, sheet);
|
||||
return sheet;
|
||||
};
|
||||
}, [layout, layoutMode, parentTabId, sheets, workspaceKey]);
|
||||
}, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]);
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ import {
|
||||
normalizeStoredHostProfile,
|
||||
orderHostsLocalFirst,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
relayConnectionFromOffer,
|
||||
resolveActiveHostServerId,
|
||||
upsertHostConnectionInProfiles,
|
||||
writeHostRegistry,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
} from "./host-connection";
|
||||
@@ -87,6 +89,25 @@ describe("normalizeStoredHostProfile", () => {
|
||||
expect(profile?.connections[0]).not.toHaveProperty("password");
|
||||
});
|
||||
|
||||
it("drops a connection kind this build doesn't know and keeps the host", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_mixed",
|
||||
password: "secret",
|
||||
connections: [
|
||||
{ id: "future:1", type: "futureKind", address: "future.example.com" },
|
||||
{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true },
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" },
|
||||
],
|
||||
preferredConnectionId: "direct:remote:6767",
|
||||
});
|
||||
|
||||
expect(profile?.password).toBe("secret");
|
||||
expect(profile?.connections).toEqual([
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false },
|
||||
]);
|
||||
expect(profile?.preferredConnectionId).toBe("direct:remote:6767");
|
||||
});
|
||||
|
||||
it("preserves legacy relay ids when TLS is absent", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_relay",
|
||||
@@ -177,6 +198,59 @@ describe("normalizeStoredHostProfile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("readHostRegistry and writeHostRegistry", () => {
|
||||
const direct: HostConnection = {
|
||||
id: "direct:lan:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan:6767",
|
||||
useTls: false,
|
||||
};
|
||||
const future = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
|
||||
it("writes back every entry it could not read", () => {
|
||||
const unreadableHost = { serverId: "srv_future", connections: [future] };
|
||||
const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 };
|
||||
const stored = [
|
||||
{ ...makeHost("srv_a"), connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
];
|
||||
|
||||
const { hosts, unreadable } = readHostRegistry(stored);
|
||||
expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]);
|
||||
expect(hosts[0]?.connections).toEqual([direct]);
|
||||
|
||||
expect(writeHostRegistry(hosts, unreadable)).toEqual([
|
||||
{ ...hosts[0], connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
]);
|
||||
});
|
||||
|
||||
it("writes a host saved again by this build in place of the entry it could not read", () => {
|
||||
const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]);
|
||||
expect(hosts).toEqual([]);
|
||||
|
||||
const saved = { ...makeHost("srv_a"), connections: [direct] };
|
||||
expect(writeHostRegistry([saved], unreadable)).toEqual([saved]);
|
||||
});
|
||||
|
||||
it("moves a stored direct TCP password to its host next to a connection it can't read", () => {
|
||||
const registry = readHostRegistry([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(registry.movedConnectionPassword).toBe(true);
|
||||
expect(registry.hosts[0]?.password).toBe("old-secret");
|
||||
expect(registry.hosts[0]?.connections).toEqual([direct]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRemoteSshHostConnection", () => {
|
||||
it("keeps optional SSH settings absent", () => {
|
||||
expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({
|
||||
|
||||
@@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({
|
||||
label: z.string().optional(),
|
||||
appearance: HostAppearanceSchema.optional(),
|
||||
lifecycle: z.strictObject({}).optional(),
|
||||
connections: z.array(StoredHostConnectionSchema).min(1),
|
||||
// Read one by one, so a connection kind another build wrote skips only that connection.
|
||||
connections: z.array(z.unknown()).min(1),
|
||||
preferredConnectionId: z.string().nullable().optional(),
|
||||
createdAt: z.string().datetime({ offset: true }).optional(),
|
||||
updatedAt: z.string().datetime({ offset: true }).optional(),
|
||||
});
|
||||
export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema);
|
||||
type StoredHostConnection = z.infer<typeof StoredHostConnectionSchema>;
|
||||
|
||||
function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null {
|
||||
@@ -590,20 +590,37 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec
|
||||
}
|
||||
|
||||
export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
|
||||
return readStoredHost(entry)?.profile ?? null;
|
||||
}
|
||||
|
||||
interface StoredHostRead {
|
||||
profile: HostProfile;
|
||||
unreadableConnections: unknown[];
|
||||
movedConnectionPassword: boolean;
|
||||
}
|
||||
|
||||
function readStoredHost(entry: unknown): StoredHostRead | null {
|
||||
const result = StoredHostProfileSchema.safeParse(entry);
|
||||
if (!result.success) {
|
||||
return null;
|
||||
}
|
||||
const record = result.data;
|
||||
const serverId = record.serverId;
|
||||
const storedConnections: StoredHostConnection[] = [];
|
||||
const unreadableConnections: unknown[] = [];
|
||||
for (const stored of record.connections) {
|
||||
const parsed = StoredHostConnectionSchema.safeParse(stored);
|
||||
if (parsed.success) storedConnections.push(parsed.data);
|
||||
else unreadableConnections.push(stored);
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated.
|
||||
const legacyPassword = record.connections.find(
|
||||
const legacyPassword = storedConnections.find(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
);
|
||||
const password =
|
||||
record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined);
|
||||
|
||||
const connections = record.connections
|
||||
const connections = storedConnections
|
||||
.map((connection) => normalizeStoredConnection(connection))
|
||||
.filter((connection): connection is HostConnection => connection !== null);
|
||||
if (connections.length === 0) {
|
||||
@@ -620,18 +637,90 @@ export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
|
||||
: (connections[0]?.id ?? null);
|
||||
|
||||
return {
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
profile: {
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
},
|
||||
unreadableConnections,
|
||||
movedConnectionPassword: legacyPassword !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stored registry entries this build can't read, such as a connection kind added by a newer
|
||||
* build. `writeHostRegistry` writes them back so that build still finds them.
|
||||
*/
|
||||
export interface UnreadableHostEntries {
|
||||
hosts: unknown[];
|
||||
connectionsByServerId: Map<string, unknown[]>;
|
||||
}
|
||||
|
||||
export function readHostRegistry(stored: unknown[]): {
|
||||
hosts: HostProfile[];
|
||||
unreadable: UnreadableHostEntries;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
movedConnectionPassword: boolean;
|
||||
} {
|
||||
const hosts: HostProfile[] = [];
|
||||
const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
let movedConnectionPassword = false;
|
||||
for (const entry of stored) {
|
||||
const read = readStoredHost(entry);
|
||||
if (!read) {
|
||||
unreadable.hosts.push(entry);
|
||||
continue;
|
||||
}
|
||||
hosts.push(read.profile);
|
||||
if (read.unreadableConnections.length > 0) {
|
||||
unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections);
|
||||
}
|
||||
movedConnectionPassword ||= read.movedConnectionPassword;
|
||||
}
|
||||
return { hosts, unreadable, movedConnectionPassword };
|
||||
}
|
||||
|
||||
export function writeHostRegistry(
|
||||
hosts: HostProfile[],
|
||||
unreadable: UnreadableHostEntries,
|
||||
): unknown[] {
|
||||
const savedServerIds = new Set(hosts.map((host) => host.serverId));
|
||||
const written: unknown[] = hosts.map((host) => {
|
||||
const kept = unreadable.connectionsByServerId.get(host.serverId);
|
||||
return kept ? { ...host, connections: [...host.connections, ...kept] } : host;
|
||||
});
|
||||
for (const entry of unreadable.hosts) {
|
||||
// A host this build saved again replaces the entry it couldn't read.
|
||||
const serverId = readStoredServerId(entry);
|
||||
if (serverId === null || !savedServerIds.has(serverId)) written.push(entry);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/** Drops the entries this build couldn't read for a host you removed. */
|
||||
export function forgetUnreadableHost(
|
||||
unreadable: UnreadableHostEntries,
|
||||
serverId: string,
|
||||
): UnreadableHostEntries {
|
||||
const connectionsByServerId = new Map(unreadable.connectionsByServerId);
|
||||
connectionsByServerId.delete(serverId);
|
||||
return {
|
||||
hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId),
|
||||
connectionsByServerId,
|
||||
};
|
||||
}
|
||||
|
||||
function readStoredServerId(entry: unknown): string | null {
|
||||
if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null;
|
||||
return typeof entry.serverId === "string" ? entry.serverId.trim() : null;
|
||||
}
|
||||
|
||||
export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean {
|
||||
return host.connections.some((existing) => hostConnectionEquals(existing, connection));
|
||||
}
|
||||
|
||||
@@ -2437,6 +2437,36 @@ describe("Codex app-server provider", () => {
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("lets idle cleanup release a session opened only to read its history", async () => {
|
||||
let spawns = 0;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"thread/resume": () =>
|
||||
Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))),
|
||||
"thread/read": () => ({ thread: { turns: [] } }),
|
||||
});
|
||||
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
|
||||
appServerProcess: createFakeCodexAppServerProcess(() => {
|
||||
spawns += 1;
|
||||
return appServer.child;
|
||||
}),
|
||||
});
|
||||
const internals = castInternals<{
|
||||
goalsEnabledPromise: Promise<boolean> | null;
|
||||
autoReviewEnabledPromise: Promise<boolean> | null;
|
||||
}>(provider);
|
||||
internals.goalsEnabledPromise = Promise.resolve(false);
|
||||
internals.autoReviewEnabledPromise = Promise.resolve(false);
|
||||
|
||||
const session = await provider.resumeSession(archivedThreadHandle(), undefined, undefined, {
|
||||
purpose: "history",
|
||||
});
|
||||
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
expect(spawns).toBe(1);
|
||||
await session.close();
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => {
|
||||
const threadRequests: string[] = [];
|
||||
let resumeAttempts = 0;
|
||||
|
||||
@@ -5385,6 +5385,8 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async canStopRuntime(): Promise<boolean> {
|
||||
// A history session released its app-server once it read the thread, so nothing runs.
|
||||
if (this.connectionState === "history-ready") return true;
|
||||
if (
|
||||
!this.client ||
|
||||
this.client.hasPendingRequests() ||
|
||||
|
||||
@@ -2477,6 +2477,42 @@ describe("OpenCode adapter startTurn error handling", () => {
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("reports a question rejected by a human steer as resolved", async () => {
|
||||
const { parent: session, openCode } = await createParentSession("ses_steer_question");
|
||||
openCode.sessionPromptAsyncEvents = [];
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
const { turnId } = await session.startTurn("first");
|
||||
openCode.emitEvent({
|
||||
type: "question.asked",
|
||||
properties: {
|
||||
id: "question-steer",
|
||||
sessionID: "ses_steer_question",
|
||||
questions: [{ question: "Which color?", header: "Color", options: [] }],
|
||||
},
|
||||
});
|
||||
await vi.waitFor(() => expect(session.getPendingPermissions()).toHaveLength(1));
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn?.("never mind", {
|
||||
expectedTurnId: turnId,
|
||||
clearPendingPermissions: true,
|
||||
}),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
|
||||
expect(openCode.calls.questionReject).toContainEqual(
|
||||
expect.objectContaining({ requestID: "question-steer" }),
|
||||
);
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "permission_resolved",
|
||||
requestId: "question-steer",
|
||||
resolution: expect.objectContaining({ behavior: "deny" }),
|
||||
}),
|
||||
);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("keeps multiple native steers correlated in admission order", async () => {
|
||||
const { parent: session, openCode } = await createParentSession("ses_native_steer_fifo");
|
||||
openCode.sessionPromptAsyncEvents = [];
|
||||
|
||||
@@ -5049,22 +5049,24 @@ class OpenCodeAgentSession implements AgentSession {
|
||||
answers,
|
||||
});
|
||||
}
|
||||
|
||||
this.pendingPermissions.delete(requestId);
|
||||
this.pendingPermissionDirectories.delete(requestId);
|
||||
return;
|
||||
} else {
|
||||
const reply = resolveOpenCodePermissionReply(response);
|
||||
await this.client.permission.reply({
|
||||
requestID: requestId,
|
||||
directory,
|
||||
reply,
|
||||
message: response.behavior === "deny" ? response.message : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const reply = resolveOpenCodePermissionReply(response);
|
||||
await this.client.permission.reply({
|
||||
requestID: requestId,
|
||||
directory,
|
||||
reply,
|
||||
message: response.behavior === "deny" ? response.message : undefined,
|
||||
});
|
||||
|
||||
this.pendingPermissions.delete(requestId);
|
||||
this.pendingPermissionDirectories.delete(requestId);
|
||||
this.notifySubscribers({
|
||||
type: "permission_resolved",
|
||||
provider: "opencode",
|
||||
requestId,
|
||||
resolution: response,
|
||||
});
|
||||
}
|
||||
|
||||
describePersistence(): AgentPersistenceHandle | null {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { beforeAll, beforeEach, describe, test, expect } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import {
|
||||
canRunRealProvider,
|
||||
createRealProviderClients,
|
||||
getRealProviderConfig,
|
||||
} from "./real-provider-test-config.js";
|
||||
|
||||
async function readStatusAndPendingIds(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
): Promise<{ status: string; pendingIds: string[] }> {
|
||||
const fetched = await client.fetchAgent(agentId);
|
||||
const snapshot = fetched!.agent;
|
||||
const pendingIds = (snapshot.pendingPermissions ?? []).map((pending) => pending.id);
|
||||
return { status: snapshot.status, pendingIds };
|
||||
}
|
||||
|
||||
describe("daemon E2E (real opencode) - a message sent instead of answering a question", () => {
|
||||
let canRun = false;
|
||||
|
||||
beforeAll(async () => {
|
||||
canRun = await canRunRealProvider("opencode");
|
||||
});
|
||||
|
||||
beforeEach((context) => {
|
||||
if (!canRun) {
|
||||
context.skip();
|
||||
}
|
||||
});
|
||||
|
||||
test("removes the superseded question from the pending list", async () => {
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-opencode-question-"));
|
||||
const logger = pino({ level: "silent" });
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: createRealProviderClients(["opencode"], logger),
|
||||
logger,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
|
||||
try {
|
||||
const agent = await client.createAgent({
|
||||
...getRealProviderConfig("opencode"),
|
||||
cwd,
|
||||
title: "OpenCode superseded question",
|
||||
});
|
||||
|
||||
await client.sendMessage(
|
||||
agent.id,
|
||||
[
|
||||
"Use the question tool to ask me exactly one clarifying question:",
|
||||
"What color should the button be?",
|
||||
"Wait for my answer before doing anything else.",
|
||||
].join(" "),
|
||||
);
|
||||
await client.waitForAgentUpsert(
|
||||
agent.id,
|
||||
(snapshot) => snapshot.pendingPermissions?.[0]?.kind === "question",
|
||||
120_000,
|
||||
);
|
||||
|
||||
// The app sends with the default send setting, which steers the running turn.
|
||||
await client.sendMessage(agent.id, "Never mind the question. Reply with the word done.", {
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
// OpenCode rejects the question and runs the steer message to completion.
|
||||
await expect
|
||||
.poll(() => readStatusAndPendingIds(client, agent.id), {
|
||||
timeout: 120_000,
|
||||
interval: 1_000,
|
||||
})
|
||||
.toEqual({ status: "idle", pendingIds: [] });
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 300_000);
|
||||
});
|
||||
@@ -193,10 +193,11 @@ test("classifies a removed file as deleted", async () => {
|
||||
});
|
||||
|
||||
await rm(target);
|
||||
// Native recursive delivery can be coalesced before the backend's deletion audit.
|
||||
// Assert eventual classification without imposing Vitest's one-second default.
|
||||
// macOS FSEvents can replay the write above as a create after the subscription starts,
|
||||
// so the delete is the latest event for the path, not the first. Native recursive delivery
|
||||
// can also be coalesced before the backend's deletion audit, hence the longer timeout.
|
||||
await expect
|
||||
.poll(() => events.find((event) => event.path === target)?.type, { timeout: 10_000 })
|
||||
.poll(() => events.findLast((event) => event.path === target)?.type, { timeout: 10_000 })
|
||||
.toBe("delete");
|
||||
await subscription.unsubscribe();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user