The VS Code of video editing, built for agents.
TypeScript
feat: add project relocation and missing project handling functionality
konstantin-paulus58af16065d6e
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex d5463fd3..54d1411f 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -13,6 +13,7 @@ import type { LogEntry, ScreenshotResult } from "@diffusionstudio/dapi";import type { SourceEdit, WriteResult } from "./edit-types";import type { AgentId } from "./mcp-config";import type { EditorId, EditorInfo } from "./editors";+import type { MissingProjectChoice } from "./projects";export const MAIN_WIRE = {REQUEST: "main:request",@@ -51,6 +52,8 @@ export const MAIN_CHANNELS = {PROJECTS_GET: "projects:get",PROJECTS_INIT: "projects:init",PROJECTS_RESOLVE: "projects:resolve",+ PROJECTS_FIND_MOVED: "projects:find-moved",+ PROJECTS_ASK_MISSING: "projects:ask-missing",PROJECTS_CREATE: "projects:create",PROJECTS_PICK_SAVE: "projects:pick-save",PROJECTS_SAVE: "projects:save",@@ -120,6 +123,7 @@ export type CompileResult =export type { SourceEdit, WriteResult };export type { AgentId };export type { EditorId, EditorInfo };+export type { MissingProjectChoice };// One agent the settings page lists: whether it is set up on this machine,// whether its config already carries the app's MCP entry, and — for the@@ -254,6 +258,17 @@ export type MainRequestMap = {request: { dir: string };response: ProjectInfo | null;};+ // The project `id` in a folder beside `dir`, which no longer holds it (a+ // folder renamed or moved in Finder); null when none does.+ [MAIN_CHANNELS.PROJECTS_FIND_MOVED]: {+ request: { dir: string; id: string };+ response: ProjectInfo | null;+ };+ // Asks what to do about a project whose folder can't be found.+ [MAIN_CHANNELS.PROJECTS_ASK_MISSING]: {+ request: { displayName: string; dir: string };+ response: MissingProjectChoice;+ };// A new project, as a draft called "Untitled" until it is saved.[MAIN_CHANNELS.PROJECTS_CREATE]: {request: void;diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex f5d2e64d..31f7659c 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -28,6 +28,8 @@ import {deleteProject,duplicateProject,getProject,+ askAboutMissingProject,+ findMovedProject,initProject,pickFolder,pickSaveLocation,@@ -388,6 +390,10 @@ if (squirrelLaunch) {mainBridge.handle(MAIN_CHANNELS.PROJECTS_GET, ({ dir }) => getProject(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_INIT, ({ dir }) => initProject(mainWindow, dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_RESOLVE, ({ dir }) => resolveProject(dir));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_FIND_MOVED, ({ dir, id }) => findMovedProject(dir, id));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_ASK_MISSING, ({ displayName, dir }) =>+ askAboutMissingProject(mainWindow, displayName, dir),+ );mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, () => createProject());mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_SAVE, ({ dir, displayName, startIn }) =>pickSaveLocation(mainWindow, dir, displayName, startIn),diff --git a/apps/desktop/src/projects.locate.test.ts b/apps/desktop/src/projects.locate.test.tsnew file mode 100644index 00000000..b350bfa5--- /dev/null+++ b/apps/desktop/src/projects.locate.test.ts@@ -0,0 +1,51 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// A project folder renamed or moved in Finder is found again next to where it+// was, by the id in its record.++import { tmpdir } from "node:os";+import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("electron", () => ({+ app: { isPackaged: false, getPath: () => tmpdir() },+ dialog: {},+ shell: {},+ ipcMain: { on: () => { } },+}));++const { findMovedProject, initProject } = await import("./projects");++let root: string;++beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), "locate-test-"));+});++afterEach(async () => {+ await rm(root, { recursive: true, force: true });+});++describe("findMovedProject", () => {+ it("finds a project renamed in place by its id", async () => {+ const project = await initProject(null, join(root, "golden-river"));+ await initProject(null, join(root, "another"));+ await rename(project.dir, join(root, "My Ad"));++ const found = await findMovedProject(project.dir, project.id);+ expect(found).toMatchObject({ id: project.id, dir: join(root, "My Ad") });+ });++ it("finds nothing when the folder left its parent, or the parent is gone", async () => {+ const project = await initProject(null, join(root, "golden-river"));+ await mkdir(join(root, "elsewhere", "deeper"), { recursive: true });+ await rename(project.dir, join(root, "elsewhere", "deeper", "My Ad"));++ expect(await findMovedProject(project.dir, project.id)).toBeNull();+ expect(await findMovedProject(join(root, "gone", "golden-river"), project.id)).toBeNull();+ expect(await findMovedProject(project.dir, "")).toBeNull();+ });+});diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex 8f0def75..433ea4f3 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -440,6 +440,54 @@ async function confirmCloudLocation(return response === 1;}+/**+ * The project `id` in a folder beside `dir`, which no longer holds it: one+ * renamed in Finder, or moved to another folder next to it. Found by the id in+ * its record, which goes wherever the folder goes. Null when no sibling holds+ * it, or `dir`'s parent is gone too. Reads only.+ */+export async function findMovedProject(dir: string, id: string): Promise<ProjectInfo | null> {+ if (!id) return null;+ const parent = dirname(dir);+ let entries;+ try {+ entries = await readdir(parent, { withFileTypes: true });+ } catch {+ return null;+ }+ for (const entry of entries) {+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;+ const candidate = join(parent, entry.name);+ if (recordedId(await readPackage(candidate)) === id) return describe(candidate);+ }+ return null;+}++/** What the user wants done about a project whose folder can't be found. */+export type MissingProjectChoice = "locate" | "remove" | "cancel";++/** Tells the user the project's folder is gone, and asks what to do about it. */+export async function askAboutMissingProject(+ window: BrowserWindow | null,+ displayName: string,+ dir: string,+): Promise<MissingProjectChoice> {+ const options: Electron.MessageBoxOptions = {+ type: "warning",+ message: `Can't find "${displayName}"`,+ detail: `It was in ${dir}. It may have been moved, renamed or deleted, or be on a disk that isn't connected.`,+ buttons: ["Locate...", "Remove from List", "Cancel"],+ defaultId: 0,+ cancelId: 2,+ };+ const { response } = window+ ? await dialog.showMessageBox(window, options)+ : await dialog.showMessageBox(options);+ if (response === 0) return "locate";+ if (response === 1) return "remove";+ return "cancel";+}+/*** The project in `dir`, left holding an id — this is where a folder that* predates ids, or was made by hand, gets one — so the caller can send thediff --git a/apps/web/src/components/dashboard/project-card.tsx b/apps/web/src/components/dashboard/project-card.tsxindex 898261b3..52b6e5c1 100644--- a/apps/web/src/components/dashboard/project-card.tsx+++ b/apps/web/src/components/dashboard/project-card.tsx@@ -2,7 +2,7 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { Show, batch, createSignal } from "solid-js";+import { For, Show, batch, createResource, createSignal } from "solid-js";import { toast } from "somoto";import {@@ -15,7 +15,8 @@ import {} from "@/components/ui/context-menu";import { TextField, TextFieldInput } from "@/components/ui/text-field";import { track } from "@/lib/analytics";-import { duplicateProject, renameProject, type ProjectRecord } from "@/projects";+import { listEditors, openInEditor, revealPath, type EditorInfo } from "@/lib/shell";+import { duplicateProject, isWindowsDesktop, renameProject, type ProjectRecord } from "@/projects";import { DashboardCardButton, DashboardCardPreview, DashboardProjectThumbnail } from "./shared";import { formatEditedAt } from "./utils";@@ -38,13 +39,15 @@ type DashboardProjectCardProps = {/*** A project in a dashboard grid: thumbnail, name, and last-edited time, with- * the context menu that opens, renames, duplicates, and deletes it. Rename+ * the context menu that opens it (here, in the file manager, or in a code+ * editor), renames, duplicates, and deletes it. Rename* happens inline, in place of the name, and lives here so every grid that* shows projects gets the same menu.*/export function DashboardProjectCard(props: DashboardProjectCardProps) {const [renaming, setRenaming] = createSignal(false);const [renameDraft, setRenameDraft] = createSignal("");+ const [editors] = createResource(listEditors, { initialValue: [] });const startRenaming = () => {batch(() => {@@ -65,6 +68,22 @@ export function DashboardProjectCard(props: DashboardProjectCardProps) {props.onOpen();};+ const handleReveal = async () => {+ try {+ await revealPath(props.project.dir);+ } catch (e) {+ toast.error("Failed to show the folder", { description: (e as Error).message });+ }+ };++ const handleOpenInEditor = async (editor: EditorInfo) => {+ try {+ await openInEditor(editor.id, props.project.dir);+ } catch (e) {+ toast.error(`Failed to open in ${editor.label}`, { description: (e as Error).message });+ }+ };+const handleDuplicate = async () => {try {await duplicateProject(props.project.dir);@@ -176,6 +195,15 @@ export function DashboardProjectCard(props: DashboardProjectCardProps) {<ContextMenuContent class="w-45 gap-0"><ContextMenuItem onSelect={handleOpen}>Open</ContextMenuItem><ContextMenuSeparator class="my-2" />+ <ContextMenuItem onSelect={handleReveal}>+ {isWindowsDesktop() ? "Show in Explorer" : "Show in Finder"}+ </ContextMenuItem>+ <For each={editors()}>+ {(editor) => (+ <ContextMenuItem onSelect={() => handleOpenInEditor(editor)}>Open in {editor.label}</ContextMenuItem>+ )}+ </For>+ <ContextMenuSeparator class="my-2" /><ContextMenuItem onSelect={startRenaming}>Rename</ContextMenuItem><ContextMenuItem onSelect={handleDuplicate}>Duplicate</ContextMenuItem><ContextMenuSeparator class="my-2" />diff --git a/apps/web/src/components/dashboard/shared.tsx b/apps/web/src/components/dashboard/shared.tsxindex 7bef962b..ea53dd7c 100644--- a/apps/web/src/components/dashboard/shared.tsx+++ b/apps/web/src/components/dashboard/shared.tsx@@ -24,11 +24,14 @@ import { toast } from "somoto";import { track } from "@/lib/analytics";import { forgetProjectBundle } from "@/lib/db";import {+ askAboutMissingProject,checkProject,createProject,deleteProject,forgetProject,isDesktop,+ locateProject,+ relocateProject,type ProjectInfo,} from "@/projects";@@ -578,10 +581,11 @@ export async function createNewProject(): Promise<ProjectInfo | null> {/*** The project as its folder holds it now, for opening it from the list: what- * the list shows is its record, and the folder is only looked at here. Null —- * with the reason shown, and a way to take the project off the list — when- * the folder is gone or no longer a project. The list is not touched on its- * own: a folder on a volume that is not mounted comes back with the volume.+ * the list shows is its record, and the folder is only looked at here. A+ * folder renamed or moved next to where it was is found by the project's id,+ * and the list follows it. Otherwise the user is asked: locate it, take it off+ * the list, or leave it be — a folder on a volume that is not mounted comes+ * back with the volume. Null unless there is a project to open.*/export async function openProjectFromList(project: ProjectInfo): Promise<ProjectInfo | null> {if (!isDesktop()) return project;@@ -589,18 +593,27 @@ export async function openProjectFromList(project: ProjectInfo): Promise<Projectconst current = await checkProject(project);if (current) return current;- toast.error(`Could not find ${project.displayName}`, {- description: `There is no project at ${project.dir}. It may be on a disk that is not connected.`,- action: {- label: "Remove from list",- onClick: () => {- forgetProject(project.dir).catch((e) => {- toast.error("Failed to remove project", { description: (e as Error).message });- });- },- },- });- return null;+ // Renamed or moved in Finder: found next to where it was, and opened there.+ const moved = await relocateProject(project);+ if (moved) return moved;++ const choice = await askAboutMissingProject(project);+ if (choice === "remove") {+ try {+ await forgetProject(project.dir);+ } catch (e) {+ toast.error("Failed to remove project", { description: (e as Error).message });+ }+ return null;+ }+ if (choice !== "locate") return null;++ try {+ return await locateProject(project);+ } catch (e) {+ toast.error(`Could not open ${project.displayName}`, { description: (e as Error).message });+ return null;+ }}/**diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.tsindex ae603ea4..5fd3eef2 100644--- a/apps/web/src/projects/host.ts+++ b/apps/web/src/projects/host.ts@@ -16,10 +16,10 @@ import {updateProjectRecord,} from '@/lib/db';-import type { CompileResult, ProjectInfo, SourceEdit, WriteResult } from '@desktop/main-channels';+import type { CompileResult, MissingProjectChoice, ProjectInfo, SourceEdit, WriteResult } from '@desktop/main-channels';import type { ProjectRecord } from '@/lib/db';-export type { CompileResult, ProjectInfo, ProjectRecord, SourceEdit, WriteResult };+export type { CompileResult, MissingProjectChoice, ProjectInfo, ProjectRecord, SourceEdit, WriteResult };// The folder the save picker starts in: the parent of the last project// saved. One localStorage value, read synchronously. Kept under the key the@@ -108,6 +108,45 @@ export async function checkProject(project: ProjectInfo): Promise<ProjectInfo |return current;}+/**+ * Finds `project` again when its folder is gone from where the record says:+ * renamed in Finder, or moved to a folder next to it. Its record follows it to+ * the new folder, and the project there comes back; null when it is nowhere+ * near where it was.+ */+export async function relocateProject(project: ProjectInfo): Promise<ProjectInfo | null> {+ const moved = await mainBridge.call(MAIN_CHANNELS.PROJECTS_FIND_MOVED, { dir: project.dir, id: project.id });+ if (!moved) return null;+ await moveProjectRecord(project.dir, moved.dir);+ await remember(moved);+ return moved;+}++/** Tells the user `project`'s folder can't be found, and asks what to do about it. */+export function askAboutMissingProject(project: ProjectInfo): Promise<MissingProjectChoice> {+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_ASK_MISSING, { displayName: project.displayName, dir: project.dir });+}++/**+ * Asks the user where `project` went, with the folder picker: the project in+ * the folder they choose, its record moved there. Null when they cancel; an+ * error when the folder holds no project, or a different one.+ */+export async function locateProject(project: ProjectInfo): Promise<ProjectInfo | null> {+ const dir = await pickProjectFolder();+ if (!dir) return null;++ const found = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { dir });+ if (!found) throw new Error("That folder doesn't hold a project.");+ // A record from before ids has nothing to compare with: the user's word goes.+ if (project.id && found.id !== project.id) {+ throw new Error(`That folder holds a different project ("${found.displayName}").`);+ }+ await moveProjectRecord(project.dir, found.dir);+ await remember(found);+ return found;+}+/*** Re-reads the project in `dir` and brings its record up to date — for a* project whose folder changed while it was open, and for one that is@@ -179,7 +218,9 @@ export async function resolveProject(ref: string): Promise<ProjectInfo | null> {if (!ref || !isDesktop()) return null;for (const record of await findProjectRecords(ref)) {- const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { dir: record.dir });+ // A folder renamed or moved since is looked for next to where it was.+ const project =+ (await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { dir: record.dir })) ?? (await relocateProject(record));if (!project || (project.id !== ref && project.name !== ref)) continue;// Just opened, and holding an id the record may not have had yet.await rememberProject(project);