mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 10:15:46 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
713b6dbbfe | ||
|
|
32c3805aad |
@@ -61,11 +61,6 @@ the chat and its replica cache would keep only the end of the reply. A recovery
|
||||
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
|
||||
row by row and an older cursor repeats rows.
|
||||
|
||||
A live row whose epoch differs from the local cursor is a rewind or replacement this client never
|
||||
saw as an invalidation, not a stale row. The app recovers like a gap: it asks `after` its own
|
||||
cursor, and the daemon answers that stale epoch with a reset tail. Dropping the rows instead would
|
||||
leave the chat on pre-rewind history while the new epoch streams.
|
||||
|
||||
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
|
||||
|
||||
Opening or resuming an agent fetches the latest available turns with a soft target of 40
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-B2hX/4xDGTtFC2LBRL/0US3YERfM/cDXvu8cjztpsd8=
|
||||
sha256-6XXAVBTH6rIdg5eQ9cUeUwV22ikVqTtdWo7i9DYO+/M=
|
||||
|
||||
@@ -15,12 +15,8 @@ import {
|
||||
disableTailscale,
|
||||
enableTailscale,
|
||||
expectTailscaleAddress,
|
||||
expectTailscaleAvailable,
|
||||
expectTailscaleRowLoadsOn,
|
||||
expectTailscaleUnavailable,
|
||||
observeDaemonStatusPolling,
|
||||
openSetupMobileStep,
|
||||
refreshTailscaleAvailability,
|
||||
slowConnectionToHost,
|
||||
expectTailscaleUpdateRequired,
|
||||
expectCompletePairingQr,
|
||||
@@ -114,54 +110,3 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("refreshes Tailscale availability in place after Tailscale starts", async ({
|
||||
page,
|
||||
baseURL,
|
||||
}) => {
|
||||
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
||||
test.setTimeout(120_000);
|
||||
if (!baseURL) throw new Error("Expected the app base URL");
|
||||
const daemon = await startTailscaleTestDaemon(baseURL, { initialAvailable: false });
|
||||
const statusPolling = observeDaemonStatusPolling(page, daemon.port);
|
||||
try {
|
||||
await preparePairingHost(page, daemon);
|
||||
await expectTailscaleUnavailable(page);
|
||||
|
||||
await test.step("Refreshing while still unavailable shows progress and stays unavailable", async () => {
|
||||
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 250);
|
||||
await preparePairingHost(page, daemon);
|
||||
await expectTailscaleUnavailable(page);
|
||||
await refreshTailscaleAvailability(page);
|
||||
await page.getByRole("button", { name: "Refreshing...", exact: true }).waitFor();
|
||||
await expectTailscaleUnavailable(page);
|
||||
restoreSpeed();
|
||||
});
|
||||
|
||||
await test.step("Refreshing after Tailscale starts enables the switch in place", async () => {
|
||||
await statusPolling.waitForFreshPollWindow();
|
||||
await daemon.setTailscaleAvailable(true);
|
||||
const refreshRequest = statusPolling.waitForStatusRequest(1_000);
|
||||
await refreshTailscaleAvailability(page);
|
||||
await refreshRequest;
|
||||
await expectTailscaleAvailable(page, { timeout: 1_000 });
|
||||
await enableTailscale(page);
|
||||
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
||||
await disableTailscale(page, daemon.tailscaleAddress);
|
||||
});
|
||||
|
||||
await test.step("Setup mobile step also refreshes Tailscale availability in place", async () => {
|
||||
await daemon.setTailscaleAvailable(false);
|
||||
await openSetupMobileStep(page, daemon);
|
||||
await expectTailscaleUnavailable(page);
|
||||
await statusPolling.waitForFreshPollWindow();
|
||||
await daemon.setTailscaleAvailable(true);
|
||||
const refreshRequest = statusPolling.waitForStatusRequest(1_000);
|
||||
await refreshTailscaleAvailability(page);
|
||||
await refreshRequest;
|
||||
await expectTailscaleAvailable(page, { timeout: 1_000 });
|
||||
});
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -358,88 +358,6 @@ export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
await expect(
|
||||
page.getByText("Tailscale is not running on this host", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "Get Tailscale", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Refresh", exact: true })).toBeEnabled();
|
||||
}
|
||||
|
||||
export async function refreshTailscaleAvailability(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
}
|
||||
|
||||
export async function expectTailscaleAvailable(
|
||||
page: Page,
|
||||
options?: { timeout?: number },
|
||||
): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Refresh", exact: true })).toHaveCount(0, options);
|
||||
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
||||
await expect(toggle).toBeEnabled(options);
|
||||
await expect(toggle).not.toBeChecked(options);
|
||||
await expect(
|
||||
page.getByText("Direct over your tailnet, enter an address", { exact: true }),
|
||||
).toBeVisible(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks `daemon.get_status` frames on the host socket so Refresh tests can align right after a
|
||||
* 2-second poll and verify the button click itself sent a fresh status request.
|
||||
*/
|
||||
export function observeDaemonStatusPolling(page: Page, port: number) {
|
||||
let lastResponseAt = 0;
|
||||
let waitingForResponse: (() => void) | null = null;
|
||||
let waitingForRequest: (() => void) | null = null;
|
||||
page.on("websocket", (socket) => {
|
||||
if (!socket.url().includes(`:${port}`)) return;
|
||||
socket.on("framesent", ({ payload }) => {
|
||||
const message = typeof payload === "string" ? payload : payload.toString();
|
||||
if (message.includes('"type":"daemon.get_status.request"')) {
|
||||
waitingForRequest?.();
|
||||
waitingForRequest = null;
|
||||
}
|
||||
});
|
||||
socket.on("framereceived", ({ payload }) => {
|
||||
const message = typeof payload === "string" ? payload : payload.toString();
|
||||
if (message.includes('"type":"daemon.get_status.response"')) {
|
||||
lastResponseAt = Date.now();
|
||||
waitingForResponse?.();
|
||||
waitingForResponse = null;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
async waitForFreshPollWindow(): Promise<void> {
|
||||
if (Date.now() - lastResponseAt < 250) return;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
waitingForResponse = null;
|
||||
reject(new Error("Timed out waiting for daemon status poll"));
|
||||
}, 5_000);
|
||||
waitingForResponse = () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
},
|
||||
waitForStatusRequest(timeoutMs = 1_000): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
waitingForRequest = null;
|
||||
reject(new Error("Refresh did not send daemon.get_status.request"));
|
||||
}, timeoutMs);
|
||||
waitingForRequest = () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function openPairDeviceModal(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
||||
|
||||
@@ -4,18 +4,13 @@ import { z } from "zod";
|
||||
import { killProcessTree, spawnTsx } from "./spawn-node";
|
||||
|
||||
const readySchema = z.object({ port: z.number(), serverId: z.string() });
|
||||
const ackSchema = z.object({ type: z.literal("tailscale-available-set"), available: z.boolean() });
|
||||
|
||||
export async function startTailscaleTestDaemon(
|
||||
origin: string,
|
||||
options?: { initialAvailable?: boolean },
|
||||
) {
|
||||
export async function startTailscaleTestDaemon(origin: string) {
|
||||
const entrypoint = path.resolve(
|
||||
__dirname,
|
||||
"../../../../server/src/server/test-utils/tailscale-daemon.ts",
|
||||
);
|
||||
const initialMode = options?.initialAvailable === false ? "unavailable" : "available";
|
||||
const child = spawnTsx(entrypoint, [origin, initialMode], {
|
||||
const child = spawnTsx(entrypoint, [origin], {
|
||||
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
||||
});
|
||||
const signal = AbortSignal.timeout(30_000);
|
||||
@@ -29,16 +24,6 @@ export async function startTailscaleTestDaemon(
|
||||
return {
|
||||
...ready,
|
||||
tailscaleAddress: `127.0.0.2:${ready.port}`,
|
||||
async setTailscaleAvailable(available: boolean): Promise<void> {
|
||||
const ack = once(child, "message", { signal: AbortSignal.timeout(10_000) }).then(
|
||||
([message]) => ackSchema.parse(message),
|
||||
);
|
||||
child.send({ type: "set-tailscale-available", available });
|
||||
const result = await ack;
|
||||
if (result.available !== available) {
|
||||
throw new Error(`Expected tailscaleAvailable=${String(available)}`);
|
||||
}
|
||||
},
|
||||
close: () => killProcessTree(child),
|
||||
};
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,18 +1,7 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { RotateCw } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import {
|
||||
SettingsAction,
|
||||
SettingsRow,
|
||||
SettingsRowChildren,
|
||||
SettingsSwitch,
|
||||
} from "@/components/settings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
@@ -20,7 +9,6 @@ import { useSessionStore } from "@/stores/session-store";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { copyToClipboard } from "@/utils/copy-to-clipboard";
|
||||
import { describeTailscale } from "./tailscale-hint";
|
||||
import { resolveTailscaleControlState } from "./tailscale-state";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
|
||||
@@ -77,53 +65,18 @@ function TailscaleControl({ serverId, client }: { serverId: string; client: Host
|
||||
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
|
||||
[t],
|
||||
);
|
||||
const refreshLabel = t(
|
||||
tailscale.refreshing ? "devices.tailscale.refreshing" : "devices.tailscale.refresh",
|
||||
);
|
||||
const refreshButton = tailscale.showRefresh ? (
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
leftIcon={RotateCw}
|
||||
onPress={tailscale.refresh}
|
||||
loading={tailscale.refreshing}
|
||||
disabled={tailscale.refreshDisabled}
|
||||
accessibilityLabel={refreshLabel}
|
||||
testID="devices-tailscale-refresh"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={6}>
|
||||
<Text style={styles.tooltipText}>{refreshLabel}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null;
|
||||
const switchControl = tailscale.showSwitch ? (
|
||||
<Switch
|
||||
value={tailscale.value}
|
||||
onValueChange={tailscale.setEnabled}
|
||||
disabled={tailscale.switchDisabled}
|
||||
accessibilityLabel={LABEL}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsRow
|
||||
<SettingsSwitch
|
||||
label={LABEL}
|
||||
hint={status ? describeTailscale(status, t) : t("devices.tailscale.hint")}
|
||||
link={tailscale.showInstallLink ? installLink : undefined}
|
||||
link={status?.state === "unavailable" ? installLink : undefined}
|
||||
error={tailscale.error}
|
||||
>
|
||||
{refreshButton && switchControl ? (
|
||||
<View style={styles.controls}>
|
||||
{refreshButton}
|
||||
{switchControl}
|
||||
</View>
|
||||
) : (
|
||||
(refreshButton ?? switchControl)
|
||||
)}
|
||||
</SettingsRow>
|
||||
value={tailscale.value}
|
||||
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
|
||||
onValueChange={tailscale.setEnabled}
|
||||
/>
|
||||
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
|
||||
</>
|
||||
);
|
||||
@@ -165,18 +118,16 @@ function useTailscale(serverId: string, client: HostClient) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
|
||||
const fetchStatus = useCallback(async () => {
|
||||
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
|
||||
if (!tailscale) throw new Error("Host did not report Tailscale status");
|
||||
return tailscale;
|
||||
}, [client]);
|
||||
|
||||
const query = useFetchQuery({
|
||||
queryKey,
|
||||
queryFn: fetchStatus,
|
||||
// Tailscale can come up after the host does; polling and returning to the window pick it up.
|
||||
queryFn: async () => {
|
||||
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
|
||||
if (!tailscale) throw new Error("Host did not report Tailscale status");
|
||||
return tailscale;
|
||||
},
|
||||
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
|
||||
refetchInterval: 2_000,
|
||||
refetchOnWindowFocus: true,
|
||||
staleTimeMs: 0,
|
||||
dataShape: "value",
|
||||
});
|
||||
@@ -189,30 +140,13 @@ function useTailscale(serverId: string, client: HostClient) {
|
||||
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
|
||||
});
|
||||
|
||||
const refreshMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
return fetchStatus();
|
||||
},
|
||||
onSuccess: (tailscale) => queryClient.setQueryData(queryKey, tailscale),
|
||||
});
|
||||
|
||||
const status = query.data;
|
||||
const control = resolveTailscaleControlState({
|
||||
status,
|
||||
statusUpdatedAt: query.dataUpdatedAt,
|
||||
statusError: query.isError,
|
||||
changePending: change.isPending,
|
||||
changePendingEnabled: change.variables?.enabled,
|
||||
changeError: change.isError,
|
||||
changeErrorEnabled: change.variables?.enabled,
|
||||
refreshPending: refreshMutation.isPending,
|
||||
refreshError: refreshMutation.isError,
|
||||
refreshSubmittedAt: refreshMutation.submittedAt,
|
||||
});
|
||||
const pending = change.isPending ? change.variables.enabled : undefined;
|
||||
const on = status?.state === "on" || status?.state === "waiting";
|
||||
// Not known until the host first answers.
|
||||
const value = pending ?? (status ? on : null);
|
||||
|
||||
const { mutate, reset: resetChange } = change;
|
||||
const { mutate: runRefresh, reset: resetRefresh } = refreshMutation;
|
||||
const { mutate } = change;
|
||||
const confirmTurnOff = useCallback(
|
||||
() =>
|
||||
confirmDialog({
|
||||
@@ -225,11 +159,8 @@ function useTailscale(serverId: string, client: HostClient) {
|
||||
[t],
|
||||
);
|
||||
const turnOffConfirmed = useCallback(async () => {
|
||||
if (await confirmTurnOff()) {
|
||||
resetRefresh();
|
||||
mutate({ enabled: false, confirmed: true });
|
||||
}
|
||||
}, [confirmTurnOff, mutate, resetRefresh]);
|
||||
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
|
||||
}, [confirmTurnOff, mutate]);
|
||||
const disconnects = status?.disconnectsCurrentConnection === true;
|
||||
const setEnabled = useCallback(
|
||||
(enabled: boolean) => {
|
||||
@@ -237,7 +168,6 @@ function useTailscale(serverId: string, client: HostClient) {
|
||||
void turnOffConfirmed();
|
||||
return;
|
||||
}
|
||||
resetRefresh();
|
||||
mutate(
|
||||
{ enabled, confirmed: false },
|
||||
{
|
||||
@@ -249,38 +179,24 @@ function useTailscale(serverId: string, client: HostClient) {
|
||||
},
|
||||
);
|
||||
},
|
||||
[disconnects, mutate, resetRefresh, turnOffConfirmed],
|
||||
[disconnects, mutate, turnOffConfirmed],
|
||||
);
|
||||
const refresh = useCallback(() => {
|
||||
resetChange();
|
||||
runRefresh();
|
||||
}, [resetChange, runRefresh]);
|
||||
|
||||
let error: string | undefined;
|
||||
if (change.isError) {
|
||||
error = t(
|
||||
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
|
||||
);
|
||||
} else if (query.isError && !status) {
|
||||
error = t("devices.tailscale.statusError");
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
value: control.value,
|
||||
showSwitch: control.showSwitch,
|
||||
switchDisabled: control.switchDisabled,
|
||||
showRefresh: control.showRefresh,
|
||||
refreshing: control.refreshing,
|
||||
refreshDisabled: control.refreshDisabled,
|
||||
showInstallLink: control.showInstallLink,
|
||||
error: control.errorKey ? t(control.errorKey) : undefined,
|
||||
value,
|
||||
error,
|
||||
// A tap is ignored until the host answers the one before it.
|
||||
setEnabled: control.switchDisabled ? undefined : setEnabled,
|
||||
refresh: control.refreshDisabled ? undefined : refresh,
|
||||
address: control.address,
|
||||
setEnabled: change.isPending ? undefined : setEnabled,
|
||||
address: status?.state === "on" && value ? status.address : null,
|
||||
};
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
controls: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
tooltipText: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||
import { resolveTailscaleControlState, type TailscaleControlStateInput } from "./tailscale-state";
|
||||
|
||||
const baseInput: TailscaleControlStateInput = {
|
||||
status: undefined,
|
||||
statusUpdatedAt: 0,
|
||||
statusError: false,
|
||||
changePending: false,
|
||||
changeError: false,
|
||||
refreshPending: false,
|
||||
refreshError: false,
|
||||
refreshSubmittedAt: 0,
|
||||
};
|
||||
|
||||
const unavailable: TailscaleStatus = { ip: null, address: null, state: "unavailable" };
|
||||
const waiting: TailscaleStatus = { ip: null, address: "100.101.102.103:6767", state: "waiting" };
|
||||
const off: TailscaleStatus = { ip: "100.101.102.103", address: null, state: "off" };
|
||||
const on: TailscaleStatus = { ip: "100.101.102.103", address: "100.101.102.103:6767", state: "on" };
|
||||
|
||||
describe("resolveTailscaleControlState", () => {
|
||||
it("reserves the switch space without Refresh during initial load", () => {
|
||||
expect(resolveTailscaleControlState(baseInput)).toEqual({
|
||||
value: null,
|
||||
showSwitch: true,
|
||||
switchDisabled: true,
|
||||
showRefresh: false,
|
||||
refreshing: false,
|
||||
refreshDisabled: false,
|
||||
showInstallLink: false,
|
||||
address: null,
|
||||
errorKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows Refresh, install link, and a disabled switch when Tailscale is unavailable", () => {
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: unavailable,
|
||||
statusUpdatedAt: 1000,
|
||||
}),
|
||||
).toEqual({
|
||||
value: false,
|
||||
showSwitch: true,
|
||||
switchDisabled: true,
|
||||
showRefresh: true,
|
||||
refreshing: false,
|
||||
refreshDisabled: false,
|
||||
showInstallLink: true,
|
||||
address: null,
|
||||
errorKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows Refresh alongside the enabled switch when Tailscale is waiting", () => {
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: waiting,
|
||||
statusUpdatedAt: 1000,
|
||||
}),
|
||||
).toEqual({
|
||||
value: true,
|
||||
showSwitch: true,
|
||||
switchDisabled: false,
|
||||
showRefresh: true,
|
||||
refreshing: false,
|
||||
refreshDisabled: false,
|
||||
showInstallLink: false,
|
||||
address: null,
|
||||
errorKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("hides Refresh once Tailscale becomes available or active", () => {
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: off,
|
||||
statusUpdatedAt: 2000,
|
||||
}),
|
||||
).toMatchObject({
|
||||
value: false,
|
||||
showSwitch: true,
|
||||
switchDisabled: false,
|
||||
showRefresh: false,
|
||||
showInstallLink: false,
|
||||
address: null,
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: on,
|
||||
statusUpdatedAt: 3000,
|
||||
}),
|
||||
).toMatchObject({
|
||||
value: true,
|
||||
showSwitch: true,
|
||||
switchDisabled: false,
|
||||
showRefresh: false,
|
||||
showInstallLink: false,
|
||||
address: "100.101.102.103:6767",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows Refresh without an empty switch spacer when initial status check fails, and keeps it visible while retrying", () => {
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
statusError: true,
|
||||
}),
|
||||
).toEqual({
|
||||
value: null,
|
||||
showSwitch: false,
|
||||
switchDisabled: true,
|
||||
showRefresh: true,
|
||||
refreshing: false,
|
||||
refreshDisabled: false,
|
||||
showInstallLink: false,
|
||||
address: null,
|
||||
errorKey: "devices.tailscale.statusError",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
statusError: true,
|
||||
refreshPending: true,
|
||||
refreshSubmittedAt: 1500,
|
||||
}),
|
||||
).toEqual({
|
||||
value: null,
|
||||
showSwitch: false,
|
||||
switchDisabled: true,
|
||||
showRefresh: true,
|
||||
refreshing: true,
|
||||
refreshDisabled: true,
|
||||
showInstallLink: false,
|
||||
address: null,
|
||||
errorKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces a failed manual refresh even when a prior status is loaded, and clears it once a newer status arrives", () => {
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: unavailable,
|
||||
statusUpdatedAt: 1000,
|
||||
refreshError: true,
|
||||
refreshSubmittedAt: 2000,
|
||||
}),
|
||||
).toMatchObject({
|
||||
showRefresh: true,
|
||||
errorKey: "devices.tailscale.statusError",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: unavailable,
|
||||
statusUpdatedAt: 3000,
|
||||
refreshError: true,
|
||||
refreshSubmittedAt: 2000,
|
||||
}),
|
||||
).toMatchObject({
|
||||
showRefresh: true,
|
||||
errorKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("prevents concurrent refresh and toggle actions", () => {
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: waiting,
|
||||
statusUpdatedAt: 1000,
|
||||
refreshPending: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
switchDisabled: true,
|
||||
refreshing: true,
|
||||
refreshDisabled: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveTailscaleControlState({
|
||||
...baseInput,
|
||||
status: waiting,
|
||||
statusUpdatedAt: 1000,
|
||||
changePending: true,
|
||||
changePendingEnabled: false,
|
||||
}),
|
||||
).toMatchObject({
|
||||
value: false,
|
||||
switchDisabled: true,
|
||||
refreshing: false,
|
||||
refreshDisabled: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||
|
||||
export type TailscaleErrorKey =
|
||||
| "devices.tailscale.turnOnError"
|
||||
| "devices.tailscale.turnOffError"
|
||||
| "devices.tailscale.statusError";
|
||||
|
||||
export interface TailscaleControlStateInput {
|
||||
status: TailscaleStatus | undefined;
|
||||
statusUpdatedAt: number;
|
||||
statusError: boolean;
|
||||
changePending: boolean;
|
||||
changePendingEnabled?: boolean;
|
||||
changeError: boolean;
|
||||
changeErrorEnabled?: boolean;
|
||||
refreshPending: boolean;
|
||||
refreshError: boolean;
|
||||
refreshSubmittedAt: number;
|
||||
}
|
||||
|
||||
export interface TailscaleControlState {
|
||||
value: boolean | null;
|
||||
showSwitch: boolean;
|
||||
switchDisabled: boolean;
|
||||
showRefresh: boolean;
|
||||
refreshing: boolean;
|
||||
refreshDisabled: boolean;
|
||||
showInstallLink: boolean;
|
||||
address: string | null;
|
||||
errorKey: TailscaleErrorKey | null;
|
||||
}
|
||||
|
||||
function resolveSwitchValue(input: TailscaleControlStateInput): boolean | null {
|
||||
if (input.changePending) return input.changePendingEnabled ?? null;
|
||||
if (!input.status) return null;
|
||||
return input.status.state === "on" || input.status.state === "waiting";
|
||||
}
|
||||
|
||||
function shouldShowRefresh(input: TailscaleControlStateInput): boolean {
|
||||
if (!input.status) {
|
||||
return input.statusError || input.refreshError || input.refreshPending;
|
||||
}
|
||||
return input.status.state === "unavailable" || input.status.state === "waiting";
|
||||
}
|
||||
|
||||
function resolveErrorKey(input: TailscaleControlStateInput): TailscaleErrorKey | null {
|
||||
if (input.changeError) {
|
||||
return input.changeErrorEnabled
|
||||
? "devices.tailscale.turnOnError"
|
||||
: "devices.tailscale.turnOffError";
|
||||
}
|
||||
if (input.refreshError && input.refreshSubmittedAt >= input.statusUpdatedAt) {
|
||||
return "devices.tailscale.statusError";
|
||||
}
|
||||
if (!input.refreshPending && input.statusError && !input.status) {
|
||||
return "devices.tailscale.statusError";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives the Tailscale row's controls and error state from the host status query and the latest
|
||||
* toggle or manual refresh attempt.
|
||||
*/
|
||||
export function resolveTailscaleControlState(
|
||||
input: TailscaleControlStateInput,
|
||||
): TailscaleControlState {
|
||||
const { status } = input;
|
||||
const value = resolveSwitchValue(input);
|
||||
const busy = input.changePending || input.refreshPending;
|
||||
const showRefresh = shouldShowRefresh(input);
|
||||
const showSwitch = Boolean(status) || !showRefresh;
|
||||
const switchDisabled =
|
||||
!status || status.state === "unavailable" || Boolean(status.lockedBy) || busy;
|
||||
|
||||
return {
|
||||
value,
|
||||
showSwitch,
|
||||
switchDisabled,
|
||||
showRefresh,
|
||||
refreshing: input.refreshPending,
|
||||
refreshDisabled: busy,
|
||||
showInstallLink: status?.state === "unavailable",
|
||||
address: status?.state === "on" && value ? status.address : null,
|
||||
errorKey: resolveErrorKey(input),
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { PairDeviceModal } from "./pair-device-modal";
|
||||
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
|
||||
import { TailscaleRow } from "./tailscale-row";
|
||||
@@ -14,6 +15,10 @@ export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
const [pairing, setPairing] = useState(false);
|
||||
const openPairing = useCallback(() => setPairing(true), []);
|
||||
const closePairing = useCallback(() => setPairing(false), []);
|
||||
const recommended = useMemo(
|
||||
() => <StatusBadge size="xs" variant="success" label={t("devices.recommended")} />,
|
||||
[t],
|
||||
);
|
||||
const docsLink = useMemo(
|
||||
() => ({
|
||||
href: CONNECTIVITY_DOCS_URL,
|
||||
@@ -28,6 +33,7 @@ export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
<SettingsCard>
|
||||
<SettingsDetailRow
|
||||
label={t("devices.relay.title")}
|
||||
labelAccessory={recommended}
|
||||
hint={t("devices.relay.hint")}
|
||||
onPress={openPairing}
|
||||
testID="devices-relay"
|
||||
|
||||
@@ -1891,13 +1891,12 @@ export const ar: TranslationResources = {
|
||||
waysToConnect: "طرق الاتصال",
|
||||
docs: "الوثائق",
|
||||
docsAccessibility: "افتح وثائق الاتصال",
|
||||
relay: { title: "التتابع", hint: "دون إعداد، مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
recommended: "موصى به",
|
||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
tailscale: {
|
||||
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
|
||||
unavailable: "Tailscale لا يعمل على هذا المضيف",
|
||||
install: "احصل على Tailscale",
|
||||
refresh: "تحديث",
|
||||
refreshing: "جارٍ التحديث...",
|
||||
waiting: "في انتظار بدء Tailscale على هذا المضيف",
|
||||
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
|
||||
socket: "متوقف، لأن هذا المضيف يستمع على مقبس محلي",
|
||||
|
||||
@@ -1920,13 +1920,12 @@ export const en = {
|
||||
waysToConnect: "Ways to connect",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Open connectivity documentation",
|
||||
relay: { title: "Relay", hint: "No setup, end-to-end encrypted, scan a QR code" },
|
||||
recommended: "Recommended",
|
||||
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
||||
tailscale: {
|
||||
hint: "Direct over your tailnet, enter an address",
|
||||
unavailable: "Tailscale is not running on this host",
|
||||
install: "Get Tailscale",
|
||||
refresh: "Refresh",
|
||||
refreshing: "Refreshing...",
|
||||
waiting: "Waiting for Tailscale to start on this host",
|
||||
alwaysOn: "Always on, because this host already accepts Tailscale connections",
|
||||
socket: "Off, because this host listens on a local socket",
|
||||
|
||||
@@ -1941,16 +1941,12 @@ export const es: TranslationResources = {
|
||||
waysToConnect: "Formas de conectarse",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir la documentación de conectividad",
|
||||
relay: {
|
||||
title: "Relé",
|
||||
hint: "Sin configuración, cifrado de extremo a extremo, escanea un código QR",
|
||||
},
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexión directa por tu tailnet, introduce una dirección",
|
||||
unavailable: "Tailscale no se está ejecutando en este host",
|
||||
install: "Obtener Tailscale",
|
||||
refresh: "Actualizar",
|
||||
refreshing: "Actualizando...",
|
||||
waiting: "Esperando a que Tailscale se inicie en este host",
|
||||
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
|
||||
socket: "Desactivado, porque este host escucha en un socket local",
|
||||
|
||||
@@ -1939,16 +1939,12 @@ export const fr: TranslationResources = {
|
||||
waysToConnect: "Moyens de connexion",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Ouvrir la documentation sur la connectivité",
|
||||
relay: {
|
||||
title: "Relais",
|
||||
hint: "Aucune configuration, chiffré de bout en bout, scannez un QR code",
|
||||
},
|
||||
recommended: "Recommandé",
|
||||
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
||||
tailscale: {
|
||||
hint: "Connexion directe via votre tailnet, saisissez une adresse",
|
||||
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
|
||||
install: "Obtenir Tailscale",
|
||||
refresh: "Actualiser",
|
||||
refreshing: "Actualisation...",
|
||||
waiting: "En attente du démarrage de Tailscale sur cet hôte",
|
||||
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
|
||||
socket: "Désactivé, car cet hôte écoute sur un socket local",
|
||||
|
||||
@@ -1912,13 +1912,12 @@ export const ja: TranslationResources = {
|
||||
waysToConnect: "接続方法",
|
||||
docs: "ドキュメント",
|
||||
docsAccessibility: "接続のドキュメントを開く",
|
||||
relay: { title: "リレー", hint: "設定不要、エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
recommended: "おすすめ",
|
||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
tailscale: {
|
||||
hint: "tailnet 経由で直接接続、アドレスを入力",
|
||||
unavailable: "このホストで Tailscale が動作していません",
|
||||
install: "Tailscale を入手",
|
||||
refresh: "更新",
|
||||
refreshing: "更新中...",
|
||||
waiting: "このホストで Tailscale が起動するのを待っています",
|
||||
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
|
||||
socket: "オフ。このホストはローカルソケットで待ち受けています",
|
||||
|
||||
@@ -1903,13 +1903,12 @@ export const ko: TranslationResources = {
|
||||
waysToConnect: "연결 방법",
|
||||
docs: "문서",
|
||||
docsAccessibility: "연결 문서 열기",
|
||||
relay: { title: "릴레이", hint: "설정 불필요, 엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
recommended: "권장",
|
||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
tailscale: {
|
||||
hint: "tailnet으로 직접 연결, 주소 입력",
|
||||
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
|
||||
install: "Tailscale 받기",
|
||||
refresh: "새로 고침",
|
||||
refreshing: "새로 고치는 중...",
|
||||
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
|
||||
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
|
||||
socket: "꺼짐. 이 호스트가 로컬 소켓에서 수신 대기 중입니다",
|
||||
|
||||
@@ -1925,16 +1925,12 @@ export const ptBR: TranslationResources = {
|
||||
waysToConnect: "Formas de conexão",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir documentação de conectividade",
|
||||
relay: {
|
||||
title: "Relay",
|
||||
hint: "Sem configuração, criptografia de ponta a ponta, escaneie um código QR",
|
||||
},
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexão direta pela sua tailnet, digite um endereço",
|
||||
unavailable: "O Tailscale não está em execução neste host",
|
||||
install: "Baixar o Tailscale",
|
||||
refresh: "Atualizar",
|
||||
refreshing: "Atualizando...",
|
||||
waiting: "Aguardando o Tailscale iniciar neste host",
|
||||
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
|
||||
socket: "Desativado, porque este host escuta em um socket local",
|
||||
|
||||
@@ -1925,16 +1925,12 @@ export const ru: TranslationResources = {
|
||||
waysToConnect: "Способы подключения",
|
||||
docs: "Документация",
|
||||
docsAccessibility: "Открыть документацию по подключению",
|
||||
relay: {
|
||||
title: "Ретранслятор",
|
||||
hint: "Без настройки, сквозное шифрование, отсканируйте QR-код",
|
||||
},
|
||||
recommended: "Рекомендуется",
|
||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||
tailscale: {
|
||||
hint: "Прямое подключение через ваш tailnet, по адресу",
|
||||
unavailable: "Tailscale не запущен на этом хосте",
|
||||
install: "Скачать Tailscale",
|
||||
refresh: "Обновить",
|
||||
refreshing: "Обновление...",
|
||||
waiting: "Ожидаем запуска Tailscale на этом хосте",
|
||||
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
|
||||
socket: "Выключено, так как хост слушает локальный сокет",
|
||||
|
||||
@@ -1873,13 +1873,12 @@ export const zhCN: TranslationResources = {
|
||||
waysToConnect: "连接方式",
|
||||
docs: "文档",
|
||||
docsAccessibility: "打开连接文档",
|
||||
relay: { title: "中继", hint: "无需配置,端到端加密,扫描二维码" },
|
||||
recommended: "推荐",
|
||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||
tailscale: {
|
||||
hint: "通过你的 tailnet 直连,输入地址即可",
|
||||
unavailable: "此主机未运行 Tailscale",
|
||||
install: "获取 Tailscale",
|
||||
refresh: "刷新",
|
||||
refreshing: "刷新中...",
|
||||
waiting: "正在等待此主机上的 Tailscale 启动",
|
||||
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
|
||||
socket: "已关闭,因为此主机监听的是本地套接字",
|
||||
|
||||
@@ -204,112 +204,6 @@ describe("viewed timeline persistence", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("replaces pre-rewind history when a live row arrives in a new epoch", async () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
applySynced(AGENT_ID, 5);
|
||||
const readTimelineState = () => {
|
||||
const timeline = selectAgentTimelineState(
|
||||
useSessionStore.getState().sessions[SERVER_ID],
|
||||
AGENT_ID,
|
||||
);
|
||||
return {
|
||||
status: timeline.status,
|
||||
texts:
|
||||
timeline.status === "cold"
|
||||
? []
|
||||
: timeline.items.flatMap((entry) =>
|
||||
entry.kind === "assistant_message" ? [entry.text] : [],
|
||||
),
|
||||
};
|
||||
};
|
||||
const fetches: Array<{
|
||||
direction: string;
|
||||
cursor?: { epoch: string; seq: number };
|
||||
}> = [];
|
||||
const replica = createTimelineReplica({
|
||||
serverId: SERVER_ID,
|
||||
storage: { readTimeline: async () => undefined, commitTimeline: () => undefined },
|
||||
prepareAgent: async () => undefined,
|
||||
});
|
||||
const owner = createViewedTimelineOwner({
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => false,
|
||||
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
|
||||
readCursor: () => undefined,
|
||||
fetchPage: async (_agentId, request) => {
|
||||
fetches.push(request);
|
||||
if (request.direction !== "after") return { hasNewer: false, endCursor: null };
|
||||
// A cursor from the pre-rewind epoch makes the daemon reset to its current tail.
|
||||
owner.applyTimelineResponse({
|
||||
requestId: "rewind-reset",
|
||||
agentId: AGENT_ID,
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
epoch: "epoch-2",
|
||||
reset: true,
|
||||
staleCursor: true,
|
||||
gap: false,
|
||||
window: { minSeq: 1, maxSeq: 2, nextSeq: 3 },
|
||||
startCursor: { epoch: "epoch-2", seq: 1 },
|
||||
endCursor: { epoch: "epoch-2", seq: 2 },
|
||||
entries: [
|
||||
{
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: "after rewind" },
|
||||
timestamp: "2026-08-26T10:05:00.000Z",
|
||||
seqStart: 1,
|
||||
seqEnd: 2,
|
||||
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
|
||||
collapsed: [],
|
||||
},
|
||||
],
|
||||
hasOlder: false,
|
||||
hasNewer: false,
|
||||
error: null,
|
||||
});
|
||||
return { hasNewer: false, endCursor: { epoch: "epoch-2", seq: 2 } };
|
||||
},
|
||||
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
||||
reportError: () => undefined,
|
||||
},
|
||||
});
|
||||
try {
|
||||
owner.setConnected(true);
|
||||
owner.replaceVisibleAgentIds("test", [AGENT_ID]);
|
||||
await expect.poll(() => fetches.length).toBe(1);
|
||||
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: "new prompt reply" },
|
||||
} as AgentStreamEventPayload,
|
||||
seq: 6,
|
||||
epoch: "epoch-2",
|
||||
timestamp: new Date("2026-08-26T10:06:00.000Z"),
|
||||
});
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
|
||||
await expect.poll(() => fetches.length).toBe(2);
|
||||
expect(fetches[1]).toMatchObject({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-1", seq: 5 },
|
||||
});
|
||||
await expect.poll(readTimelineState).toEqual({
|
||||
status: "synced",
|
||||
texts: ["after rewind"],
|
||||
});
|
||||
} finally {
|
||||
owner.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("shares an in-flight cache preparation with the viewed owner", async () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
let release!: (value: CachedTimeline) => void;
|
||||
|
||||
@@ -3834,7 +3834,7 @@ describe("processAgentStreamEvent", () => {
|
||||
expect(result.sideEffects).toEqual([]);
|
||||
});
|
||||
|
||||
it("requests authoritative recovery when a live row has a different epoch", () => {
|
||||
it("drops timeline event with epoch mismatch", () => {
|
||||
const existingCursor: TimelineCursor = {
|
||||
epoch: "epoch-1",
|
||||
startSeq: 1,
|
||||
@@ -3852,9 +3852,7 @@ describe("processAgentStreamEvent", () => {
|
||||
expect(result.cursorChanged).toBe(false);
|
||||
expect(result.changedTail).toBe(false);
|
||||
expect(result.changedHead).toBe(false);
|
||||
expect(result.sideEffects).toEqual([
|
||||
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 5 } },
|
||||
]);
|
||||
expect(result.sideEffects).toEqual([]);
|
||||
});
|
||||
|
||||
it("resets visible timeline when a new epoch starts at seq 1", () => {
|
||||
|
||||
@@ -1545,20 +1545,7 @@ function processTimelineSequencingGate(input: {
|
||||
cursorChanged: true,
|
||||
};
|
||||
}
|
||||
if (decision === "drop_epoch" && seq === 1) {
|
||||
return {
|
||||
...base,
|
||||
nextTimelineCursor: { epoch, startSeq: seq, endSeq: seq },
|
||||
cursorChanged: true,
|
||||
resetLiveTimeline: true,
|
||||
};
|
||||
}
|
||||
// A gap and an epoch change both mean the local cursor cannot certify the next row.
|
||||
// The epoch case is a rewind or replacement this client did not observe as an
|
||||
// invalidation; the daemon answers an `after` request carrying the stale epoch with a
|
||||
// reset tail, which installs current history. Dropping those rows would leave the chat
|
||||
// on pre-rewind history while the new epoch streams.
|
||||
if (decision === "gap" || decision === "drop_epoch") {
|
||||
if (decision === "gap") {
|
||||
return {
|
||||
...base,
|
||||
shouldApplyStreamEvent: false,
|
||||
@@ -1572,6 +1559,14 @@ function processTimelineSequencingGate(input: {
|
||||
],
|
||||
};
|
||||
}
|
||||
if (decision === "drop_epoch" && seq === 1) {
|
||||
return {
|
||||
...base,
|
||||
nextTimelineCursor: { epoch, startSeq: seq, endSeq: seq },
|
||||
cursorChanged: true,
|
||||
resetLiveTimeline: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
shouldApplyStreamEvent: false,
|
||||
|
||||
@@ -6,7 +6,6 @@ import type { ChildProcess } from "node:child_process";
|
||||
import type { Query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ClaudeAgentClient } from "./agent/providers/claude/agent.js";
|
||||
import http from "node:http";
|
||||
import { createServer as createNetServer } from "node:net";
|
||||
import path from "node:path";
|
||||
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import pino from "pino";
|
||||
@@ -190,44 +189,6 @@ describe("paseo daemon bootstrap", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test("re-probes a waiting Tailscale listener immediately on getDaemonStatus", async () => {
|
||||
const blocker = createNetServer().listen(0, "127.0.0.2");
|
||||
await once(blocker, "listening");
|
||||
const bound = blocker.address();
|
||||
if (!bound || typeof bound === "string") throw new Error("Expected TCP");
|
||||
const address = `127.0.0.2:${bound.port}`;
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: false,
|
||||
listenPort: bound.port,
|
||||
getTailscaleNetwork: () => ({ addresses: ["127.0.0.2"], otherAddresses: new Set() }),
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
|
||||
try {
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen: daemon.config.listen } }),
|
||||
);
|
||||
await client.connect();
|
||||
expect(await client.setTailscaleEnabled(true)).toMatchObject({
|
||||
tailscale: { address, state: "waiting" },
|
||||
extraListeners: [{ address, state: "waiting" }],
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => blocker.close(() => resolve()));
|
||||
expect(await client.getDaemonStatus({ includeProviders: false })).toMatchObject({
|
||||
tailscale: { address, state: "on" },
|
||||
extraListeners: [{ address, state: "listening" }],
|
||||
});
|
||||
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
blocker.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps Tailscale on its original port across a main port change", async () => {
|
||||
const tailscaleIp = "127.0.0.2";
|
||||
const carrierNatIp = "100.127.255.254";
|
||||
|
||||
@@ -1925,7 +1925,7 @@ export async function createPaseoDaemon(
|
||||
providerSnapshotManager,
|
||||
{
|
||||
listen: formatListenTarget(boundListenTarget ?? listenTarget),
|
||||
getListenStatus: listeners.refreshStatus,
|
||||
getListenStatus: listeners.status,
|
||||
setTailscaleEnabled: (enabled, localEndpoint, confirmed) =>
|
||||
daemonConfigStore.setTailscaleEnabled(enabled, localEndpoint, confirmed),
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
|
||||
@@ -172,42 +172,3 @@ test("does not count an extra listener on a non-Tailscale interface in the share
|
||||
await listeners.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("re-probes a waiting Tailscale listener immediately on refreshStatus", async () => {
|
||||
const blocker = createTcpServer().listen(0, "127.0.0.2");
|
||||
await once(blocker, "listening");
|
||||
const bound = blocker.address();
|
||||
if (!bound || typeof bound === "string") throw new Error("Expected TCP");
|
||||
const address = `127.0.0.2:${bound.port}`;
|
||||
const listen = `127.0.0.1:${bound.port},${address}`;
|
||||
const http = createServer((_req, res) => res.end("ok"));
|
||||
const listeners = createDaemonListeners({
|
||||
http,
|
||||
listen,
|
||||
overridden: false,
|
||||
retryMs: 60_000,
|
||||
getMain: () => ({ type: "tcp", host: "127.0.0.1", port: bound.port }),
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: ["127.0.0.2"],
|
||||
otherAddresses: new Set(),
|
||||
}),
|
||||
});
|
||||
try {
|
||||
await listeners.apply(listen);
|
||||
expect(listeners.status()).toMatchObject({
|
||||
tailscale: { ip: "127.0.0.2", address, state: "waiting" },
|
||||
extraListeners: [{ address, state: "waiting" }],
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => blocker.close(() => resolve()));
|
||||
|
||||
expect(await listeners.refreshStatus()).toMatchObject({
|
||||
tailscale: { ip: "127.0.0.2", address, state: "on" },
|
||||
extraListeners: [{ address, state: "listening" }],
|
||||
});
|
||||
expect(await (await fetch(`http://${address}`)).text()).toBe("ok");
|
||||
} finally {
|
||||
await listeners.stop();
|
||||
blocker.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -99,50 +99,35 @@ export function createExtraListeners(http: HttpServer, retryMs = 2_000) {
|
||||
const { port, host } = parseExtra(address);
|
||||
const sockets = new Set<Socket>();
|
||||
let retry: ReturnType<typeof setTimeout> | undefined;
|
||||
let pending: Promise<void> | null = null;
|
||||
let stopped = false;
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.once("close", () => sockets.delete(socket));
|
||||
http.emit("connection", socket);
|
||||
});
|
||||
function listen(): Promise<void> {
|
||||
if (pending) return pending;
|
||||
if (stopped || server.listening) return Promise.resolve();
|
||||
clearTimeout(retry);
|
||||
retry = undefined;
|
||||
pending = new Promise<void>((resolve) => {
|
||||
function listen() {
|
||||
return new Promise<void>((resolve) => {
|
||||
const settled = () => {
|
||||
server.off("listening", onListening);
|
||||
server.off("listening", settled);
|
||||
server.off("error", settled);
|
||||
server.off("close", settled);
|
||||
pending = null;
|
||||
resolve();
|
||||
};
|
||||
const onListening = () => {
|
||||
settled();
|
||||
if (stopped) server.close();
|
||||
};
|
||||
server.once("listening", onListening);
|
||||
server.once("listening", settled);
|
||||
server.once("error", settled);
|
||||
server.once("close", settled);
|
||||
server.listen(port, host);
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
server.on("error", () => {
|
||||
if (stopped) return;
|
||||
clearTimeout(retry);
|
||||
retry = setTimeout(() => void listen(), retryMs).unref();
|
||||
if (!stopped) retry = setTimeout(() => void listen(), retryMs).unref();
|
||||
});
|
||||
return {
|
||||
ready: listen(),
|
||||
retry: listen,
|
||||
state: () => (server.listening ? ("listening" as const) : ("waiting" as const)),
|
||||
close() {
|
||||
stopped = true;
|
||||
clearTimeout(retry);
|
||||
retry = undefined;
|
||||
server.close();
|
||||
// Let the request that removed this listener queue its response first.
|
||||
setImmediate(() => {
|
||||
@@ -164,13 +149,6 @@ export function createExtraListeners(http: HttpServer, retryMs = 2_000) {
|
||||
}
|
||||
await Promise.all(Array.from(active.values(), (listener) => listener.ready));
|
||||
},
|
||||
async retryWaiting() {
|
||||
const waiting = Array.from(active.values()).filter(
|
||||
(listener) => listener.state() === "waiting",
|
||||
);
|
||||
if (waiting.length === 0) return;
|
||||
await Promise.all(waiting.map((listener) => listener.retry()));
|
||||
},
|
||||
status() {
|
||||
return Array.from(active, ([address, listener]) => ({ address, state: listener.state() }));
|
||||
},
|
||||
@@ -227,7 +205,6 @@ export function createDaemonListeners(options: {
|
||||
http: HttpServer;
|
||||
listen: string;
|
||||
overridden: boolean;
|
||||
retryMs?: number;
|
||||
getMain: () => ListenTarget | null;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
}) {
|
||||
@@ -235,12 +212,11 @@ export function createDaemonListeners(options: {
|
||||
http,
|
||||
listen,
|
||||
overridden,
|
||||
retryMs,
|
||||
getMain,
|
||||
getTailscaleNetwork = inspectTailscaleNetwork,
|
||||
} = options;
|
||||
const [startupMain] = splitListen(listen);
|
||||
const extras = createExtraListeners(http, retryMs);
|
||||
const extras = createExtraListeners(http);
|
||||
let stopped = false;
|
||||
|
||||
async function applyLive(addresses: readonly string[]) {
|
||||
@@ -285,22 +261,16 @@ export function createDaemonListeners(options: {
|
||||
};
|
||||
}
|
||||
|
||||
function status(localEndpoint?: string) {
|
||||
const { tailscale, configured, extraListeners } = describeTailscale();
|
||||
const disconnectsCurrentConnection =
|
||||
!tailscale.lockedBy &&
|
||||
configured.some(({ target }) => formatListenTarget(target) === localEndpoint);
|
||||
return {
|
||||
tailscale: { ...tailscale, disconnectsCurrentConnection },
|
||||
extraListeners,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
async refreshStatus(localEndpoint?: string) {
|
||||
if (!stopped) await extras.retryWaiting();
|
||||
return status(localEndpoint);
|
||||
status(localEndpoint?: string) {
|
||||
const { tailscale, configured, extraListeners } = describeTailscale();
|
||||
const disconnectsCurrentConnection =
|
||||
!tailscale.lockedBy &&
|
||||
configured.some(({ target }) => formatListenTarget(target) === localEndpoint);
|
||||
return {
|
||||
tailscale: { ...tailscale, disconnectsCurrentConnection },
|
||||
extraListeners,
|
||||
};
|
||||
},
|
||||
async apply(persisted: string | undefined) {
|
||||
const [main, ...addresses] = splitListen(overridden ? listen : (persisted ?? listen));
|
||||
|
||||
@@ -718,8 +718,6 @@ export default function contribute(server) {
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
// Two daemon starts, four archives, and two restores. On Windows CI this takes 18 to 46 seconds
|
||||
// and went over 60 on a slow runner, so it gets the same budget as the worktrunk journey above.
|
||||
test("untrusted workspaces pass untrusted=true to worktree manager remove and restore, and worktrunk skips hooks", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktrunk-untrusted-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
@@ -869,7 +867,7 @@ test("untrusted workspaces pass untrusted=true to worktree manager remove and re
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 90_000);
|
||||
}, 60_000);
|
||||
|
||||
test("concurrent restores across two daemon clients wait for the in-flight manager restore and share its failure", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-restore-race-"));
|
||||
|
||||
@@ -21,11 +21,7 @@ export interface DaemonRuntimeConfig {
|
||||
worktreesRoot?: string;
|
||||
appBaseUrl?: string;
|
||||
desktopManaged?: boolean;
|
||||
getListenStatus?: (
|
||||
localEndpoint?: string,
|
||||
) =>
|
||||
| ReturnType<ReturnType<typeof createDaemonListeners>["status"]>
|
||||
| Promise<ReturnType<ReturnType<typeof createDaemonListeners>["status"]>>;
|
||||
getListenStatus?: ReturnType<typeof createDaemonListeners>["status"];
|
||||
setTailscaleEnabled?: DaemonConfigStore["setTailscaleEnabled"];
|
||||
getRelayConfig(): {
|
||||
enabled: boolean;
|
||||
@@ -207,7 +203,6 @@ export class DaemonSession {
|
||||
({ pid, role, reason, detail }) => ({ pid, role, reason, detail }),
|
||||
);
|
||||
const terminalsUnavailable = this.getTerminalsUnavailable();
|
||||
const listenStatus = await this.daemonRuntimeConfig?.getListenStatus?.(localEndpoint);
|
||||
try {
|
||||
const pidInfo = await getPidLockInfo(this.paseoHome);
|
||||
const availability =
|
||||
@@ -230,7 +225,7 @@ export class DaemonSession {
|
||||
relay: this.daemonRuntimeConfig?.getRelayConfig() ?? null,
|
||||
providers,
|
||||
terminalCleanupUnconfirmed,
|
||||
...listenStatus,
|
||||
...this.daemonRuntimeConfig?.getListenStatus?.(localEndpoint),
|
||||
...(terminalsUnavailable ? { terminalsUnavailable } : {}),
|
||||
},
|
||||
});
|
||||
@@ -249,7 +244,7 @@ export class DaemonSession {
|
||||
relay: null,
|
||||
providers: [],
|
||||
terminalCleanupUnconfirmed,
|
||||
...listenStatus,
|
||||
...this.daemonRuntimeConfig?.getListenStatus?.(localEndpoint),
|
||||
...(terminalsUnavailable ? { terminalsUnavailable } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,36 +2,18 @@ import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createTestPaseoDaemon } from "./paseo-daemon.js";
|
||||
|
||||
const [, , origin, initialMode = "available"] = process.argv;
|
||||
const [, , origin] = process.argv;
|
||||
if (!origin) throw new Error("Expected the app origin");
|
||||
|
||||
let tailscaleAvailable = initialMode !== "unavailable";
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
corsAllowedOrigins: [origin],
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: tailscaleAvailable ? ["127.0.0.2"] : [],
|
||||
otherAddresses: new Set(),
|
||||
}),
|
||||
getTailscaleNetwork: () => ({ addresses: ["127.0.0.2"], otherAddresses: new Set() }),
|
||||
});
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(daemon.paseoHome, "config.json"),
|
||||
JSON.stringify({ version: 1, daemon: { listen: `127.0.0.1:${daemon.port}` } }),
|
||||
);
|
||||
process.on("message", (message: unknown) => {
|
||||
if (
|
||||
message &&
|
||||
typeof message === "object" &&
|
||||
"type" in message &&
|
||||
message.type === "set-tailscale-available" &&
|
||||
"available" in message &&
|
||||
typeof message.available === "boolean"
|
||||
) {
|
||||
tailscaleAvailable = message.available;
|
||||
process.send?.({ type: "tailscale-available-set", available: tailscaleAvailable });
|
||||
}
|
||||
});
|
||||
process.once("SIGTERM", async () => {
|
||||
await daemon.close();
|
||||
process.exit(0);
|
||||
|
||||
@@ -2530,13 +2530,7 @@ it.each([3000, 12050])(
|
||||
watcher.close();process.stdout.write("\\r\\nROWS-COMPLETE");
|
||||
}
|
||||
});
|
||||
// Batch writes so Windows ConPTY does not spend 15s on 12,050 individual TTY writes.
|
||||
for(let start=0;start<${count};start+=256){
|
||||
let chunk="";
|
||||
const end=Math.min(${count},start+256);
|
||||
for(let i=start;i<end;i++) chunk+="\\x1b[31mrow-"+String(i).padStart(5,"0")+" 界é🙂\\x1b[0m"+(i===${count}-1?"":"\\r\\n");
|
||||
process.stdout.write(chunk);
|
||||
}
|
||||
for(let i=0;i<${count};i++) process.stdout.write("\\x1b[31mrow-"+String(i).padStart(5,"0")+" 界é🙂\\x1b[0m"+(i===${count}-1?"":"\\r\\n"));
|
||||
setInterval(()=>{},1000)`,
|
||||
),
|
||||
}),
|
||||
|
||||
@@ -220,7 +220,7 @@ test("the plugins scene installs the panel, then changes it on request", async (
|
||||
test("the code review scene comments on a line and sends the feedback to an agent", async ({
|
||||
page,
|
||||
}) => {
|
||||
await openHomepageWithSceneClock(page);
|
||||
await openHomepage(page);
|
||||
const mockup = page.getByRole("img", { name: desktopName, exact: true });
|
||||
const comment = mockup.getByText("Add “write”. The agent edits files too.", { exact: true });
|
||||
const sendFeedback = mockup.getByText("Send feedback (1)", { exact: true });
|
||||
@@ -232,17 +232,18 @@ test("the code review scene comments on a line and sends the feedback to an agen
|
||||
await expect(comment).toHaveCount(0);
|
||||
|
||||
// The pointer opens the editor on a line, and the typed comment is saved under that line.
|
||||
await page.clock.runFor(3500);
|
||||
await expect(sendFeedback).toBeVisible();
|
||||
await expect(sendFeedback).toBeVisible({ timeout: 10_000 });
|
||||
await expect(comment).toBeVisible();
|
||||
|
||||
// Send feedback asks which agent, and the sent comment leaves the diff.
|
||||
await page.clock.runFor(1300);
|
||||
await expect(mockup.getByText("Claude Code", { exact: true })).toHaveCount(2);
|
||||
await page.clock.runFor(1500);
|
||||
await expect(mockup.getByText("Feedback sent to Codex", { exact: true })).toBeVisible();
|
||||
await finishPanelSwap(page, mockup, sendFeedback);
|
||||
await finishPanelSwap(page, mockup, comment);
|
||||
await expect(mockup.getByText("Claude Code", { exact: true })).toHaveCount(2, {
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(mockup.getByText("Feedback sent to Codex", { exact: true })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(sendFeedback).toHaveCount(0);
|
||||
await expect(comment).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("picking a scene brings the pills and the whole mockup on screen", async ({ page }) => {
|
||||
|
||||
Reference in New Issue
Block a user