Files
paseo/packages/app/src/workspace/legacy-daemon-workspaces.ts
T
Mohamed BoudraandGitHub 20e46e3e3f Restore project grouping across hosts (#2565)
* fix(projects): restore cross-host grouping

Random host-local project IDs replaced the remote-derived value that had also served as grouping identity. Persist a separate opaque group key and let normal boot reconciliation backfill older records without a migration.

* fix(projects): keep ambiguous clones separate

A shared remote can identify a project across hosts, but it cannot distinguish two independent clones on one host. Treat those keys as ambiguous so host-local project IDs remain separate.

* fix(projects): preserve host-local project identity

* fix(projects): strengthen grouping identity

* test(app): update project host shape contract

* fix(projects): preserve selected host identity

* fix(projects): close grouped routing gaps

* fix(projects): stabilize legacy subproject grouping

* fix(projects): preserve selected project identity

* fix(projects): isolate legacy host identity

* fix(projects): preserve symlinked bootstrap roots

* fix(projects): reconcile grouped custom names

* fix(projects): stabilize settings and path identity

* fix(projects): normalize default remote ports

* fix(projects): harden host and remote identity

* fix(projects): preserve host-scoped actions

* fix(projects): preserve remote path semantics

* fix(projects): model SCP remote semantics

* fix(projects): keep settings on routed host

* fix(projects): preserve SSH URL path semantics

* fix(projects): separate identity from presentation

* test(projects): use grouped identity in UI specs

* fix(projects): harden grouped project routing

* test(projects): expect framed settings route

* fix(projects): preserve exact placement identity

* fix(projects): harden grouping identity and routing

* fix(projects): restore project key as grouping identity

Random host-local project IDs had replaced the persisted cross-host value carried by projectKey. Keep projectId for routing while reconciliation owns and persists projectKey for grouping.

* fix(projects): prevent project key collisions

Preserve platform path semantics and generic remote transports in cross-host keys, and compare legacy checkout roots using filesystem equivalence before materializing ownership.

* test(projects): assert host-scoped project keys

* fix(projects): preserve project key compatibility

Resolve legacy workspace project references at the daemon boundary while keeping projectKey as the cross-host identity. Complete generic SSH normalization without collapsing distinct repositories.

* fix(projects): harden project reference identity

* fix(projects): retain archived reference errors

* fix(projects): scope legacy paths to hosts

* test(app): model persisted project keys

* fix(projects): retain absolute scp users

* fix(projects): resolve legacy mutation aliases

* fix(projects): preserve conservative identity boundaries

* fix(projects): preserve legacy placement identity

* test(projects): assert legacy placement identity

* test(projects): expect canonical Windows keys

* fix(projects): separate bootstrap identity fields

* fix(projects): scope legacy paths by host

* fix(projects): stabilize opaque project identity

* fix(projects): preserve remaining opaque identities

* fix(projects): classify forward-slash UNC roots

* fix(projects): preserve opaque selection keys

* fix(projects): frame host-local project keys

* fix(projects): canonicalize framed identities

* test(projects): isolate repeated remote fixtures

* fix(projects): keep project key as UI identity

* fix(projects): reconcile hydrated project references

* fix(projects): preserve archived project identity

* refactor(projects): group projects from project records, not workspaces

Cross-host grouping had been built by hanging a projectKey off every
workspace descriptor. That scoped the key to the wrong entity: the app
then had to reconstruct project identity per workspace in six modules,
which forced projectKey fallbacks into RPC arguments and a server-side
resolver that turned grouping keys back into project ids.

A workspace has a projectId. The key belongs to the project, and
grouping is a display concern, so the daemon now publishes projects
over project.list plus the existing project.update channel and the app
groups them in one place. Projects are addressed by host-local
projectId everywhere, including the settings route.

Projects persisted without a key are backfilled by ordinary boot
reconciliation, with no migration. Old daemons advertise no projectList
capability and simply do not group.

* test(projects): seed projects alongside workspaces in fixtures

Sidebar fixtures seeded workspaces without their projects, which the
daemon cannot produce now that projects arrive on their own channel, so
nothing rendered. Adds a seeding helper that supplies both.

Also drops the provisioning test for accepting a project key where a
project id belongs; that resolver was removed deliberately.

* fix(projects): keep derived project identity stable

Four gaps left by shrinking the key derivation:

Local keys used a bare path resolve, so one directory reached by a
different spelling produced a different key and reset grouped identity.
Windows CI caught this with the 8.3 and long-name forms of one temp
path. Canonicalize through the shared realpath-aware normalization.

Subproject display names lost their selected-path input, so every
subproject of a monorepo rendered under the same remote-derived name.

Reconciliation only ever backfilled a missing key, so a project whose
remote changed stayed grouped with hosts on the old remote.

Project settings kept a disconnected host selected and rendered a dead
end with no way back to an editable host.

* fix(projects): read scheme remotes as URLs, not scp form

An `ssh://user@host:22/org/repo` remote matched the scp-form pattern
first, because `[^@]+` happily eats `ssh://git`, so the port landed in
the path and the project keyed as `remote:host/22/org/repo`. Two
spellings of one remote therefore never grouped.

Try scp form only when there is no scheme, and drop protocol-default
ports so an explicitly written `:22` matches the same remote without it.
2026-07-29 23:36:31 +02:00

414 lines
12 KiB
TypeScript

import type {
DaemonClient,
FetchAgentsEntry,
FetchAgentsOptions,
} from "@getpaseo/client/internal/daemon-client";
import {
deriveAgentStateBucket,
getWorkspaceStateBucketPriority,
} from "@getpaseo/protocol/agent-state-bucket";
import type {
Agent,
DaemonServerInfo,
ProjectDescriptor,
WorkspaceDescriptor,
} from "@/stores/session-store";
import { useSessionStore } from "@/stores/session-store";
import {
buildAgentDirectoryState,
replaceFetchedAgentDirectory,
} from "@/utils/agent-directory-sync";
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
export interface LegacyDaemonWorkspaceSnapshot {
agents: Map<string, Agent>;
workspaces: Map<string, WorkspaceDescriptor>;
}
export interface LegacyDaemonWorkspaceFetchResult extends LegacyDaemonWorkspaceSnapshot {
subscriptionId: string | null;
}
interface LegacyDaemonWorkspaceDirectoryReadResult {
entries: FetchAgentsEntry[];
subscriptionId: string | null;
}
interface LegacyDaemonWorkspaceBackfillInput {
client: Pick<DaemonClient, "fetchAgents">;
serverId: string;
workspaces: ReadonlyMap<unknown, unknown>;
projects: ReadonlyMap<unknown, unknown>;
isCancelled?: () => boolean;
}
const LEGACY_AGENT_DIRECTORY_SORT: NonNullable<FetchAgentsOptions["sort"]> = [
{ key: "updated_at", direction: "desc" },
];
// COMPAT(legacyWorkspaceDaemon): v0.1.97 app talking to <=v0.1.96 daemons.
// Older daemons expose agents by cwd but may have no workspace registry rows.
// Keep all cwd -> synthetic workspace behavior in this file so the shim is
// deleted by removing this module and its call sites once the daemon floor is v0.1.97.
export function buildLegacyDaemonWorkspaceSnapshot(input: {
serverId: string;
entries: FetchAgentsEntry[];
}): LegacyDaemonWorkspaceSnapshot {
const entries = stampLegacyWorkspaceIds(input.entries);
const { agents } = buildAgentDirectoryState({
serverId: input.serverId,
entries,
});
return {
agents,
workspaces: buildLegacyWorkspaces(entries),
};
}
export function shouldUseLegacyDaemonWorkspaceDirectory(
serverInfo: DaemonServerInfo | null | undefined,
): boolean {
return (
serverInfo !== null &&
serverInfo !== undefined &&
serverInfo.features?.workspaceMultiplicity !== true
);
}
function shouldBackfillLegacyDaemonWorkspaceDirectory(
serverInfo: DaemonServerInfo | null | undefined,
): boolean {
return serverInfo?.features?.workspaceMultiplicity !== true;
}
export async function fetchLegacyDaemonWorkspaceDirectory(input: {
client: Pick<DaemonClient, "fetchAgents">;
serverId: string;
subscribe?: FetchAgentsOptions["subscribe"];
page?: FetchAgentsOptions["page"];
}): Promise<LegacyDaemonWorkspaceFetchResult> {
const directory = await readLegacyDaemonWorkspaceDirectory(input);
if (!directory) {
throw new Error("Legacy daemon workspace directory fetch was cancelled.");
}
const snapshot = replaceLegacyDaemonWorkspaceDirectory({
serverId: input.serverId,
entries: directory.entries,
});
return { ...snapshot, subscriptionId: directory.subscriptionId };
}
export async function backfillLegacyDaemonWorkspaceDirectoryIfEmpty(
input: LegacyDaemonWorkspaceBackfillInput,
): Promise<boolean> {
if (input.workspaces.size > 0 || input.projects.size > 0) {
return false;
}
const serverInfo = useSessionStore.getState().sessions[input.serverId]?.serverInfo;
if (!shouldBackfillLegacyDaemonWorkspaceDirectory(serverInfo)) {
return false;
}
if (input.isCancelled?.()) {
return true;
}
const directory = await readLegacyDaemonWorkspaceDirectory({
client: input.client,
isCancelled: input.isCancelled,
});
if (!directory || input.isCancelled?.()) {
return true;
}
replaceLegacyDaemonWorkspaceDirectory({
serverId: input.serverId,
entries: directory.entries,
});
return true;
}
export async function readLegacyDaemonWorkspaceDirectory(input: {
client: Pick<DaemonClient, "fetchAgents">;
subscribe?: FetchAgentsOptions["subscribe"];
page?: FetchAgentsOptions["page"];
isCancelled?: () => boolean;
}): Promise<LegacyDaemonWorkspaceDirectoryReadResult | null> {
const entries: FetchAgentsEntry[] = [];
let cursor = input.page?.cursor ?? null;
let includeSubscribe = true;
let subscriptionId: string | null = null;
const pageLimit = input.page?.limit ?? 200;
while (true) {
if (input.isCancelled?.()) {
return null;
}
const payload = await input.client.fetchAgents({
sort: LEGACY_AGENT_DIRECTORY_SORT,
...(includeSubscribe && input.subscribe ? { subscribe: input.subscribe } : {}),
page: cursor ? { limit: pageLimit, cursor } : { limit: pageLimit },
});
if (input.isCancelled?.()) {
return null;
}
entries.push(...payload.entries);
subscriptionId = subscriptionId ?? payload.subscriptionId ?? null;
includeSubscribe = false;
if (!readFetchAgentsHasMore(payload.pageInfo)) {
break;
}
const nextCursor = readFetchAgentsNextCursor(payload.pageInfo);
if (!nextCursor) {
break;
}
cursor = nextCursor;
}
return { entries, subscriptionId };
}
export function applyLegacyDaemonWorkspaceOwnership(input: {
serverId: string;
agent: Agent;
}): Agent {
if (input.agent.workspaceId) {
return input.agent;
}
const session = useSessionStore.getState().sessions[input.serverId];
if (!shouldBackfillLegacyDaemonWorkspaceDirectory(session?.serverInfo)) {
return input.agent;
}
const existingAgent =
session?.agents.get(input.agent.id) ?? session?.agentDetails.get(input.agent.id) ?? null;
const workspaceId =
existingAgent?.workspaceId ??
resolveLegacyWorkspaceIdFromAgent(input.agent, session?.workspaces) ??
null;
if (!workspaceId) {
return input.agent;
}
return {
...input.agent,
workspaceId,
projectPlacement: input.agent.projectPlacement ?? existingAgent?.projectPlacement,
};
}
export function replaceLegacyDaemonWorkspaceDirectory(input: {
serverId: string;
entries: FetchAgentsEntry[];
}): LegacyDaemonWorkspaceSnapshot {
const entries = stampLegacyWorkspaceIds(input.entries);
const { agents } = replaceFetchedAgentDirectory({
serverId: input.serverId,
entries,
});
const workspaces = buildLegacyWorkspaces(entries);
const store = useSessionStore.getState();
store.setWorkspaces(input.serverId, workspaces);
store.setProjects(
input.serverId,
Array.from(workspaces.values(), legacyProjectDescriptorFromWorkspace),
);
store.setHasHydratedWorkspaces(input.serverId, true);
return { agents, workspaces };
}
function legacyProjectDescriptorFromWorkspace(workspace: WorkspaceDescriptor): ProjectDescriptor {
return {
projectId: workspace.projectId,
projectKey: null,
projectDisplayName: workspace.projectDisplayName,
projectCustomName: workspace.projectCustomName ?? null,
projectRootPath: workspace.projectRootPath,
projectKind: workspace.projectKind,
};
}
function readFetchAgentsHasMore(
pageInfo: Awaited<ReturnType<DaemonClient["fetchAgents"]>>["pageInfo"],
): boolean {
const page = pageInfo as {
hasMore?: boolean;
hasMoreAfter?: boolean;
};
if (typeof page.hasMore === "boolean") {
return page.hasMore;
}
if (typeof page.hasMoreAfter === "boolean") {
return page.hasMoreAfter;
}
return false;
}
function readFetchAgentsNextCursor(
pageInfo: Awaited<ReturnType<DaemonClient["fetchAgents"]>>["pageInfo"],
): string | null {
const page = pageInfo as {
nextCursor?: string | null;
afterCursor?: string | null;
};
if (typeof page.nextCursor === "string") {
return page.nextCursor;
}
if (typeof page.afterCursor === "string") {
return page.afterCursor;
}
return null;
}
export function stampLegacyWorkspaceIds(entries: FetchAgentsEntry[]): FetchAgentsEntry[] {
return entries.map((entry) => {
const workspaceId = resolveLegacyWorkspaceId(entry);
return {
...entry,
agent: {
...entry.agent,
workspaceId,
},
};
});
}
export function buildLegacyWorkspaces(
entries: FetchAgentsEntry[],
): Map<string, WorkspaceDescriptor> {
const workspaces = new Map<string, WorkspaceDescriptor>();
for (const entry of entries) {
const workspaceId = entry.agent.workspaceId ?? resolveLegacyWorkspaceId(entry);
const status = deriveAgentStateBucket({
status: entry.agent.status,
pendingPermissionCount: entry.agent.pendingPermissions.length,
requiresAttention: entry.agent.requiresAttention,
attentionReason: entry.agent.attentionReason,
});
const statusEnteredAt = parseLegacyAgentTimestamp(entry);
const existing = workspaces.get(workspaceId);
if (!existing) {
workspaces.set(workspaceId, createLegacyWorkspace(entry, status, statusEnteredAt));
continue;
}
if (
getWorkspaceStateBucketPriority(status) < getWorkspaceStateBucketPriority(existing.status)
) {
workspaces.set(workspaceId, {
...existing,
status,
statusEnteredAt,
});
}
}
return workspaces;
}
function createLegacyWorkspace(
entry: FetchAgentsEntry,
status: WorkspaceDescriptor["status"],
statusEnteredAt: Date | null,
): WorkspaceDescriptor {
const workspaceDirectory = resolveLegacyWorkspaceId(entry);
const checkout = entry.project.checkout;
const projectRootPath =
normalizeWorkspacePath(checkout.mainRepoRoot ?? checkout.worktreeRoot ?? checkout.cwd) ??
workspaceDirectory;
return {
id: workspaceDirectory,
projectId: entry.project.projectKey,
projectDisplayName: entry.project.projectName,
projectCustomName: null,
projectRootPath,
workspaceDirectory,
projectKind: checkout.isGit ? "git" : "non_git",
workspaceKind: resolveLegacyWorkspaceKind(checkout),
name: resolveLegacyWorkspaceName(entry, workspaceDirectory),
title: null,
status,
statusEnteredAt,
archivingAt: null,
diffStat: null,
scripts: [],
gitRuntime: checkout.isGit
? {
currentBranch: checkout.currentBranch,
remoteUrl: checkout.remoteUrl,
isPaseoOwnedWorktree: checkout.isPaseoOwnedWorktree,
isDirty: null,
aheadBehind: null,
aheadOfOrigin: null,
behindOfOrigin: null,
}
: null,
githubRuntime: null,
project: entry.project,
};
}
function resolveLegacyWorkspaceKind(
checkout: FetchAgentsEntry["project"]["checkout"],
): WorkspaceDescriptor["workspaceKind"] {
if (!checkout.isGit) {
return "directory";
}
if (checkout.isPaseoOwnedWorktree) {
return "worktree";
}
return "checkout";
}
function resolveLegacyWorkspaceId(entry: FetchAgentsEntry): string {
return (
normalizeWorkspacePath(entry.project.checkout.cwd) ??
normalizeWorkspacePath(entry.agent.cwd) ??
entry.agent.cwd
);
}
function resolveLegacyWorkspaceIdFromAgent(
agent: Agent,
workspaces: Map<string, WorkspaceDescriptor> | undefined,
): string | null {
const cwd = normalizeWorkspacePath(agent.cwd);
if (!cwd) {
return null;
}
for (const workspace of workspaces?.values() ?? []) {
if (normalizeWorkspacePath(workspace.workspaceDirectory) === cwd) {
return workspace.id;
}
}
return cwd;
}
function resolveLegacyWorkspaceName(entry: FetchAgentsEntry, workspaceDirectory: string): string {
const explicitName = entry.project.workspaceName?.trim();
if (explicitName) {
return explicitName;
}
const branchName = entry.project.checkout.currentBranch?.trim();
if (branchName && branchName !== "HEAD") {
return branchName;
}
return workspaceDirectoryName(workspaceDirectory);
}
function workspaceDirectoryName(directory: string): string {
const trimmed = directory.trim().replace(/[/]+$/g, "");
const separator = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
return separator >= 0 ? trimmed.slice(separator + 1) : trimmed;
}
function parseLegacyAgentTimestamp(entry: FetchAgentsEntry): Date | null {
const value = entry.agent.attentionTimestamp ?? entry.agent.updatedAt;
if (!value) {
return null;
}
const date = new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}