mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-17 13:54:54 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc1f715184 | ||
|
|
40275bc3a4 | ||
|
|
02124454bc |
@@ -466,12 +466,12 @@ test("downloads a file over direct TCP with its original filename and bytes", as
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openFileExplorer(page);
|
||||
|
||||
const daemonRequest = page.waitForRequest("**/api/files/download?*");
|
||||
const downloaded = await downloadFileFromExplorer(page, fileName);
|
||||
const url = new URL(downloaded.url());
|
||||
expect(url.protocol).toBe("http:");
|
||||
expect(url.port).toBe(getE2EDaemonPort());
|
||||
expect(url.pathname).toBe("/api/files/download");
|
||||
expect(url.searchParams.get("token")).toBeTruthy();
|
||||
const requestUrl = new URL((await daemonRequest).url());
|
||||
expect(requestUrl.port).toBe(getE2EDaemonPort());
|
||||
expect(requestUrl.searchParams.get("token")).toBeTruthy();
|
||||
expect(new URL(downloaded.url()).protocol).toBe("blob:");
|
||||
expect(downloaded.suggestedFilename()).toBe(fileName);
|
||||
const savedFile = testInfo.outputPath(fileName);
|
||||
await downloaded.saveAs(savedFile);
|
||||
@@ -479,6 +479,45 @@ test("downloads a file over direct TCP with its original filename and bytes", as
|
||||
expect(await readFile(savedFile)).toEqual(source);
|
||||
});
|
||||
|
||||
test("keeps the app open and shows the error when the host rejects a download", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const fileName = "removed-during-download.bin";
|
||||
const filePath = path.join(workspace.workspaceDirectory, fileName);
|
||||
const source = Buffer.from([0, 1, 2, 255]);
|
||||
await writeFile(filePath, source);
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openFileExplorer(page);
|
||||
const workspaceUrl = page.url();
|
||||
|
||||
// The file disappears after the token is issued, so the real daemon answers 404.
|
||||
await page.route(
|
||||
"**/api/files/download?*",
|
||||
async (route) => {
|
||||
await rm(filePath);
|
||||
await route.continue();
|
||||
},
|
||||
{ times: 1 },
|
||||
);
|
||||
await page
|
||||
.getByTestId("file-explorer-tree-scroll")
|
||||
.getByText(fileName, { exact: true })
|
||||
.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
|
||||
|
||||
await expect(
|
||||
page.getByText("Failed to download file (HTTP 404).", { exact: true }),
|
||||
).toBeVisible();
|
||||
expect(page.url()).toBe(workspaceUrl);
|
||||
|
||||
await writeFile(filePath, source);
|
||||
const downloaded = await downloadFileFromExplorer(page, fileName);
|
||||
const savedFile = testInfo.outputPath(fileName);
|
||||
await downloaded.saveAs(savedFile);
|
||||
expect(await readFile(savedFile)).toEqual(source);
|
||||
expect(page.url()).toBe(workspaceUrl);
|
||||
});
|
||||
|
||||
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state";
|
||||
import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
|
||||
type ColorScheme = "dark" | "light";
|
||||
@@ -85,8 +86,16 @@ export function useFaviconStatus() {
|
||||
// The favicon reads the whole fleet, so it has to keep every host's directory loading even
|
||||
// though it no longer subscribes to the agent maps.
|
||||
useAllDirectoryDemand({ serverIds, enabled: !isNative });
|
||||
const selectFaviconStatus = useMemo(createFaviconStatusSelector, []);
|
||||
const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []);
|
||||
// Background workspaces count exactly when the sidebar shows them.
|
||||
const showBackground = useSidebarViewStore((state) => state.showBackground);
|
||||
const selectFaviconStatus = useMemo(
|
||||
() => createFaviconStatusSelector({ showBackground }),
|
||||
[showBackground],
|
||||
);
|
||||
const selectMacDockBadgeCount = useMemo(
|
||||
() => createMacDockBadgeCountSelector({ showBackground }),
|
||||
[showBackground],
|
||||
);
|
||||
const status = useSessionStore(selectFaviconStatus);
|
||||
const dockBadgeCount = useSessionStore(selectMacDockBadgeCount);
|
||||
const [colorScheme, setColorScheme] = useState<ColorScheme>(getSystemColorScheme);
|
||||
|
||||
@@ -2017,6 +2017,7 @@ export const ar: TranslationResources = {
|
||||
hostUnavailable: "مضيف التنزيل غير متاح.",
|
||||
cancelled: "تم إلغاء التنزيل.",
|
||||
failed: "فشل تنزيل الملف.",
|
||||
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
|
||||
shareFile: "مشاركة الملف",
|
||||
shareFileNamed: "مشاركة{{fileName}}",
|
||||
},
|
||||
|
||||
@@ -2045,6 +2045,7 @@ export const en = {
|
||||
hostUnavailable: "Download host is unavailable.",
|
||||
cancelled: "Download was cancelled.",
|
||||
failed: "Failed to download file.",
|
||||
httpFailed: "Failed to download file (HTTP {{status}}).",
|
||||
shareFile: "Share file",
|
||||
shareFileNamed: "Share {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -2066,6 +2066,7 @@ export const es: TranslationResources = {
|
||||
hostUnavailable: "El host de descarga no está disponible.",
|
||||
cancelled: "La descarga fue cancelada.",
|
||||
failed: "No se pudo descargar el archivo.",
|
||||
httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).",
|
||||
shareFile: "compartir archivo",
|
||||
shareFileNamed: "Compartir{{fileName}}",
|
||||
},
|
||||
|
||||
@@ -2065,6 +2065,7 @@ export const fr: TranslationResources = {
|
||||
hostUnavailable: "L’hôte de téléchargement est indisponible.",
|
||||
cancelled: "Téléchargement annulé.",
|
||||
failed: "Impossible de télécharger le fichier.",
|
||||
httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).",
|
||||
shareFile: "Partager le fichier",
|
||||
shareFileNamed: "Partager {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -2038,6 +2038,7 @@ export const ja: TranslationResources = {
|
||||
hostUnavailable: "ダウンロードホストが利用できません。",
|
||||
cancelled: "ダウンロードがキャンセルされました。",
|
||||
failed: "ファイルのダウンロードに失敗しました。",
|
||||
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
|
||||
shareFile: "ファイルを共有",
|
||||
shareFileNamed: "{{fileName}}を共有",
|
||||
},
|
||||
|
||||
@@ -2028,6 +2028,7 @@ export const ko: TranslationResources = {
|
||||
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
|
||||
cancelled: "다운로드가 취소되었습니다.",
|
||||
failed: "파일을 다운로드하지 못했습니다.",
|
||||
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
|
||||
shareFile: "파일 공유",
|
||||
shareFileNamed: "{{fileName}} 공유",
|
||||
},
|
||||
|
||||
@@ -2051,6 +2051,7 @@ export const ptBR: TranslationResources = {
|
||||
hostUnavailable: "Host de download indisponível.",
|
||||
cancelled: "Download cancelado.",
|
||||
failed: "Falha ao baixar arquivo.",
|
||||
httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).",
|
||||
shareFile: "Compartilhar arquivo",
|
||||
shareFileNamed: "Compartilhar {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -2051,6 +2051,7 @@ export const ru: TranslationResources = {
|
||||
hostUnavailable: "Хост загрузки недоступен.",
|
||||
cancelled: "Загрузка отменена.",
|
||||
failed: "Не удалось загрузить файл.",
|
||||
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
|
||||
shareFile: "Поделиться файлом",
|
||||
shareFileNamed: "Поделиться {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -1994,6 +1994,7 @@ export const zhCN: TranslationResources = {
|
||||
hostUnavailable: "下载 Host 不可用。",
|
||||
cancelled: "下载已取消。",
|
||||
failed: "下载文件失败。",
|
||||
httpFailed: "下载文件失败 (HTTP {{status}}).",
|
||||
shareFile: "共享文件",
|
||||
shareFileNamed: "共享 {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -90,6 +90,7 @@ interface StartInput {
|
||||
token?: ReturnType<typeof createTokenRequest>;
|
||||
reader?: ReturnType<typeof createFileReader>;
|
||||
saver?: ReturnType<typeof createFileSaver>;
|
||||
fetchFile?: typeof fetch;
|
||||
}
|
||||
|
||||
async function startDownload(input: StartInput): Promise<Download | undefined> {
|
||||
@@ -108,6 +109,7 @@ async function startDownload(input: StartInput): Promise<Download | undefined> {
|
||||
requestFileDownloadToken: token.request,
|
||||
readFile: reader.read,
|
||||
saveFile: saver.save,
|
||||
fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)),
|
||||
});
|
||||
const { activeDownloadId, downloads } = useDownloadStore.getState();
|
||||
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
|
||||
@@ -203,6 +205,57 @@ describe("download store transport selection", () => {
|
||||
expect(saver.savedFiles).toEqual([]);
|
||||
});
|
||||
|
||||
it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => {
|
||||
const requests: Array<RequestInit | undefined> = [];
|
||||
const download = await startDownload({
|
||||
profile: profileWith([localTcpConnection]),
|
||||
activeConnectionId: localTcpConnection.id,
|
||||
fetchFile: async (_url, init) => {
|
||||
requests.push(init);
|
||||
return new Response("<h1>401 Authorization Required</h1>", {
|
||||
status: 401,
|
||||
headers: { "WWW-Authenticate": 'Basic realm="Paseo"' },
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
expect(download).toMatchObject({
|
||||
status: "error",
|
||||
message: i18n.t("downloads.httpFailed", { status: 401 }),
|
||||
});
|
||||
expect(requests).toEqual([{ credentials: "include", redirect: "error" }]);
|
||||
});
|
||||
|
||||
it("fails with a readable message when the download request cannot reach the host", async () => {
|
||||
const download = await startDownload({
|
||||
profile: profileWith([localTcpConnection]),
|
||||
activeConnectionId: localTcpConnection.id,
|
||||
fetchFile: async () => {
|
||||
throw new TypeError("Failed to fetch");
|
||||
},
|
||||
});
|
||||
|
||||
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
|
||||
});
|
||||
|
||||
it("fails with a readable message when the connection drops while the file is downloading", async () => {
|
||||
const saver = createFileSaver();
|
||||
const download = await startDownload({
|
||||
profile: profileWith([localTcpConnection]),
|
||||
activeConnectionId: localTcpConnection.id,
|
||||
fetchFile: async () =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start: (controller) => controller.error(new TypeError("network error")),
|
||||
}),
|
||||
),
|
||||
saver,
|
||||
});
|
||||
|
||||
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
|
||||
expect(saver.savedFiles).toEqual([]);
|
||||
});
|
||||
|
||||
it("fails the download and saves nothing when the session read fails", async () => {
|
||||
const reader = createFileReader(async () => {
|
||||
throw new Error("Connection lost");
|
||||
|
||||
@@ -4,7 +4,6 @@ import * as LegacyFileSystem from "expo-file-system/legacy";
|
||||
import * as Sharing from "expo-sharing";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
@@ -59,6 +58,7 @@ interface DownloadState {
|
||||
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
|
||||
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
|
||||
saveFile?: typeof saveDownloadedBytes;
|
||||
fetchFile?: typeof fetch;
|
||||
}) => Promise<void>;
|
||||
|
||||
updateProgress: (id: string, progress: DownloadProgress) => void;
|
||||
@@ -86,6 +86,7 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
|
||||
requestFileDownloadToken,
|
||||
readFile,
|
||||
saveFile = saveDownloadedBytes,
|
||||
fetchFile = fetch,
|
||||
}) => {
|
||||
const id = generateDownloadId();
|
||||
const download: Download = {
|
||||
@@ -144,14 +145,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
|
||||
throw new Error(i18n.t("downloads.hostUnavailable"));
|
||||
}
|
||||
|
||||
const downloadUrl = buildDownloadUrl(
|
||||
downloadTarget.baseUrl,
|
||||
tokenResponse.token,
|
||||
isWeb ? downloadTarget.authCredentials : null,
|
||||
);
|
||||
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
|
||||
|
||||
if (isWeb) {
|
||||
triggerBrowserDownload(downloadUrl, resolvedFileName);
|
||||
const file = await fetchDownload(fetchFile, downloadUrl);
|
||||
saveBrowserFile(file, resolvedFileName);
|
||||
get().completeDownload(id);
|
||||
return;
|
||||
}
|
||||
@@ -198,11 +196,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
|
||||
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
|
||||
if (isWeb) {
|
||||
console.warn("[DownloadStore] Download failed:", message);
|
||||
get().failDownload(id, message);
|
||||
return;
|
||||
}
|
||||
get().failDownload(id, message);
|
||||
}
|
||||
},
|
||||
@@ -283,7 +276,6 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
|
||||
interface DownloadTarget {
|
||||
baseUrl: string | null;
|
||||
authHeader: string | null;
|
||||
authCredentials: { username: string; password: string } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -306,7 +298,7 @@ function resolveDaemonDownloadTarget(
|
||||
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
|
||||
);
|
||||
} catch {
|
||||
return { baseUrl: null, authHeader: null, authCredentials: null };
|
||||
return { baseUrl: null, authHeader: null };
|
||||
}
|
||||
|
||||
if (parsed.protocol === "ws:") {
|
||||
@@ -332,23 +324,41 @@ function resolveDaemonDownloadTarget(
|
||||
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
|
||||
: null;
|
||||
|
||||
return { baseUrl, authHeader, authCredentials };
|
||||
return { baseUrl, authHeader };
|
||||
}
|
||||
|
||||
function buildDownloadUrl(
|
||||
baseUrl: string,
|
||||
token: string,
|
||||
authCredentials: { username: string; password: string } | null,
|
||||
): string {
|
||||
function buildDownloadUrl(baseUrl: string, token: string): string {
|
||||
const url = new URL("/api/files/download", baseUrl);
|
||||
url.searchParams.set("token", token);
|
||||
if (authCredentials) {
|
||||
url.username = authCredentials.username;
|
||||
url.password = authCredentials.password;
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the file instead of navigating to it. The app runs on another origin than the host
|
||||
* (paseo://app on desktop), so a link to the download URL navigates the whole window, and any
|
||||
* response that is not the file (a proxy's 401 page, a 404) replaces the app.
|
||||
*/
|
||||
async function fetchDownload(fetchFile: typeof fetch, url: string): Promise<Blob> {
|
||||
let response: Response;
|
||||
try {
|
||||
// Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the
|
||||
// host lets the download through. Refuse redirects: a proxy that redirects to a login page
|
||||
// would otherwise be saved as the file.
|
||||
response = await fetchFile(url, { credentials: "include", redirect: "error" });
|
||||
} catch {
|
||||
throw new Error(i18n.t("downloads.failed"));
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(i18n.t("downloads.httpFailed", { status: response.status }));
|
||||
}
|
||||
try {
|
||||
// The body streams after the headers, so the connection can still drop here.
|
||||
return await response.blob();
|
||||
} catch {
|
||||
throw new Error(i18n.t("downloads.failed"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves bytes read over the session. Web and Electron hand them to the browser's download
|
||||
* manager and return `null`; native writes the file and returns its URI for the share sheet.
|
||||
@@ -361,12 +371,7 @@ async function saveDownloadedBytes({
|
||||
if (isWeb) {
|
||||
const buffer = new ArrayBuffer(bytes.byteLength);
|
||||
new Uint8Array(buffer).set(bytes);
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
|
||||
);
|
||||
triggerBrowserDownload(url, fileName);
|
||||
// The browser may still be reading the blob while its save prompt is open.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
|
||||
return null;
|
||||
}
|
||||
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
|
||||
@@ -390,14 +395,12 @@ async function shareSavedFile(
|
||||
}
|
||||
}
|
||||
|
||||
function triggerBrowserDownload(url: string, fileName: string) {
|
||||
function saveBrowserFile(file: Blob, fileName: string) {
|
||||
if (typeof document === "undefined") {
|
||||
if (typeof window !== "undefined") {
|
||||
void openExternalUrl(url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const url = URL.createObjectURL(file);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = fileName;
|
||||
@@ -405,6 +408,8 @@ function triggerBrowserDownload(url: string, fileName: string) {
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
// The browser may still be reading the blob while its save prompt is open.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
function resolveDownloadTargetFile(fileName: string): FSFile {
|
||||
|
||||
@@ -73,6 +73,18 @@ describe("desktop-badge-state", () => {
|
||||
expect(selectMacDockBadgeCount(state)).toBe(3);
|
||||
});
|
||||
|
||||
it("leaves out background workspaces, which the sidebar hides", () => {
|
||||
const hidden = { ...workspace("a", "attention"), background: true };
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden))).toBeUndefined();
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden, workspace("b", "failed")))).toBe(1);
|
||||
});
|
||||
|
||||
it("counts background workspaces while Show background puts them in the sidebar", () => {
|
||||
const hidden = { ...workspace("a", "attention"), background: true };
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden), { showBackground: true })).toBe(1);
|
||||
expect(createMacDockBadgeCountSelector({ showBackground: true })(stateWith(hidden))).toBe(1);
|
||||
});
|
||||
|
||||
it("recounts only when a workspace map is replaced", () => {
|
||||
const select = createMacDockBadgeCountSelector();
|
||||
const state = stateWith(workspace("a", "attention"));
|
||||
|
||||
@@ -19,11 +19,21 @@ export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspa
|
||||
* The macOS dock badge only needs a count, so count here instead of materialising every
|
||||
* workspace status and comparing the whole list on every store write.
|
||||
*/
|
||||
export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | undefined {
|
||||
export interface DockBadgeOptions {
|
||||
/** Count background workspaces too, as the sidebar shows them while Show background is on. */
|
||||
showBackground?: boolean;
|
||||
}
|
||||
|
||||
export function selectMacDockBadgeCount(
|
||||
state: WorkspaceStatusSource,
|
||||
options: DockBadgeOptions = {},
|
||||
): number | undefined {
|
||||
let actionableCount = 0;
|
||||
for (const session of Object.values(state.sessions)) {
|
||||
if (!session) continue;
|
||||
for (const workspace of session.workspaces.values()) {
|
||||
// A hidden background workspace would leave the badge pointing at nothing in the sidebar.
|
||||
if (workspace.background && !options.showBackground) continue;
|
||||
if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1;
|
||||
}
|
||||
}
|
||||
@@ -31,11 +41,11 @@ export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number |
|
||||
}
|
||||
|
||||
/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */
|
||||
export function createMacDockBadgeCountSelector(): (
|
||||
state: WorkspaceStatusSource,
|
||||
) => number | undefined {
|
||||
export function createMacDockBadgeCountSelector(
|
||||
options: DockBadgeOptions = {},
|
||||
): (state: WorkspaceStatusSource) => number | undefined {
|
||||
return memoizeOnSessionMaps<WorkspaceStatusSession, WorkspaceStatusSource, number | undefined>(
|
||||
(session) => session.workspaces,
|
||||
selectMacDockBadgeCount,
|
||||
(session) => [session.workspaces],
|
||||
(state) => selectMacDockBadgeCount(state, options),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status";
|
||||
|
||||
function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
@@ -14,7 +14,21 @@ function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
}
|
||||
|
||||
function stateWith(...agents: Agent[]) {
|
||||
return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } };
|
||||
return stateWithWorkspaces([], ...agents);
|
||||
}
|
||||
|
||||
function stateWithWorkspaces(
|
||||
workspaces: Array<Pick<WorkspaceDescriptor, "id" | "background">>,
|
||||
...agents: Agent[]
|
||||
) {
|
||||
return {
|
||||
sessions: {
|
||||
srv: {
|
||||
agents: new Map(agents.map((entry) => [entry.id, entry])),
|
||||
workspaces: new Map(workspaces.map((entry) => [entry.id, entry])),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveFaviconStatus", () => {
|
||||
@@ -50,6 +64,37 @@ describe("deriveFaviconStatus", () => {
|
||||
),
|
||||
).toBe("none");
|
||||
});
|
||||
|
||||
it("ignores agents in background workspaces, which the sidebar hides", () => {
|
||||
const hidden = { id: "ws-hidden", background: true };
|
||||
expect(
|
||||
deriveFaviconStatus(
|
||||
stateWithWorkspaces(
|
||||
[hidden],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
agent({ id: "b", workspaceId: "ws-hidden", status: "running" }),
|
||||
),
|
||||
),
|
||||
).toBe("none");
|
||||
expect(
|
||||
deriveFaviconStatus(
|
||||
stateWithWorkspaces(
|
||||
[hidden, { id: "ws-shown", background: false }],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", status: "running" }),
|
||||
agent({ id: "b", workspaceId: "ws-shown", requiresAttention: true }),
|
||||
),
|
||||
),
|
||||
).toBe("attention");
|
||||
});
|
||||
|
||||
it("counts agents in background workspaces while Show background puts them in the sidebar", () => {
|
||||
const state = stateWithWorkspaces(
|
||||
[{ id: "ws-hidden", background: true }],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
);
|
||||
expect(deriveFaviconStatus(state, { showBackground: true })).toBe("attention");
|
||||
expect(createFaviconStatusSelector({ showBackground: true })(state)).toBe("attention");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createFaviconStatusSelector", () => {
|
||||
@@ -63,6 +108,18 @@ describe("createFaviconStatusSelector", () => {
|
||||
expect(select({ sessions: { ...state.sessions } })).toBe("running");
|
||||
});
|
||||
|
||||
it("rescans when a workspace map is replaced", () => {
|
||||
const select = createFaviconStatusSelector();
|
||||
const state = stateWithWorkspaces(
|
||||
[],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
);
|
||||
expect(select(state)).toBe("attention");
|
||||
// The agent synced before its workspace; only the workspace map changes.
|
||||
const workspaces = new Map([["ws-hidden", { id: "ws-hidden", background: true }]]);
|
||||
expect(select({ sessions: { srv: { ...state.sessions.srv, workspaces } } })).toBe("none");
|
||||
});
|
||||
|
||||
it("rescans when an agent map is replaced", () => {
|
||||
const select = createFaviconStatusSelector();
|
||||
expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running");
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { memoizeOnSessionMaps } from "./memoize-on-session-maps";
|
||||
|
||||
export type FaviconStatus = "none" | "running" | "attention";
|
||||
|
||||
interface FaviconAgentSession {
|
||||
agents: ReadonlyMap<string, Agent>;
|
||||
workspaces: ReadonlyMap<string, Pick<WorkspaceDescriptor, "background">>;
|
||||
}
|
||||
|
||||
interface FaviconAgentSource {
|
||||
@@ -16,13 +17,22 @@ interface FaviconAgentSource {
|
||||
* three states here instead of building the aggregated agent list: the list allocates a
|
||||
* projection per agent, deep-compares it and sorts every agent on the host on each update.
|
||||
*/
|
||||
export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus {
|
||||
export interface FaviconStatusOptions {
|
||||
/** Count agents in background workspaces too, as the sidebar shows them while Show background is on. */
|
||||
showBackground?: boolean;
|
||||
}
|
||||
|
||||
export function deriveFaviconStatus(
|
||||
state: FaviconAgentSource,
|
||||
options: FaviconStatusOptions = {},
|
||||
): FaviconStatus {
|
||||
let hasAttention = false;
|
||||
let hasNeedsInput = false;
|
||||
for (const session of Object.values(state.sessions)) {
|
||||
if (!session) continue;
|
||||
for (const agent of session.agents.values()) {
|
||||
if (agent.background || agent.archivedAt) continue;
|
||||
if (!options.showBackground && isInBackgroundWorkspace(agent, session)) continue;
|
||||
if (agent.status === "running") return "running";
|
||||
if (agent.requiresAttention) hasAttention = true;
|
||||
if (agent.pendingPermissions.length > 0) hasNeedsInput = true;
|
||||
@@ -31,10 +41,16 @@ export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus {
|
||||
return hasAttention || hasNeedsInput ? "attention" : "none";
|
||||
}
|
||||
|
||||
/** A session-store selector for the favicon status that rescans only when an agent map changes. */
|
||||
export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus {
|
||||
function isInBackgroundWorkspace(agent: Agent, session: FaviconAgentSession): boolean {
|
||||
return agent.workspaceId ? session.workspaces.get(agent.workspaceId)?.background === true : false;
|
||||
}
|
||||
|
||||
/** A session-store selector for the favicon status that rescans only when an agent or workspace map changes. */
|
||||
export function createFaviconStatusSelector(
|
||||
options: FaviconStatusOptions = {},
|
||||
): (state: FaviconAgentSource) => FaviconStatus {
|
||||
return memoizeOnSessionMaps<FaviconAgentSession, FaviconAgentSource, FaviconStatus>(
|
||||
(session) => session.agents,
|
||||
deriveFaviconStatus,
|
||||
(session) => [session.agents, session.workspaces],
|
||||
(state) => deriveFaviconStatus(state, options),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,18 +4,18 @@ interface SessionsSource<TSession> {
|
||||
|
||||
/**
|
||||
* Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has
|
||||
* changed. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
|
||||
* changed. `pickMaps` returns every map the selector reads from one session. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
|
||||
* a reference check per host instead of a walk over every entry.
|
||||
*/
|
||||
export function memoizeOnSessionMaps<TSession, TState extends SessionsSource<TSession>, TResult>(
|
||||
pickMap: (session: TSession) => unknown,
|
||||
pickMaps: (session: TSession) => readonly unknown[],
|
||||
derive: (state: TState) => TResult,
|
||||
): (state: TState) => TResult {
|
||||
let previousMaps: unknown[] | null = null;
|
||||
let previousResult: TResult;
|
||||
return (state) => {
|
||||
const maps = Object.values(state.sessions).map((session) =>
|
||||
session ? pickMap(session) : undefined,
|
||||
const maps = Object.values(state.sessions).flatMap((session) =>
|
||||
session ? pickMaps(session) : [undefined],
|
||||
);
|
||||
if (
|
||||
previousMaps &&
|
||||
|
||||
@@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
|
||||
);
|
||||
}
|
||||
|
||||
import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
|
||||
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
|
||||
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
|
||||
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
|
||||
import { createGitHubService } from "../services/github-service.js";
|
||||
@@ -813,7 +813,7 @@ export async function createPaseoDaemon(
|
||||
|
||||
app.use((req, res, next) => {
|
||||
const origin = req.headers.origin;
|
||||
if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) {
|
||||
if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) {
|
||||
res.setHeader("Access-Control-Allow-Origin", origin);
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
symlinkSync,
|
||||
} from "fs";
|
||||
import { once } from "node:events";
|
||||
import { get } from "node:http";
|
||||
import { get, type IncomingMessage } from "node:http";
|
||||
import { tmpdir } from "os";
|
||||
import path from "path";
|
||||
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
|
||||
@@ -69,6 +69,29 @@ describe("daemon E2E", () => {
|
||||
}, 60000);
|
||||
|
||||
describe("file download tokens", () => {
|
||||
test("lets a page on a loopback alias of the request's host and port fetch a download", async () => {
|
||||
const cwd = tmpCwd();
|
||||
writeFileSync(path.join(cwd, "download.bin"), "download bytes");
|
||||
try {
|
||||
// The web UI behind a remapped port (for example Docker -p 8080:6767): the page is at
|
||||
// http://127.0.0.1:8080 and the app sends the request to localhost:8080. The WebSocket
|
||||
// accepts this origin, so the download must as well.
|
||||
const token = await ctx.client.requestDownloadToken(cwd, "download.bin");
|
||||
const request = get({
|
||||
host: "127.0.0.1",
|
||||
port: ctx.daemon.port,
|
||||
path: `/api/files/download?token=${token.token}`,
|
||||
headers: { Host: "localhost:8080", Origin: "http://127.0.0.1:8080" },
|
||||
});
|
||||
const [response] = (await once(request, "response")) as [IncomingMessage];
|
||||
response.resume();
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.headers["access-control-allow-origin"]).toBe("http://127.0.0.1:8080");
|
||||
} finally {
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== "linux")(
|
||||
"releases file descriptors after repeated HTTP download cancellations",
|
||||
async () => {
|
||||
|
||||
@@ -998,9 +998,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
callback(false, 403, "Host not allowed");
|
||||
return;
|
||||
}
|
||||
const sameOrigin = isWebSocketSameOrigin(origin, requestHost);
|
||||
|
||||
if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) {
|
||||
if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) {
|
||||
callback(true);
|
||||
} else {
|
||||
this.incrementRuntimeCounter("originRejected");
|
||||
@@ -3267,6 +3265,22 @@ function isLoopbackAlias(hostname: string): boolean {
|
||||
return /^127(?:\.\d{1,3}){3}$/.test(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket
|
||||
* upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch.
|
||||
*/
|
||||
export function isDaemonOriginAllowed(
|
||||
origin: string,
|
||||
requestHost: string | null,
|
||||
allowedOrigins: Set<string>,
|
||||
): boolean {
|
||||
return (
|
||||
allowedOrigins.has("*") ||
|
||||
allowedOrigins.has(origin) ||
|
||||
isWebSocketSameOrigin(origin, requestHost)
|
||||
);
|
||||
}
|
||||
|
||||
export function isWebSocketSameOrigin(
|
||||
origin: string | undefined,
|
||||
requestHost: string | null,
|
||||
|
||||
Reference in New Issue
Block a user